From 986339ee2b249a079b217a11a7ed21bdea62f4a1 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 30 Aug 2021 10:47:22 +0000 Subject: [PATCH 1/2] feat: Update osconfig v1 and v1alpha with WindowsApplication Committer: @coodie PiperOrigin-RevId: 393730900 Source-Link: https://github.com/googleapis/googleapis/commit/69fe13f7ca3ca96f34e042596c11e40bb3277924 Source-Link: https://github.com/googleapis/googleapis-gen/commit/69509318baafc42cbe4253dd9b53d56dd5a8f8ad --- 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 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../v1/docs/osconfig_v1/os_config_service.rst | 10 + .../v1/docs/osconfig_v1/services.rst | 6 + owl-bot-staging/v1/docs/osconfig_v1/types.rst | 7 + .../v1/google/cloud/osconfig/__init__.py | 91 + .../v1/google/cloud/osconfig/py.typed | 2 + .../v1/google/cloud/osconfig_v1/__init__.py | 92 + .../cloud/osconfig_v1/gapic_metadata.json | 113 + .../v1/google/cloud/osconfig_v1/py.typed | 2 + .../cloud/osconfig_v1/services/__init__.py | 15 + .../services/os_config_service/__init__.py | 22 + .../os_config_service/async_client.py | 896 +++ .../services/os_config_service/client.py | 1107 ++++ .../services/os_config_service/pagers.py | 385 ++ .../os_config_service/transports/__init__.py | 33 + .../os_config_service/transports/base.py | 282 + .../os_config_service/transports/grpc.py | 470 ++ .../transports/grpc_asyncio.py | 474 ++ .../cloud/osconfig_v1/types/__init__.py | 94 + .../cloud/osconfig_v1/types/inventory.py | 520 ++ .../osconfig_v1/types/osconfig_common.py | 52 + .../osconfig_v1/types/osconfig_service.py | 25 + .../osconfig_v1/types/patch_deployments.py | 439 ++ .../cloud/osconfig_v1/types/patch_jobs.py | 1080 ++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../v1/scripts/fixup_osconfig_v1_keywords.py | 184 + owl-bot-staging/v1/setup.py | 54 + 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/osconfig_v1/__init__.py | 16 + .../osconfig_v1/test_os_config_service.py | 3566 ++++++++++++ owl-bot-staging/v1alpha/.coveragerc | 17 + owl-bot-staging/v1alpha/MANIFEST.in | 2 + owl-bot-staging/v1alpha/README.rst | 49 + owl-bot-staging/v1alpha/docs/conf.py | 376 ++ owl-bot-staging/v1alpha/docs/index.rst | 7 + .../os_config_zonal_service.rst | 10 + .../docs/osconfig_v1alpha/services.rst | 6 + .../v1alpha/docs/osconfig_v1alpha/types.rst | 7 + .../v1alpha/google/cloud/osconfig/__init__.py | 81 + .../v1alpha/google/cloud/osconfig/py.typed | 2 + .../google/cloud/osconfig_v1alpha/__init__.py | 82 + .../osconfig_v1alpha/gapic_metadata.json | 143 + .../google/cloud/osconfig_v1alpha/py.typed | 2 + .../osconfig_v1alpha/services/__init__.py | 15 + .../os_config_zonal_service/__init__.py | 22 + .../os_config_zonal_service/async_client.py | 1372 +++++ .../os_config_zonal_service/client.py | 1599 ++++++ .../os_config_zonal_service/pagers.py | 631 +++ .../transports/__init__.py | 33 + .../transports/base.py | 332 ++ .../transports/grpc.py | 612 +++ .../transports/grpc_asyncio.py | 616 +++ .../cloud/osconfig_v1alpha/types/__init__.py | 90 + .../osconfig_v1alpha/types/config_common.py | 131 + .../types/instance_os_policies_compliance.py | 263 + .../cloud/osconfig_v1alpha/types/inventory.py | 670 +++ .../cloud/osconfig_v1alpha/types/os_policy.py | 865 +++ .../types/os_policy_assignments.py | 540 ++ .../osconfig_v1alpha/types/osconfig_common.py | 52 + .../types/osconfig_zonal_service.py | 25 + .../osconfig_v1alpha/types/vulnerability.py | 451 ++ owl-bot-staging/v1alpha/mypy.ini | 3 + owl-bot-staging/v1alpha/noxfile.py | 132 + .../fixup_osconfig_v1alpha_keywords.py | 187 + owl-bot-staging/v1alpha/setup.py | 54 + owl-bot-staging/v1alpha/tests/__init__.py | 16 + .../v1alpha/tests/unit/__init__.py | 16 + .../v1alpha/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/osconfig_v1alpha/__init__.py | 16 + .../test_os_config_zonal_service.py | 4846 +++++++++++++++++ 77 files changed, 25060 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/index.rst create mode 100644 owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst create mode 100644 owl-bot-staging/v1/docs/osconfig_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/osconfig_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/osconfig/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_service.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py create mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.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_osconfig_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/osconfig_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/test_os_config_service.py create mode 100644 owl-bot-staging/v1alpha/.coveragerc create mode 100644 owl-bot-staging/v1alpha/MANIFEST.in create mode 100644 owl-bot-staging/v1alpha/README.rst create mode 100644 owl-bot-staging/v1alpha/docs/conf.py create mode 100644 owl-bot-staging/v1alpha/docs/index.rst create mode 100644 owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst create mode 100644 owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst create mode 100644 owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_service.py create mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py create mode 100644 owl-bot-staging/v1alpha/mypy.ini create mode 100644 owl-bot-staging/v1alpha/noxfile.py create mode 100644 owl-bot-staging/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py create mode 100644 owl-bot-staging/v1alpha/setup.py create mode 100644 owl-bot-staging/v1alpha/tests/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/__init__.py create mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..d146ff0 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/osconfig/__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..92df5fe --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/osconfig *.py +recursive-include google/cloud/osconfig_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..d649bbe --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Osconfig 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 Cloud Osconfig 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..9dc389a --- /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-cloud-osconfig 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-cloud-osconfig" +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 Cloud 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-cloud-osconfig-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-cloud-osconfig.tex", + u"google-cloud-osconfig Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-osconfig", + u"Google Cloud Osconfig Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-osconfig", + u"google-cloud-osconfig Documentation", + author, + "google-cloud-osconfig", + "GAPIC library for Google Cloud Osconfig 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/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..a469ba0 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + osconfig_v1/services + osconfig_v1/types diff --git a/owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst b/owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst new file mode 100644 index 0000000..e082a4b --- /dev/null +++ b/owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst @@ -0,0 +1,10 @@ +OsConfigService +--------------------------------- + +.. automodule:: google.cloud.osconfig_v1.services.os_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.osconfig_v1.services.os_config_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/osconfig_v1/services.rst b/owl-bot-staging/v1/docs/osconfig_v1/services.rst new file mode 100644 index 0000000..e0dad88 --- /dev/null +++ b/owl-bot-staging/v1/docs/osconfig_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Osconfig v1 API +========================================= +.. toctree:: + :maxdepth: 2 + + os_config_service diff --git a/owl-bot-staging/v1/docs/osconfig_v1/types.rst b/owl-bot-staging/v1/docs/osconfig_v1/types.rst new file mode 100644 index 0000000..5c7249d --- /dev/null +++ b/owl-bot-staging/v1/docs/osconfig_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Osconfig v1 API +====================================== + +.. automodule:: google.cloud.osconfig_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/osconfig/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig/__init__.py new file mode 100644 index 0000000..ceb94a0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig/__init__.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.osconfig_v1.services.os_config_service.client import OsConfigServiceClient +from google.cloud.osconfig_v1.services.os_config_service.async_client import OsConfigServiceAsyncClient + +from google.cloud.osconfig_v1.types.inventory import Inventory +from google.cloud.osconfig_v1.types.osconfig_common import FixedOrPercent +from google.cloud.osconfig_v1.types.patch_deployments import CreatePatchDeploymentRequest +from google.cloud.osconfig_v1.types.patch_deployments import DeletePatchDeploymentRequest +from google.cloud.osconfig_v1.types.patch_deployments import GetPatchDeploymentRequest +from google.cloud.osconfig_v1.types.patch_deployments import ListPatchDeploymentsRequest +from google.cloud.osconfig_v1.types.patch_deployments import ListPatchDeploymentsResponse +from google.cloud.osconfig_v1.types.patch_deployments import MonthlySchedule +from google.cloud.osconfig_v1.types.patch_deployments import OneTimeSchedule +from google.cloud.osconfig_v1.types.patch_deployments import PatchDeployment +from google.cloud.osconfig_v1.types.patch_deployments import RecurringSchedule +from google.cloud.osconfig_v1.types.patch_deployments import WeekDayOfMonth +from google.cloud.osconfig_v1.types.patch_deployments import WeeklySchedule +from google.cloud.osconfig_v1.types.patch_jobs import AptSettings +from google.cloud.osconfig_v1.types.patch_jobs import CancelPatchJobRequest +from google.cloud.osconfig_v1.types.patch_jobs import ExecStep +from google.cloud.osconfig_v1.types.patch_jobs import ExecStepConfig +from google.cloud.osconfig_v1.types.patch_jobs import ExecutePatchJobRequest +from google.cloud.osconfig_v1.types.patch_jobs import GcsObject +from google.cloud.osconfig_v1.types.patch_jobs import GetPatchJobRequest +from google.cloud.osconfig_v1.types.patch_jobs import GooSettings +from google.cloud.osconfig_v1.types.patch_jobs import Instance +from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobInstanceDetailsRequest +from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobInstanceDetailsResponse +from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobsRequest +from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobsResponse +from google.cloud.osconfig_v1.types.patch_jobs import PatchConfig +from google.cloud.osconfig_v1.types.patch_jobs import PatchInstanceFilter +from google.cloud.osconfig_v1.types.patch_jobs import PatchJob +from google.cloud.osconfig_v1.types.patch_jobs import PatchJobInstanceDetails +from google.cloud.osconfig_v1.types.patch_jobs import PatchRollout +from google.cloud.osconfig_v1.types.patch_jobs import WindowsUpdateSettings +from google.cloud.osconfig_v1.types.patch_jobs import YumSettings +from google.cloud.osconfig_v1.types.patch_jobs import ZypperSettings + +__all__ = ('OsConfigServiceClient', + 'OsConfigServiceAsyncClient', + 'Inventory', + 'FixedOrPercent', + 'CreatePatchDeploymentRequest', + 'DeletePatchDeploymentRequest', + 'GetPatchDeploymentRequest', + 'ListPatchDeploymentsRequest', + 'ListPatchDeploymentsResponse', + 'MonthlySchedule', + 'OneTimeSchedule', + 'PatchDeployment', + 'RecurringSchedule', + 'WeekDayOfMonth', + 'WeeklySchedule', + 'AptSettings', + 'CancelPatchJobRequest', + 'ExecStep', + 'ExecStepConfig', + 'ExecutePatchJobRequest', + 'GcsObject', + 'GetPatchJobRequest', + 'GooSettings', + 'Instance', + 'ListPatchJobInstanceDetailsRequest', + 'ListPatchJobInstanceDetailsResponse', + 'ListPatchJobsRequest', + 'ListPatchJobsResponse', + 'PatchConfig', + 'PatchInstanceFilter', + 'PatchJob', + 'PatchJobInstanceDetails', + 'PatchRollout', + 'WindowsUpdateSettings', + 'YumSettings', + 'ZypperSettings', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig/py.typed b/owl-bot-staging/v1/google/cloud/osconfig/py.typed new file mode 100644 index 0000000..e2df01b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py new file mode 100644 index 0000000..3adda66 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py @@ -0,0 +1,92 @@ +# -*- 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.os_config_service import OsConfigServiceClient +from .services.os_config_service import OsConfigServiceAsyncClient + +from .types.inventory import Inventory +from .types.osconfig_common import FixedOrPercent +from .types.patch_deployments import CreatePatchDeploymentRequest +from .types.patch_deployments import DeletePatchDeploymentRequest +from .types.patch_deployments import GetPatchDeploymentRequest +from .types.patch_deployments import ListPatchDeploymentsRequest +from .types.patch_deployments import ListPatchDeploymentsResponse +from .types.patch_deployments import MonthlySchedule +from .types.patch_deployments import OneTimeSchedule +from .types.patch_deployments import PatchDeployment +from .types.patch_deployments import RecurringSchedule +from .types.patch_deployments import WeekDayOfMonth +from .types.patch_deployments import WeeklySchedule +from .types.patch_jobs import AptSettings +from .types.patch_jobs import CancelPatchJobRequest +from .types.patch_jobs import ExecStep +from .types.patch_jobs import ExecStepConfig +from .types.patch_jobs import ExecutePatchJobRequest +from .types.patch_jobs import GcsObject +from .types.patch_jobs import GetPatchJobRequest +from .types.patch_jobs import GooSettings +from .types.patch_jobs import Instance +from .types.patch_jobs import ListPatchJobInstanceDetailsRequest +from .types.patch_jobs import ListPatchJobInstanceDetailsResponse +from .types.patch_jobs import ListPatchJobsRequest +from .types.patch_jobs import ListPatchJobsResponse +from .types.patch_jobs import PatchConfig +from .types.patch_jobs import PatchInstanceFilter +from .types.patch_jobs import PatchJob +from .types.patch_jobs import PatchJobInstanceDetails +from .types.patch_jobs import PatchRollout +from .types.patch_jobs import WindowsUpdateSettings +from .types.patch_jobs import YumSettings +from .types.patch_jobs import ZypperSettings + +__all__ = ( + 'OsConfigServiceAsyncClient', +'AptSettings', +'CancelPatchJobRequest', +'CreatePatchDeploymentRequest', +'DeletePatchDeploymentRequest', +'ExecStep', +'ExecStepConfig', +'ExecutePatchJobRequest', +'FixedOrPercent', +'GcsObject', +'GetPatchDeploymentRequest', +'GetPatchJobRequest', +'GooSettings', +'Instance', +'Inventory', +'ListPatchDeploymentsRequest', +'ListPatchDeploymentsResponse', +'ListPatchJobInstanceDetailsRequest', +'ListPatchJobInstanceDetailsResponse', +'ListPatchJobsRequest', +'ListPatchJobsResponse', +'MonthlySchedule', +'OneTimeSchedule', +'OsConfigServiceClient', +'PatchConfig', +'PatchDeployment', +'PatchInstanceFilter', +'PatchJob', +'PatchJobInstanceDetails', +'PatchRollout', +'RecurringSchedule', +'WeekDayOfMonth', +'WeeklySchedule', +'WindowsUpdateSettings', +'YumSettings', +'ZypperSettings', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json new file mode 100644 index 0000000..8f824ed --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json @@ -0,0 +1,113 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.osconfig_v1", + "protoPackage": "google.cloud.osconfig.v1", + "schema": "1.0", + "services": { + "OsConfigService": { + "clients": { + "grpc": { + "libraryClient": "OsConfigServiceClient", + "rpcs": { + "CancelPatchJob": { + "methods": [ + "cancel_patch_job" + ] + }, + "CreatePatchDeployment": { + "methods": [ + "create_patch_deployment" + ] + }, + "DeletePatchDeployment": { + "methods": [ + "delete_patch_deployment" + ] + }, + "ExecutePatchJob": { + "methods": [ + "execute_patch_job" + ] + }, + "GetPatchDeployment": { + "methods": [ + "get_patch_deployment" + ] + }, + "GetPatchJob": { + "methods": [ + "get_patch_job" + ] + }, + "ListPatchDeployments": { + "methods": [ + "list_patch_deployments" + ] + }, + "ListPatchJobInstanceDetails": { + "methods": [ + "list_patch_job_instance_details" + ] + }, + "ListPatchJobs": { + "methods": [ + "list_patch_jobs" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OsConfigServiceAsyncClient", + "rpcs": { + "CancelPatchJob": { + "methods": [ + "cancel_patch_job" + ] + }, + "CreatePatchDeployment": { + "methods": [ + "create_patch_deployment" + ] + }, + "DeletePatchDeployment": { + "methods": [ + "delete_patch_deployment" + ] + }, + "ExecutePatchJob": { + "methods": [ + "execute_patch_job" + ] + }, + "GetPatchDeployment": { + "methods": [ + "get_patch_deployment" + ] + }, + "GetPatchJob": { + "methods": [ + "get_patch_job" + ] + }, + "ListPatchDeployments": { + "methods": [ + "list_patch_deployments" + ] + }, + "ListPatchJobInstanceDetails": { + "methods": [ + "list_patch_job_instance_details" + ] + }, + "ListPatchJobs": { + "methods": [ + "list_patch_jobs" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed b/owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed new file mode 100644 index 0000000..e2df01b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_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/cloud/osconfig_v1/services/os_config_service/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/__init__.py new file mode 100644 index 0000000..8948b2c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_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 OsConfigServiceClient +from .async_client import OsConfigServiceAsyncClient + +__all__ = ( + 'OsConfigServiceClient', + 'OsConfigServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py new file mode 100644 index 0000000..3a919bd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py @@ -0,0 +1,896 @@ +# -*- 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.cloud.osconfig_v1.services.os_config_service import pagers +from google.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OsConfigServiceGrpcAsyncIOTransport +from .client import OsConfigServiceClient + + +class OsConfigServiceAsyncClient: + """OS Config API + The OS Config service is a server-side component that you can + use to manage package installations and patch jobs for virtual + machine instances. + """ + + _client: OsConfigServiceClient + + DEFAULT_ENDPOINT = OsConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OsConfigServiceClient.DEFAULT_MTLS_ENDPOINT + + instance_path = staticmethod(OsConfigServiceClient.instance_path) + parse_instance_path = staticmethod(OsConfigServiceClient.parse_instance_path) + patch_deployment_path = staticmethod(OsConfigServiceClient.patch_deployment_path) + parse_patch_deployment_path = staticmethod(OsConfigServiceClient.parse_patch_deployment_path) + patch_job_path = staticmethod(OsConfigServiceClient.patch_job_path) + parse_patch_job_path = staticmethod(OsConfigServiceClient.parse_patch_job_path) + common_billing_account_path = staticmethod(OsConfigServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OsConfigServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OsConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OsConfigServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OsConfigServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OsConfigServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OsConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod(OsConfigServiceClient.parse_common_project_path) + common_location_path = staticmethod(OsConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod(OsConfigServiceClient.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: + OsConfigServiceAsyncClient: The constructed client. + """ + return OsConfigServiceClient.from_service_account_info.__func__(OsConfigServiceAsyncClient, 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: + OsConfigServiceAsyncClient: The constructed client. + """ + return OsConfigServiceClient.from_service_account_file.__func__(OsConfigServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> OsConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OsConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(OsConfigServiceClient).get_transport_class, type(OsConfigServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, OsConfigServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the os config 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, ~.OsConfigServiceTransport]): 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 = OsConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def execute_patch_job(self, + request: patch_jobs.ExecutePatchJobRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_jobs.PatchJob: + r"""Patch VM instances by creating and running a patch + job. + + Args: + request (:class:`google.cloud.osconfig_v1.types.ExecutePatchJobRequest`): + The request object. A request message to initiate + patching across Compute Engine instances. + 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.cloud.osconfig_v1.types.PatchJob: + A high level representation of a patch job that is either in progress + or has completed. + + Instance details are not included in the job. To + paginate through instance details, use + ListPatchJobInstanceDetails. + + For more information about patch jobs, see [Creating + patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). + + """ + # Create or coerce a protobuf request object. + request = patch_jobs.ExecutePatchJobRequest(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.execute_patch_job, + 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, + ) + + # Done; return the response. + return response + + async def get_patch_job(self, + request: patch_jobs.GetPatchJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_jobs.PatchJob: + r"""Get the patch job. This can be used to track the + progress of an ongoing patch job or review the details + of completed jobs. + + Args: + request (:class:`google.cloud.osconfig_v1.types.GetPatchJobRequest`): + The request object. Request to get an active or + completed patch job. + name (:class:`str`): + Required. Name of the patch in the form + ``projects/*/patchJobs/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.types.PatchJob: + A high level representation of a patch job that is either in progress + or has completed. + + Instance details are not included in the job. To + paginate through instance details, use + ListPatchJobInstanceDetails. + + For more information about patch jobs, see [Creating + patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_jobs.GetPatchJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_patch_job, + 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 cancel_patch_job(self, + request: patch_jobs.CancelPatchJobRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_jobs.PatchJob: + r"""Cancel a patch job. The patch job must be active. + Canceled patch jobs cannot be restarted. + + Args: + request (:class:`google.cloud.osconfig_v1.types.CancelPatchJobRequest`): + The request object. Message for canceling a patch job. + 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.cloud.osconfig_v1.types.PatchJob: + A high level representation of a patch job that is either in progress + or has completed. + + Instance details are not included in the job. To + paginate through instance details, use + ListPatchJobInstanceDetails. + + For more information about patch jobs, see [Creating + patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). + + """ + # Create or coerce a protobuf request object. + request = patch_jobs.CancelPatchJobRequest(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.cancel_patch_job, + 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 list_patch_jobs(self, + request: patch_jobs.ListPatchJobsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPatchJobsAsyncPager: + r"""Get a list of patch jobs. + + Args: + request (:class:`google.cloud.osconfig_v1.types.ListPatchJobsRequest`): + The request object. A request message for listing patch + jobs. + parent (:class:`str`): + Required. In the form of ``projects/*`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobsAsyncPager: + A response message for listing patch + jobs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_jobs.ListPatchJobsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_patch_jobs, + 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.ListPatchJobsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_patch_job_instance_details(self, + request: patch_jobs.ListPatchJobInstanceDetailsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPatchJobInstanceDetailsAsyncPager: + r"""Get a list of instance details for a given patch job. + + Args: + request (:class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest`): + The request object. Request to list details for all + instances that are part of a patch job. + parent (:class:`str`): + Required. The parent for the instances are in the form + of ``projects/*/patchJobs/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobInstanceDetailsAsyncPager: + A response message for listing the + instances details for a patch job. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_jobs.ListPatchJobInstanceDetailsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_patch_job_instance_details, + 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.ListPatchJobInstanceDetailsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_patch_deployment(self, + request: patch_deployments.CreatePatchDeploymentRequest = None, + *, + parent: str = None, + patch_deployment: patch_deployments.PatchDeployment = None, + patch_deployment_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_deployments.PatchDeployment: + r"""Create an OS Config patch deployment. + + Args: + request (:class:`google.cloud.osconfig_v1.types.CreatePatchDeploymentRequest`): + The request object. A request message for creating a + patch deployment. + parent (:class:`str`): + Required. The project to apply this patch deployment to + in the form ``projects/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + patch_deployment (:class:`google.cloud.osconfig_v1.types.PatchDeployment`): + Required. The patch deployment to + create. + + This corresponds to the ``patch_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + patch_deployment_id (:class:`str`): + Required. A name for the patch deployment in the + project. When creating a name the following rules apply: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + + This corresponds to the ``patch_deployment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.types.PatchDeployment: + Patch deployments are configurations that individual patch jobs use to + complete a patch. These configurations include + instance filter, package repository settings, and a + schedule. For more information about creating and + managing patch deployments, see [Scheduling patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, patch_deployment, patch_deployment_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_deployments.CreatePatchDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if patch_deployment is not None: + request.patch_deployment = patch_deployment + if patch_deployment_id is not None: + request.patch_deployment_id = patch_deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_patch_deployment, + 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, + ) + + # Done; return the response. + return response + + async def get_patch_deployment(self, + request: patch_deployments.GetPatchDeploymentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_deployments.PatchDeployment: + r"""Get an OS Config patch deployment. + + Args: + request (:class:`google.cloud.osconfig_v1.types.GetPatchDeploymentRequest`): + The request object. A request message for retrieving a + patch deployment. + name (:class:`str`): + Required. The resource name of the patch deployment in + the form ``projects/*/patchDeployments/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.types.PatchDeployment: + Patch deployments are configurations that individual patch jobs use to + complete a patch. These configurations include + instance filter, package repository settings, and a + schedule. For more information about creating and + managing patch deployments, see [Scheduling patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_deployments.GetPatchDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_patch_deployment, + 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 list_patch_deployments(self, + request: patch_deployments.ListPatchDeploymentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPatchDeploymentsAsyncPager: + r"""Get a page of OS Config patch deployments. + + Args: + request (:class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest`): + The request object. A request message for listing patch + deployments. + parent (:class:`str`): + Required. The resource name of the parent in the form + ``projects/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchDeploymentsAsyncPager: + A response message for listing patch + deployments. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_deployments.ListPatchDeploymentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_patch_deployments, + 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.ListPatchDeploymentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_patch_deployment(self, + request: patch_deployments.DeletePatchDeploymentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete an OS Config patch deployment. + + Args: + request (:class:`google.cloud.osconfig_v1.types.DeletePatchDeploymentRequest`): + The request object. A request message for deleting a + patch deployment. + name (:class:`str`): + Required. The resource name of the patch deployment in + the form ``projects/*/patchDeployments/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = patch_deployments.DeletePatchDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_patch_deployment, + 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-osconfig", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "OsConfigServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py new file mode 100644 index 0000000..42c6b69 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py @@ -0,0 +1,1107 @@ +# -*- 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.cloud.osconfig_v1.services.os_config_service import pagers +from google.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OsConfigServiceGrpcTransport +from .transports.grpc_asyncio import OsConfigServiceGrpcAsyncIOTransport + + +class OsConfigServiceClientMeta(type): + """Metaclass for the OsConfigService 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[OsConfigServiceTransport]] + _transport_registry["grpc"] = OsConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OsConfigServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[OsConfigServiceTransport]: + """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 OsConfigServiceClient(metaclass=OsConfigServiceClientMeta): + """OS Config API + The OS Config service is a server-side component that you can + use to manage package installations and patch jobs for virtual + machine instances. + """ + + @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 = "osconfig.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: + OsConfigServiceClient: 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: + OsConfigServiceClient: 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) -> OsConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OsConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def instance_path(project: str,zone: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/zones/{zone}/instances/{instance}".format(project=project, zone=zone, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/zones/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def patch_deployment_path(project: str,patch_deployment: str,) -> str: + """Returns a fully-qualified patch_deployment string.""" + return "projects/{project}/patchDeployments/{patch_deployment}".format(project=project, patch_deployment=patch_deployment, ) + + @staticmethod + def parse_patch_deployment_path(path: str) -> Dict[str,str]: + """Parses a patch_deployment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/patchDeployments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def patch_job_path(project: str,patch_job: str,) -> str: + """Returns a fully-qualified patch_job string.""" + return "projects/{project}/patchJobs/{patch_job}".format(project=project, patch_job=patch_job, ) + + @staticmethod + def parse_patch_job_path(path: str) -> Dict[str,str]: + """Parses a patch_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/patchJobs/(?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, OsConfigServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the os config 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, OsConfigServiceTransport]): 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, OsConfigServiceTransport): + # transport is a OsConfigServiceTransport 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, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def execute_patch_job(self, + request: patch_jobs.ExecutePatchJobRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_jobs.PatchJob: + r"""Patch VM instances by creating and running a patch + job. + + Args: + request (google.cloud.osconfig_v1.types.ExecutePatchJobRequest): + The request object. A request message to initiate + patching across Compute Engine instances. + 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.cloud.osconfig_v1.types.PatchJob: + A high level representation of a patch job that is either in progress + or has completed. + + Instance details are not included in the job. To + paginate through instance details, use + ListPatchJobInstanceDetails. + + For more information about patch jobs, see [Creating + patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a patch_jobs.ExecutePatchJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_jobs.ExecutePatchJobRequest): + request = patch_jobs.ExecutePatchJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.execute_patch_job] + + # 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 get_patch_job(self, + request: patch_jobs.GetPatchJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_jobs.PatchJob: + r"""Get the patch job. This can be used to track the + progress of an ongoing patch job or review the details + of completed jobs. + + Args: + request (google.cloud.osconfig_v1.types.GetPatchJobRequest): + The request object. Request to get an active or + completed patch job. + name (str): + Required. Name of the patch in the form + ``projects/*/patchJobs/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.types.PatchJob: + A high level representation of a patch job that is either in progress + or has completed. + + Instance details are not included in the job. To + paginate through instance details, use + ListPatchJobInstanceDetails. + + For more information about patch jobs, see [Creating + patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_jobs.GetPatchJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_jobs.GetPatchJobRequest): + request = patch_jobs.GetPatchJobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_patch_job] + + # 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 cancel_patch_job(self, + request: patch_jobs.CancelPatchJobRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_jobs.PatchJob: + r"""Cancel a patch job. The patch job must be active. + Canceled patch jobs cannot be restarted. + + Args: + request (google.cloud.osconfig_v1.types.CancelPatchJobRequest): + The request object. Message for canceling a patch job. + 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.cloud.osconfig_v1.types.PatchJob: + A high level representation of a patch job that is either in progress + or has completed. + + Instance details are not included in the job. To + paginate through instance details, use + ListPatchJobInstanceDetails. + + For more information about patch jobs, see [Creating + patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a patch_jobs.CancelPatchJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_jobs.CancelPatchJobRequest): + request = patch_jobs.CancelPatchJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_patch_job] + + # 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 list_patch_jobs(self, + request: patch_jobs.ListPatchJobsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPatchJobsPager: + r"""Get a list of patch jobs. + + Args: + request (google.cloud.osconfig_v1.types.ListPatchJobsRequest): + The request object. A request message for listing patch + jobs. + parent (str): + Required. In the form of ``projects/*`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobsPager: + A response message for listing patch + jobs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_jobs.ListPatchJobsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_jobs.ListPatchJobsRequest): + request = patch_jobs.ListPatchJobsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_patch_jobs] + + # 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.ListPatchJobsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_patch_job_instance_details(self, + request: patch_jobs.ListPatchJobInstanceDetailsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPatchJobInstanceDetailsPager: + r"""Get a list of instance details for a given patch job. + + Args: + request (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest): + The request object. Request to list details for all + instances that are part of a patch job. + parent (str): + Required. The parent for the instances are in the form + of ``projects/*/patchJobs/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobInstanceDetailsPager: + A response message for listing the + instances details for a patch job. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_jobs.ListPatchJobInstanceDetailsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_jobs.ListPatchJobInstanceDetailsRequest): + request = patch_jobs.ListPatchJobInstanceDetailsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_patch_job_instance_details] + + # 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.ListPatchJobInstanceDetailsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_patch_deployment(self, + request: patch_deployments.CreatePatchDeploymentRequest = None, + *, + parent: str = None, + patch_deployment: patch_deployments.PatchDeployment = None, + patch_deployment_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_deployments.PatchDeployment: + r"""Create an OS Config patch deployment. + + Args: + request (google.cloud.osconfig_v1.types.CreatePatchDeploymentRequest): + The request object. A request message for creating a + patch deployment. + parent (str): + Required. The project to apply this patch deployment to + in the form ``projects/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + patch_deployment (google.cloud.osconfig_v1.types.PatchDeployment): + Required. The patch deployment to + create. + + This corresponds to the ``patch_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + patch_deployment_id (str): + Required. A name for the patch deployment in the + project. When creating a name the following rules apply: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + + This corresponds to the ``patch_deployment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.types.PatchDeployment: + Patch deployments are configurations that individual patch jobs use to + complete a patch. These configurations include + instance filter, package repository settings, and a + schedule. For more information about creating and + managing patch deployments, see [Scheduling patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, patch_deployment, patch_deployment_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_deployments.CreatePatchDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_deployments.CreatePatchDeploymentRequest): + request = patch_deployments.CreatePatchDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if patch_deployment is not None: + request.patch_deployment = patch_deployment + if patch_deployment_id is not None: + request.patch_deployment_id = patch_deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_patch_deployment] + + # 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 get_patch_deployment(self, + request: patch_deployments.GetPatchDeploymentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> patch_deployments.PatchDeployment: + r"""Get an OS Config patch deployment. + + Args: + request (google.cloud.osconfig_v1.types.GetPatchDeploymentRequest): + The request object. A request message for retrieving a + patch deployment. + name (str): + Required. The resource name of the patch deployment in + the form ``projects/*/patchDeployments/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.types.PatchDeployment: + Patch deployments are configurations that individual patch jobs use to + complete a patch. These configurations include + instance filter, package repository settings, and a + schedule. For more information about creating and + managing patch deployments, see [Scheduling patch + jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_deployments.GetPatchDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_deployments.GetPatchDeploymentRequest): + request = patch_deployments.GetPatchDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_patch_deployment] + + # 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 list_patch_deployments(self, + request: patch_deployments.ListPatchDeploymentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPatchDeploymentsPager: + r"""Get a page of OS Config patch deployments. + + Args: + request (google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest): + The request object. A request message for listing patch + deployments. + parent (str): + Required. The resource name of the parent in the form + ``projects/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchDeploymentsPager: + A response message for listing patch + deployments. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_deployments.ListPatchDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_deployments.ListPatchDeploymentsRequest): + request = patch_deployments.ListPatchDeploymentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_patch_deployments] + + # 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.ListPatchDeploymentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_patch_deployment(self, + request: patch_deployments.DeletePatchDeploymentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete an OS Config patch deployment. + + Args: + request (google.cloud.osconfig_v1.types.DeletePatchDeploymentRequest): + The request object. A request message for deleting a + patch deployment. + name (str): + Required. The resource name of the patch deployment in + the form ``projects/*/patchDeployments/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a patch_deployments.DeletePatchDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, patch_deployments.DeletePatchDeploymentRequest): + request = patch_deployments.DeletePatchDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_patch_deployment] + + # 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-osconfig", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "OsConfigServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py new file mode 100644 index 0000000..0598845 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py @@ -0,0 +1,385 @@ +# -*- 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.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs + + +class ListPatchJobsPager: + """A pager for iterating through ``list_patch_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``patch_jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPatchJobs`` requests and continue to iterate + through the ``patch_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` + 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[..., patch_jobs.ListPatchJobsResponse], + request: patch_jobs.ListPatchJobsRequest, + response: patch_jobs.ListPatchJobsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListPatchJobsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListPatchJobsResponse): + 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 = patch_jobs.ListPatchJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[patch_jobs.ListPatchJobsResponse]: + 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[patch_jobs.PatchJob]: + for page in self.pages: + yield from page.patch_jobs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPatchJobsAsyncPager: + """A pager for iterating through ``list_patch_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``patch_jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPatchJobs`` requests and continue to iterate + through the ``patch_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` + 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[patch_jobs.ListPatchJobsResponse]], + request: patch_jobs.ListPatchJobsRequest, + response: patch_jobs.ListPatchJobsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListPatchJobsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListPatchJobsResponse): + 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 = patch_jobs.ListPatchJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[patch_jobs.ListPatchJobsResponse]: + 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[patch_jobs.PatchJob]: + async def async_generator(): + async for page in self.pages: + for response in page.patch_jobs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPatchJobInstanceDetailsPager: + """A pager for iterating through ``list_patch_job_instance_details`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``patch_job_instance_details`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPatchJobInstanceDetails`` requests and continue to iterate + through the ``patch_job_instance_details`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` + 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[..., patch_jobs.ListPatchJobInstanceDetailsResponse], + request: patch_jobs.ListPatchJobInstanceDetailsRequest, + response: patch_jobs.ListPatchJobInstanceDetailsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse): + 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 = patch_jobs.ListPatchJobInstanceDetailsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[patch_jobs.ListPatchJobInstanceDetailsResponse]: + 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[patch_jobs.PatchJobInstanceDetails]: + for page in self.pages: + yield from page.patch_job_instance_details + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPatchJobInstanceDetailsAsyncPager: + """A pager for iterating through ``list_patch_job_instance_details`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``patch_job_instance_details`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPatchJobInstanceDetails`` requests and continue to iterate + through the ``patch_job_instance_details`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` + 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[patch_jobs.ListPatchJobInstanceDetailsResponse]], + request: patch_jobs.ListPatchJobInstanceDetailsRequest, + response: patch_jobs.ListPatchJobInstanceDetailsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse): + 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 = patch_jobs.ListPatchJobInstanceDetailsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[patch_jobs.ListPatchJobInstanceDetailsResponse]: + 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[patch_jobs.PatchJobInstanceDetails]: + async def async_generator(): + async for page in self.pages: + for response in page.patch_job_instance_details: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPatchDeploymentsPager: + """A pager for iterating through ``list_patch_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``patch_deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPatchDeployments`` requests and continue to iterate + through the ``patch_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` + 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[..., patch_deployments.ListPatchDeploymentsResponse], + request: patch_deployments.ListPatchDeploymentsRequest, + response: patch_deployments.ListPatchDeploymentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse): + 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 = patch_deployments.ListPatchDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[patch_deployments.ListPatchDeploymentsResponse]: + 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[patch_deployments.PatchDeployment]: + for page in self.pages: + yield from page.patch_deployments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPatchDeploymentsAsyncPager: + """A pager for iterating through ``list_patch_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``patch_deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPatchDeployments`` requests and continue to iterate + through the ``patch_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` + 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[patch_deployments.ListPatchDeploymentsResponse]], + request: patch_deployments.ListPatchDeploymentsRequest, + response: patch_deployments.ListPatchDeploymentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse): + 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 = patch_deployments.ListPatchDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[patch_deployments.ListPatchDeploymentsResponse]: + 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[patch_deployments.PatchDeployment]: + async def async_generator(): + async for page in self.pages: + for response in page.patch_deployments: + 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/cloud/osconfig_v1/services/os_config_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/__init__.py new file mode 100644 index 0000000..35e0b32 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_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 OsConfigServiceTransport +from .grpc import OsConfigServiceGrpcTransport +from .grpc_asyncio import OsConfigServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OsConfigServiceTransport]] +_transport_registry['grpc'] = OsConfigServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OsConfigServiceGrpcAsyncIOTransport + +__all__ = ( + 'OsConfigServiceTransport', + 'OsConfigServiceGrpcTransport', + 'OsConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py new file mode 100644 index 0000000..166b068 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py @@ -0,0 +1,282 @@ +# -*- 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.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-osconfig', + ).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 OsConfigServiceTransport(abc.ABC): + """Abstract transport class for OsConfigService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'osconfig.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 + + # 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.execute_patch_job: gapic_v1.method.wrap_method( + self.execute_patch_job, + default_timeout=None, + client_info=client_info, + ), + self.get_patch_job: gapic_v1.method.wrap_method( + self.get_patch_job, + default_timeout=None, + client_info=client_info, + ), + self.cancel_patch_job: gapic_v1.method.wrap_method( + self.cancel_patch_job, + default_timeout=None, + client_info=client_info, + ), + self.list_patch_jobs: gapic_v1.method.wrap_method( + self.list_patch_jobs, + default_timeout=None, + client_info=client_info, + ), + self.list_patch_job_instance_details: gapic_v1.method.wrap_method( + self.list_patch_job_instance_details, + default_timeout=None, + client_info=client_info, + ), + self.create_patch_deployment: gapic_v1.method.wrap_method( + self.create_patch_deployment, + default_timeout=None, + client_info=client_info, + ), + self.get_patch_deployment: gapic_v1.method.wrap_method( + self.get_patch_deployment, + default_timeout=None, + client_info=client_info, + ), + self.list_patch_deployments: gapic_v1.method.wrap_method( + self.list_patch_deployments, + default_timeout=None, + client_info=client_info, + ), + self.delete_patch_deployment: gapic_v1.method.wrap_method( + self.delete_patch_deployment, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def execute_patch_job(self) -> Callable[ + [patch_jobs.ExecutePatchJobRequest], + Union[ + patch_jobs.PatchJob, + Awaitable[patch_jobs.PatchJob] + ]]: + raise NotImplementedError() + + @property + def get_patch_job(self) -> Callable[ + [patch_jobs.GetPatchJobRequest], + Union[ + patch_jobs.PatchJob, + Awaitable[patch_jobs.PatchJob] + ]]: + raise NotImplementedError() + + @property + def cancel_patch_job(self) -> Callable[ + [patch_jobs.CancelPatchJobRequest], + Union[ + patch_jobs.PatchJob, + Awaitable[patch_jobs.PatchJob] + ]]: + raise NotImplementedError() + + @property + def list_patch_jobs(self) -> Callable[ + [patch_jobs.ListPatchJobsRequest], + Union[ + patch_jobs.ListPatchJobsResponse, + Awaitable[patch_jobs.ListPatchJobsResponse] + ]]: + raise NotImplementedError() + + @property + def list_patch_job_instance_details(self) -> Callable[ + [patch_jobs.ListPatchJobInstanceDetailsRequest], + Union[ + patch_jobs.ListPatchJobInstanceDetailsResponse, + Awaitable[patch_jobs.ListPatchJobInstanceDetailsResponse] + ]]: + raise NotImplementedError() + + @property + def create_patch_deployment(self) -> Callable[ + [patch_deployments.CreatePatchDeploymentRequest], + Union[ + patch_deployments.PatchDeployment, + Awaitable[patch_deployments.PatchDeployment] + ]]: + raise NotImplementedError() + + @property + def get_patch_deployment(self) -> Callable[ + [patch_deployments.GetPatchDeploymentRequest], + Union[ + patch_deployments.PatchDeployment, + Awaitable[patch_deployments.PatchDeployment] + ]]: + raise NotImplementedError() + + @property + def list_patch_deployments(self) -> Callable[ + [patch_deployments.ListPatchDeploymentsRequest], + Union[ + patch_deployments.ListPatchDeploymentsResponse, + Awaitable[patch_deployments.ListPatchDeploymentsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_patch_deployment(self) -> Callable[ + [patch_deployments.DeletePatchDeploymentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'OsConfigServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py new file mode 100644 index 0000000..dc6df23 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py @@ -0,0 +1,470 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs +from google.protobuf import empty_pb2 # type: ignore +from .base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO + + +class OsConfigServiceGrpcTransport(OsConfigServiceTransport): + """gRPC backend transport for OsConfigService. + + OS Config API + The OS Config service is a server-side component that you can + use to manage package installations and patch jobs for virtual + machine instances. + + 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 = 'osconfig.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, + always_use_jwt_access: Optional[bool] = False, + ) -> 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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=always_use_jwt_access, + ) + + 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 = 'osconfig.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 execute_patch_job(self) -> Callable[ + [patch_jobs.ExecutePatchJobRequest], + patch_jobs.PatchJob]: + r"""Return a callable for the execute patch job method over gRPC. + + Patch VM instances by creating and running a patch + job. + + Returns: + Callable[[~.ExecutePatchJobRequest], + ~.PatchJob]: + 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 'execute_patch_job' not in self._stubs: + self._stubs['execute_patch_job'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ExecutePatchJob', + request_serializer=patch_jobs.ExecutePatchJobRequest.serialize, + response_deserializer=patch_jobs.PatchJob.deserialize, + ) + return self._stubs['execute_patch_job'] + + @property + def get_patch_job(self) -> Callable[ + [patch_jobs.GetPatchJobRequest], + patch_jobs.PatchJob]: + r"""Return a callable for the get patch job method over gRPC. + + Get the patch job. This can be used to track the + progress of an ongoing patch job or review the details + of completed jobs. + + Returns: + Callable[[~.GetPatchJobRequest], + ~.PatchJob]: + 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_patch_job' not in self._stubs: + self._stubs['get_patch_job'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/GetPatchJob', + request_serializer=patch_jobs.GetPatchJobRequest.serialize, + response_deserializer=patch_jobs.PatchJob.deserialize, + ) + return self._stubs['get_patch_job'] + + @property + def cancel_patch_job(self) -> Callable[ + [patch_jobs.CancelPatchJobRequest], + patch_jobs.PatchJob]: + r"""Return a callable for the cancel patch job method over gRPC. + + Cancel a patch job. The patch job must be active. + Canceled patch jobs cannot be restarted. + + Returns: + Callable[[~.CancelPatchJobRequest], + ~.PatchJob]: + 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 'cancel_patch_job' not in self._stubs: + self._stubs['cancel_patch_job'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/CancelPatchJob', + request_serializer=patch_jobs.CancelPatchJobRequest.serialize, + response_deserializer=patch_jobs.PatchJob.deserialize, + ) + return self._stubs['cancel_patch_job'] + + @property + def list_patch_jobs(self) -> Callable[ + [patch_jobs.ListPatchJobsRequest], + patch_jobs.ListPatchJobsResponse]: + r"""Return a callable for the list patch jobs method over gRPC. + + Get a list of patch jobs. + + Returns: + Callable[[~.ListPatchJobsRequest], + ~.ListPatchJobsResponse]: + 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_patch_jobs' not in self._stubs: + self._stubs['list_patch_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobs', + request_serializer=patch_jobs.ListPatchJobsRequest.serialize, + response_deserializer=patch_jobs.ListPatchJobsResponse.deserialize, + ) + return self._stubs['list_patch_jobs'] + + @property + def list_patch_job_instance_details(self) -> Callable[ + [patch_jobs.ListPatchJobInstanceDetailsRequest], + patch_jobs.ListPatchJobInstanceDetailsResponse]: + r"""Return a callable for the list patch job instance + details method over gRPC. + + Get a list of instance details for a given patch job. + + Returns: + Callable[[~.ListPatchJobInstanceDetailsRequest], + ~.ListPatchJobInstanceDetailsResponse]: + 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_patch_job_instance_details' not in self._stubs: + self._stubs['list_patch_job_instance_details'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobInstanceDetails', + request_serializer=patch_jobs.ListPatchJobInstanceDetailsRequest.serialize, + response_deserializer=patch_jobs.ListPatchJobInstanceDetailsResponse.deserialize, + ) + return self._stubs['list_patch_job_instance_details'] + + @property + def create_patch_deployment(self) -> Callable[ + [patch_deployments.CreatePatchDeploymentRequest], + patch_deployments.PatchDeployment]: + r"""Return a callable for the create patch deployment method over gRPC. + + Create an OS Config patch deployment. + + Returns: + Callable[[~.CreatePatchDeploymentRequest], + ~.PatchDeployment]: + 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_patch_deployment' not in self._stubs: + self._stubs['create_patch_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/CreatePatchDeployment', + request_serializer=patch_deployments.CreatePatchDeploymentRequest.serialize, + response_deserializer=patch_deployments.PatchDeployment.deserialize, + ) + return self._stubs['create_patch_deployment'] + + @property + def get_patch_deployment(self) -> Callable[ + [patch_deployments.GetPatchDeploymentRequest], + patch_deployments.PatchDeployment]: + r"""Return a callable for the get patch deployment method over gRPC. + + Get an OS Config patch deployment. + + Returns: + Callable[[~.GetPatchDeploymentRequest], + ~.PatchDeployment]: + 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_patch_deployment' not in self._stubs: + self._stubs['get_patch_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/GetPatchDeployment', + request_serializer=patch_deployments.GetPatchDeploymentRequest.serialize, + response_deserializer=patch_deployments.PatchDeployment.deserialize, + ) + return self._stubs['get_patch_deployment'] + + @property + def list_patch_deployments(self) -> Callable[ + [patch_deployments.ListPatchDeploymentsRequest], + patch_deployments.ListPatchDeploymentsResponse]: + r"""Return a callable for the list patch deployments method over gRPC. + + Get a page of OS Config patch deployments. + + Returns: + Callable[[~.ListPatchDeploymentsRequest], + ~.ListPatchDeploymentsResponse]: + 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_patch_deployments' not in self._stubs: + self._stubs['list_patch_deployments'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ListPatchDeployments', + request_serializer=patch_deployments.ListPatchDeploymentsRequest.serialize, + response_deserializer=patch_deployments.ListPatchDeploymentsResponse.deserialize, + ) + return self._stubs['list_patch_deployments'] + + @property + def delete_patch_deployment(self) -> Callable[ + [patch_deployments.DeletePatchDeploymentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete patch deployment method over gRPC. + + Delete an OS Config patch deployment. + + Returns: + Callable[[~.DeletePatchDeploymentRequest], + ~.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_patch_deployment' not in self._stubs: + self._stubs['delete_patch_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/DeletePatchDeployment', + request_serializer=patch_deployments.DeletePatchDeploymentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_patch_deployment'] + + +__all__ = ( + 'OsConfigServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..e624b6b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py @@ -0,0 +1,474 @@ +# -*- 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.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs +from google.protobuf import empty_pb2 # type: ignore +from .base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OsConfigServiceGrpcTransport + + +class OsConfigServiceGrpcAsyncIOTransport(OsConfigServiceTransport): + """gRPC AsyncIO backend transport for OsConfigService. + + OS Config API + The OS Config service is a server-side component that you can + use to manage package installations and patch jobs for virtual + machine instances. + + 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 = 'osconfig.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 = 'osconfig.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, + always_use_jwt_access: Optional[bool] = False, + ) -> 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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=always_use_jwt_access, + ) + + 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 execute_patch_job(self) -> Callable[ + [patch_jobs.ExecutePatchJobRequest], + Awaitable[patch_jobs.PatchJob]]: + r"""Return a callable for the execute patch job method over gRPC. + + Patch VM instances by creating and running a patch + job. + + Returns: + Callable[[~.ExecutePatchJobRequest], + Awaitable[~.PatchJob]]: + 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 'execute_patch_job' not in self._stubs: + self._stubs['execute_patch_job'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ExecutePatchJob', + request_serializer=patch_jobs.ExecutePatchJobRequest.serialize, + response_deserializer=patch_jobs.PatchJob.deserialize, + ) + return self._stubs['execute_patch_job'] + + @property + def get_patch_job(self) -> Callable[ + [patch_jobs.GetPatchJobRequest], + Awaitable[patch_jobs.PatchJob]]: + r"""Return a callable for the get patch job method over gRPC. + + Get the patch job. This can be used to track the + progress of an ongoing patch job or review the details + of completed jobs. + + Returns: + Callable[[~.GetPatchJobRequest], + Awaitable[~.PatchJob]]: + 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_patch_job' not in self._stubs: + self._stubs['get_patch_job'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/GetPatchJob', + request_serializer=patch_jobs.GetPatchJobRequest.serialize, + response_deserializer=patch_jobs.PatchJob.deserialize, + ) + return self._stubs['get_patch_job'] + + @property + def cancel_patch_job(self) -> Callable[ + [patch_jobs.CancelPatchJobRequest], + Awaitable[patch_jobs.PatchJob]]: + r"""Return a callable for the cancel patch job method over gRPC. + + Cancel a patch job. The patch job must be active. + Canceled patch jobs cannot be restarted. + + Returns: + Callable[[~.CancelPatchJobRequest], + Awaitable[~.PatchJob]]: + 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 'cancel_patch_job' not in self._stubs: + self._stubs['cancel_patch_job'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/CancelPatchJob', + request_serializer=patch_jobs.CancelPatchJobRequest.serialize, + response_deserializer=patch_jobs.PatchJob.deserialize, + ) + return self._stubs['cancel_patch_job'] + + @property + def list_patch_jobs(self) -> Callable[ + [patch_jobs.ListPatchJobsRequest], + Awaitable[patch_jobs.ListPatchJobsResponse]]: + r"""Return a callable for the list patch jobs method over gRPC. + + Get a list of patch jobs. + + Returns: + Callable[[~.ListPatchJobsRequest], + Awaitable[~.ListPatchJobsResponse]]: + 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_patch_jobs' not in self._stubs: + self._stubs['list_patch_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobs', + request_serializer=patch_jobs.ListPatchJobsRequest.serialize, + response_deserializer=patch_jobs.ListPatchJobsResponse.deserialize, + ) + return self._stubs['list_patch_jobs'] + + @property + def list_patch_job_instance_details(self) -> Callable[ + [patch_jobs.ListPatchJobInstanceDetailsRequest], + Awaitable[patch_jobs.ListPatchJobInstanceDetailsResponse]]: + r"""Return a callable for the list patch job instance + details method over gRPC. + + Get a list of instance details for a given patch job. + + Returns: + Callable[[~.ListPatchJobInstanceDetailsRequest], + Awaitable[~.ListPatchJobInstanceDetailsResponse]]: + 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_patch_job_instance_details' not in self._stubs: + self._stubs['list_patch_job_instance_details'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobInstanceDetails', + request_serializer=patch_jobs.ListPatchJobInstanceDetailsRequest.serialize, + response_deserializer=patch_jobs.ListPatchJobInstanceDetailsResponse.deserialize, + ) + return self._stubs['list_patch_job_instance_details'] + + @property + def create_patch_deployment(self) -> Callable[ + [patch_deployments.CreatePatchDeploymentRequest], + Awaitable[patch_deployments.PatchDeployment]]: + r"""Return a callable for the create patch deployment method over gRPC. + + Create an OS Config patch deployment. + + Returns: + Callable[[~.CreatePatchDeploymentRequest], + Awaitable[~.PatchDeployment]]: + 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_patch_deployment' not in self._stubs: + self._stubs['create_patch_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/CreatePatchDeployment', + request_serializer=patch_deployments.CreatePatchDeploymentRequest.serialize, + response_deserializer=patch_deployments.PatchDeployment.deserialize, + ) + return self._stubs['create_patch_deployment'] + + @property + def get_patch_deployment(self) -> Callable[ + [patch_deployments.GetPatchDeploymentRequest], + Awaitable[patch_deployments.PatchDeployment]]: + r"""Return a callable for the get patch deployment method over gRPC. + + Get an OS Config patch deployment. + + Returns: + Callable[[~.GetPatchDeploymentRequest], + Awaitable[~.PatchDeployment]]: + 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_patch_deployment' not in self._stubs: + self._stubs['get_patch_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/GetPatchDeployment', + request_serializer=patch_deployments.GetPatchDeploymentRequest.serialize, + response_deserializer=patch_deployments.PatchDeployment.deserialize, + ) + return self._stubs['get_patch_deployment'] + + @property + def list_patch_deployments(self) -> Callable[ + [patch_deployments.ListPatchDeploymentsRequest], + Awaitable[patch_deployments.ListPatchDeploymentsResponse]]: + r"""Return a callable for the list patch deployments method over gRPC. + + Get a page of OS Config patch deployments. + + Returns: + Callable[[~.ListPatchDeploymentsRequest], + Awaitable[~.ListPatchDeploymentsResponse]]: + 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_patch_deployments' not in self._stubs: + self._stubs['list_patch_deployments'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/ListPatchDeployments', + request_serializer=patch_deployments.ListPatchDeploymentsRequest.serialize, + response_deserializer=patch_deployments.ListPatchDeploymentsResponse.deserialize, + ) + return self._stubs['list_patch_deployments'] + + @property + def delete_patch_deployment(self) -> Callable[ + [patch_deployments.DeletePatchDeploymentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete patch deployment method over gRPC. + + Delete an OS Config patch deployment. + + Returns: + Callable[[~.DeletePatchDeploymentRequest], + 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_patch_deployment' not in self._stubs: + self._stubs['delete_patch_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1.OsConfigService/DeletePatchDeployment', + request_serializer=patch_deployments.DeletePatchDeploymentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_patch_deployment'] + + +__all__ = ( + 'OsConfigServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py new file mode 100644 index 0000000..300a970 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py @@ -0,0 +1,94 @@ +# -*- 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 .inventory import ( + Inventory, +) +from .osconfig_common import ( + FixedOrPercent, +) +from .patch_deployments import ( + CreatePatchDeploymentRequest, + DeletePatchDeploymentRequest, + GetPatchDeploymentRequest, + ListPatchDeploymentsRequest, + ListPatchDeploymentsResponse, + MonthlySchedule, + OneTimeSchedule, + PatchDeployment, + RecurringSchedule, + WeekDayOfMonth, + WeeklySchedule, +) +from .patch_jobs import ( + AptSettings, + CancelPatchJobRequest, + ExecStep, + ExecStepConfig, + ExecutePatchJobRequest, + GcsObject, + GetPatchJobRequest, + GooSettings, + Instance, + ListPatchJobInstanceDetailsRequest, + ListPatchJobInstanceDetailsResponse, + ListPatchJobsRequest, + ListPatchJobsResponse, + PatchConfig, + PatchInstanceFilter, + PatchJob, + PatchJobInstanceDetails, + PatchRollout, + WindowsUpdateSettings, + YumSettings, + ZypperSettings, +) + +__all__ = ( + 'Inventory', + 'FixedOrPercent', + 'CreatePatchDeploymentRequest', + 'DeletePatchDeploymentRequest', + 'GetPatchDeploymentRequest', + 'ListPatchDeploymentsRequest', + 'ListPatchDeploymentsResponse', + 'MonthlySchedule', + 'OneTimeSchedule', + 'PatchDeployment', + 'RecurringSchedule', + 'WeekDayOfMonth', + 'WeeklySchedule', + 'AptSettings', + 'CancelPatchJobRequest', + 'ExecStep', + 'ExecStepConfig', + 'ExecutePatchJobRequest', + 'GcsObject', + 'GetPatchJobRequest', + 'GooSettings', + 'Instance', + 'ListPatchJobInstanceDetailsRequest', + 'ListPatchJobInstanceDetailsResponse', + 'ListPatchJobsRequest', + 'ListPatchJobsResponse', + 'PatchConfig', + 'PatchInstanceFilter', + 'PatchJob', + 'PatchJobInstanceDetails', + 'PatchRollout', + 'WindowsUpdateSettings', + 'YumSettings', + 'ZypperSettings', +) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py new file mode 100644 index 0000000..311a9dc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py @@ -0,0 +1,520 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1', + manifest={ + 'Inventory', + }, +) + + +class Inventory(proto.Message): + r"""The inventory details of a VM. + Attributes: + os_info (google.cloud.osconfig_v1.types.Inventory.OsInfo): + Base level operating system information for + the VM. + items (Sequence[google.cloud.osconfig_v1.types.Inventory.ItemsEntry]): + Inventory items related to the VM keyed by an + opaque unique identifier for each inventory + item. The identifier is unique to each distinct + and addressable inventory item and will change, + when there is a new package version. + """ + + class OsInfo(proto.Message): + r"""Operating system information for the VM. + Attributes: + hostname (str): + The VM hostname. + long_name (str): + The operating system long name. + For example 'Debian GNU/Linux 9' or 'Microsoft + Window Server 2019 Datacenter'. + short_name (str): + The operating system short name. + For example, 'windows' or 'debian'. + version (str): + The version of the operating system. + architecture (str): + The system architecture of the operating + system. + kernel_version (str): + The kernel version of the operating system. + kernel_release (str): + The kernel release of the operating system. + osconfig_agent_version (str): + The current version of the OS Config agent + running on the VM. + """ + + hostname = proto.Field( + proto.STRING, + number=9, + ) + long_name = proto.Field( + proto.STRING, + number=2, + ) + short_name = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + architecture = proto.Field( + proto.STRING, + number=5, + ) + kernel_version = proto.Field( + proto.STRING, + number=6, + ) + kernel_release = proto.Field( + proto.STRING, + number=7, + ) + osconfig_agent_version = proto.Field( + proto.STRING, + number=8, + ) + + class Item(proto.Message): + r"""A single piece of inventory on a VM. + Attributes: + id (str): + Identifier for this item, unique across items + for this VM. + origin_type (google.cloud.osconfig_v1.types.Inventory.Item.OriginType): + The origin of this inventory item. + create_time (google.protobuf.timestamp_pb2.Timestamp): + When this inventory item was first detected. + update_time (google.protobuf.timestamp_pb2.Timestamp): + When this inventory item was last modified. + type_ (google.cloud.osconfig_v1.types.Inventory.Item.Type): + The specific type of inventory, correlating + to its specific details. + installed_package (google.cloud.osconfig_v1.types.Inventory.SoftwarePackage): + Software package present on the VM instance. + available_package (google.cloud.osconfig_v1.types.Inventory.SoftwarePackage): + Software package available to be installed on + the VM instance. + """ + class OriginType(proto.Enum): + r"""The origin of a specific inventory item.""" + ORIGIN_TYPE_UNSPECIFIED = 0 + INVENTORY_REPORT = 1 + + class Type(proto.Enum): + r"""The different types of inventory that are tracked on a VM.""" + TYPE_UNSPECIFIED = 0 + INSTALLED_PACKAGE = 1 + AVAILABLE_PACKAGE = 2 + + id = proto.Field( + proto.STRING, + number=1, + ) + origin_type = proto.Field( + proto.ENUM, + number=2, + enum='Inventory.Item.OriginType', + ) + create_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + type_ = proto.Field( + proto.ENUM, + number=5, + enum='Inventory.Item.Type', + ) + installed_package = proto.Field( + proto.MESSAGE, + number=6, + oneof='details', + message='Inventory.SoftwarePackage', + ) + available_package = proto.Field( + proto.MESSAGE, + number=7, + oneof='details', + message='Inventory.SoftwarePackage', + ) + + class SoftwarePackage(proto.Message): + r"""Software package information of the operating system. + Attributes: + yum_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): + Yum package info. For details about the yum package manager, + see + https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-yum. + apt_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): + Details of an APT package. + For details about the apt package manager, see + https://wiki.debian.org/Apt. + zypper_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): + Details of a Zypper package. For details about the Zypper + package manager, see + https://en.opensuse.org/SDB:Zypper_manual. + googet_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): + Details of a Googet package. + For details about the googet package manager, + see https://github.com/google/googet. + zypper_patch (google.cloud.osconfig_v1.types.Inventory.ZypperPatch): + Details of a Zypper patch. For details about the Zypper + package manager, see + https://en.opensuse.org/SDB:Zypper_manual. + wua_package (google.cloud.osconfig_v1.types.Inventory.WindowsUpdatePackage): + Details of a Windows Update package. See + https://docs.microsoft.com/en-us/windows/win32/api/_wua/ for + information about Windows Update. + qfe_package (google.cloud.osconfig_v1.types.Inventory.WindowsQuickFixEngineeringPackage): + Details of a Windows Quick Fix engineering + package. See + https://docs.microsoft.com/en- + us/windows/win32/cimwin32prov/win32-quickfixengineering + for info in Windows Quick Fix Engineering. + cos_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): + Details of a COS package. + windows_application (google.cloud.osconfig_v1.types.Inventory.WindowsApplication): + Details of a Windows Application + """ + + yum_package = proto.Field( + proto.MESSAGE, + number=1, + oneof='details', + message='Inventory.VersionedPackage', + ) + apt_package = proto.Field( + proto.MESSAGE, + number=2, + oneof='details', + message='Inventory.VersionedPackage', + ) + zypper_package = proto.Field( + proto.MESSAGE, + number=3, + oneof='details', + message='Inventory.VersionedPackage', + ) + googet_package = proto.Field( + proto.MESSAGE, + number=4, + oneof='details', + message='Inventory.VersionedPackage', + ) + zypper_patch = proto.Field( + proto.MESSAGE, + number=5, + oneof='details', + message='Inventory.ZypperPatch', + ) + wua_package = proto.Field( + proto.MESSAGE, + number=6, + oneof='details', + message='Inventory.WindowsUpdatePackage', + ) + qfe_package = proto.Field( + proto.MESSAGE, + number=7, + oneof='details', + message='Inventory.WindowsQuickFixEngineeringPackage', + ) + cos_package = proto.Field( + proto.MESSAGE, + number=8, + oneof='details', + message='Inventory.VersionedPackage', + ) + windows_application = proto.Field( + proto.MESSAGE, + number=9, + oneof='details', + message='Inventory.WindowsApplication', + ) + + class VersionedPackage(proto.Message): + r"""Information related to the a standard versioned package. + This includes package info for APT, Yum, Zypper, and Googet + package managers. + + Attributes: + package_name (str): + The name of the package. + architecture (str): + The system architecture this package is + intended for. + version (str): + The version of the package. + """ + + package_name = proto.Field( + proto.STRING, + number=4, + ) + architecture = proto.Field( + proto.STRING, + number=2, + ) + version = proto.Field( + proto.STRING, + number=3, + ) + + class WindowsUpdatePackage(proto.Message): + r"""Details related to a Windows Update package. Field data and names + are taken from Windows Update API IUpdate Interface: + https://docs.microsoft.com/en-us/windows/win32/api/_wua/ Descriptive + fields like title, and description are localized based on the locale + of the VM being updated. + + Attributes: + title (str): + The localized title of the update package. + description (str): + The localized description of the update + package. + categories (Sequence[google.cloud.osconfig_v1.types.Inventory.WindowsUpdatePackage.WindowsUpdateCategory]): + The categories that are associated with this + update package. + kb_article_ids (Sequence[str]): + A collection of Microsoft Knowledge Base + article IDs that are associated with the update + package. + support_url (str): + A hyperlink to the language-specific support + information for the update. + more_info_urls (Sequence[str]): + A collection of URLs that provide more + information about the update package. + update_id (str): + Gets the identifier of an update package. + Stays the same across revisions. + revision_number (int): + The revision number of this update package. + last_deployment_change_time (google.protobuf.timestamp_pb2.Timestamp): + The last published date of the update, in + (UTC) date and time. + """ + + class WindowsUpdateCategory(proto.Message): + r"""Categories specified by the Windows Update. + Attributes: + id (str): + The identifier of the windows update + category. + name (str): + The name of the windows update category. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + name = proto.Field( + proto.STRING, + number=2, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + categories = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Inventory.WindowsUpdatePackage.WindowsUpdateCategory', + ) + kb_article_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + support_url = proto.Field( + proto.STRING, + number=11, + ) + more_info_urls = proto.RepeatedField( + proto.STRING, + number=5, + ) + update_id = proto.Field( + proto.STRING, + number=6, + ) + revision_number = proto.Field( + proto.INT32, + number=7, + ) + last_deployment_change_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + class ZypperPatch(proto.Message): + r"""Details related to a Zypper Patch. + Attributes: + patch_name (str): + The name of the patch. + category (str): + The category of the patch. + severity (str): + The severity specified for this patch + summary (str): + Any summary information provided about this + patch. + """ + + patch_name = proto.Field( + proto.STRING, + number=5, + ) + category = proto.Field( + proto.STRING, + number=2, + ) + severity = proto.Field( + proto.STRING, + number=3, + ) + summary = proto.Field( + proto.STRING, + number=4, + ) + + class WindowsQuickFixEngineeringPackage(proto.Message): + r"""Information related to a Quick Fix Engineering package. + Fields are taken from Windows QuickFixEngineering Interface and + match the source names: + https://docs.microsoft.com/en- + us/windows/win32/cimwin32prov/win32-quickfixengineering + + Attributes: + caption (str): + A short textual description of the QFE + update. + description (str): + A textual description of the QFE update. + hot_fix_id (str): + Unique identifier associated with a + particular QFE update. + install_time (google.protobuf.timestamp_pb2.Timestamp): + Date that the QFE update was installed. Mapped from + installed_on field. + """ + + caption = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + hot_fix_id = proto.Field( + proto.STRING, + number=3, + ) + install_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + class WindowsApplication(proto.Message): + r"""Contains information about a Windows application as retrieved from + the Windows Registry. For more information about these fields, see + + `Windows Installer Properties for the Uninstall + Registry `__\ {: + class="external" } + + Attributes: + display_name (str): + The name of the application or product. + display_version (str): + The version of the product or application in + string format. + publisher (str): + The name of the manufacturer for the product + or application. + install_date (google.type.date_pb2.Date): + The last time this product received service. + The value of this property is replaced each time + a patch is applied or removed from the product + or the command-line option is used to repair the + product. + help_link (str): + The internet address for technical support. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + display_version = proto.Field( + proto.STRING, + number=2, + ) + publisher = proto.Field( + proto.STRING, + number=3, + ) + install_date = proto.Field( + proto.MESSAGE, + number=4, + message=date_pb2.Date, + ) + help_link = proto.Field( + proto.STRING, + number=5, + ) + + os_info = proto.Field( + proto.MESSAGE, + number=1, + message=OsInfo, + ) + items = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=Item, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.py new file mode 100644 index 0000000..8d53f80 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.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.cloud.osconfig.v1', + manifest={ + 'FixedOrPercent', + }, +) + + +class FixedOrPercent(proto.Message): + r"""Message encapsulating a value that can be either absolute + ("fixed") or relative ("percent") to a value. + + Attributes: + fixed (int): + Specifies a fixed value. + percent (int): + Specifies the relative value defined as a + percentage, which will be multiplied by a + reference value. + """ + + fixed = proto.Field( + proto.INT32, + number=1, + oneof='mode', + ) + percent = proto.Field( + proto.INT32, + number=2, + oneof='mode', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_service.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_service.py new file mode 100644 index 0000000..9a1ec8c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_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.cloud.osconfig.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py new file mode 100644 index 0000000..73cad96 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.osconfig_v1.types import patch_jobs +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import dayofweek_pb2 # type: ignore +from google.type import timeofday_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1', + manifest={ + 'PatchDeployment', + 'OneTimeSchedule', + 'RecurringSchedule', + 'WeeklySchedule', + 'MonthlySchedule', + 'WeekDayOfMonth', + 'CreatePatchDeploymentRequest', + 'GetPatchDeploymentRequest', + 'ListPatchDeploymentsRequest', + 'ListPatchDeploymentsResponse', + 'DeletePatchDeploymentRequest', + }, +) + + +class PatchDeployment(proto.Message): + r"""Patch deployments are configurations that individual patch jobs use + to complete a patch. These configurations include instance filter, + package repository settings, and a schedule. For more information + about creating and managing patch deployments, see `Scheduling patch + jobs `__. + + Attributes: + name (str): + Unique name for the patch deployment resource in a project. + The patch deployment name is in the form: + ``projects/{project_id}/patchDeployments/{patch_deployment_id}``. + This field is ignored when you create a new patch + deployment. + description (str): + Optional. Description of the patch + deployment. Length of the description is limited + to 1024 characters. + instance_filter (google.cloud.osconfig_v1.types.PatchInstanceFilter): + Required. VM instances to patch. + patch_config (google.cloud.osconfig_v1.types.PatchConfig): + Optional. Patch configuration that is + applied. + duration (google.protobuf.duration_pb2.Duration): + Optional. Duration of the patch. After the + duration ends, the patch times out. + one_time_schedule (google.cloud.osconfig_v1.types.OneTimeSchedule): + Required. Schedule a one-time execution. + recurring_schedule (google.cloud.osconfig_v1.types.RecurringSchedule): + Required. Schedule recurring executions. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the patch deployment was created. + Timestamp is in + `RFC3339 `__ text + format. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the patch deployment was last updated. + Timestamp is in + `RFC3339 `__ text + format. + last_execute_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time a patch job was started by this + deployment. Timestamp is in + `RFC3339 `__ text + format. + rollout (google.cloud.osconfig_v1.types.PatchRollout): + Optional. Rollout strategy of the patch job. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + instance_filter = proto.Field( + proto.MESSAGE, + number=3, + message=patch_jobs.PatchInstanceFilter, + ) + patch_config = proto.Field( + proto.MESSAGE, + number=4, + message=patch_jobs.PatchConfig, + ) + duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + one_time_schedule = proto.Field( + proto.MESSAGE, + number=6, + oneof='schedule', + message='OneTimeSchedule', + ) + recurring_schedule = proto.Field( + proto.MESSAGE, + number=7, + oneof='schedule', + message='RecurringSchedule', + ) + create_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + last_execute_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + rollout = proto.Field( + proto.MESSAGE, + number=11, + message=patch_jobs.PatchRollout, + ) + + +class OneTimeSchedule(proto.Message): + r"""Sets the time for a one time patch deployment. Timestamp is in + `RFC3339 `__ text format. + + Attributes: + execute_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The desired patch job execution + time. + """ + + execute_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +class RecurringSchedule(proto.Message): + r"""Sets the time for recurring patch deployments. + Attributes: + time_zone (google.type.datetime_pb2.TimeZone): + Required. Defines the time zone that ``time_of_day`` is + relative to. The rules for daylight saving time are + determined by the chosen time zone. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time that the recurring schedule becomes + effective. Defaults to ``create_time`` of the patch + deployment. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The end time at which a recurring + patch deployment schedule is no longer active. + time_of_day (google.type.timeofday_pb2.TimeOfDay): + Required. Time of the day to run a recurring + deployment. + frequency (google.cloud.osconfig_v1.types.RecurringSchedule.Frequency): + Required. The frequency unit of this + recurring schedule. + weekly (google.cloud.osconfig_v1.types.WeeklySchedule): + Required. Schedule with weekly executions. + monthly (google.cloud.osconfig_v1.types.MonthlySchedule): + Required. Schedule with monthly executions. + last_execute_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the last patch job ran + successfully. + next_execute_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the next patch job is + scheduled to run. + """ + class Frequency(proto.Enum): + r"""Specifies the frequency of the recurring patch deployments.""" + FREQUENCY_UNSPECIFIED = 0 + WEEKLY = 1 + MONTHLY = 2 + + time_zone = proto.Field( + proto.MESSAGE, + number=1, + message=datetime_pb2.TimeZone, + ) + start_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + time_of_day = proto.Field( + proto.MESSAGE, + number=4, + message=timeofday_pb2.TimeOfDay, + ) + frequency = proto.Field( + proto.ENUM, + number=5, + enum=Frequency, + ) + weekly = proto.Field( + proto.MESSAGE, + number=6, + oneof='schedule_config', + message='WeeklySchedule', + ) + monthly = proto.Field( + proto.MESSAGE, + number=7, + oneof='schedule_config', + message='MonthlySchedule', + ) + last_execute_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + next_execute_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class WeeklySchedule(proto.Message): + r"""Represents a weekly schedule. + Attributes: + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + Required. Day of the week. + """ + + day_of_week = proto.Field( + proto.ENUM, + number=1, + enum=dayofweek_pb2.DayOfWeek, + ) + + +class MonthlySchedule(proto.Message): + r"""Represents a monthly schedule. An example of a valid monthly + schedule is "on the third Tuesday of the month" or "on the 15th + of the month". + + Attributes: + week_day_of_month (google.cloud.osconfig_v1.types.WeekDayOfMonth): + Required. Week day in a month. + month_day (int): + Required. One day of the month. 1-31 + indicates the 1st to the 31st day. -1 indicates + the last day of the month. Months without the + target day will be skipped. For example, a + schedule to run "every month on the 31st" will + not run in February, April, June, etc. + """ + + week_day_of_month = proto.Field( + proto.MESSAGE, + number=1, + oneof='day_of_month', + message='WeekDayOfMonth', + ) + month_day = proto.Field( + proto.INT32, + number=2, + oneof='day_of_month', + ) + + +class WeekDayOfMonth(proto.Message): + r"""Represents one week day in a month. An example is "the 4th + Sunday". + + Attributes: + week_ordinal (int): + Required. Week number in a month. 1-4 + indicates the 1st to 4th week of the month. -1 + indicates the last week of the month. + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + Required. A day of the week. + """ + + week_ordinal = proto.Field( + proto.INT32, + number=1, + ) + day_of_week = proto.Field( + proto.ENUM, + number=2, + enum=dayofweek_pb2.DayOfWeek, + ) + + +class CreatePatchDeploymentRequest(proto.Message): + r"""A request message for creating a patch deployment. + Attributes: + parent (str): + Required. The project to apply this patch deployment to in + the form ``projects/*``. + patch_deployment_id (str): + Required. A name for the patch deployment in the project. + When creating a name the following rules apply: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + patch_deployment (google.cloud.osconfig_v1.types.PatchDeployment): + Required. The patch deployment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + patch_deployment_id = proto.Field( + proto.STRING, + number=2, + ) + patch_deployment = proto.Field( + proto.MESSAGE, + number=3, + message='PatchDeployment', + ) + + +class GetPatchDeploymentRequest(proto.Message): + r"""A request message for retrieving a patch deployment. + Attributes: + name (str): + Required. The resource name of the patch deployment in the + form ``projects/*/patchDeployments/*``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPatchDeploymentsRequest(proto.Message): + r"""A request message for listing patch deployments. + Attributes: + parent (str): + Required. The resource name of the parent in the form + ``projects/*``. + page_size (int): + Optional. The maximum number of patch + deployments to return. Default is 100. + page_token (str): + Optional. A pagination token returned from a + previous call to ListPatchDeployments that + indicates where this listing should continue + from. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPatchDeploymentsResponse(proto.Message): + r"""A response message for listing patch deployments. + Attributes: + patch_deployments (Sequence[google.cloud.osconfig_v1.types.PatchDeployment]): + The list of patch deployments. + next_page_token (str): + A pagination token that can be used to get + the next page of patch deployments. + """ + + @property + def raw_page(self): + return self + + patch_deployments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PatchDeployment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeletePatchDeploymentRequest(proto.Message): + r"""A request message for deleting a patch deployment. + Attributes: + name (str): + Required. The resource name of the patch deployment in the + form ``projects/*/patchDeployments/*``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.py new file mode 100644 index 0000000..cf6a700 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.py @@ -0,0 +1,1080 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.osconfig_v1.types import osconfig_common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1', + manifest={ + 'ExecutePatchJobRequest', + 'GetPatchJobRequest', + 'ListPatchJobInstanceDetailsRequest', + 'ListPatchJobInstanceDetailsResponse', + 'PatchJobInstanceDetails', + 'ListPatchJobsRequest', + 'ListPatchJobsResponse', + 'PatchJob', + 'PatchConfig', + 'Instance', + 'CancelPatchJobRequest', + 'AptSettings', + 'YumSettings', + 'GooSettings', + 'ZypperSettings', + 'WindowsUpdateSettings', + 'ExecStep', + 'ExecStepConfig', + 'GcsObject', + 'PatchInstanceFilter', + 'PatchRollout', + }, +) + + +class ExecutePatchJobRequest(proto.Message): + r"""A request message to initiate patching across Compute Engine + instances. + + Attributes: + parent (str): + Required. The project in which to run this patch in the form + ``projects/*`` + description (str): + Description of the patch job. Length of the + description is limited to 1024 characters. + instance_filter (google.cloud.osconfig_v1.types.PatchInstanceFilter): + Required. Instances to patch, either + explicitly or filtered by some criteria such as + zone or labels. + patch_config (google.cloud.osconfig_v1.types.PatchConfig): + Patch configuration being applied. If + omitted, instances are patched using the default + configurations. + duration (google.protobuf.duration_pb2.Duration): + Duration of the patch job. After the duration + ends, the patch job times out. + dry_run (bool): + If this patch is a dry-run only, instances + are contacted but will do nothing. + display_name (str): + Display name for this patch job. This does + not have to be unique. + rollout (google.cloud.osconfig_v1.types.PatchRollout): + Rollout strategy of the patch job. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + instance_filter = proto.Field( + proto.MESSAGE, + number=7, + message='PatchInstanceFilter', + ) + patch_config = proto.Field( + proto.MESSAGE, + number=4, + message='PatchConfig', + ) + duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + dry_run = proto.Field( + proto.BOOL, + number=6, + ) + display_name = proto.Field( + proto.STRING, + number=8, + ) + rollout = proto.Field( + proto.MESSAGE, + number=9, + message='PatchRollout', + ) + + +class GetPatchJobRequest(proto.Message): + r"""Request to get an active or completed patch job. + Attributes: + name (str): + Required. Name of the patch in the form + ``projects/*/patchJobs/*`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPatchJobInstanceDetailsRequest(proto.Message): + r"""Request to list details for all instances that are part of a + patch job. + + Attributes: + parent (str): + Required. The parent for the instances are in the form of + ``projects/*/patchJobs/*``. + page_size (int): + The maximum number of instance details + records to return. Default is 100. + page_token (str): + A pagination token returned from a previous + call that indicates where this listing should + continue from. + filter (str): + A filter expression that filters results listed in the + response. This field supports filtering results by instance + zone, name, state, or ``failure_reason``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPatchJobInstanceDetailsResponse(proto.Message): + r"""A response message for listing the instances details for a + patch job. + + Attributes: + patch_job_instance_details (Sequence[google.cloud.osconfig_v1.types.PatchJobInstanceDetails]): + A list of instance status. + next_page_token (str): + A pagination token that can be used to get + the next page of results. + """ + + @property + def raw_page(self): + return self + + patch_job_instance_details = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PatchJobInstanceDetails', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class PatchJobInstanceDetails(proto.Message): + r"""Patch details for a VM instance. For more information about + reviewing VM instance details, see `Listing all VM instance details + for a specific patch + job `__. + + Attributes: + name (str): + The instance name in the form + ``projects/*/zones/*/instances/*`` + instance_system_id (str): + The unique identifier for the instance. This + identifier is defined by the server. + state (google.cloud.osconfig_v1.types.Instance.PatchState): + Current state of instance patch. + failure_reason (str): + If the patch fails, this field provides the + reason. + attempt_count (int): + The number of times the agent that the agent + attempts to apply the patch. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + instance_system_id = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum='Instance.PatchState', + ) + failure_reason = proto.Field( + proto.STRING, + number=4, + ) + attempt_count = proto.Field( + proto.INT64, + number=5, + ) + + +class ListPatchJobsRequest(proto.Message): + r"""A request message for listing patch jobs. + Attributes: + parent (str): + Required. In the form of ``projects/*`` + page_size (int): + The maximum number of instance status to + return. + page_token (str): + A pagination token returned from a previous + call that indicates where this listing should + continue from. + filter (str): + If provided, this field specifies the criteria that must be + met by patch jobs to be included in the response. Currently, + filtering is only available on the patch_deployment field. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPatchJobsResponse(proto.Message): + r"""A response message for listing patch jobs. + Attributes: + patch_jobs (Sequence[google.cloud.osconfig_v1.types.PatchJob]): + The list of patch jobs. + next_page_token (str): + A pagination token that can be used to get + the next page of results. + """ + + @property + def raw_page(self): + return self + + patch_jobs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PatchJob', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class PatchJob(proto.Message): + r"""A high level representation of a patch job that is either in + progress or has completed. + + Instance details are not included in the job. To paginate through + instance details, use ListPatchJobInstanceDetails. + + For more information about patch jobs, see `Creating patch + jobs `__. + + Attributes: + name (str): + Unique identifier for this patch job in the form + ``projects/*/patchJobs/*`` + display_name (str): + Display name for this patch job. This is not + a unique identifier. + description (str): + Description of the patch job. Length of the + description is limited to 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time this patch job was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Last time this patch job was updated. + state (google.cloud.osconfig_v1.types.PatchJob.State): + The current state of the PatchJob. + instance_filter (google.cloud.osconfig_v1.types.PatchInstanceFilter): + Instances to patch. + patch_config (google.cloud.osconfig_v1.types.PatchConfig): + Patch configuration being applied. + duration (google.protobuf.duration_pb2.Duration): + Duration of the patch job. After the duration + ends, the patch job times out. + instance_details_summary (google.cloud.osconfig_v1.types.PatchJob.InstanceDetailsSummary): + Summary of instance details. + dry_run (bool): + If this patch job is a dry run, the agent + reports that it has finished without running any + updates on the VM instance. + error_message (str): + If this patch job failed, this message + provides information about the failure. + percent_complete (float): + Reflects the overall progress of the patch + job in the range of 0.0 being no progress to + 100.0 being complete. + patch_deployment (str): + Output only. Name of the patch deployment + that created this patch job. + rollout (google.cloud.osconfig_v1.types.PatchRollout): + Rollout strategy being applied. + """ + class State(proto.Enum): + r"""Enumeration of the various states a patch job passes through + as it executes. + """ + STATE_UNSPECIFIED = 0 + STARTED = 1 + INSTANCE_LOOKUP = 2 + PATCHING = 3 + SUCCEEDED = 4 + COMPLETED_WITH_ERRORS = 5 + CANCELED = 6 + TIMED_OUT = 7 + + class InstanceDetailsSummary(proto.Message): + r"""A summary of the current patch state across all instances that this + patch job affects. Contains counts of instances in different states. + These states map to ``InstancePatchState``. List patch job instance + details to see the specific states of each instance. + + Attributes: + pending_instance_count (int): + Number of instances pending patch job. + inactive_instance_count (int): + Number of instances that are inactive. + notified_instance_count (int): + Number of instances notified about patch job. + started_instance_count (int): + Number of instances that have started. + downloading_patches_instance_count (int): + Number of instances that are downloading + patches. + applying_patches_instance_count (int): + Number of instances that are applying + patches. + rebooting_instance_count (int): + Number of instances rebooting. + succeeded_instance_count (int): + Number of instances that have completed + successfully. + succeeded_reboot_required_instance_count (int): + Number of instances that require reboot. + failed_instance_count (int): + Number of instances that failed. + acked_instance_count (int): + Number of instances that have acked and will + start shortly. + timed_out_instance_count (int): + Number of instances that exceeded the time + out while applying the patch. + pre_patch_step_instance_count (int): + Number of instances that are running the pre- + atch step. + post_patch_step_instance_count (int): + Number of instances that are running the + post-patch step. + no_agent_detected_instance_count (int): + Number of instances that do not appear to be + running the agent. Check to ensure that the + agent is installed, running, and able to + communicate with the service. + """ + + pending_instance_count = proto.Field( + proto.INT64, + number=1, + ) + inactive_instance_count = proto.Field( + proto.INT64, + number=2, + ) + notified_instance_count = proto.Field( + proto.INT64, + number=3, + ) + started_instance_count = proto.Field( + proto.INT64, + number=4, + ) + downloading_patches_instance_count = proto.Field( + proto.INT64, + number=5, + ) + applying_patches_instance_count = proto.Field( + proto.INT64, + number=6, + ) + rebooting_instance_count = proto.Field( + proto.INT64, + number=7, + ) + succeeded_instance_count = proto.Field( + proto.INT64, + number=8, + ) + succeeded_reboot_required_instance_count = proto.Field( + proto.INT64, + number=9, + ) + failed_instance_count = proto.Field( + proto.INT64, + number=10, + ) + acked_instance_count = proto.Field( + proto.INT64, + number=11, + ) + timed_out_instance_count = proto.Field( + proto.INT64, + number=12, + ) + pre_patch_step_instance_count = proto.Field( + proto.INT64, + number=13, + ) + post_patch_step_instance_count = proto.Field( + proto.INT64, + number=14, + ) + no_agent_detected_instance_count = proto.Field( + proto.INT64, + number=15, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=14, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + instance_filter = proto.Field( + proto.MESSAGE, + number=13, + message='PatchInstanceFilter', + ) + patch_config = proto.Field( + proto.MESSAGE, + number=7, + message='PatchConfig', + ) + duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + instance_details_summary = proto.Field( + proto.MESSAGE, + number=9, + message=InstanceDetailsSummary, + ) + dry_run = proto.Field( + proto.BOOL, + number=10, + ) + error_message = proto.Field( + proto.STRING, + number=11, + ) + percent_complete = proto.Field( + proto.DOUBLE, + number=12, + ) + patch_deployment = proto.Field( + proto.STRING, + number=15, + ) + rollout = proto.Field( + proto.MESSAGE, + number=16, + message='PatchRollout', + ) + + +class PatchConfig(proto.Message): + r"""Patch configuration specifications. Contains details on how + to apply the patch(es) to a VM instance. + + Attributes: + reboot_config (google.cloud.osconfig_v1.types.PatchConfig.RebootConfig): + Post-patch reboot settings. + apt (google.cloud.osconfig_v1.types.AptSettings): + Apt update settings. Use this setting to override the + default ``apt`` patch rules. + yum (google.cloud.osconfig_v1.types.YumSettings): + Yum update settings. Use this setting to override the + default ``yum`` patch rules. + goo (google.cloud.osconfig_v1.types.GooSettings): + Goo update settings. Use this setting to override the + default ``goo`` patch rules. + zypper (google.cloud.osconfig_v1.types.ZypperSettings): + Zypper update settings. Use this setting to override the + default ``zypper`` patch rules. + windows_update (google.cloud.osconfig_v1.types.WindowsUpdateSettings): + Windows update settings. Use this override + the default windows patch rules. + pre_step (google.cloud.osconfig_v1.types.ExecStep): + The ``ExecStep`` to run before the patch update. + post_step (google.cloud.osconfig_v1.types.ExecStep): + The ``ExecStep`` to run after the patch update. + """ + class RebootConfig(proto.Enum): + r"""Post-patch reboot settings.""" + REBOOT_CONFIG_UNSPECIFIED = 0 + DEFAULT = 1 + ALWAYS = 2 + NEVER = 3 + + reboot_config = proto.Field( + proto.ENUM, + number=1, + enum=RebootConfig, + ) + apt = proto.Field( + proto.MESSAGE, + number=3, + message='AptSettings', + ) + yum = proto.Field( + proto.MESSAGE, + number=4, + message='YumSettings', + ) + goo = proto.Field( + proto.MESSAGE, + number=5, + message='GooSettings', + ) + zypper = proto.Field( + proto.MESSAGE, + number=6, + message='ZypperSettings', + ) + windows_update = proto.Field( + proto.MESSAGE, + number=7, + message='WindowsUpdateSettings', + ) + pre_step = proto.Field( + proto.MESSAGE, + number=8, + message='ExecStep', + ) + post_step = proto.Field( + proto.MESSAGE, + number=9, + message='ExecStep', + ) + + +class Instance(proto.Message): + r"""Namespace for instance state enums. """ + class PatchState(proto.Enum): + r"""Patch state of an instance.""" + PATCH_STATE_UNSPECIFIED = 0 + PENDING = 1 + INACTIVE = 2 + NOTIFIED = 3 + STARTED = 4 + DOWNLOADING_PATCHES = 5 + APPLYING_PATCHES = 6 + REBOOTING = 7 + SUCCEEDED = 8 + SUCCEEDED_REBOOT_REQUIRED = 9 + FAILED = 10 + ACKED = 11 + TIMED_OUT = 12 + RUNNING_PRE_PATCH_STEP = 13 + RUNNING_POST_PATCH_STEP = 14 + NO_AGENT_DETECTED = 15 + + +class CancelPatchJobRequest(proto.Message): + r"""Message for canceling a patch job. + Attributes: + name (str): + Required. Name of the patch in the form + ``projects/*/patchJobs/*`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class AptSettings(proto.Message): + r"""Apt patching is completed by executing + ``apt-get update && apt-get upgrade``. Additional options can be set + to control how this is executed. + + Attributes: + type_ (google.cloud.osconfig_v1.types.AptSettings.Type): + By changing the type to DIST, the patching is performed + using ``apt-get dist-upgrade`` instead. + excludes (Sequence[str]): + List of packages to exclude from update. + These packages will be excluded + exclusive_packages (Sequence[str]): + An exclusive list of packages to be updated. + These are the only packages that will be + updated. If these packages are not installed, + they will be ignored. This field cannot be + specified with any other patch configuration + fields. + """ + class Type(proto.Enum): + r"""Apt patch type.""" + TYPE_UNSPECIFIED = 0 + DIST = 1 + UPGRADE = 2 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + excludes = proto.RepeatedField( + proto.STRING, + number=2, + ) + exclusive_packages = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class YumSettings(proto.Message): + r"""Yum patching is performed by executing ``yum update``. Additional + options can be set to control how this is executed. + + Note that not all settings are supported on all platforms. + + Attributes: + security (bool): + Adds the ``--security`` flag to ``yum update``. Not + supported on all platforms. + minimal (bool): + Will cause patch to run ``yum update-minimal`` instead. + excludes (Sequence[str]): + List of packages to exclude from update. These packages are + excluded by using the yum ``--exclude`` flag. + exclusive_packages (Sequence[str]): + An exclusive list of packages to be updated. + These are the only packages that will be + updated. If these packages are not installed, + they will be ignored. This field must not be + specified with any other patch configuration + fields. + """ + + security = proto.Field( + proto.BOOL, + number=1, + ) + minimal = proto.Field( + proto.BOOL, + number=2, + ) + excludes = proto.RepeatedField( + proto.STRING, + number=3, + ) + exclusive_packages = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class GooSettings(proto.Message): + r"""Googet patching is performed by running ``googet update``. """ + + +class ZypperSettings(proto.Message): + r"""Zypper patching is performed by running ``zypper patch``. See also + https://en.opensuse.org/SDB:Zypper_manual. + + Attributes: + with_optional (bool): + Adds the ``--with-optional`` flag to ``zypper patch``. + with_update (bool): + Adds the ``--with-update`` flag, to ``zypper patch``. + categories (Sequence[str]): + Install only patches with these categories. + Common categories include security, recommended, + and feature. + severities (Sequence[str]): + Install only patches with these severities. + Common severities include critical, important, + moderate, and low. + excludes (Sequence[str]): + List of patches to exclude from update. + exclusive_patches (Sequence[str]): + An exclusive list of patches to be updated. These are the + only patches that will be installed using 'zypper patch + patch:' command. This field must not be used + with any other patch configuration fields. + """ + + with_optional = proto.Field( + proto.BOOL, + number=1, + ) + with_update = proto.Field( + proto.BOOL, + number=2, + ) + categories = proto.RepeatedField( + proto.STRING, + number=3, + ) + severities = proto.RepeatedField( + proto.STRING, + number=4, + ) + excludes = proto.RepeatedField( + proto.STRING, + number=5, + ) + exclusive_patches = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class WindowsUpdateSettings(proto.Message): + r"""Windows patching is performed using the Windows Update Agent. + Attributes: + classifications (Sequence[google.cloud.osconfig_v1.types.WindowsUpdateSettings.Classification]): + Only apply updates of these windows update + classifications. If empty, all updates are + applied. + excludes (Sequence[str]): + List of KBs to exclude from update. + exclusive_patches (Sequence[str]): + An exclusive list of kbs to be updated. These + are the only patches that will be updated. This + field must not be used with other patch + configurations. + """ + class Classification(proto.Enum): + r"""Microsoft Windows update classifications as defined in [1] + https://support.microsoft.com/en-us/help/824684/description-of-the-standard-terminology-that-is-used-to-describe-micro + """ + CLASSIFICATION_UNSPECIFIED = 0 + CRITICAL = 1 + SECURITY = 2 + DEFINITION = 3 + DRIVER = 4 + FEATURE_PACK = 5 + SERVICE_PACK = 6 + TOOL = 7 + UPDATE_ROLLUP = 8 + UPDATE = 9 + + classifications = proto.RepeatedField( + proto.ENUM, + number=1, + enum=Classification, + ) + excludes = proto.RepeatedField( + proto.STRING, + number=2, + ) + exclusive_patches = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ExecStep(proto.Message): + r"""A step that runs an executable for a PatchJob. + Attributes: + linux_exec_step_config (google.cloud.osconfig_v1.types.ExecStepConfig): + The ExecStepConfig for all Linux VMs targeted + by the PatchJob. + windows_exec_step_config (google.cloud.osconfig_v1.types.ExecStepConfig): + The ExecStepConfig for all Windows VMs + targeted by the PatchJob. + """ + + linux_exec_step_config = proto.Field( + proto.MESSAGE, + number=1, + message='ExecStepConfig', + ) + windows_exec_step_config = proto.Field( + proto.MESSAGE, + number=2, + message='ExecStepConfig', + ) + + +class ExecStepConfig(proto.Message): + r"""Common configurations for an ExecStep. + Attributes: + local_path (str): + An absolute path to the executable on the VM. + gcs_object (google.cloud.osconfig_v1.types.GcsObject): + A Cloud Storage object containing the + executable. + allowed_success_codes (Sequence[int]): + Defaults to [0]. A list of possible return values that the + execution can return to indicate a success. + interpreter (google.cloud.osconfig_v1.types.ExecStepConfig.Interpreter): + The script interpreter to use to run the script. If no + interpreter is specified the script will be executed + directly, which will likely only succeed for scripts with + [shebang lines] + (https://en.wikipedia.org/wiki/Shebang_(Unix)). + """ + class Interpreter(proto.Enum): + r"""The interpreter used to execute the a file.""" + INTERPRETER_UNSPECIFIED = 0 + SHELL = 1 + POWERSHELL = 2 + + local_path = proto.Field( + proto.STRING, + number=1, + oneof='executable', + ) + gcs_object = proto.Field( + proto.MESSAGE, + number=2, + oneof='executable', + message='GcsObject', + ) + allowed_success_codes = proto.RepeatedField( + proto.INT32, + number=3, + ) + interpreter = proto.Field( + proto.ENUM, + number=4, + enum=Interpreter, + ) + + +class GcsObject(proto.Message): + r"""Cloud Storage object representation. + Attributes: + bucket (str): + Required. Bucket of the Cloud Storage object. + object_ (str): + Required. Name of the Cloud Storage object. + generation_number (int): + Required. Generation number of the Cloud + Storage object. This is used to ensure that the + ExecStep specified by this PatchJob does not + change. + """ + + bucket = proto.Field( + proto.STRING, + number=1, + ) + object_ = proto.Field( + proto.STRING, + number=2, + ) + generation_number = proto.Field( + proto.INT64, + number=3, + ) + + +class PatchInstanceFilter(proto.Message): + r"""A filter to target VM instances for patching. The targeted + VMs must meet all criteria specified. So if both labels and + zones are specified, the patch job targets only VMs with those + labels and in those zones. + + Attributes: + all_ (bool): + Target all VM instances in the project. If + true, no other criteria is permitted. + group_labels (Sequence[google.cloud.osconfig_v1.types.PatchInstanceFilter.GroupLabel]): + Targets VM instances matching ANY of these + GroupLabels. This allows targeting of disparate + groups of VM instances. + zones (Sequence[str]): + Targets VM instances in ANY of these zones. + Leave empty to target VM instances in any zone. + instances (Sequence[str]): + Targets any of the VM instances specified. Instances are + specified by their URI in the form + ``zones/[ZONE]/instances/[INSTANCE_NAME]``, + ``projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]``, + or + ``https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]`` + instance_name_prefixes (Sequence[str]): + Targets VMs whose name starts with one of + these prefixes. Similar to labels, this is + another way to group VMs when targeting configs, + for example prefix="prod-". + """ + + class GroupLabel(proto.Message): + r"""Targets a group of VM instances by using their `assigned + labels `__. + Labels are key-value pairs. A ``GroupLabel`` is a combination of + labels that is used to target VMs for a patch job. + + For example, a patch job can target VMs that have the following + ``GroupLabel``: ``{"env":"test", "app":"web"}``. This means that the + patch job is applied to VMs that have both the labels ``env=test`` + and ``app=web``. + + Attributes: + labels (Sequence[google.cloud.osconfig_v1.types.PatchInstanceFilter.GroupLabel.LabelsEntry]): + Compute Engine instance labels that must be + present for a VM instance to be targeted by this + filter. + """ + + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + all_ = proto.Field( + proto.BOOL, + number=1, + ) + group_labels = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=GroupLabel, + ) + zones = proto.RepeatedField( + proto.STRING, + number=3, + ) + instances = proto.RepeatedField( + proto.STRING, + number=4, + ) + instance_name_prefixes = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class PatchRollout(proto.Message): + r"""Patch rollout configuration specifications. Contains details + on the concurrency control when applying patch(es) to all + targeted VMs. + + Attributes: + mode (google.cloud.osconfig_v1.types.PatchRollout.Mode): + Mode of the patch rollout. + disruption_budget (google.cloud.osconfig_v1.types.FixedOrPercent): + The maximum number (or percentage) of VMs per zone to + disrupt at any given moment. The number of VMs calculated + from multiplying the percentage by the total number of VMs + in a zone is rounded up. + + During patching, a VM is considered disrupted from the time + the agent is notified to begin until patching has completed. + This disruption time includes the time to complete reboot + and any post-patch steps. + + A VM contributes to the disruption budget if its patching + operation fails either when applying the patches, running + pre or post patch steps, or if it fails to respond with a + success notification before timing out. VMs that are not + running or do not have an active agent do not count toward + this disruption budget. + + For zone-by-zone rollouts, if the disruption budget in a + zone is exceeded, the patch job stops, because continuing to + the next zone requires completion of the patch process in + the previous zone. + + For example, if the disruption budget has a fixed value of + ``10``, and 8 VMs fail to patch in the current zone, the + patch job continues to patch 2 VMs at a time until the zone + is completed. When that zone is completed successfully, + patching begins with 10 VMs at a time in the next zone. If + 10 VMs in the next zone fail to patch, the patch job stops. + """ + class Mode(proto.Enum): + r"""Type of the rollout.""" + MODE_UNSPECIFIED = 0 + ZONE_BY_ZONE = 1 + CONCURRENT_ZONES = 2 + + mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + disruption_budget = proto.Field( + proto.MESSAGE, + number=2, + message=osconfig_common.FixedOrPercent, + ) + + +__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..7a59b05 --- /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/cloud/osconfig_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_osconfig_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_osconfig_v1_keywords.py new file mode 100644 index 0000000..b5accfb --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_osconfig_v1_keywords.py @@ -0,0 +1,184 @@ +#! /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 osconfigCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'cancel_patch_job': ('name', ), + 'create_patch_deployment': ('parent', 'patch_deployment_id', 'patch_deployment', ), + 'delete_patch_deployment': ('name', ), + 'execute_patch_job': ('parent', 'instance_filter', 'description', 'patch_config', 'duration', 'dry_run', 'display_name', 'rollout', ), + 'get_patch_deployment': ('name', ), + 'get_patch_job': ('name', ), + 'list_patch_deployments': ('parent', 'page_size', 'page_token', ), + 'list_patch_job_instance_details': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_patch_jobs': ('parent', 'page_size', 'page_token', 'filter', ), + } + + 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=osconfigCallTransformer(), +): + """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 osconfig 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..903433f --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- 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-cloud-osconfig', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.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', + 'Programming Language :: Python :: 3.9', + '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/osconfig_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/osconfig_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/osconfig_v1/test_os_config_service.py b/owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/test_os_config_service.py new file mode 100644 index 0000000..3071b5a --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/test_os_config_service.py @@ -0,0 +1,3566 @@ +# -*- 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.cloud.osconfig_v1.services.os_config_service import OsConfigServiceAsyncClient +from google.cloud.osconfig_v1.services.os_config_service import OsConfigServiceClient +from google.cloud.osconfig_v1.services.os_config_service import pagers +from google.cloud.osconfig_v1.services.os_config_service import transports +from google.cloud.osconfig_v1.services.os_config_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.osconfig_v1.types import osconfig_common +from google.cloud.osconfig_v1.types import patch_deployments +from google.cloud.osconfig_v1.types import patch_jobs +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import dayofweek_pb2 # type: ignore +from google.type import timeofday_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 OsConfigServiceClient._get_default_mtls_endpoint(None) is None + assert OsConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OsConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OsConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OsConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OsConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + OsConfigServiceClient, + OsConfigServiceAsyncClient, +]) +def test_os_config_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 == 'osconfig.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.OsConfigServiceGrpcTransport, "grpc"), + (transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_os_config_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + OsConfigServiceClient, + OsConfigServiceAsyncClient, +]) +def test_os_config_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 == 'osconfig.googleapis.com:443' + + +def test_os_config_service_client_get_transport_class(): + transport = OsConfigServiceClient.get_transport_class() + available_transports = [ + transports.OsConfigServiceGrpcTransport, + ] + assert transport in available_transports + + transport = OsConfigServiceClient.get_transport_class("grpc") + assert transport == transports.OsConfigServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"), + (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(OsConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceClient)) +@mock.patch.object(OsConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceAsyncClient)) +def test_os_config_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(OsConfigServiceClient, '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(OsConfigServiceClient, '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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc", "true"), + (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc", "false"), + (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(OsConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceClient)) +@mock.patch.object(OsConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_os_config_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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"), + (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_os_config_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, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"), + (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_os_config_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, + always_use_jwt_access=True, + ) + + +def test_os_config_service_client_client_options_from_dict(): + with mock.patch('google.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OsConfigServiceClient( + 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, + always_use_jwt_access=True, + ) + + +def test_execute_patch_job(transport: str = 'grpc', request_type=patch_jobs.ExecutePatchJobRequest): + client = OsConfigServiceClient( + 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.execute_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.PatchJob( + name='name_value', + display_name='display_name_value', + description='description_value', + state=patch_jobs.PatchJob.State.STARTED, + dry_run=True, + error_message='error_message_value', + percent_complete=0.1705, + patch_deployment='patch_deployment_value', + ) + response = client.execute_patch_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ExecutePatchJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_jobs.PatchJob) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == patch_jobs.PatchJob.State.STARTED + assert response.dry_run is True + assert response.error_message == 'error_message_value' + assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) + assert response.patch_deployment == 'patch_deployment_value' + + +def test_execute_patch_job_from_dict(): + test_execute_patch_job(request_type=dict) + + +def test_execute_patch_job_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 = OsConfigServiceClient( + 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.execute_patch_job), + '__call__') as call: + client.execute_patch_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ExecutePatchJobRequest() + + +@pytest.mark.asyncio +async def test_execute_patch_job_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.ExecutePatchJobRequest): + client = OsConfigServiceAsyncClient( + 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.execute_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob( + name='name_value', + display_name='display_name_value', + description='description_value', + state=patch_jobs.PatchJob.State.STARTED, + dry_run=True, + error_message='error_message_value', + percent_complete=0.1705, + patch_deployment='patch_deployment_value', + )) + response = await client.execute_patch_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ExecutePatchJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_jobs.PatchJob) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == patch_jobs.PatchJob.State.STARTED + assert response.dry_run is True + assert response.error_message == 'error_message_value' + assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) + assert response.patch_deployment == 'patch_deployment_value' + + +@pytest.mark.asyncio +async def test_execute_patch_job_async_from_dict(): + await test_execute_patch_job_async(request_type=dict) + + +def test_execute_patch_job_field_headers(): + client = OsConfigServiceClient( + 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 = patch_jobs.ExecutePatchJobRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_patch_job), + '__call__') as call: + call.return_value = patch_jobs.PatchJob() + client.execute_patch_job(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_execute_patch_job_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_jobs.ExecutePatchJobRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_patch_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) + await client.execute_patch_job(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_get_patch_job(transport: str = 'grpc', request_type=patch_jobs.GetPatchJobRequest): + client = OsConfigServiceClient( + 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_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.PatchJob( + name='name_value', + display_name='display_name_value', + description='description_value', + state=patch_jobs.PatchJob.State.STARTED, + dry_run=True, + error_message='error_message_value', + percent_complete=0.1705, + patch_deployment='patch_deployment_value', + ) + response = client.get_patch_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.GetPatchJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_jobs.PatchJob) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == patch_jobs.PatchJob.State.STARTED + assert response.dry_run is True + assert response.error_message == 'error_message_value' + assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) + assert response.patch_deployment == 'patch_deployment_value' + + +def test_get_patch_job_from_dict(): + test_get_patch_job(request_type=dict) + + +def test_get_patch_job_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 = OsConfigServiceClient( + 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_patch_job), + '__call__') as call: + client.get_patch_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.GetPatchJobRequest() + + +@pytest.mark.asyncio +async def test_get_patch_job_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.GetPatchJobRequest): + client = OsConfigServiceAsyncClient( + 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_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob( + name='name_value', + display_name='display_name_value', + description='description_value', + state=patch_jobs.PatchJob.State.STARTED, + dry_run=True, + error_message='error_message_value', + percent_complete=0.1705, + patch_deployment='patch_deployment_value', + )) + response = await client.get_patch_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.GetPatchJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_jobs.PatchJob) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == patch_jobs.PatchJob.State.STARTED + assert response.dry_run is True + assert response.error_message == 'error_message_value' + assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) + assert response.patch_deployment == 'patch_deployment_value' + + +@pytest.mark.asyncio +async def test_get_patch_job_async_from_dict(): + await test_get_patch_job_async(request_type=dict) + + +def test_get_patch_job_field_headers(): + client = OsConfigServiceClient( + 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 = patch_jobs.GetPatchJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_job), + '__call__') as call: + call.return_value = patch_jobs.PatchJob() + client.get_patch_job(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_patch_job_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_jobs.GetPatchJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) + await client.get_patch_job(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_get_patch_job_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.PatchJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_patch_job( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_patch_job_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_patch_job( + patch_jobs.GetPatchJobRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_patch_job_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.PatchJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_patch_job( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_patch_job_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_patch_job( + patch_jobs.GetPatchJobRequest(), + name='name_value', + ) + + +def test_cancel_patch_job(transport: str = 'grpc', request_type=patch_jobs.CancelPatchJobRequest): + client = OsConfigServiceClient( + 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.cancel_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.PatchJob( + name='name_value', + display_name='display_name_value', + description='description_value', + state=patch_jobs.PatchJob.State.STARTED, + dry_run=True, + error_message='error_message_value', + percent_complete=0.1705, + patch_deployment='patch_deployment_value', + ) + response = client.cancel_patch_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.CancelPatchJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_jobs.PatchJob) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == patch_jobs.PatchJob.State.STARTED + assert response.dry_run is True + assert response.error_message == 'error_message_value' + assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) + assert response.patch_deployment == 'patch_deployment_value' + + +def test_cancel_patch_job_from_dict(): + test_cancel_patch_job(request_type=dict) + + +def test_cancel_patch_job_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 = OsConfigServiceClient( + 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.cancel_patch_job), + '__call__') as call: + client.cancel_patch_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.CancelPatchJobRequest() + + +@pytest.mark.asyncio +async def test_cancel_patch_job_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.CancelPatchJobRequest): + client = OsConfigServiceAsyncClient( + 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.cancel_patch_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob( + name='name_value', + display_name='display_name_value', + description='description_value', + state=patch_jobs.PatchJob.State.STARTED, + dry_run=True, + error_message='error_message_value', + percent_complete=0.1705, + patch_deployment='patch_deployment_value', + )) + response = await client.cancel_patch_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.CancelPatchJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_jobs.PatchJob) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == patch_jobs.PatchJob.State.STARTED + assert response.dry_run is True + assert response.error_message == 'error_message_value' + assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) + assert response.patch_deployment == 'patch_deployment_value' + + +@pytest.mark.asyncio +async def test_cancel_patch_job_async_from_dict(): + await test_cancel_patch_job_async(request_type=dict) + + +def test_cancel_patch_job_field_headers(): + client = OsConfigServiceClient( + 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 = patch_jobs.CancelPatchJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_patch_job), + '__call__') as call: + call.return_value = patch_jobs.PatchJob() + client.cancel_patch_job(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_cancel_patch_job_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_jobs.CancelPatchJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_patch_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) + await client.cancel_patch_job(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_list_patch_jobs(transport: str = 'grpc', request_type=patch_jobs.ListPatchJobsRequest): + client = OsConfigServiceClient( + 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_patch_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.ListPatchJobsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_patch_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ListPatchJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPatchJobsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_patch_jobs_from_dict(): + test_list_patch_jobs(request_type=dict) + + +def test_list_patch_jobs_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 = OsConfigServiceClient( + 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_patch_jobs), + '__call__') as call: + client.list_patch_jobs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ListPatchJobsRequest() + + +@pytest.mark.asyncio +async def test_list_patch_jobs_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.ListPatchJobsRequest): + client = OsConfigServiceAsyncClient( + 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_patch_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_patch_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ListPatchJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPatchJobsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_patch_jobs_async_from_dict(): + await test_list_patch_jobs_async(request_type=dict) + + +def test_list_patch_jobs_field_headers(): + client = OsConfigServiceClient( + 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 = patch_jobs.ListPatchJobsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__') as call: + call.return_value = patch_jobs.ListPatchJobsResponse() + client.list_patch_jobs(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_patch_jobs_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_jobs.ListPatchJobsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobsResponse()) + await client.list_patch_jobs(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_patch_jobs_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.ListPatchJobsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_patch_jobs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_patch_jobs_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_patch_jobs( + patch_jobs.ListPatchJobsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_patch_jobs_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.ListPatchJobsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_patch_jobs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_patch_jobs_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_patch_jobs( + patch_jobs.ListPatchJobsRequest(), + parent='parent_value', + ) + + +def test_list_patch_jobs_pager(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_patch_jobs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, patch_jobs.PatchJob) + for i in results) + +def test_list_patch_jobs_pages(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + ), + RuntimeError, + ) + pages = list(client.list_patch_jobs(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_patch_jobs_async_pager(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_patch_jobs(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, patch_jobs.PatchJob) + for i in responses) + +@pytest.mark.asyncio +async def test_list_patch_jobs_async_pages(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobsResponse( + patch_jobs=[ + patch_jobs.PatchJob(), + patch_jobs.PatchJob(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_patch_jobs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_patch_job_instance_details(transport: str = 'grpc', request_type=patch_jobs.ListPatchJobInstanceDetailsRequest): + client = OsConfigServiceClient( + 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_patch_job_instance_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_patch_job_instance_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ListPatchJobInstanceDetailsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPatchJobInstanceDetailsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_patch_job_instance_details_from_dict(): + test_list_patch_job_instance_details(request_type=dict) + + +def test_list_patch_job_instance_details_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 = OsConfigServiceClient( + 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_patch_job_instance_details), + '__call__') as call: + client.list_patch_job_instance_details() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ListPatchJobInstanceDetailsRequest() + + +@pytest.mark.asyncio +async def test_list_patch_job_instance_details_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.ListPatchJobInstanceDetailsRequest): + client = OsConfigServiceAsyncClient( + 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_patch_job_instance_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobInstanceDetailsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_patch_job_instance_details(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_jobs.ListPatchJobInstanceDetailsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPatchJobInstanceDetailsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_patch_job_instance_details_async_from_dict(): + await test_list_patch_job_instance_details_async(request_type=dict) + + +def test_list_patch_job_instance_details_field_headers(): + client = OsConfigServiceClient( + 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 = patch_jobs.ListPatchJobInstanceDetailsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__') as call: + call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse() + client.list_patch_job_instance_details(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_patch_job_instance_details_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_jobs.ListPatchJobInstanceDetailsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobInstanceDetailsResponse()) + await client.list_patch_job_instance_details(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_patch_job_instance_details_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_patch_job_instance_details( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_patch_job_instance_details_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_patch_job_instance_details( + patch_jobs.ListPatchJobInstanceDetailsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_patch_job_instance_details_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobInstanceDetailsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_patch_job_instance_details( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_patch_job_instance_details_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_patch_job_instance_details( + patch_jobs.ListPatchJobInstanceDetailsRequest(), + parent='parent_value', + ) + + +def test_list_patch_job_instance_details_pager(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_patch_job_instance_details(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, patch_jobs.PatchJobInstanceDetails) + for i in results) + +def test_list_patch_job_instance_details_pages(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + ), + RuntimeError, + ) + pages = list(client.list_patch_job_instance_details(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_patch_job_instance_details_async_pager(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_patch_job_instance_details(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, patch_jobs.PatchJobInstanceDetails) + for i in responses) + +@pytest.mark.asyncio +async def test_list_patch_job_instance_details_async_pages(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_job_instance_details), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='abc', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[], + next_page_token='def', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + ], + next_page_token='ghi', + ), + patch_jobs.ListPatchJobInstanceDetailsResponse( + patch_job_instance_details=[ + patch_jobs.PatchJobInstanceDetails(), + patch_jobs.PatchJobInstanceDetails(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_patch_job_instance_details(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_create_patch_deployment(transport: str = 'grpc', request_type=patch_deployments.CreatePatchDeploymentRequest): + client = OsConfigServiceClient( + 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_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.PatchDeployment( + name='name_value', + description='description_value', + one_time_schedule=patch_deployments.OneTimeSchedule(execute_time=timestamp_pb2.Timestamp(seconds=751)), + ) + response = client.create_patch_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.CreatePatchDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_deployments.PatchDeployment) + assert response.name == 'name_value' + assert response.description == 'description_value' + + +def test_create_patch_deployment_from_dict(): + test_create_patch_deployment(request_type=dict) + + +def test_create_patch_deployment_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 = OsConfigServiceClient( + 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_patch_deployment), + '__call__') as call: + client.create_patch_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.CreatePatchDeploymentRequest() + + +@pytest.mark.asyncio +async def test_create_patch_deployment_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.CreatePatchDeploymentRequest): + client = OsConfigServiceAsyncClient( + 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_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment( + name='name_value', + description='description_value', + )) + response = await client.create_patch_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.CreatePatchDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_deployments.PatchDeployment) + assert response.name == 'name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_patch_deployment_async_from_dict(): + await test_create_patch_deployment_async(request_type=dict) + + +def test_create_patch_deployment_field_headers(): + client = OsConfigServiceClient( + 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 = patch_deployments.CreatePatchDeploymentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_patch_deployment), + '__call__') as call: + call.return_value = patch_deployments.PatchDeployment() + client.create_patch_deployment(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_patch_deployment_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_deployments.CreatePatchDeploymentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_patch_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) + await client.create_patch_deployment(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_create_patch_deployment_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.PatchDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_patch_deployment( + parent='parent_value', + patch_deployment=patch_deployments.PatchDeployment(name='name_value'), + patch_deployment_id='patch_deployment_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].patch_deployment == patch_deployments.PatchDeployment(name='name_value') + assert args[0].patch_deployment_id == 'patch_deployment_id_value' + + +def test_create_patch_deployment_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_patch_deployment( + patch_deployments.CreatePatchDeploymentRequest(), + parent='parent_value', + patch_deployment=patch_deployments.PatchDeployment(name='name_value'), + patch_deployment_id='patch_deployment_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_patch_deployment_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.PatchDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_patch_deployment( + parent='parent_value', + patch_deployment=patch_deployments.PatchDeployment(name='name_value'), + patch_deployment_id='patch_deployment_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].patch_deployment == patch_deployments.PatchDeployment(name='name_value') + assert args[0].patch_deployment_id == 'patch_deployment_id_value' + + +@pytest.mark.asyncio +async def test_create_patch_deployment_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_patch_deployment( + patch_deployments.CreatePatchDeploymentRequest(), + parent='parent_value', + patch_deployment=patch_deployments.PatchDeployment(name='name_value'), + patch_deployment_id='patch_deployment_id_value', + ) + + +def test_get_patch_deployment(transport: str = 'grpc', request_type=patch_deployments.GetPatchDeploymentRequest): + client = OsConfigServiceClient( + 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_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.PatchDeployment( + name='name_value', + description='description_value', + one_time_schedule=patch_deployments.OneTimeSchedule(execute_time=timestamp_pb2.Timestamp(seconds=751)), + ) + response = client.get_patch_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.GetPatchDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_deployments.PatchDeployment) + assert response.name == 'name_value' + assert response.description == 'description_value' + + +def test_get_patch_deployment_from_dict(): + test_get_patch_deployment(request_type=dict) + + +def test_get_patch_deployment_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 = OsConfigServiceClient( + 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_patch_deployment), + '__call__') as call: + client.get_patch_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.GetPatchDeploymentRequest() + + +@pytest.mark.asyncio +async def test_get_patch_deployment_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.GetPatchDeploymentRequest): + client = OsConfigServiceAsyncClient( + 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_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment( + name='name_value', + description='description_value', + )) + response = await client.get_patch_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.GetPatchDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, patch_deployments.PatchDeployment) + assert response.name == 'name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_patch_deployment_async_from_dict(): + await test_get_patch_deployment_async(request_type=dict) + + +def test_get_patch_deployment_field_headers(): + client = OsConfigServiceClient( + 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 = patch_deployments.GetPatchDeploymentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_deployment), + '__call__') as call: + call.return_value = patch_deployments.PatchDeployment() + client.get_patch_deployment(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_patch_deployment_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_deployments.GetPatchDeploymentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) + await client.get_patch_deployment(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_get_patch_deployment_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.PatchDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_patch_deployment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_patch_deployment_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_patch_deployment( + patch_deployments.GetPatchDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_patch_deployment_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.PatchDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_patch_deployment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_patch_deployment_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_patch_deployment( + patch_deployments.GetPatchDeploymentRequest(), + name='name_value', + ) + + +def test_list_patch_deployments(transport: str = 'grpc', request_type=patch_deployments.ListPatchDeploymentsRequest): + client = OsConfigServiceClient( + 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_patch_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.ListPatchDeploymentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_patch_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.ListPatchDeploymentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPatchDeploymentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_patch_deployments_from_dict(): + test_list_patch_deployments(request_type=dict) + + +def test_list_patch_deployments_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 = OsConfigServiceClient( + 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_patch_deployments), + '__call__') as call: + client.list_patch_deployments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.ListPatchDeploymentsRequest() + + +@pytest.mark.asyncio +async def test_list_patch_deployments_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.ListPatchDeploymentsRequest): + client = OsConfigServiceAsyncClient( + 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_patch_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.ListPatchDeploymentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_patch_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.ListPatchDeploymentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPatchDeploymentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_patch_deployments_async_from_dict(): + await test_list_patch_deployments_async(request_type=dict) + + +def test_list_patch_deployments_field_headers(): + client = OsConfigServiceClient( + 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 = patch_deployments.ListPatchDeploymentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__') as call: + call.return_value = patch_deployments.ListPatchDeploymentsResponse() + client.list_patch_deployments(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_patch_deployments_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_deployments.ListPatchDeploymentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.ListPatchDeploymentsResponse()) + await client.list_patch_deployments(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_patch_deployments_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.ListPatchDeploymentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_patch_deployments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_patch_deployments_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_patch_deployments( + patch_deployments.ListPatchDeploymentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_patch_deployments_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = patch_deployments.ListPatchDeploymentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.ListPatchDeploymentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_patch_deployments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_patch_deployments_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_patch_deployments( + patch_deployments.ListPatchDeploymentsRequest(), + parent='parent_value', + ) + + +def test_list_patch_deployments_pager(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + next_page_token='abc', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[], + next_page_token='def', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + ], + next_page_token='ghi', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_patch_deployments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, patch_deployments.PatchDeployment) + for i in results) + +def test_list_patch_deployments_pages(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + next_page_token='abc', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[], + next_page_token='def', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + ], + next_page_token='ghi', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_patch_deployments(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_patch_deployments_async_pager(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + next_page_token='abc', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[], + next_page_token='def', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + ], + next_page_token='ghi', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_patch_deployments(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, patch_deployments.PatchDeployment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_patch_deployments_async_pages(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_patch_deployments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + next_page_token='abc', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[], + next_page_token='def', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + ], + next_page_token='ghi', + ), + patch_deployments.ListPatchDeploymentsResponse( + patch_deployments=[ + patch_deployments.PatchDeployment(), + patch_deployments.PatchDeployment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_patch_deployments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_patch_deployment(transport: str = 'grpc', request_type=patch_deployments.DeletePatchDeploymentRequest): + client = OsConfigServiceClient( + 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_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_patch_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.DeletePatchDeploymentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_patch_deployment_from_dict(): + test_delete_patch_deployment(request_type=dict) + + +def test_delete_patch_deployment_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 = OsConfigServiceClient( + 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_patch_deployment), + '__call__') as call: + client.delete_patch_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.DeletePatchDeploymentRequest() + + +@pytest.mark.asyncio +async def test_delete_patch_deployment_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.DeletePatchDeploymentRequest): + client = OsConfigServiceAsyncClient( + 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_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_patch_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == patch_deployments.DeletePatchDeploymentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_patch_deployment_async_from_dict(): + await test_delete_patch_deployment_async(request_type=dict) + + +def test_delete_patch_deployment_field_headers(): + client = OsConfigServiceClient( + 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 = patch_deployments.DeletePatchDeploymentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_patch_deployment), + '__call__') as call: + call.return_value = None + client.delete_patch_deployment(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_patch_deployment_field_headers_async(): + client = OsConfigServiceAsyncClient( + 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 = patch_deployments.DeletePatchDeploymentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_patch_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_patch_deployment(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_patch_deployment_flattened(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_patch_deployment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_patch_deployment_flattened_error(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_patch_deployment( + patch_deployments.DeletePatchDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_patch_deployment_flattened_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_patch_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_patch_deployment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_patch_deployment_flattened_error_async(): + client = OsConfigServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_patch_deployment( + patch_deployments.DeletePatchDeploymentRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OsConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OsConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OsConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OsConfigServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OsConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OsConfigServiceGrpcTransport, + transports.OsConfigServiceGrpcAsyncIOTransport, +]) +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 = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OsConfigServiceGrpcTransport, + ) + +def test_os_config_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OsConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_os_config_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OsConfigServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'execute_patch_job', + 'get_patch_job', + 'cancel_patch_job', + 'list_patch_jobs', + 'list_patch_job_instance_details', + 'create_patch_deployment', + 'get_patch_deployment', + 'list_patch_deployments', + 'delete_patch_deployment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_os_config_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.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigServiceTransport( + 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', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_os_config_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.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_os_config_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.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_os_config_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) + OsConfigServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_os_config_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) + OsConfigServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigServiceGrpcTransport, + transports.OsConfigServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_os_config_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',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigServiceGrpcTransport, + transports.OsConfigServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_os_config_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', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OsConfigServiceGrpcTransport, grpc_helpers), + (transports.OsConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_os_config_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( + "osconfig.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="osconfig.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.OsConfigServiceGrpcTransport, transports.OsConfigServiceGrpcAsyncIOTransport]) +def test_os_config_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=None, + 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_os_config_service_host_no_port(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com'), + ) + assert client.transport._host == 'osconfig.googleapis.com:443' + + +def test_os_config_service_host_with_port(): + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com:8000'), + ) + assert client.transport._host == 'osconfig.googleapis.com:8000' + +def test_os_config_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OsConfigServiceGrpcTransport( + 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_os_config_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OsConfigServiceGrpcAsyncIOTransport( + 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.OsConfigServiceGrpcTransport, transports.OsConfigServiceGrpcAsyncIOTransport]) +def test_os_config_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=None, + 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.OsConfigServiceGrpcTransport, transports.OsConfigServiceGrpcAsyncIOTransport]) +def test_os_config_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=None, + 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_instance_path(): + project = "squid" + zone = "clam" + instance = "whelk" + expected = "projects/{project}/zones/{zone}/instances/{instance}".format(project=project, zone=zone, instance=instance, ) + actual = OsConfigServiceClient.instance_path(project, zone, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "octopus", + "zone": "oyster", + "instance": "nudibranch", + } + path = OsConfigServiceClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_instance_path(path) + assert expected == actual + +def test_patch_deployment_path(): + project = "cuttlefish" + patch_deployment = "mussel" + expected = "projects/{project}/patchDeployments/{patch_deployment}".format(project=project, patch_deployment=patch_deployment, ) + actual = OsConfigServiceClient.patch_deployment_path(project, patch_deployment) + assert expected == actual + + +def test_parse_patch_deployment_path(): + expected = { + "project": "winkle", + "patch_deployment": "nautilus", + } + path = OsConfigServiceClient.patch_deployment_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_patch_deployment_path(path) + assert expected == actual + +def test_patch_job_path(): + project = "scallop" + patch_job = "abalone" + expected = "projects/{project}/patchJobs/{patch_job}".format(project=project, patch_job=patch_job, ) + actual = OsConfigServiceClient.patch_job_path(project, patch_job) + assert expected == actual + + +def test_parse_patch_job_path(): + expected = { + "project": "squid", + "patch_job": "clam", + } + path = OsConfigServiceClient.patch_job_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_patch_job_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OsConfigServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = OsConfigServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = OsConfigServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = OsConfigServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OsConfigServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = OsConfigServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = OsConfigServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = OsConfigServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = OsConfigServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = OsConfigServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigServiceClient.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.OsConfigServiceTransport, '_prep_wrapped_messages') as prep: + client = OsConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OsConfigServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OsConfigServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc new file mode 100644 index 0000000..d146ff0 --- /dev/null +++ b/owl-bot-staging/v1alpha/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/osconfig/__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/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in new file mode 100644 index 0000000..5e29933 --- /dev/null +++ b/owl-bot-staging/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/osconfig *.py +recursive-include google/cloud/osconfig_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst new file mode 100644 index 0000000..d649bbe --- /dev/null +++ b/owl-bot-staging/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Osconfig 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 Cloud Osconfig 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/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py new file mode 100644 index 0000000..9dc389a --- /dev/null +++ b/owl-bot-staging/v1alpha/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-cloud-osconfig 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-cloud-osconfig" +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 Cloud 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-cloud-osconfig-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-cloud-osconfig.tex", + u"google-cloud-osconfig Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-osconfig", + u"Google Cloud Osconfig Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-osconfig", + u"google-cloud-osconfig Documentation", + author, + "google-cloud-osconfig", + "GAPIC library for Google Cloud Osconfig 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/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst new file mode 100644 index 0000000..b4b9003 --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + osconfig_v1alpha/services + osconfig_v1alpha/types diff --git a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst new file mode 100644 index 0000000..c4cbbee --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst @@ -0,0 +1,10 @@ +OsConfigZonalService +-------------------------------------- + +.. automodule:: google.cloud.osconfig_v1alpha.services.os_config_zonal_service + :members: + :inherited-members: + +.. automodule:: google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst new file mode 100644 index 0000000..2f77a4c --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Osconfig v1alpha API +============================================== +.. toctree:: + :maxdepth: 2 + + os_config_zonal_service diff --git a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst new file mode 100644 index 0000000..84add7e --- /dev/null +++ b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Osconfig v1alpha API +=========================================== + +.. automodule:: google.cloud.osconfig_v1alpha.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py new file mode 100644 index 0000000..e241de9 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service.client import OsConfigZonalServiceClient +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service.async_client import OsConfigZonalServiceAsyncClient + +from google.cloud.osconfig_v1alpha.types.config_common import OSPolicyResourceCompliance +from google.cloud.osconfig_v1alpha.types.config_common import OSPolicyResourceConfigStep +from google.cloud.osconfig_v1alpha.types.config_common import OSPolicyComplianceState +from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import GetInstanceOSPoliciesComplianceRequest +from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import InstanceOSPoliciesCompliance +from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesRequest +from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesResponse +from google.cloud.osconfig_v1alpha.types.inventory import GetInventoryRequest +from google.cloud.osconfig_v1alpha.types.inventory import Inventory +from google.cloud.osconfig_v1alpha.types.inventory import ListInventoriesRequest +from google.cloud.osconfig_v1alpha.types.inventory import ListInventoriesResponse +from google.cloud.osconfig_v1alpha.types.inventory import InventoryView +from google.cloud.osconfig_v1alpha.types.os_policy import OSPolicy +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import CreateOSPolicyAssignmentRequest +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import DeleteOSPolicyAssignmentRequest +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import GetOSPolicyAssignmentRequest +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentRevisionsRequest +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentRevisionsResponse +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentsRequest +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentsResponse +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import OSPolicyAssignment +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import OSPolicyAssignmentOperationMetadata +from google.cloud.osconfig_v1alpha.types.os_policy_assignments import UpdateOSPolicyAssignmentRequest +from google.cloud.osconfig_v1alpha.types.osconfig_common import FixedOrPercent +from google.cloud.osconfig_v1alpha.types.vulnerability import CVSSv3 +from google.cloud.osconfig_v1alpha.types.vulnerability import GetVulnerabilityReportRequest +from google.cloud.osconfig_v1alpha.types.vulnerability import ListVulnerabilityReportsRequest +from google.cloud.osconfig_v1alpha.types.vulnerability import ListVulnerabilityReportsResponse +from google.cloud.osconfig_v1alpha.types.vulnerability import VulnerabilityReport + +__all__ = ('OsConfigZonalServiceClient', + 'OsConfigZonalServiceAsyncClient', + 'OSPolicyResourceCompliance', + 'OSPolicyResourceConfigStep', + 'OSPolicyComplianceState', + 'GetInstanceOSPoliciesComplianceRequest', + 'InstanceOSPoliciesCompliance', + 'ListInstanceOSPoliciesCompliancesRequest', + 'ListInstanceOSPoliciesCompliancesResponse', + 'GetInventoryRequest', + 'Inventory', + 'ListInventoriesRequest', + 'ListInventoriesResponse', + 'InventoryView', + 'OSPolicy', + 'CreateOSPolicyAssignmentRequest', + 'DeleteOSPolicyAssignmentRequest', + 'GetOSPolicyAssignmentRequest', + 'ListOSPolicyAssignmentRevisionsRequest', + 'ListOSPolicyAssignmentRevisionsResponse', + 'ListOSPolicyAssignmentsRequest', + 'ListOSPolicyAssignmentsResponse', + 'OSPolicyAssignment', + 'OSPolicyAssignmentOperationMetadata', + 'UpdateOSPolicyAssignmentRequest', + 'FixedOrPercent', + 'CVSSv3', + 'GetVulnerabilityReportRequest', + 'ListVulnerabilityReportsRequest', + 'ListVulnerabilityReportsResponse', + 'VulnerabilityReport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed b/owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed new file mode 100644 index 0000000..e2df01b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py new file mode 100644 index 0000000..3de3d41 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py @@ -0,0 +1,82 @@ +# -*- 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.os_config_zonal_service import OsConfigZonalServiceClient +from .services.os_config_zonal_service import OsConfigZonalServiceAsyncClient + +from .types.config_common import OSPolicyResourceCompliance +from .types.config_common import OSPolicyResourceConfigStep +from .types.config_common import OSPolicyComplianceState +from .types.instance_os_policies_compliance import GetInstanceOSPoliciesComplianceRequest +from .types.instance_os_policies_compliance import InstanceOSPoliciesCompliance +from .types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesRequest +from .types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesResponse +from .types.inventory import GetInventoryRequest +from .types.inventory import Inventory +from .types.inventory import ListInventoriesRequest +from .types.inventory import ListInventoriesResponse +from .types.inventory import InventoryView +from .types.os_policy import OSPolicy +from .types.os_policy_assignments import CreateOSPolicyAssignmentRequest +from .types.os_policy_assignments import DeleteOSPolicyAssignmentRequest +from .types.os_policy_assignments import GetOSPolicyAssignmentRequest +from .types.os_policy_assignments import ListOSPolicyAssignmentRevisionsRequest +from .types.os_policy_assignments import ListOSPolicyAssignmentRevisionsResponse +from .types.os_policy_assignments import ListOSPolicyAssignmentsRequest +from .types.os_policy_assignments import ListOSPolicyAssignmentsResponse +from .types.os_policy_assignments import OSPolicyAssignment +from .types.os_policy_assignments import OSPolicyAssignmentOperationMetadata +from .types.os_policy_assignments import UpdateOSPolicyAssignmentRequest +from .types.osconfig_common import FixedOrPercent +from .types.vulnerability import CVSSv3 +from .types.vulnerability import GetVulnerabilityReportRequest +from .types.vulnerability import ListVulnerabilityReportsRequest +from .types.vulnerability import ListVulnerabilityReportsResponse +from .types.vulnerability import VulnerabilityReport + +__all__ = ( + 'OsConfigZonalServiceAsyncClient', +'CVSSv3', +'CreateOSPolicyAssignmentRequest', +'DeleteOSPolicyAssignmentRequest', +'FixedOrPercent', +'GetInstanceOSPoliciesComplianceRequest', +'GetInventoryRequest', +'GetOSPolicyAssignmentRequest', +'GetVulnerabilityReportRequest', +'InstanceOSPoliciesCompliance', +'Inventory', +'InventoryView', +'ListInstanceOSPoliciesCompliancesRequest', +'ListInstanceOSPoliciesCompliancesResponse', +'ListInventoriesRequest', +'ListInventoriesResponse', +'ListOSPolicyAssignmentRevisionsRequest', +'ListOSPolicyAssignmentRevisionsResponse', +'ListOSPolicyAssignmentsRequest', +'ListOSPolicyAssignmentsResponse', +'ListVulnerabilityReportsRequest', +'ListVulnerabilityReportsResponse', +'OSPolicy', +'OSPolicyAssignment', +'OSPolicyAssignmentOperationMetadata', +'OSPolicyComplianceState', +'OSPolicyResourceCompliance', +'OSPolicyResourceConfigStep', +'OsConfigZonalServiceClient', +'UpdateOSPolicyAssignmentRequest', +'VulnerabilityReport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json new file mode 100644 index 0000000..7429575 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json @@ -0,0 +1,143 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.osconfig_v1alpha", + "protoPackage": "google.cloud.osconfig.v1alpha", + "schema": "1.0", + "services": { + "OsConfigZonalService": { + "clients": { + "grpc": { + "libraryClient": "OsConfigZonalServiceClient", + "rpcs": { + "CreateOSPolicyAssignment": { + "methods": [ + "create_os_policy_assignment" + ] + }, + "DeleteOSPolicyAssignment": { + "methods": [ + "delete_os_policy_assignment" + ] + }, + "GetInstanceOSPoliciesCompliance": { + "methods": [ + "get_instance_os_policies_compliance" + ] + }, + "GetInventory": { + "methods": [ + "get_inventory" + ] + }, + "GetOSPolicyAssignment": { + "methods": [ + "get_os_policy_assignment" + ] + }, + "GetVulnerabilityReport": { + "methods": [ + "get_vulnerability_report" + ] + }, + "ListInstanceOSPoliciesCompliances": { + "methods": [ + "list_instance_os_policies_compliances" + ] + }, + "ListInventories": { + "methods": [ + "list_inventories" + ] + }, + "ListOSPolicyAssignmentRevisions": { + "methods": [ + "list_os_policy_assignment_revisions" + ] + }, + "ListOSPolicyAssignments": { + "methods": [ + "list_os_policy_assignments" + ] + }, + "ListVulnerabilityReports": { + "methods": [ + "list_vulnerability_reports" + ] + }, + "UpdateOSPolicyAssignment": { + "methods": [ + "update_os_policy_assignment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OsConfigZonalServiceAsyncClient", + "rpcs": { + "CreateOSPolicyAssignment": { + "methods": [ + "create_os_policy_assignment" + ] + }, + "DeleteOSPolicyAssignment": { + "methods": [ + "delete_os_policy_assignment" + ] + }, + "GetInstanceOSPoliciesCompliance": { + "methods": [ + "get_instance_os_policies_compliance" + ] + }, + "GetInventory": { + "methods": [ + "get_inventory" + ] + }, + "GetOSPolicyAssignment": { + "methods": [ + "get_os_policy_assignment" + ] + }, + "GetVulnerabilityReport": { + "methods": [ + "get_vulnerability_report" + ] + }, + "ListInstanceOSPoliciesCompliances": { + "methods": [ + "list_instance_os_policies_compliances" + ] + }, + "ListInventories": { + "methods": [ + "list_inventories" + ] + }, + "ListOSPolicyAssignmentRevisions": { + "methods": [ + "list_os_policy_assignment_revisions" + ] + }, + "ListOSPolicyAssignments": { + "methods": [ + "list_os_policy_assignments" + ] + }, + "ListVulnerabilityReports": { + "methods": [ + "list_vulnerability_reports" + ] + }, + "UpdateOSPolicyAssignment": { + "methods": [ + "update_os_policy_assignment" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed new file mode 100644 index 0000000..e2df01b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/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/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/__init__.py new file mode 100644 index 0000000..aa429a5 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_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 OsConfigZonalServiceClient +from .async_client import OsConfigZonalServiceAsyncClient + +__all__ = ( + 'OsConfigZonalServiceClient', + 'OsConfigZonalServiceAsyncClient', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py new file mode 100644 index 0000000..0835ba2 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py @@ -0,0 +1,1372 @@ +# -*- 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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import pagers +from google.cloud.osconfig_v1alpha.types import config_common +from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import vulnerability +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport +from .client import OsConfigZonalServiceClient + + +class OsConfigZonalServiceAsyncClient: + """Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + """ + + _client: OsConfigZonalServiceClient + + DEFAULT_ENDPOINT = OsConfigZonalServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OsConfigZonalServiceClient.DEFAULT_MTLS_ENDPOINT + + instance_path = staticmethod(OsConfigZonalServiceClient.instance_path) + parse_instance_path = staticmethod(OsConfigZonalServiceClient.parse_instance_path) + instance_os_policies_compliance_path = staticmethod(OsConfigZonalServiceClient.instance_os_policies_compliance_path) + parse_instance_os_policies_compliance_path = staticmethod(OsConfigZonalServiceClient.parse_instance_os_policies_compliance_path) + inventory_path = staticmethod(OsConfigZonalServiceClient.inventory_path) + parse_inventory_path = staticmethod(OsConfigZonalServiceClient.parse_inventory_path) + os_policy_assignment_path = staticmethod(OsConfigZonalServiceClient.os_policy_assignment_path) + parse_os_policy_assignment_path = staticmethod(OsConfigZonalServiceClient.parse_os_policy_assignment_path) + vulnerability_report_path = staticmethod(OsConfigZonalServiceClient.vulnerability_report_path) + parse_vulnerability_report_path = staticmethod(OsConfigZonalServiceClient.parse_vulnerability_report_path) + common_billing_account_path = staticmethod(OsConfigZonalServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OsConfigZonalServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OsConfigZonalServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OsConfigZonalServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OsConfigZonalServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OsConfigZonalServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OsConfigZonalServiceClient.common_project_path) + parse_common_project_path = staticmethod(OsConfigZonalServiceClient.parse_common_project_path) + common_location_path = staticmethod(OsConfigZonalServiceClient.common_location_path) + parse_common_location_path = staticmethod(OsConfigZonalServiceClient.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: + OsConfigZonalServiceAsyncClient: The constructed client. + """ + return OsConfigZonalServiceClient.from_service_account_info.__func__(OsConfigZonalServiceAsyncClient, 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: + OsConfigZonalServiceAsyncClient: The constructed client. + """ + return OsConfigZonalServiceClient.from_service_account_file.__func__(OsConfigZonalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> OsConfigZonalServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OsConfigZonalServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(OsConfigZonalServiceClient).get_transport_class, type(OsConfigZonalServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, OsConfigZonalServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the os config zonal 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, ~.OsConfigZonalServiceTransport]): 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 = OsConfigZonalServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_os_policy_assignment(self, + request: os_policy_assignments.CreateOSPolicyAssignmentRequest = None, + *, + parent: str = None, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + os_policy_assignment_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.CreateOSPolicyAssignmentRequest`): + The request object. A request message to create an OS + policy assignment + parent (:class:`str`): + Required. The parent resource name in + the form: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment (:class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment`): + Required. The OS policy assignment to + be created. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment_id (:class:`str`): + Required. The logical name of the OS policy assignment + in the project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + + This corresponds to the ``os_policy_assignment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, os_policy_assignment, os_policy_assignment_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = os_policy_assignments.CreateOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if os_policy_assignment_id is not None: + request.os_policy_assignment_id = os_policy_assignment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_os_policy_assignment, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_os_policy_assignment(self, + request: os_policy_assignments.UpdateOSPolicyAssignmentRequest = None, + *, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.UpdateOSPolicyAssignmentRequest`): + The request object. A request message to update an OS + policy assignment + os_policy_assignment (:class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment`): + Required. The updated OS policy + assignment. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask that controls + which fields of the assignment should be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([os_policy_assignment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = os_policy_assignments.UpdateOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if update_mask is not None: + request.update_mask = update_mask + + # 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_os_policy_assignment, + 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(( + ("os_policy_assignment.name", request.os_policy_assignment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_os_policy_assignment(self, + request: os_policy_assignments.GetOSPolicyAssignmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> os_policy_assignments.OSPolicyAssignment: + r"""Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.GetOSPolicyAssignmentRequest`): + The request object. A request message to get an OS + policy assignment + name (:class:`str`): + Required. The resource name of OS policy assignment. + + Format: + ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.OSPolicyAssignment: + OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = os_policy_assignments.GetOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_os_policy_assignment, + 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 list_os_policy_assignments(self, + request: os_policy_assignments.ListOSPolicyAssignmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentsAsyncPager: + r"""List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest`): + The request object. A request message to list OS policy + assignments for a parent resource + parent (:class:`str`): + Required. The parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentsAsyncPager: + A response message for listing all + assignments under given parent. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_os_policy_assignments, + 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.ListOSPolicyAssignmentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_os_policy_assignment_revisions(self, + request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentRevisionsAsyncPager: + r"""List the OS policy assignment revisions for a given + OS policy assignment. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest`): + The request object. A request message to list revisions + for a OS policy assignment + name (:class:`str`): + Required. The name of the OS policy + assignment to list revisions for. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentRevisionsAsyncPager: + A response message for listing all + revisions for a OS policy assignment. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_os_policy_assignment_revisions, + 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListOSPolicyAssignmentRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_os_policy_assignment(self, + request: os_policy_assignments.DeleteOSPolicyAssignmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.DeleteOSPolicyAssignmentRequest`): + The request object. A request message for deleting a OS + policy assignment. + name (:class:`str`): + Required. The name of the OS policy + assignment to be deleted + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = os_policy_assignments.DeleteOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_os_policy_assignment, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_instance_os_policies_compliance(self, + request: instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instance_os_policies_compliance.InstanceOSPoliciesCompliance: + r"""Get OS policies compliance data for the specified + Compute Engine VM instance. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.GetInstanceOSPoliciesComplianceRequest`): + The request object. A request message for getting OS + policies compliance data for the given Compute Engine VM + instance. + name (:class:`str`): + Required. API resource name for instance OS policies + compliance resource. + + Format: + ``projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}`` + + For ``{project}``, either Compute Engine project-number + or project-id can be provided. For ``{instance}``, + either Compute Engine VM instance-id or instance-name + can be provided. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance: + This API resource represents the OS policies compliance data for a Compute + Engine virtual machine (VM) instance at a given point + in time. + + A Compute Engine VM can have multiple OS policy + assignments, and each assignment can have multiple OS + policies. As a result, multiple OS policies could be + applied to a single VM. + + You can use this API resource to determine both the + compliance state of your VM as well as the compliance + state of an individual OS policy. + + For more information, see [View + compliance](\ https://cloud.google.com/compute/docs/os-configuration-management/view-compliance). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_instance_os_policies_compliance, + 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 list_instance_os_policies_compliances(self, + request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstanceOSPoliciesCompliancesAsyncPager: + r"""List OS policies compliance data for all Compute + Engine VM instances in the specified zone. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest`): + The request object. A request message for listing OS + policies compliance data for all Compute Engine VMs in + the given location. + parent (:class:`str`): + Required. The parent resource name. + + Format: ``projects/{project}/locations/{location}`` + + For ``{project}``, either Compute Engine project-number + or project-id can be provided. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInstanceOSPoliciesCompliancesAsyncPager: + A response message for listing OS + policies compliance data for all Compute + Engine VMs in the given location. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_instance_os_policies_compliances, + 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.ListInstanceOSPoliciesCompliancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_inventory(self, + request: inventory.GetInventoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> inventory.Inventory: + r"""Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.GetInventoryRequest`): + The request object. A request message for getting + inventory data for the specified VM. + name (:class:`str`): + Required. API resource name for inventory resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/inventory`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.Inventory: + This API resource represents the available inventory data for a + Compute Engine virtual machine (VM) instance at a + given point in time. + + You can use this API resource to determine the + inventory data of your VM. + + For more information, see [Information provided by OS + inventory + management](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = inventory.GetInventoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_inventory, + 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 list_inventories(self, + request: inventory.ListInventoriesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInventoriesAsyncPager: + r"""List inventory data for all VM instances in the + specified zone. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.ListInventoriesRequest`): + The request object. A request message for listing + inventory data for all VMs in the specified location. + parent (:class:`str`): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, only + hyphen or dash character is supported to list + inventories across VMs. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInventoriesAsyncPager: + A response message for listing + inventory data for all VMs in a + specified location. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = inventory.ListInventoriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_inventories, + 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.ListInventoriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_vulnerability_report(self, + request: vulnerability.GetVulnerabilityReportRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vulnerability.VulnerabilityReport: + r"""Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.GetVulnerabilityReportRequest`): + The request object. A request message for getting the + vulnerability report for the specified VM. + name (:class:`str`): + Required. API resource name for vulnerability resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.VulnerabilityReport: + This API resource represents the vulnerability report for a specified + Compute Engine virtual machine (VM) instance at a + given point in time. + + For more information, see [Vulnerability + reports](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#vulnerability-reports). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = vulnerability.GetVulnerabilityReportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_vulnerability_report, + 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 list_vulnerability_reports(self, + request: vulnerability.ListVulnerabilityReportsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVulnerabilityReportsAsyncPager: + r"""List vulnerability reports for all VM instances in + the specified zone. + + Args: + request (:class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest`): + The request object. A request message for listing + vulnerability reports for all VM instances in the + specified location. + parent (:class:`str`): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, only + ``-`` character is supported to list vulnerability + reports across VMs. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListVulnerabilityReportsAsyncPager: + A response message for listing + vulnerability reports for all VM + instances in the specified location. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = vulnerability.ListVulnerabilityReportsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_vulnerability_reports, + 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.ListVulnerabilityReportsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-osconfig", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "OsConfigZonalServiceAsyncClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py new file mode 100644 index 0000000..e538314 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py @@ -0,0 +1,1599 @@ +# -*- 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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import pagers +from google.cloud.osconfig_v1alpha.types import config_common +from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import vulnerability +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OsConfigZonalServiceGrpcTransport +from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport + + +class OsConfigZonalServiceClientMeta(type): + """Metaclass for the OsConfigZonalService 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[OsConfigZonalServiceTransport]] + _transport_registry["grpc"] = OsConfigZonalServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OsConfigZonalServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[OsConfigZonalServiceTransport]: + """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 OsConfigZonalServiceClient(metaclass=OsConfigZonalServiceClientMeta): + """Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + """ + + @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 = "osconfig.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: + OsConfigZonalServiceClient: 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: + OsConfigZonalServiceClient: 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) -> OsConfigZonalServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OsConfigZonalServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def instance_path(project: str,location: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def instance_os_policies_compliance_path(project: str,location: str,instance: str,) -> str: + """Returns a fully-qualified instance_os_policies_compliance string.""" + return "projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}".format(project=project, location=location, instance=instance, ) + + @staticmethod + def parse_instance_os_policies_compliance_path(path: str) -> Dict[str,str]: + """Parses a instance_os_policies_compliance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instanceOSPoliciesCompliances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def inventory_path(project: str,location: str,instance: str,) -> str: + """Returns a fully-qualified inventory string.""" + return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) + + @staticmethod + def parse_inventory_path(path: str) -> Dict[str,str]: + """Parses a inventory path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) + return m.groupdict() if m else {} + + @staticmethod + def os_policy_assignment_path(project: str,location: str,os_policy_assignment: str,) -> str: + """Returns a fully-qualified os_policy_assignment string.""" + return "projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}".format(project=project, location=location, os_policy_assignment=os_policy_assignment, ) + + @staticmethod + def parse_os_policy_assignment_path(path: str) -> Dict[str,str]: + """Parses a os_policy_assignment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/osPolicyAssignments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def vulnerability_report_path(project: str,location: str,instance: str,) -> str: + """Returns a fully-qualified vulnerability_report string.""" + return "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format(project=project, location=location, instance=instance, ) + + @staticmethod + def parse_vulnerability_report_path(path: str) -> Dict[str,str]: + """Parses a vulnerability_report path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/vulnerabilityReport$", 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, OsConfigZonalServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the os config zonal 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, OsConfigZonalServiceTransport]): 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, OsConfigZonalServiceTransport): + # transport is a OsConfigZonalServiceTransport 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, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_os_policy_assignment(self, + request: os_policy_assignments.CreateOSPolicyAssignmentRequest = None, + *, + parent: str = None, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + os_policy_assignment_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (google.cloud.osconfig_v1alpha.types.CreateOSPolicyAssignmentRequest): + The request object. A request message to create an OS + policy assignment + parent (str): + Required. The parent resource name in + the form: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): + Required. The OS policy assignment to + be created. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment_id (str): + Required. The logical name of the OS policy assignment + in the project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + + This corresponds to the ``os_policy_assignment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, os_policy_assignment, os_policy_assignment_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a os_policy_assignments.CreateOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.CreateOSPolicyAssignmentRequest): + request = os_policy_assignments.CreateOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if os_policy_assignment_id is not None: + request.os_policy_assignment_id = os_policy_assignment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_os_policy_assignment] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + def update_os_policy_assignment(self, + request: os_policy_assignments.UpdateOSPolicyAssignmentRequest = None, + *, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (google.cloud.osconfig_v1alpha.types.UpdateOSPolicyAssignmentRequest): + The request object. A request message to update an OS + policy assignment + os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): + Required. The updated OS policy + assignment. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that controls + which fields of the assignment should be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([os_policy_assignment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a os_policy_assignments.UpdateOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.UpdateOSPolicyAssignmentRequest): + request = os_policy_assignments.UpdateOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_os_policy_assignment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("os_policy_assignment.name", request.os_policy_assignment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + def get_os_policy_assignment(self, + request: os_policy_assignments.GetOSPolicyAssignmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> os_policy_assignments.OSPolicyAssignment: + r"""Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Args: + request (google.cloud.osconfig_v1alpha.types.GetOSPolicyAssignmentRequest): + The request object. A request message to get an OS + policy assignment + name (str): + Required. The resource name of OS policy assignment. + + Format: + ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.OSPolicyAssignment: + OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a os_policy_assignments.GetOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.GetOSPolicyAssignmentRequest): + request = os_policy_assignments.GetOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_os_policy_assignment] + + # 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 list_os_policy_assignments(self, + request: os_policy_assignments.ListOSPolicyAssignmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentsPager: + r"""List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Args: + request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest): + The request object. A request message to list OS policy + assignments for a parent resource + parent (str): + Required. The parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentsPager: + A response message for listing all + assignments under given parent. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a os_policy_assignments.ListOSPolicyAssignmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.ListOSPolicyAssignmentsRequest): + request = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_os_policy_assignments] + + # 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.ListOSPolicyAssignmentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_os_policy_assignment_revisions(self, + request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentRevisionsPager: + r"""List the OS policy assignment revisions for a given + OS policy assignment. + + Args: + request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest): + The request object. A request message to list revisions + for a OS policy assignment + name (str): + Required. The name of the OS policy + assignment to list revisions for. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentRevisionsPager: + A response message for listing all + revisions for a OS policy assignment. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest): + request = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_os_policy_assignment_revisions] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListOSPolicyAssignmentRevisionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_os_policy_assignment(self, + request: os_policy_assignments.DeleteOSPolicyAssignmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (google.cloud.osconfig_v1alpha.types.DeleteOSPolicyAssignmentRequest): + The request object. A request message for deleting a OS + policy assignment. + name (str): + Required. The name of the OS policy + assignment to be deleted + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a os_policy_assignments.DeleteOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.DeleteOSPolicyAssignmentRequest): + request = os_policy_assignments.DeleteOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_os_policy_assignment] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + def get_instance_os_policies_compliance(self, + request: instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instance_os_policies_compliance.InstanceOSPoliciesCompliance: + r"""Get OS policies compliance data for the specified + Compute Engine VM instance. + + Args: + request (google.cloud.osconfig_v1alpha.types.GetInstanceOSPoliciesComplianceRequest): + The request object. A request message for getting OS + policies compliance data for the given Compute Engine VM + instance. + name (str): + Required. API resource name for instance OS policies + compliance resource. + + Format: + ``projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}`` + + For ``{project}``, either Compute Engine project-number + or project-id can be provided. For ``{instance}``, + either Compute Engine VM instance-id or instance-name + can be provided. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance: + This API resource represents the OS policies compliance data for a Compute + Engine virtual machine (VM) instance at a given point + in time. + + A Compute Engine VM can have multiple OS policy + assignments, and each assignment can have multiple OS + policies. As a result, multiple OS policies could be + applied to a single VM. + + You can use this API resource to determine both the + compliance state of your VM as well as the compliance + state of an individual OS policy. + + For more information, see [View + compliance](\ https://cloud.google.com/compute/docs/os-configuration-management/view-compliance). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest): + request = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_instance_os_policies_compliance] + + # 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 list_instance_os_policies_compliances(self, + request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstanceOSPoliciesCompliancesPager: + r"""List OS policies compliance data for all Compute + Engine VM instances in the specified zone. + + Args: + request (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest): + The request object. A request message for listing OS + policies compliance data for all Compute Engine VMs in + the given location. + parent (str): + Required. The parent resource name. + + Format: ``projects/{project}/locations/{location}`` + + For ``{project}``, either Compute Engine project-number + or project-id can be provided. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInstanceOSPoliciesCompliancesPager: + A response message for listing OS + policies compliance data for all Compute + Engine VMs in the given location. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest): + request = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_instance_os_policies_compliances] + + # 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.ListInstanceOSPoliciesCompliancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_inventory(self, + request: inventory.GetInventoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> inventory.Inventory: + r"""Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Args: + request (google.cloud.osconfig_v1alpha.types.GetInventoryRequest): + The request object. A request message for getting + inventory data for the specified VM. + name (str): + Required. API resource name for inventory resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/inventory`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.Inventory: + This API resource represents the available inventory data for a + Compute Engine virtual machine (VM) instance at a + given point in time. + + You can use this API resource to determine the + inventory data of your VM. + + For more information, see [Information provided by OS + inventory + management](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a inventory.GetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, inventory.GetInventoryRequest): + request = inventory.GetInventoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_inventory] + + # 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 list_inventories(self, + request: inventory.ListInventoriesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInventoriesPager: + r"""List inventory data for all VM instances in the + specified zone. + + Args: + request (google.cloud.osconfig_v1alpha.types.ListInventoriesRequest): + The request object. A request message for listing + inventory data for all VMs in the specified location. + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, only + hyphen or dash character is supported to list + inventories across VMs. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInventoriesPager: + A response message for listing + inventory data for all VMs in a + specified location. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a inventory.ListInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, inventory.ListInventoriesRequest): + request = inventory.ListInventoriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_inventories] + + # 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.ListInventoriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_vulnerability_report(self, + request: vulnerability.GetVulnerabilityReportRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vulnerability.VulnerabilityReport: + r"""Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Args: + request (google.cloud.osconfig_v1alpha.types.GetVulnerabilityReportRequest): + The request object. A request message for getting the + vulnerability report for the specified VM. + name (str): + Required. API resource name for vulnerability resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.types.VulnerabilityReport: + This API resource represents the vulnerability report for a specified + Compute Engine virtual machine (VM) instance at a + given point in time. + + For more information, see [Vulnerability + reports](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#vulnerability-reports). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a vulnerability.GetVulnerabilityReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, vulnerability.GetVulnerabilityReportRequest): + request = vulnerability.GetVulnerabilityReportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_vulnerability_report] + + # 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 list_vulnerability_reports(self, + request: vulnerability.ListVulnerabilityReportsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVulnerabilityReportsPager: + r"""List vulnerability reports for all VM instances in + the specified zone. + + Args: + request (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest): + The request object. A request message for listing + vulnerability reports for all VM instances in the + specified location. + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, only + ``-`` character is supported to list vulnerability + reports across VMs. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListVulnerabilityReportsPager: + A response message for listing + vulnerability reports for all VM + instances in the specified location. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a vulnerability.ListVulnerabilityReportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, vulnerability.ListVulnerabilityReportsRequest): + request = vulnerability.ListVulnerabilityReportsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_vulnerability_reports] + + # 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.ListVulnerabilityReportsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-osconfig", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "OsConfigZonalServiceClient", +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py new file mode 100644 index 0000000..8c83011 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py @@ -0,0 +1,631 @@ +# -*- 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.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import vulnerability + + +class ListOSPolicyAssignmentsPager: + """A pager for iterating through ``list_os_policy_assignments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOSPolicyAssignments`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` + 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[..., os_policy_assignments.ListOSPolicyAssignmentsResponse], + request: os_policy_assignments.ListOSPolicyAssignmentsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[os_policy_assignments.ListOSPolicyAssignmentsResponse]: + 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[os_policy_assignments.OSPolicyAssignment]: + for page in self.pages: + yield from page.os_policy_assignments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentsAsyncPager: + """A pager for iterating through ``list_os_policy_assignments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOSPolicyAssignments`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` + 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[os_policy_assignments.ListOSPolicyAssignmentsResponse]], + request: os_policy_assignments.ListOSPolicyAssignmentsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[os_policy_assignments.ListOSPolicyAssignmentsResponse]: + 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[os_policy_assignments.OSPolicyAssignment]: + async def async_generator(): + async for page in self.pages: + for response in page.os_policy_assignments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentRevisionsPager: + """A pager for iterating through ``list_os_policy_assignment_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOSPolicyAssignmentRevisions`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` + 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[..., os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse], + request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: + 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[os_policy_assignments.OSPolicyAssignment]: + for page in self.pages: + yield from page.os_policy_assignments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentRevisionsAsyncPager: + """A pager for iterating through ``list_os_policy_assignment_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOSPolicyAssignmentRevisions`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` + 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[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]], + request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: + 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[os_policy_assignments.OSPolicyAssignment]: + async def async_generator(): + async for page in self.pages: + for response in page.os_policy_assignments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstanceOSPoliciesCompliancesPager: + """A pager for iterating through ``list_instance_os_policies_compliances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instance_os_policies_compliances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstanceOSPoliciesCompliances`` requests and continue to iterate + through the ``instance_os_policies_compliances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` + 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[..., instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse], + request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest, + response: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse): + 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]: + 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[instance_os_policies_compliance.InstanceOSPoliciesCompliance]: + for page in self.pages: + yield from page.instance_os_policies_compliances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstanceOSPoliciesCompliancesAsyncPager: + """A pager for iterating through ``list_instance_os_policies_compliances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instance_os_policies_compliances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstanceOSPoliciesCompliances`` requests and continue to iterate + through the ``instance_os_policies_compliances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` + 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[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]], + request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest, + response: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse): + 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]: + 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[instance_os_policies_compliance.InstanceOSPoliciesCompliance]: + async def async_generator(): + async for page in self.pages: + for response in page.instance_os_policies_compliances: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInventoriesPager: + """A pager for iterating through ``list_inventories`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInventories`` requests and continue to iterate + through the ``inventories`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` + 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[..., inventory.ListInventoriesResponse], + request: inventory.ListInventoriesRequest, + response: inventory.ListInventoriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListInventoriesRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListInventoriesResponse): + 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 = inventory.ListInventoriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[inventory.ListInventoriesResponse]: + 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[inventory.Inventory]: + for page in self.pages: + yield from page.inventories + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInventoriesAsyncPager: + """A pager for iterating through ``list_inventories`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInventories`` requests and continue to iterate + through the ``inventories`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` + 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[inventory.ListInventoriesResponse]], + request: inventory.ListInventoriesRequest, + response: inventory.ListInventoriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListInventoriesRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListInventoriesResponse): + 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 = inventory.ListInventoriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[inventory.ListInventoriesResponse]: + 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[inventory.Inventory]: + async def async_generator(): + async for page in self.pages: + for response in page.inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVulnerabilityReportsPager: + """A pager for iterating through ``list_vulnerability_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``vulnerability_reports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVulnerabilityReports`` requests and continue to iterate + through the ``vulnerability_reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` + 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[..., vulnerability.ListVulnerabilityReportsResponse], + request: vulnerability.ListVulnerabilityReportsRequest, + response: vulnerability.ListVulnerabilityReportsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse): + 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 = vulnerability.ListVulnerabilityReportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[vulnerability.ListVulnerabilityReportsResponse]: + 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[vulnerability.VulnerabilityReport]: + for page in self.pages: + yield from page.vulnerability_reports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVulnerabilityReportsAsyncPager: + """A pager for iterating through ``list_vulnerability_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``vulnerability_reports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVulnerabilityReports`` requests and continue to iterate + through the ``vulnerability_reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` + 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[vulnerability.ListVulnerabilityReportsResponse]], + request: vulnerability.ListVulnerabilityReportsRequest, + response: vulnerability.ListVulnerabilityReportsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest): + The initial request object. + response (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse): + 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 = vulnerability.ListVulnerabilityReportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[vulnerability.ListVulnerabilityReportsResponse]: + 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[vulnerability.VulnerabilityReport]: + async def async_generator(): + async for page in self.pages: + for response in page.vulnerability_reports: + 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/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/__init__.py new file mode 100644 index 0000000..81d3d8a --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_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 OsConfigZonalServiceTransport +from .grpc import OsConfigZonalServiceGrpcTransport +from .grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OsConfigZonalServiceTransport]] +_transport_registry['grpc'] = OsConfigZonalServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OsConfigZonalServiceGrpcAsyncIOTransport + +__all__ = ( + 'OsConfigZonalServiceTransport', + 'OsConfigZonalServiceGrpcTransport', + 'OsConfigZonalServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py new file mode 100644 index 0000000..9ecb8d2 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py @@ -0,0 +1,332 @@ +# -*- 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.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import vulnerability +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-osconfig', + ).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 OsConfigZonalServiceTransport(abc.ABC): + """Abstract transport class for OsConfigZonalService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'osconfig.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 + + # 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_os_policy_assignment: gapic_v1.method.wrap_method( + self.create_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.update_os_policy_assignment: gapic_v1.method.wrap_method( + self.update_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.get_os_policy_assignment: gapic_v1.method.wrap_method( + self.get_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.list_os_policy_assignments: gapic_v1.method.wrap_method( + self.list_os_policy_assignments, + default_timeout=None, + client_info=client_info, + ), + self.list_os_policy_assignment_revisions: gapic_v1.method.wrap_method( + self.list_os_policy_assignment_revisions, + default_timeout=None, + client_info=client_info, + ), + self.delete_os_policy_assignment: gapic_v1.method.wrap_method( + self.delete_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.get_instance_os_policies_compliance: gapic_v1.method.wrap_method( + self.get_instance_os_policies_compliance, + default_timeout=None, + client_info=client_info, + ), + self.list_instance_os_policies_compliances: gapic_v1.method.wrap_method( + self.list_instance_os_policies_compliances, + default_timeout=None, + client_info=client_info, + ), + self.get_inventory: gapic_v1.method.wrap_method( + self.get_inventory, + default_timeout=None, + client_info=client_info, + ), + self.list_inventories: gapic_v1.method.wrap_method( + self.list_inventories, + default_timeout=None, + client_info=client_info, + ), + self.get_vulnerability_report: gapic_v1.method.wrap_method( + self.get_vulnerability_report, + default_timeout=None, + client_info=client_info, + ), + self.list_vulnerability_reports: gapic_v1.method.wrap_method( + self.list_vulnerability_reports, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.CreateOSPolicyAssignmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.UpdateOSPolicyAssignmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.GetOSPolicyAssignmentRequest], + Union[ + os_policy_assignments.OSPolicyAssignment, + Awaitable[os_policy_assignments.OSPolicyAssignment] + ]]: + raise NotImplementedError() + + @property + def list_os_policy_assignments(self) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentsRequest], + Union[ + os_policy_assignments.ListOSPolicyAssignmentsResponse, + Awaitable[os_policy_assignments.ListOSPolicyAssignmentsResponse] + ]]: + raise NotImplementedError() + + @property + def list_os_policy_assignment_revisions(self) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], + Union[ + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + Awaitable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.DeleteOSPolicyAssignmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_instance_os_policies_compliance(self) -> Callable[ + [instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest], + Union[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance, + Awaitable[instance_os_policies_compliance.InstanceOSPoliciesCompliance] + ]]: + raise NotImplementedError() + + @property + def list_instance_os_policies_compliances(self) -> Callable[ + [instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest], + Union[ + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse, + Awaitable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_inventory(self) -> Callable[ + [inventory.GetInventoryRequest], + Union[ + inventory.Inventory, + Awaitable[inventory.Inventory] + ]]: + raise NotImplementedError() + + @property + def list_inventories(self) -> Callable[ + [inventory.ListInventoriesRequest], + Union[ + inventory.ListInventoriesResponse, + Awaitable[inventory.ListInventoriesResponse] + ]]: + raise NotImplementedError() + + @property + def get_vulnerability_report(self) -> Callable[ + [vulnerability.GetVulnerabilityReportRequest], + Union[ + vulnerability.VulnerabilityReport, + Awaitable[vulnerability.VulnerabilityReport] + ]]: + raise NotImplementedError() + + @property + def list_vulnerability_reports(self) -> Callable[ + [vulnerability.ListVulnerabilityReportsRequest], + Union[ + vulnerability.ListVulnerabilityReportsResponse, + Awaitable[vulnerability.ListVulnerabilityReportsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'OsConfigZonalServiceTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py new file mode 100644 index 0000000..0086218 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py @@ -0,0 +1,612 @@ +# -*- 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 operations_v1 # 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.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import vulnerability +from google.longrunning import operations_pb2 # type: ignore +from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO + + +class OsConfigZonalServiceGrpcTransport(OsConfigZonalServiceTransport): + """gRPC backend transport for OsConfigZonalService. + + Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + + 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 = 'osconfig.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, + always_use_jwt_access: Optional[bool] = False, + ) -> 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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] = {} + self._operations_client = None + + 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=always_use_jwt_access, + ) + + 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 = 'osconfig.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.CreateOSPolicyAssignmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create os policy assignment method over gRPC. + + Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.CreateOSPolicyAssignmentRequest], + ~.Operation]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['create_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/CreateOSPolicyAssignment', + request_serializer=os_policy_assignments.CreateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_os_policy_assignment'] + + @property + def update_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.UpdateOSPolicyAssignmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update os policy assignment method over gRPC. + + Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.UpdateOSPolicyAssignmentRequest], + ~.Operation]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['update_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/UpdateOSPolicyAssignment', + request_serializer=os_policy_assignments.UpdateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_os_policy_assignment'] + + @property + def get_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.GetOSPolicyAssignmentRequest], + os_policy_assignments.OSPolicyAssignment]: + r"""Return a callable for the get os policy assignment method over gRPC. + + Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Returns: + Callable[[~.GetOSPolicyAssignmentRequest], + ~.OSPolicyAssignment]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['get_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetOSPolicyAssignment', + request_serializer=os_policy_assignments.GetOSPolicyAssignmentRequest.serialize, + response_deserializer=os_policy_assignments.OSPolicyAssignment.deserialize, + ) + return self._stubs['get_os_policy_assignment'] + + @property + def list_os_policy_assignments(self) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentsRequest], + os_policy_assignments.ListOSPolicyAssignmentsResponse]: + r"""Return a callable for the list os policy assignments method over gRPC. + + List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Returns: + Callable[[~.ListOSPolicyAssignmentsRequest], + ~.ListOSPolicyAssignmentsResponse]: + 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_os_policy_assignments' not in self._stubs: + self._stubs['list_os_policy_assignments'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignments', + request_serializer=os_policy_assignments.ListOSPolicyAssignmentsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentsResponse.deserialize, + ) + return self._stubs['list_os_policy_assignments'] + + @property + def list_os_policy_assignment_revisions(self) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: + r"""Return a callable for the list os policy assignment + revisions method over gRPC. + + List the OS policy assignment revisions for a given + OS policy assignment. + + Returns: + Callable[[~.ListOSPolicyAssignmentRevisionsRequest], + ~.ListOSPolicyAssignmentRevisionsResponse]: + 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_os_policy_assignment_revisions' not in self._stubs: + self._stubs['list_os_policy_assignment_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignmentRevisions', + request_serializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse.deserialize, + ) + return self._stubs['list_os_policy_assignment_revisions'] + + @property + def delete_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.DeleteOSPolicyAssignmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete os policy assignment method over gRPC. + + Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.DeleteOSPolicyAssignmentRequest], + ~.Operation]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['delete_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/DeleteOSPolicyAssignment', + request_serializer=os_policy_assignments.DeleteOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_os_policy_assignment'] + + @property + def get_instance_os_policies_compliance(self) -> Callable[ + [instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest], + instance_os_policies_compliance.InstanceOSPoliciesCompliance]: + r"""Return a callable for the get instance os policies + compliance method over gRPC. + + Get OS policies compliance data for the specified + Compute Engine VM instance. + + Returns: + Callable[[~.GetInstanceOSPoliciesComplianceRequest], + ~.InstanceOSPoliciesCompliance]: + 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_instance_os_policies_compliance' not in self._stubs: + self._stubs['get_instance_os_policies_compliance'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInstanceOSPoliciesCompliance', + request_serializer=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest.serialize, + response_deserializer=instance_os_policies_compliance.InstanceOSPoliciesCompliance.deserialize, + ) + return self._stubs['get_instance_os_policies_compliance'] + + @property + def list_instance_os_policies_compliances(self) -> Callable[ + [instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest], + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]: + r"""Return a callable for the list instance os policies + compliances method over gRPC. + + List OS policies compliance data for all Compute + Engine VM instances in the specified zone. + + Returns: + Callable[[~.ListInstanceOSPoliciesCompliancesRequest], + ~.ListInstanceOSPoliciesCompliancesResponse]: + 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_instance_os_policies_compliances' not in self._stubs: + self._stubs['list_instance_os_policies_compliances'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInstanceOSPoliciesCompliances', + request_serializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest.serialize, + response_deserializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse.deserialize, + ) + return self._stubs['list_instance_os_policies_compliances'] + + @property + def get_inventory(self) -> Callable[ + [inventory.GetInventoryRequest], + inventory.Inventory]: + r"""Return a callable for the get inventory method over gRPC. + + Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Returns: + Callable[[~.GetInventoryRequest], + ~.Inventory]: + 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_inventory' not in self._stubs: + self._stubs['get_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInventory', + request_serializer=inventory.GetInventoryRequest.serialize, + response_deserializer=inventory.Inventory.deserialize, + ) + return self._stubs['get_inventory'] + + @property + def list_inventories(self) -> Callable[ + [inventory.ListInventoriesRequest], + inventory.ListInventoriesResponse]: + r"""Return a callable for the list inventories method over gRPC. + + List inventory data for all VM instances in the + specified zone. + + Returns: + Callable[[~.ListInventoriesRequest], + ~.ListInventoriesResponse]: + 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_inventories' not in self._stubs: + self._stubs['list_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInventories', + request_serializer=inventory.ListInventoriesRequest.serialize, + response_deserializer=inventory.ListInventoriesResponse.deserialize, + ) + return self._stubs['list_inventories'] + + @property + def get_vulnerability_report(self) -> Callable[ + [vulnerability.GetVulnerabilityReportRequest], + vulnerability.VulnerabilityReport]: + r"""Return a callable for the get vulnerability report method over gRPC. + + Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Returns: + Callable[[~.GetVulnerabilityReportRequest], + ~.VulnerabilityReport]: + 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_vulnerability_report' not in self._stubs: + self._stubs['get_vulnerability_report'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetVulnerabilityReport', + request_serializer=vulnerability.GetVulnerabilityReportRequest.serialize, + response_deserializer=vulnerability.VulnerabilityReport.deserialize, + ) + return self._stubs['get_vulnerability_report'] + + @property + def list_vulnerability_reports(self) -> Callable[ + [vulnerability.ListVulnerabilityReportsRequest], + vulnerability.ListVulnerabilityReportsResponse]: + r"""Return a callable for the list vulnerability reports method over gRPC. + + List vulnerability reports for all VM instances in + the specified zone. + + Returns: + Callable[[~.ListVulnerabilityReportsRequest], + ~.ListVulnerabilityReportsResponse]: + 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_vulnerability_reports' not in self._stubs: + self._stubs['list_vulnerability_reports'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListVulnerabilityReports', + request_serializer=vulnerability.ListVulnerabilityReportsRequest.serialize, + response_deserializer=vulnerability.ListVulnerabilityReportsResponse.deserialize, + ) + return self._stubs['list_vulnerability_reports'] + + +__all__ = ( + 'OsConfigZonalServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..0507441 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py @@ -0,0 +1,616 @@ +# -*- 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.api_core import operations_v1 # 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.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import vulnerability +from google.longrunning import operations_pb2 # type: ignore +from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OsConfigZonalServiceGrpcTransport + + +class OsConfigZonalServiceGrpcAsyncIOTransport(OsConfigZonalServiceTransport): + """gRPC AsyncIO backend transport for OsConfigZonalService. + + Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + + 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 = 'osconfig.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 = 'osconfig.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, + always_use_jwt_access: Optional[bool] = False, + ) -> 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. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + 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] = {} + self._operations_client = None + + 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=always_use_jwt_access, + ) + + 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 operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.CreateOSPolicyAssignmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create os policy assignment method over gRPC. + + Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.CreateOSPolicyAssignmentRequest], + Awaitable[~.Operation]]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['create_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/CreateOSPolicyAssignment', + request_serializer=os_policy_assignments.CreateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_os_policy_assignment'] + + @property + def update_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.UpdateOSPolicyAssignmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update os policy assignment method over gRPC. + + Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.UpdateOSPolicyAssignmentRequest], + Awaitable[~.Operation]]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['update_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/UpdateOSPolicyAssignment', + request_serializer=os_policy_assignments.UpdateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_os_policy_assignment'] + + @property + def get_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.GetOSPolicyAssignmentRequest], + Awaitable[os_policy_assignments.OSPolicyAssignment]]: + r"""Return a callable for the get os policy assignment method over gRPC. + + Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Returns: + Callable[[~.GetOSPolicyAssignmentRequest], + Awaitable[~.OSPolicyAssignment]]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['get_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetOSPolicyAssignment', + request_serializer=os_policy_assignments.GetOSPolicyAssignmentRequest.serialize, + response_deserializer=os_policy_assignments.OSPolicyAssignment.deserialize, + ) + return self._stubs['get_os_policy_assignment'] + + @property + def list_os_policy_assignments(self) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentsRequest], + Awaitable[os_policy_assignments.ListOSPolicyAssignmentsResponse]]: + r"""Return a callable for the list os policy assignments method over gRPC. + + List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Returns: + Callable[[~.ListOSPolicyAssignmentsRequest], + Awaitable[~.ListOSPolicyAssignmentsResponse]]: + 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_os_policy_assignments' not in self._stubs: + self._stubs['list_os_policy_assignments'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignments', + request_serializer=os_policy_assignments.ListOSPolicyAssignmentsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentsResponse.deserialize, + ) + return self._stubs['list_os_policy_assignments'] + + @property + def list_os_policy_assignment_revisions(self) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], + Awaitable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]]: + r"""Return a callable for the list os policy assignment + revisions method over gRPC. + + List the OS policy assignment revisions for a given + OS policy assignment. + + Returns: + Callable[[~.ListOSPolicyAssignmentRevisionsRequest], + Awaitable[~.ListOSPolicyAssignmentRevisionsResponse]]: + 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_os_policy_assignment_revisions' not in self._stubs: + self._stubs['list_os_policy_assignment_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignmentRevisions', + request_serializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse.deserialize, + ) + return self._stubs['list_os_policy_assignment_revisions'] + + @property + def delete_os_policy_assignment(self) -> Callable[ + [os_policy_assignments.DeleteOSPolicyAssignmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete os policy assignment method over gRPC. + + Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.DeleteOSPolicyAssignmentRequest], + Awaitable[~.Operation]]: + 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_os_policy_assignment' not in self._stubs: + self._stubs['delete_os_policy_assignment'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/DeleteOSPolicyAssignment', + request_serializer=os_policy_assignments.DeleteOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_os_policy_assignment'] + + @property + def get_instance_os_policies_compliance(self) -> Callable[ + [instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest], + Awaitable[instance_os_policies_compliance.InstanceOSPoliciesCompliance]]: + r"""Return a callable for the get instance os policies + compliance method over gRPC. + + Get OS policies compliance data for the specified + Compute Engine VM instance. + + Returns: + Callable[[~.GetInstanceOSPoliciesComplianceRequest], + Awaitable[~.InstanceOSPoliciesCompliance]]: + 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_instance_os_policies_compliance' not in self._stubs: + self._stubs['get_instance_os_policies_compliance'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInstanceOSPoliciesCompliance', + request_serializer=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest.serialize, + response_deserializer=instance_os_policies_compliance.InstanceOSPoliciesCompliance.deserialize, + ) + return self._stubs['get_instance_os_policies_compliance'] + + @property + def list_instance_os_policies_compliances(self) -> Callable[ + [instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest], + Awaitable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]]: + r"""Return a callable for the list instance os policies + compliances method over gRPC. + + List OS policies compliance data for all Compute + Engine VM instances in the specified zone. + + Returns: + Callable[[~.ListInstanceOSPoliciesCompliancesRequest], + Awaitable[~.ListInstanceOSPoliciesCompliancesResponse]]: + 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_instance_os_policies_compliances' not in self._stubs: + self._stubs['list_instance_os_policies_compliances'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInstanceOSPoliciesCompliances', + request_serializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest.serialize, + response_deserializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse.deserialize, + ) + return self._stubs['list_instance_os_policies_compliances'] + + @property + def get_inventory(self) -> Callable[ + [inventory.GetInventoryRequest], + Awaitable[inventory.Inventory]]: + r"""Return a callable for the get inventory method over gRPC. + + Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Returns: + Callable[[~.GetInventoryRequest], + Awaitable[~.Inventory]]: + 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_inventory' not in self._stubs: + self._stubs['get_inventory'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInventory', + request_serializer=inventory.GetInventoryRequest.serialize, + response_deserializer=inventory.Inventory.deserialize, + ) + return self._stubs['get_inventory'] + + @property + def list_inventories(self) -> Callable[ + [inventory.ListInventoriesRequest], + Awaitable[inventory.ListInventoriesResponse]]: + r"""Return a callable for the list inventories method over gRPC. + + List inventory data for all VM instances in the + specified zone. + + Returns: + Callable[[~.ListInventoriesRequest], + Awaitable[~.ListInventoriesResponse]]: + 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_inventories' not in self._stubs: + self._stubs['list_inventories'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInventories', + request_serializer=inventory.ListInventoriesRequest.serialize, + response_deserializer=inventory.ListInventoriesResponse.deserialize, + ) + return self._stubs['list_inventories'] + + @property + def get_vulnerability_report(self) -> Callable[ + [vulnerability.GetVulnerabilityReportRequest], + Awaitable[vulnerability.VulnerabilityReport]]: + r"""Return a callable for the get vulnerability report method over gRPC. + + Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Returns: + Callable[[~.GetVulnerabilityReportRequest], + Awaitable[~.VulnerabilityReport]]: + 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_vulnerability_report' not in self._stubs: + self._stubs['get_vulnerability_report'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetVulnerabilityReport', + request_serializer=vulnerability.GetVulnerabilityReportRequest.serialize, + response_deserializer=vulnerability.VulnerabilityReport.deserialize, + ) + return self._stubs['get_vulnerability_report'] + + @property + def list_vulnerability_reports(self) -> Callable[ + [vulnerability.ListVulnerabilityReportsRequest], + Awaitable[vulnerability.ListVulnerabilityReportsResponse]]: + r"""Return a callable for the list vulnerability reports method over gRPC. + + List vulnerability reports for all VM instances in + the specified zone. + + Returns: + Callable[[~.ListVulnerabilityReportsRequest], + Awaitable[~.ListVulnerabilityReportsResponse]]: + 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_vulnerability_reports' not in self._stubs: + self._stubs['list_vulnerability_reports'] = self.grpc_channel.unary_unary( + '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListVulnerabilityReports', + request_serializer=vulnerability.ListVulnerabilityReportsRequest.serialize, + response_deserializer=vulnerability.ListVulnerabilityReportsResponse.deserialize, + ) + return self._stubs['list_vulnerability_reports'] + + +__all__ = ( + 'OsConfigZonalServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py new file mode 100644 index 0000000..d2d0699 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py @@ -0,0 +1,90 @@ +# -*- 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 .config_common import ( + OSPolicyResourceCompliance, + OSPolicyResourceConfigStep, + OSPolicyComplianceState, +) +from .instance_os_policies_compliance import ( + GetInstanceOSPoliciesComplianceRequest, + InstanceOSPoliciesCompliance, + ListInstanceOSPoliciesCompliancesRequest, + ListInstanceOSPoliciesCompliancesResponse, +) +from .inventory import ( + GetInventoryRequest, + Inventory, + ListInventoriesRequest, + ListInventoriesResponse, + InventoryView, +) +from .os_policy import ( + OSPolicy, +) +from .os_policy_assignments import ( + CreateOSPolicyAssignmentRequest, + DeleteOSPolicyAssignmentRequest, + GetOSPolicyAssignmentRequest, + ListOSPolicyAssignmentRevisionsRequest, + ListOSPolicyAssignmentRevisionsResponse, + ListOSPolicyAssignmentsRequest, + ListOSPolicyAssignmentsResponse, + OSPolicyAssignment, + OSPolicyAssignmentOperationMetadata, + UpdateOSPolicyAssignmentRequest, +) +from .osconfig_common import ( + FixedOrPercent, +) +from .vulnerability import ( + CVSSv3, + GetVulnerabilityReportRequest, + ListVulnerabilityReportsRequest, + ListVulnerabilityReportsResponse, + VulnerabilityReport, +) + +__all__ = ( + 'OSPolicyResourceCompliance', + 'OSPolicyResourceConfigStep', + 'OSPolicyComplianceState', + 'GetInstanceOSPoliciesComplianceRequest', + 'InstanceOSPoliciesCompliance', + 'ListInstanceOSPoliciesCompliancesRequest', + 'ListInstanceOSPoliciesCompliancesResponse', + 'GetInventoryRequest', + 'Inventory', + 'ListInventoriesRequest', + 'ListInventoriesResponse', + 'InventoryView', + 'OSPolicy', + 'CreateOSPolicyAssignmentRequest', + 'DeleteOSPolicyAssignmentRequest', + 'GetOSPolicyAssignmentRequest', + 'ListOSPolicyAssignmentRevisionsRequest', + 'ListOSPolicyAssignmentRevisionsResponse', + 'ListOSPolicyAssignmentsRequest', + 'ListOSPolicyAssignmentsResponse', + 'OSPolicyAssignment', + 'OSPolicyAssignmentOperationMetadata', + 'UpdateOSPolicyAssignmentRequest', + 'FixedOrPercent', + 'CVSSv3', + 'GetVulnerabilityReportRequest', + 'ListVulnerabilityReportsRequest', + 'ListVulnerabilityReportsResponse', + 'VulnerabilityReport', +) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py new file mode 100644 index 0000000..0bb9fda --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py @@ -0,0 +1,131 @@ +# -*- 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.cloud.osconfig.v1alpha', + manifest={ + 'OSPolicyComplianceState', + 'OSPolicyResourceConfigStep', + 'OSPolicyResourceCompliance', + }, +) + + +class OSPolicyComplianceState(proto.Enum): + r"""Supported OSPolicy compliance states.""" + OS_POLICY_COMPLIANCE_STATE_UNSPECIFIED = 0 + COMPLIANT = 1 + NON_COMPLIANT = 2 + UNKNOWN = 3 + NO_OS_POLICIES_APPLICABLE = 4 + + +class OSPolicyResourceConfigStep(proto.Message): + r"""Step performed by the OS Config agent for configuring an + ``OSPolicyResource`` to its desired state. + + Attributes: + type_ (google.cloud.osconfig_v1alpha.types.OSPolicyResourceConfigStep.Type): + Configuration step type. + outcome (google.cloud.osconfig_v1alpha.types.OSPolicyResourceConfigStep.Outcome): + Outcome of the configuration step. + error_message (str): + An error message recorded during the + execution of this step. Only populated when + outcome is FAILED. + """ + class Type(proto.Enum): + r"""Supported configuration step types""" + TYPE_UNSPECIFIED = 0 + VALIDATION = 1 + DESIRED_STATE_CHECK = 2 + DESIRED_STATE_ENFORCEMENT = 3 + DESIRED_STATE_CHECK_POST_ENFORCEMENT = 4 + + class Outcome(proto.Enum): + r"""Supported outcomes for a configuration step.""" + OUTCOME_UNSPECIFIED = 0 + SUCCEEDED = 1 + FAILED = 2 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + outcome = proto.Field( + proto.ENUM, + number=2, + enum=Outcome, + ) + error_message = proto.Field( + proto.STRING, + number=3, + ) + + +class OSPolicyResourceCompliance(proto.Message): + r"""Compliance data for an OS policy resource. + Attributes: + os_policy_resource_id (str): + The id of the OS policy resource. + config_steps (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyResourceConfigStep]): + Ordered list of configuration steps taken by + the agent for the OS policy resource. + state (google.cloud.osconfig_v1alpha.types.OSPolicyComplianceState): + Compliance state of the OS policy resource. + exec_resource_output (google.cloud.osconfig_v1alpha.types.OSPolicyResourceCompliance.ExecResourceOutput): + ExecResource specific output. + """ + + class ExecResourceOutput(proto.Message): + r"""ExecResource specific output. + Attributes: + enforcement_output (bytes): + Output from Enforcement phase output file (if + run). Output size is limited to 100K bytes. + """ + + enforcement_output = proto.Field( + proto.BYTES, + number=2, + ) + + os_policy_resource_id = proto.Field( + proto.STRING, + number=1, + ) + config_steps = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OSPolicyResourceConfigStep', + ) + state = proto.Field( + proto.ENUM, + number=3, + enum='OSPolicyComplianceState', + ) + exec_resource_output = proto.Field( + proto.MESSAGE, + number=4, + oneof='output', + message=ExecResourceOutput, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py new file mode 100644 index 0000000..b95ca34 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.osconfig_v1alpha.types import config_common +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1alpha', + manifest={ + 'InstanceOSPoliciesCompliance', + 'GetInstanceOSPoliciesComplianceRequest', + 'ListInstanceOSPoliciesCompliancesRequest', + 'ListInstanceOSPoliciesCompliancesResponse', + }, +) + + +class InstanceOSPoliciesCompliance(proto.Message): + r"""This API resource represents the OS policies compliance data for a + Compute Engine virtual machine (VM) instance at a given point in + time. + + A Compute Engine VM can have multiple OS policy assignments, and + each assignment can have multiple OS policies. As a result, multiple + OS policies could be applied to a single VM. + + You can use this API resource to determine both the compliance state + of your VM as well as the compliance state of an individual OS + policy. + + For more information, see `View + compliance `__. + + Attributes: + name (str): + Output only. The ``InstanceOSPoliciesCompliance`` API + resource name. + + Format: + ``projects/{project_number}/locations/{location}/instanceOSPoliciesCompliances/{instance_id}`` + instance (str): + Output only. The Compute Engine VM instance + name. + state (google.cloud.osconfig_v1alpha.types.OSPolicyComplianceState): + Output only. Compliance state of the VM. + detailed_state (str): + Output only. Detailed compliance state of the VM. This field + is populated only when compliance state is ``UNKNOWN``. + + It may contain one of the following values: + + - ``no-compliance-data``: Compliance data is not available + for this VM. + - ``no-agent-detected``: OS Config agent is not detected + for this VM. + - ``config-not-supported-by-agent``: The version of the OS + Config agent running on this VM does not support + configuration management. + - ``inactive``: VM is not running. + - ``internal-service-errors``: There were internal service + errors encountered while enforcing compliance. + - ``agent-errors``: OS config agent encountered errors + while enforcing compliance. + detailed_state_reason (str): + Output only. The reason for the ``detailed_state`` of the VM + (if any). + os_policy_compliances (Sequence[google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance.OSPolicyCompliance]): + Output only. Compliance data for each ``OSPolicy`` that is + applied to the VM. + last_compliance_check_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of the last compliance + check for the VM. + last_compliance_run_id (str): + Output only. Unique identifier for the last + compliance run. This id will be logged by the OS + config agent during a compliance run and can be + used for debugging and tracing purpose. + """ + + class OSPolicyCompliance(proto.Message): + r"""Compliance data for an OS policy + Attributes: + os_policy_id (str): + The OS policy id + os_policy_assignment (str): + Reference to the ``OSPolicyAssignment`` API resource that + the ``OSPolicy`` belongs to. + + Format: + ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id@revision_id}`` + state (google.cloud.osconfig_v1alpha.types.OSPolicyComplianceState): + Compliance state of the OS policy. + os_policy_resource_compliances (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyResourceCompliance]): + Compliance data for each ``OSPolicyResource`` that is + applied to the VM. + """ + + os_policy_id = proto.Field( + proto.STRING, + number=1, + ) + os_policy_assignment = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=config_common.OSPolicyComplianceState, + ) + os_policy_resource_compliances = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=config_common.OSPolicyResourceCompliance, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + instance = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum=config_common.OSPolicyComplianceState, + ) + detailed_state = proto.Field( + proto.STRING, + number=4, + ) + detailed_state_reason = proto.Field( + proto.STRING, + number=5, + ) + os_policy_compliances = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=OSPolicyCompliance, + ) + last_compliance_check_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + last_compliance_run_id = proto.Field( + proto.STRING, + number=8, + ) + + +class GetInstanceOSPoliciesComplianceRequest(proto.Message): + r"""A request message for getting OS policies compliance data for + the given Compute Engine VM instance. + + Attributes: + name (str): + Required. API resource name for instance OS policies + compliance resource. + + Format: + ``projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}`` + + For ``{project}``, either Compute Engine project-number or + project-id can be provided. For ``{instance}``, either + Compute Engine VM instance-id or instance-name can be + provided. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListInstanceOSPoliciesCompliancesRequest(proto.Message): + r"""A request message for listing OS policies compliance data for + all Compute Engine VMs in the given location. + + Attributes: + parent (str): + Required. The parent resource name. + + Format: ``projects/{project}/locations/{location}`` + + For ``{project}``, either Compute Engine project-number or + project-id can be provided. + page_size (int): + The maximum number of results to return. + page_token (str): + A pagination token returned from a previous call to + ``ListInstanceOSPoliciesCompliances`` that indicates where + this listing should continue from. + filter (str): + If provided, this field specifies the criteria that must be + met by a ``InstanceOSPoliciesCompliance`` API resource to be + included in the response. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListInstanceOSPoliciesCompliancesResponse(proto.Message): + r"""A response message for listing OS policies compliance data + for all Compute Engine VMs in the given location. + + Attributes: + instance_os_policies_compliances (Sequence[google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance]): + List of instance OS policies compliance + objects. + next_page_token (str): + The pagination token to retrieve the next + page of instance OS policies compliance objects. + """ + + @property + def raw_page(self): + return self + + instance_os_policies_compliances = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='InstanceOSPoliciesCompliance', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py new file mode 100644 index 0000000..dc5f595 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py @@ -0,0 +1,670 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1alpha', + manifest={ + 'InventoryView', + 'Inventory', + 'GetInventoryRequest', + 'ListInventoriesRequest', + 'ListInventoriesResponse', + }, +) + + +class InventoryView(proto.Enum): + r"""The view for inventory objects.""" + INVENTORY_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + +class Inventory(proto.Message): + r"""This API resource represents the available inventory data for a + Compute Engine virtual machine (VM) instance at a given point in + time. + + You can use this API resource to determine the inventory data of + your VM. + + For more information, see `Information provided by OS inventory + management `__. + + Attributes: + name (str): + Output only. The ``Inventory`` API resource name. + + Format: + ``projects/{project_number}/locations/{location}/instances/{instance_id}/inventory`` + os_info (google.cloud.osconfig_v1alpha.types.Inventory.OsInfo): + Output only. Base level operating system + information for the VM. + items (Sequence[google.cloud.osconfig_v1alpha.types.Inventory.ItemsEntry]): + Output only. Inventory items related to the + VM keyed by an opaque unique identifier for each + inventory item. The identifier is unique to each + distinct and addressable inventory item and will + change, when there is a new package version. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of the last reported + inventory for the VM. + """ + + class OsInfo(proto.Message): + r"""Operating system information for the VM. + Attributes: + hostname (str): + The VM hostname. + long_name (str): + The operating system long name. + For example 'Debian GNU/Linux 9' or 'Microsoft + Window Server 2019 Datacenter'. + short_name (str): + The operating system short name. + For example, 'windows' or 'debian'. + version (str): + The version of the operating system. + architecture (str): + The system architecture of the operating + system. + kernel_version (str): + The kernel version of the operating system. + kernel_release (str): + The kernel release of the operating system. + osconfig_agent_version (str): + The current version of the OS Config agent + running on the VM. + """ + + hostname = proto.Field( + proto.STRING, + number=9, + ) + long_name = proto.Field( + proto.STRING, + number=2, + ) + short_name = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + architecture = proto.Field( + proto.STRING, + number=5, + ) + kernel_version = proto.Field( + proto.STRING, + number=6, + ) + kernel_release = proto.Field( + proto.STRING, + number=7, + ) + osconfig_agent_version = proto.Field( + proto.STRING, + number=8, + ) + + class Item(proto.Message): + r"""A single piece of inventory on a VM. + Attributes: + id (str): + Identifier for this item, unique across items + for this VM. + origin_type (google.cloud.osconfig_v1alpha.types.Inventory.Item.OriginType): + The origin of this inventory item. + create_time (google.protobuf.timestamp_pb2.Timestamp): + When this inventory item was first detected. + update_time (google.protobuf.timestamp_pb2.Timestamp): + When this inventory item was last modified. + type_ (google.cloud.osconfig_v1alpha.types.Inventory.Item.Type): + The specific type of inventory, correlating + to its specific details. + installed_package (google.cloud.osconfig_v1alpha.types.Inventory.SoftwarePackage): + Software package present on the VM instance. + available_package (google.cloud.osconfig_v1alpha.types.Inventory.SoftwarePackage): + Software package available to be installed on + the VM instance. + """ + class OriginType(proto.Enum): + r"""The origin of a specific inventory item.""" + ORIGIN_TYPE_UNSPECIFIED = 0 + INVENTORY_REPORT = 1 + + class Type(proto.Enum): + r"""The different types of inventory that are tracked on a VM.""" + TYPE_UNSPECIFIED = 0 + INSTALLED_PACKAGE = 1 + AVAILABLE_PACKAGE = 2 + + id = proto.Field( + proto.STRING, + number=1, + ) + origin_type = proto.Field( + proto.ENUM, + number=2, + enum='Inventory.Item.OriginType', + ) + create_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + type_ = proto.Field( + proto.ENUM, + number=5, + enum='Inventory.Item.Type', + ) + installed_package = proto.Field( + proto.MESSAGE, + number=6, + oneof='details', + message='Inventory.SoftwarePackage', + ) + available_package = proto.Field( + proto.MESSAGE, + number=7, + oneof='details', + message='Inventory.SoftwarePackage', + ) + + class SoftwarePackage(proto.Message): + r"""Software package information of the operating system. + Attributes: + yum_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): + Yum package info. For details about the yum package manager, + see + https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-yum. + apt_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): + Details of an APT package. + For details about the apt package manager, see + https://wiki.debian.org/Apt. + zypper_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): + Details of a Zypper package. For details about the Zypper + package manager, see + https://en.opensuse.org/SDB:Zypper_manual. + googet_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): + Details of a Googet package. + For details about the googet package manager, + see https://github.com/google/googet. + zypper_patch (google.cloud.osconfig_v1alpha.types.Inventory.ZypperPatch): + Details of a Zypper patch. For details about the Zypper + package manager, see + https://en.opensuse.org/SDB:Zypper_manual. + wua_package (google.cloud.osconfig_v1alpha.types.Inventory.WindowsUpdatePackage): + Details of a Windows Update package. See + https://docs.microsoft.com/en-us/windows/win32/api/_wua/ for + information about Windows Update. + qfe_package (google.cloud.osconfig_v1alpha.types.Inventory.WindowsQuickFixEngineeringPackage): + Details of a Windows Quick Fix engineering + package. See + https://docs.microsoft.com/en- + us/windows/win32/cimwin32prov/win32-quickfixengineering + for info in Windows Quick Fix Engineering. + cos_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): + Details of a COS package. + windows_application (google.cloud.osconfig_v1alpha.types.Inventory.WindowsApplication): + Details of Windows Application. + """ + + yum_package = proto.Field( + proto.MESSAGE, + number=1, + oneof='details', + message='Inventory.VersionedPackage', + ) + apt_package = proto.Field( + proto.MESSAGE, + number=2, + oneof='details', + message='Inventory.VersionedPackage', + ) + zypper_package = proto.Field( + proto.MESSAGE, + number=3, + oneof='details', + message='Inventory.VersionedPackage', + ) + googet_package = proto.Field( + proto.MESSAGE, + number=4, + oneof='details', + message='Inventory.VersionedPackage', + ) + zypper_patch = proto.Field( + proto.MESSAGE, + number=5, + oneof='details', + message='Inventory.ZypperPatch', + ) + wua_package = proto.Field( + proto.MESSAGE, + number=6, + oneof='details', + message='Inventory.WindowsUpdatePackage', + ) + qfe_package = proto.Field( + proto.MESSAGE, + number=7, + oneof='details', + message='Inventory.WindowsQuickFixEngineeringPackage', + ) + cos_package = proto.Field( + proto.MESSAGE, + number=8, + oneof='details', + message='Inventory.VersionedPackage', + ) + windows_application = proto.Field( + proto.MESSAGE, + number=9, + oneof='details', + message='Inventory.WindowsApplication', + ) + + class VersionedPackage(proto.Message): + r"""Information related to the a standard versioned package. + This includes package info for APT, Yum, Zypper, and Googet + package managers. + + Attributes: + package_name (str): + The name of the package. + architecture (str): + The system architecture this package is + intended for. + version (str): + The version of the package. + """ + + package_name = proto.Field( + proto.STRING, + number=4, + ) + architecture = proto.Field( + proto.STRING, + number=2, + ) + version = proto.Field( + proto.STRING, + number=3, + ) + + class ZypperPatch(proto.Message): + r"""Details related to a Zypper Patch. + Attributes: + patch_name (str): + The name of the patch. + category (str): + The category of the patch. + severity (str): + The severity specified for this patch + summary (str): + Any summary information provided about this + patch. + """ + + patch_name = proto.Field( + proto.STRING, + number=5, + ) + category = proto.Field( + proto.STRING, + number=2, + ) + severity = proto.Field( + proto.STRING, + number=3, + ) + summary = proto.Field( + proto.STRING, + number=4, + ) + + class WindowsUpdatePackage(proto.Message): + r"""Details related to a Windows Update package. Field data and names + are taken from Windows Update API IUpdate Interface: + https://docs.microsoft.com/en-us/windows/win32/api/_wua/ Descriptive + fields like title, and description are localized based on the locale + of the VM being updated. + + Attributes: + title (str): + The localized title of the update package. + description (str): + The localized description of the update + package. + categories (Sequence[google.cloud.osconfig_v1alpha.types.Inventory.WindowsUpdatePackage.WindowsUpdateCategory]): + The categories that are associated with this + update package. + kb_article_ids (Sequence[str]): + A collection of Microsoft Knowledge Base + article IDs that are associated with the update + package. + support_url (str): + A hyperlink to the language-specific support + information for the update. + more_info_urls (Sequence[str]): + A collection of URLs that provide more + information about the update package. + update_id (str): + Gets the identifier of an update package. + Stays the same across revisions. + revision_number (int): + The revision number of this update package. + last_deployment_change_time (google.protobuf.timestamp_pb2.Timestamp): + The last published date of the update, in + (UTC) date and time. + """ + + class WindowsUpdateCategory(proto.Message): + r"""Categories specified by the Windows Update. + Attributes: + id (str): + The identifier of the windows update + category. + name (str): + The name of the windows update category. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + name = proto.Field( + proto.STRING, + number=2, + ) + + title = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + categories = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Inventory.WindowsUpdatePackage.WindowsUpdateCategory', + ) + kb_article_ids = proto.RepeatedField( + proto.STRING, + number=4, + ) + support_url = proto.Field( + proto.STRING, + number=11, + ) + more_info_urls = proto.RepeatedField( + proto.STRING, + number=5, + ) + update_id = proto.Field( + proto.STRING, + number=6, + ) + revision_number = proto.Field( + proto.INT32, + number=7, + ) + last_deployment_change_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + class WindowsQuickFixEngineeringPackage(proto.Message): + r"""Information related to a Quick Fix Engineering package. + Fields are taken from Windows QuickFixEngineering Interface and + match the source names: + https://docs.microsoft.com/en- + us/windows/win32/cimwin32prov/win32-quickfixengineering + + Attributes: + caption (str): + A short textual description of the QFE + update. + description (str): + A textual description of the QFE update. + hot_fix_id (str): + Unique identifier associated with a + particular QFE update. + install_time (google.protobuf.timestamp_pb2.Timestamp): + Date that the QFE update was installed. Mapped from + installed_on field. + """ + + caption = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + hot_fix_id = proto.Field( + proto.STRING, + number=3, + ) + install_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + class WindowsApplication(proto.Message): + r"""Contains information about a Windows application as retrieved from + the Windows Registry. For more information about these fields, see + + `Windows Installer Properties for the Uninstall + Registry `__\ {: + class="external" } + + Attributes: + display_name (str): + The name of the application or product. + display_version (str): + The version of the product or application in + string format. + publisher (str): + The name of the manufacturer for the product + or application. + install_date (google.type.date_pb2.Date): + The last time this product received service. + The value of this property is replaced each time + a patch is applied or removed from the product + or the command-line option is used to repair the + product. + help_link (str): + The internet address for technical support. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + display_version = proto.Field( + proto.STRING, + number=2, + ) + publisher = proto.Field( + proto.STRING, + number=3, + ) + install_date = proto.Field( + proto.MESSAGE, + number=4, + message=date_pb2.Date, + ) + help_link = proto.Field( + proto.STRING, + number=5, + ) + + name = proto.Field( + proto.STRING, + number=3, + ) + os_info = proto.Field( + proto.MESSAGE, + number=1, + message=OsInfo, + ) + items = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=Item, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class GetInventoryRequest(proto.Message): + r"""A request message for getting inventory data for the + specified VM. + + Attributes: + name (str): + Required. API resource name for inventory resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/inventory`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, either + Compute Engine ``instance-id`` or ``instance-name`` can be + provided. + view (google.cloud.osconfig_v1alpha.types.InventoryView): + Inventory view indicating what information + should be included in the inventory resource. If + unspecified, the default view is BASIC. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + view = proto.Field( + proto.ENUM, + number=2, + enum='InventoryView', + ) + + +class ListInventoriesRequest(proto.Message): + r"""A request message for listing inventory data for all VMs in + the specified location. + + Attributes: + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, only + hyphen or dash character is supported to list inventories + across VMs. + view (google.cloud.osconfig_v1alpha.types.InventoryView): + Inventory view indicating what information + should be included in the inventory resource. If + unspecified, the default view is BASIC. + page_size (int): + The maximum number of results to return. + page_token (str): + A pagination token returned from a previous call to + ``ListInventories`` that indicates where this listing should + continue from. + filter (str): + If provided, this field specifies the criteria that must be + met by a ``Inventory`` API resource to be included in the + response. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + view = proto.Field( + proto.ENUM, + number=2, + enum='InventoryView', + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInventoriesResponse(proto.Message): + r"""A response message for listing inventory data for all VMs in + a specified location. + + Attributes: + inventories (Sequence[google.cloud.osconfig_v1alpha.types.Inventory]): + List of inventory objects. + next_page_token (str): + The pagination token to retrieve the next + page of inventory objects. + """ + + @property + def raw_page(self): + return self + + inventories = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Inventory', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py new file mode 100644 index 0000000..c8cc8c2 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py @@ -0,0 +1,865 @@ +# -*- 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.cloud.osconfig.v1alpha', + manifest={ + 'OSPolicy', + }, +) + + +class OSPolicy(proto.Message): + r"""An OS policy defines the desired state configuration for a + VM. + + Attributes: + id (str): + Required. The id of the OS policy with the following + restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the assignment. + description (str): + Policy description. + Length of the description is limited to 1024 + characters. + mode (google.cloud.osconfig_v1alpha.types.OSPolicy.Mode): + Required. Policy mode + resource_groups (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicy.ResourceGroup]): + Required. List of resource groups for the policy. For a + particular VM, resource groups are evaluated in the order + specified and the first resource group that is applicable is + selected and the rest are ignored. + + If none of the resource groups are applicable for a VM, the + VM is considered to be non-compliant w.r.t this policy. This + behavior can be toggled by the flag + ``allow_no_resource_group_match`` + allow_no_resource_group_match (bool): + This flag determines the OS policy compliance status when + none of the resource groups within the policy are applicable + for a VM. Set this value to ``true`` if the policy needs to + be reported as compliant even if the policy has nothing to + validate or enforce. + """ + class Mode(proto.Enum): + r"""Policy mode""" + MODE_UNSPECIFIED = 0 + VALIDATION = 1 + ENFORCEMENT = 2 + + class OSFilter(proto.Message): + r"""The ``OSFilter`` is used to specify the OS filtering criteria for + the resource group. + + Attributes: + os_short_name (str): + This should match OS short name emitted by + the OS inventory agent. An empty value matches + any OS. + os_version (str): + This value should match the version emitted by the OS + inventory agent. Prefix matches are supported if asterisk(*) + is provided as the last character. For example, to match all + versions with a major version of ``7``, specify the + following value for this field ``7.*`` + """ + + os_short_name = proto.Field( + proto.STRING, + number=1, + ) + os_version = proto.Field( + proto.STRING, + number=2, + ) + + class Resource(proto.Message): + r"""An OS policy resource is used to define the desired state + configuration and provides a specific functionality like + installing/removing packages, executing a script etc. + + The system ensures that resources are always in their desired + state by taking necessary actions if they have drifted from + their desired state. + + Attributes: + id (str): + Required. The id of the resource with the following + restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the OS policy. + pkg (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource): + Package resource + repository (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource): + Package repository resource + exec_ (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource): + Exec resource + file (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.FileResource): + File resource + """ + + class File(proto.Message): + r"""A remote or local file. + Attributes: + remote (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File.Remote): + A generic remote file. + gcs (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File.Gcs): + A Cloud Storage object. + local_path (str): + A local path within the VM to use. + allow_insecure (bool): + Defaults to false. When false, files are + subject to validations based on the file type: + Remote: A checksum must be specified. + Cloud Storage: An object generation number must + be specified. + """ + + class Remote(proto.Message): + r"""Specifies a file available via some URI. + Attributes: + uri (str): + Required. URI from which to fetch the object. It should + contain both the protocol and path following the format + ``{protocol}://{location}``. + sha256_checksum (str): + SHA256 checksum of the remote file. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + sha256_checksum = proto.Field( + proto.STRING, + number=2, + ) + + class Gcs(proto.Message): + r"""Specifies a file available as a Cloud Storage Object. + Attributes: + bucket (str): + Required. Bucket of the Cloud Storage object. + object_ (str): + Required. Name of the Cloud Storage object. + generation (int): + Generation number of the Cloud Storage + object. + """ + + bucket = proto.Field( + proto.STRING, + number=1, + ) + object_ = proto.Field( + proto.STRING, + number=2, + ) + generation = proto.Field( + proto.INT64, + number=3, + ) + + remote = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message='OSPolicy.Resource.File.Remote', + ) + gcs = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='OSPolicy.Resource.File.Gcs', + ) + local_path = proto.Field( + proto.STRING, + number=3, + oneof='type', + ) + allow_insecure = proto.Field( + proto.BOOL, + number=4, + ) + + class PackageResource(proto.Message): + r"""A resource that manages a system package. + Attributes: + desired_state (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.DesiredState): + Required. The desired state the agent should + maintain for this package. + apt (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.APT): + A package managed by Apt. + deb (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.Deb): + A deb package file. + yum (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.YUM): + A package managed by YUM. + zypper (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.Zypper): + A package managed by Zypper. + rpm (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.RPM): + An rpm package file. + googet (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.GooGet): + A package managed by GooGet. + msi (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.MSI): + An MSI package. + """ + class DesiredState(proto.Enum): + r"""The desired state that the OS Config agent maintains on the + VM. + """ + DESIRED_STATE_UNSPECIFIED = 0 + INSTALLED = 1 + REMOVED = 2 + + class Deb(proto.Message): + r"""A deb package file. dpkg packages only support INSTALLED + state. + + Attributes: + source (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): + Required. A deb package. + pull_deps (bool): + Whether dependencies should also be installed. + + - install when false: ``dpkg -i package`` + - install when true: + ``apt-get update && apt-get -y install package.deb`` + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message='OSPolicy.Resource.File', + ) + pull_deps = proto.Field( + proto.BOOL, + number=2, + ) + + class APT(proto.Message): + r"""A package managed by APT. + + - install: ``apt-get update && apt-get -y install [name]`` + - remove: ``apt-get -y remove [name]`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + class RPM(proto.Message): + r"""An RPM package file. RPM packages only support INSTALLED + state. + + Attributes: + source (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): + Required. An rpm package. + pull_deps (bool): + Whether dependencies should also be installed. + + - install when false: + ``rpm --upgrade --replacepkgs package.rpm`` + - install when true: ``yum -y install package.rpm`` or + ``zypper -y install package.rpm`` + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message='OSPolicy.Resource.File', + ) + pull_deps = proto.Field( + proto.BOOL, + number=2, + ) + + class YUM(proto.Message): + r"""A package managed by YUM. + + - install: ``yum -y install package`` + - remove: ``yum -y remove package`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + class Zypper(proto.Message): + r"""A package managed by Zypper. + + - install: ``zypper -y install package`` + - remove: ``zypper -y rm package`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + class GooGet(proto.Message): + r"""A package managed by GooGet. + + - install: ``googet -noconfirm install package`` + - remove: ``googet -noconfirm remove package`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + class MSI(proto.Message): + r"""An MSI package. MSI packages only support INSTALLED state. + Attributes: + source (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): + Required. The MSI package. + properties (Sequence[str]): + Additional properties to use during installation. This + should be in the format of Property=Setting. Appended to the + defaults of ``ACTION=INSTALL REBOOT=ReallySuppress``. + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message='OSPolicy.Resource.File', + ) + properties = proto.RepeatedField( + proto.STRING, + number=2, + ) + + desired_state = proto.Field( + proto.ENUM, + number=1, + enum='OSPolicy.Resource.PackageResource.DesiredState', + ) + apt = proto.Field( + proto.MESSAGE, + number=2, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.APT', + ) + deb = proto.Field( + proto.MESSAGE, + number=3, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.Deb', + ) + yum = proto.Field( + proto.MESSAGE, + number=4, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.YUM', + ) + zypper = proto.Field( + proto.MESSAGE, + number=5, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.Zypper', + ) + rpm = proto.Field( + proto.MESSAGE, + number=6, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.RPM', + ) + googet = proto.Field( + proto.MESSAGE, + number=7, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.GooGet', + ) + msi = proto.Field( + proto.MESSAGE, + number=8, + oneof='system_package', + message='OSPolicy.Resource.PackageResource.MSI', + ) + + class RepositoryResource(proto.Message): + r"""A resource that manages a package repository. + Attributes: + apt (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.AptRepository): + An Apt Repository. + yum (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.YumRepository): + A Yum Repository. + zypper (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.ZypperRepository): + A Zypper Repository. + goo (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.GooRepository): + A Goo Repository. + """ + + class AptRepository(proto.Message): + r"""Represents a single apt package repository. These will be added to a + repo file that will be managed at + ``/etc/apt/sources.list.d/google_osconfig.list``. + + Attributes: + archive_type (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType): + Required. Type of archive files in this + repository. + uri (str): + Required. URI for this repository. + distribution (str): + Required. Distribution of this repository. + components (Sequence[str]): + Required. List of components for this + repository. Must contain at least one item. + gpg_key (str): + URI of the key file for this repository. The agent maintains + a keyring at + ``/etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg``. + """ + class ArchiveType(proto.Enum): + r"""Type of archive.""" + ARCHIVE_TYPE_UNSPECIFIED = 0 + DEB = 1 + DEB_SRC = 2 + + archive_type = proto.Field( + proto.ENUM, + number=1, + enum='OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType', + ) + uri = proto.Field( + proto.STRING, + number=2, + ) + distribution = proto.Field( + proto.STRING, + number=3, + ) + components = proto.RepeatedField( + proto.STRING, + number=4, + ) + gpg_key = proto.Field( + proto.STRING, + number=5, + ) + + class YumRepository(proto.Message): + r"""Represents a single yum package repository. These are added to a + repo file that is managed at + ``/etc/yum.repos.d/google_osconfig.repo``. + + Attributes: + id (str): + Required. A one word, unique name for this repository. This + is the ``repo id`` in the yum config file and also the + ``display_name`` if ``display_name`` is omitted. This id is + also used as the unique identifier when checking for + resource conflicts. + display_name (str): + The display name of the repository. + base_url (str): + Required. The location of the repository + directory. + gpg_keys (Sequence[str]): + URIs of GPG keys. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + base_url = proto.Field( + proto.STRING, + number=3, + ) + gpg_keys = proto.RepeatedField( + proto.STRING, + number=4, + ) + + class ZypperRepository(proto.Message): + r"""Represents a single zypper package repository. These are added to a + repo file that is managed at + ``/etc/zypp/repos.d/google_osconfig.repo``. + + Attributes: + id (str): + Required. A one word, unique name for this repository. This + is the ``repo id`` in the zypper config file and also the + ``display_name`` if ``display_name`` is omitted. This id is + also used as the unique identifier when checking for + GuestPolicy conflicts. + display_name (str): + The display name of the repository. + base_url (str): + Required. The location of the repository + directory. + gpg_keys (Sequence[str]): + URIs of GPG keys. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + base_url = proto.Field( + proto.STRING, + number=3, + ) + gpg_keys = proto.RepeatedField( + proto.STRING, + number=4, + ) + + class GooRepository(proto.Message): + r"""Represents a Goo package repository. These are added to a repo file + that is managed at + ``C:/ProgramData/GooGet/repos/google_osconfig.repo``. + + Attributes: + name (str): + Required. The name of the repository. + url (str): + Required. The url of the repository. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + url = proto.Field( + proto.STRING, + number=2, + ) + + apt = proto.Field( + proto.MESSAGE, + number=1, + oneof='repository', + message='OSPolicy.Resource.RepositoryResource.AptRepository', + ) + yum = proto.Field( + proto.MESSAGE, + number=2, + oneof='repository', + message='OSPolicy.Resource.RepositoryResource.YumRepository', + ) + zypper = proto.Field( + proto.MESSAGE, + number=3, + oneof='repository', + message='OSPolicy.Resource.RepositoryResource.ZypperRepository', + ) + goo = proto.Field( + proto.MESSAGE, + number=4, + oneof='repository', + message='OSPolicy.Resource.RepositoryResource.GooRepository', + ) + + class ExecResource(proto.Message): + r"""A resource that allows executing scripts on the VM. + + The ``ExecResource`` has 2 stages: ``validate`` and ``enforce`` and + both stages accept a script as an argument to execute. + + When the ``ExecResource`` is applied by the agent, it first executes + the script in the ``validate`` stage. The ``validate`` stage can + signal that the ``ExecResource`` is already in the desired state by + returning an exit code of ``100``. If the ``ExecResource`` is not in + the desired state, it should return an exit code of ``101``. Any + other exit code returned by this stage is considered an error. + + If the ``ExecResource`` is not in the desired state based on the + exit code from the ``validate`` stage, the agent proceeds to execute + the script from the ``enforce`` stage. If the ``ExecResource`` is + already in the desired state, the ``enforce`` stage will not be run. + Similar to ``validate`` stage, the ``enforce`` stage should return + an exit code of ``100`` to indicate that the resource in now in its + desired state. Any other exit code is considered an error. + + NOTE: An exit code of ``100`` was chosen over ``0`` (and ``101`` vs + ``1``) to have an explicit indicator of ``in desired state``, + ``not in desired state`` and errors. Because, for example, + Powershell will always return an exit code of ``0`` unless an + ``exit`` statement is provided in the script. So, for reasons of + consistency and being explicit, exit codes ``100`` and ``101`` were + chosen. + + Attributes: + validate (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource.Exec): + Required. What to run to validate this + resource is in the desired state. An exit code + of 100 indicates "in desired state", and exit + code of 101 indicates "not in desired state". + Any other exit code indicates a failure running + validate. + enforce (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource.Exec): + What to run to bring this resource into the + desired state. An exit code of 100 indicates + "success", any other exit code indicates a + failure running enforce. + """ + + class Exec(proto.Message): + r"""A file or script to execute. + Attributes: + file (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): + A remote or local file. + script (str): + An inline script. + The size of the script is limited to 1024 + characters. + args (Sequence[str]): + Optional arguments to pass to the source + during execution. + interpreter (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource.Exec.Interpreter): + Required. The script interpreter to use. + output_file_path (str): + Only recorded for enforce Exec. + Path to an output file (that is created by this + Exec) whose content will be recorded in + OSPolicyResourceCompliance after a successful + run. Absence or failure to read this file will + result in this ExecResource being non-compliant. + Output file size is limited to 100K bytes. + """ + class Interpreter(proto.Enum): + r"""The interpreter to use.""" + INTERPRETER_UNSPECIFIED = 0 + NONE = 1 + SHELL = 2 + POWERSHELL = 3 + + file = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='OSPolicy.Resource.File', + ) + script = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + args = proto.RepeatedField( + proto.STRING, + number=3, + ) + interpreter = proto.Field( + proto.ENUM, + number=4, + enum='OSPolicy.Resource.ExecResource.Exec.Interpreter', + ) + output_file_path = proto.Field( + proto.STRING, + number=5, + ) + + validate = proto.Field( + proto.MESSAGE, + number=1, + message='OSPolicy.Resource.ExecResource.Exec', + ) + enforce = proto.Field( + proto.MESSAGE, + number=2, + message='OSPolicy.Resource.ExecResource.Exec', + ) + + class FileResource(proto.Message): + r"""A resource that manages the state of a file. + Attributes: + file (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): + A remote or local source. + content (str): + A a file with this content. + The size of the content is limited to 1024 + characters. + path (str): + Required. The absolute path of the file + within the VM. + state (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.FileResource.DesiredState): + Required. Desired state of the file. + permissions (str): + Consists of three octal digits which + represent, in order, the permissions of the + owner, group, and other users for the file + (similarly to the numeric mode used in the linux + chmod utility). Each digit represents a three + bit number with the 4 bit corresponding to the + read permissions, the 2 bit corresponds to the + write bit, and the one bit corresponds to the + execute permission. Default behavior is 755. + + Below are some examples of permissions and their + associated values: read, write, and execute: 7 + read and execute: 5 + read and write: 6 + read only: 4 + """ + class DesiredState(proto.Enum): + r"""Desired state of the file.""" + DESIRED_STATE_UNSPECIFIED = 0 + PRESENT = 1 + ABSENT = 2 + CONTENTS_MATCH = 3 + + file = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='OSPolicy.Resource.File', + ) + content = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + path = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum='OSPolicy.Resource.FileResource.DesiredState', + ) + permissions = proto.Field( + proto.STRING, + number=5, + ) + + id = proto.Field( + proto.STRING, + number=1, + ) + pkg = proto.Field( + proto.MESSAGE, + number=2, + oneof='resource_type', + message='OSPolicy.Resource.PackageResource', + ) + repository = proto.Field( + proto.MESSAGE, + number=3, + oneof='resource_type', + message='OSPolicy.Resource.RepositoryResource', + ) + exec_ = proto.Field( + proto.MESSAGE, + number=4, + oneof='resource_type', + message='OSPolicy.Resource.ExecResource', + ) + file = proto.Field( + proto.MESSAGE, + number=5, + oneof='resource_type', + message='OSPolicy.Resource.FileResource', + ) + + class ResourceGroup(proto.Message): + r"""Resource groups provide a mechanism to group OS policy resources. + + Resource groups enable OS policy authors to create a single OS + policy to be applied to VMs running different operating Systems. + + When the OS policy is applied to a target VM, the appropriate + resource group within the OS policy is selected based on the + ``OSFilter`` specified within the resource group. + + Attributes: + os_filter (google.cloud.osconfig_v1alpha.types.OSPolicy.OSFilter): + Used to specify the OS filter for a resource + group + resources (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicy.Resource]): + Required. List of resources configured for + this resource group. The resources are executed + in the exact order specified here. + """ + + os_filter = proto.Field( + proto.MESSAGE, + number=1, + message='OSPolicy.OSFilter', + ) + resources = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='OSPolicy.Resource', + ) + + id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + mode = proto.Field( + proto.ENUM, + number=3, + enum=Mode, + ) + resource_groups = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=ResourceGroup, + ) + allow_no_resource_group_match = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py new file mode 100644 index 0000000..2314d05 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py @@ -0,0 +1,540 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.osconfig_v1alpha.types import os_policy +from google.cloud.osconfig_v1alpha.types import osconfig_common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1alpha', + manifest={ + 'OSPolicyAssignment', + 'OSPolicyAssignmentOperationMetadata', + 'CreateOSPolicyAssignmentRequest', + 'UpdateOSPolicyAssignmentRequest', + 'GetOSPolicyAssignmentRequest', + 'ListOSPolicyAssignmentsRequest', + 'ListOSPolicyAssignmentsResponse', + 'ListOSPolicyAssignmentRevisionsRequest', + 'ListOSPolicyAssignmentRevisionsResponse', + 'DeleteOSPolicyAssignmentRequest', + }, +) + + +class OSPolicyAssignment(proto.Message): + r"""OS policy assignment is an API resource that is used to apply a set + of OS policies to a dynamically targeted group of Compute Engine VM + instances. + + An OS policy is used to define the desired state configuration for a + Compute Engine VM instance through a set of configuration resources + that provide capabilities such as installing or removing software + packages, or executing a script. + + For more information, see `OS policy and OS policy + assignment `__. + + Attributes: + name (str): + Resource name. + + Format: + ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id}`` + + This field is ignored when you create an OS policy + assignment. + description (str): + OS policy assignment description. + Length of the description is limited to 1024 + characters. + os_policies (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicy]): + Required. List of OS policies to be applied + to the VMs. + instance_filter (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.InstanceFilter): + Required. Filter to select VMs. + rollout (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.Rollout): + Required. Rollout to deploy the OS policy assignment. A + rollout is triggered in the following situations: + + 1) OSPolicyAssignment is created. + 2) OSPolicyAssignment is updated and the update contains + changes to one of the following fields: + + - instance_filter + - os_policies + + 3) OSPolicyAssignment is deleted. + revision_id (str): + Output only. The assignment revision ID + A new revision is committed whenever a rollout + is triggered for a OS policy assignment + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp that the revision + was created. + rollout_state (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.RolloutState): + Output only. OS policy assignment rollout + state + baseline (bool): + Output only. Indicates that this revision has been + successfully rolled out in this zone and new VMs will be + assigned OS policies from this revision. + + For a given OS policy assignment, there is only one revision + with a value of ``true`` for this field. + deleted (bool): + Output only. Indicates that this revision + deletes the OS policy assignment. + reconciling (bool): + Output only. Indicates that reconciliation is in progress + for the revision. This value is ``true`` when the + ``rollout_state`` is one of: + + - IN_PROGRESS + - CANCELLING + uid (str): + Output only. Server generated unique id for + the OS policy assignment resource. + """ + class RolloutState(proto.Enum): + r"""OS policy assignment rollout state""" + ROLLOUT_STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + CANCELLING = 2 + CANCELLED = 3 + SUCCEEDED = 4 + + class LabelSet(proto.Message): + r"""Message representing label set. + + - A label is a key value pair set for a VM. + - A LabelSet is a set of labels. + - Labels within a LabelSet are ANDed. In other words, a LabelSet is + applicable for a VM only if it matches all the labels in the + LabelSet. + - Example: A LabelSet with 2 labels: ``env=prod`` and + ``type=webserver`` will only be applicable for those VMs with + both labels present. + + Attributes: + labels (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.LabelSet.LabelsEntry]): + Labels are identified by key/value pairs in + this map. A VM should contain all the key/value + pairs specified in this map to be selected. + """ + + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + + class InstanceFilter(proto.Message): + r"""Message to represent the filters to select VMs for an + assignment + + Attributes: + all_ (bool): + Target all VMs in the project. If true, no + other criteria is permitted. + os_short_names (Sequence[str]): + A VM is included if it's OS short name + matches with any of the values provided in this + list. + inclusion_labels (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.LabelSet]): + List of label sets used for VM inclusion. + + If the list has more than one ``LabelSet``, the VM is + included if any of the label sets are applicable for the VM. + exclusion_labels (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.LabelSet]): + List of label sets used for VM exclusion. + If the list has more than one label set, the VM + is excluded if any of the label sets are + applicable for the VM. + + This filter is applied last in the filtering + chain and therefore a VM is guaranteed to be + excluded if it satisfies one of the below label + sets. + """ + + all_ = proto.Field( + proto.BOOL, + number=1, + ) + os_short_names = proto.RepeatedField( + proto.STRING, + number=2, + ) + inclusion_labels = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='OSPolicyAssignment.LabelSet', + ) + exclusion_labels = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='OSPolicyAssignment.LabelSet', + ) + + class Rollout(proto.Message): + r"""Message to configure the rollout at the zonal level for the + OS policy assignment. + + Attributes: + disruption_budget (google.cloud.osconfig_v1alpha.types.FixedOrPercent): + Required. The maximum number (or percentage) + of VMs per zone to disrupt at any given moment. + min_wait_duration (google.protobuf.duration_pb2.Duration): + Required. This determines the minimum duration of time to + wait after the configuration changes are applied through the + current rollout. A VM continues to count towards the + ``disruption_budget`` at least until this duration of time + has passed after configuration changes are applied. + """ + + disruption_budget = proto.Field( + proto.MESSAGE, + number=1, + message=osconfig_common.FixedOrPercent, + ) + min_wait_duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + os_policies = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=os_policy.OSPolicy, + ) + instance_filter = proto.Field( + proto.MESSAGE, + number=4, + message=InstanceFilter, + ) + rollout = proto.Field( + proto.MESSAGE, + number=5, + message=Rollout, + ) + revision_id = proto.Field( + proto.STRING, + number=6, + ) + revision_create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + rollout_state = proto.Field( + proto.ENUM, + number=9, + enum=RolloutState, + ) + baseline = proto.Field( + proto.BOOL, + number=10, + ) + deleted = proto.Field( + proto.BOOL, + number=11, + ) + reconciling = proto.Field( + proto.BOOL, + number=12, + ) + uid = proto.Field( + proto.STRING, + number=13, + ) + + +class OSPolicyAssignmentOperationMetadata(proto.Message): + r"""OS policy assignment operation metadata provided by OS policy + assignment API methods that return long running operations. + + Attributes: + os_policy_assignment (str): + Reference to the ``OSPolicyAssignment`` API resource. + + Format: + ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id@revision_id}`` + api_method (google.cloud.osconfig_v1alpha.types.OSPolicyAssignmentOperationMetadata.APIMethod): + The OS policy assignment API method. + rollout_state (google.cloud.osconfig_v1alpha.types.OSPolicyAssignmentOperationMetadata.RolloutState): + State of the rollout + rollout_start_time (google.protobuf.timestamp_pb2.Timestamp): + Rollout start time + rollout_update_time (google.protobuf.timestamp_pb2.Timestamp): + Rollout update time + """ + class APIMethod(proto.Enum): + r"""The OS policy assignment API method.""" + API_METHOD_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + + class RolloutState(proto.Enum): + r"""State of the rollout""" + ROLLOUT_STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + CANCELLING = 2 + CANCELLED = 3 + SUCCEEDED = 4 + + os_policy_assignment = proto.Field( + proto.STRING, + number=1, + ) + api_method = proto.Field( + proto.ENUM, + number=2, + enum=APIMethod, + ) + rollout_state = proto.Field( + proto.ENUM, + number=3, + enum=RolloutState, + ) + rollout_start_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + rollout_update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class CreateOSPolicyAssignmentRequest(proto.Message): + r"""A request message to create an OS policy assignment + Attributes: + parent (str): + Required. The parent resource name in the + form: projects/{project}/locations/{location} + os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): + Required. The OS policy assignment to be + created. + os_policy_assignment_id (str): + Required. The logical name of the OS policy assignment in + the project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + os_policy_assignment = proto.Field( + proto.MESSAGE, + number=2, + message='OSPolicyAssignment', + ) + os_policy_assignment_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateOSPolicyAssignmentRequest(proto.Message): + r"""A request message to update an OS policy assignment + Attributes: + os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): + Required. The updated OS policy assignment. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that controls which + fields of the assignment should be updated. + """ + + os_policy_assignment = proto.Field( + proto.MESSAGE, + number=1, + message='OSPolicyAssignment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetOSPolicyAssignmentRequest(proto.Message): + r"""A request message to get an OS policy assignment + Attributes: + name (str): + Required. The resource name of OS policy assignment. + + Format: + ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOSPolicyAssignmentsRequest(proto.Message): + r"""A request message to list OS policy assignments for a parent + resource + + Attributes: + parent (str): + Required. The parent resource name. + page_size (int): + The maximum number of assignments to return. + page_token (str): + A pagination token returned from a previous call to + ``ListOSPolicyAssignments`` that indicates where this + listing should continue from. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListOSPolicyAssignmentsResponse(proto.Message): + r"""A response message for listing all assignments under given + parent. + + Attributes: + os_policy_assignments (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment]): + The list of assignments + next_page_token (str): + The pagination token to retrieve the next + page of OS policy assignments. + """ + + @property + def raw_page(self): + return self + + os_policy_assignments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OSPolicyAssignment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListOSPolicyAssignmentRevisionsRequest(proto.Message): + r"""A request message to list revisions for a OS policy + assignment + + Attributes: + name (str): + Required. The name of the OS policy + assignment to list revisions for. + page_size (int): + The maximum number of revisions to return. + page_token (str): + A pagination token returned from a previous call to + ``ListOSPolicyAssignmentRevisions`` that indicates where + this listing should continue from. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListOSPolicyAssignmentRevisionsResponse(proto.Message): + r"""A response message for listing all revisions for a OS policy + assignment. + + Attributes: + os_policy_assignments (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment]): + The OS policy assignment revisions + next_page_token (str): + The pagination token to retrieve the next + page of OS policy assignment revisions. + """ + + @property + def raw_page(self): + return self + + os_policy_assignments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OSPolicyAssignment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteOSPolicyAssignmentRequest(proto.Message): + r"""A request message for deleting a OS policy assignment. + Attributes: + name (str): + Required. The name of the OS policy + assignment to be deleted + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.py new file mode 100644 index 0000000..ac13f0e --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.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.cloud.osconfig.v1alpha', + manifest={ + 'FixedOrPercent', + }, +) + + +class FixedOrPercent(proto.Message): + r"""Message encapsulating a value that can be either absolute + ("fixed") or relative ("percent") to a value. + + Attributes: + fixed (int): + Specifies a fixed value. + percent (int): + Specifies the relative value defined as a + percentage, which will be multiplied by a + reference value. + """ + + fixed = proto.Field( + proto.INT32, + number=1, + oneof='mode', + ) + percent = proto.Field( + proto.INT32, + number=2, + oneof='mode', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_service.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_service.py new file mode 100644 index 0000000..0956e1b --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_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.cloud.osconfig.v1alpha', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py new file mode 100644 index 0000000..3f59e94 --- /dev/null +++ b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py @@ -0,0 +1,451 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.osconfig.v1alpha', + manifest={ + 'VulnerabilityReport', + 'GetVulnerabilityReportRequest', + 'ListVulnerabilityReportsRequest', + 'ListVulnerabilityReportsResponse', + 'CVSSv3', + }, +) + + +class VulnerabilityReport(proto.Message): + r"""This API resource represents the vulnerability report for a + specified Compute Engine virtual machine (VM) instance at a given + point in time. + + For more information, see `Vulnerability + reports `__. + + Attributes: + name (str): + Output only. The ``vulnerabilityReport`` API resource name. + + Format: + ``projects/{project_number}/locations/{location}/instances/{instance_id}/vulnerabilityReport`` + vulnerabilities (Sequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability]): + Output only. List of vulnerabilities + affecting the VM. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp for when the last + vulnerability report was generated for the VM. + """ + + class Vulnerability(proto.Message): + r"""A vulnerability affecting the VM instance. + Attributes: + details (google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Details): + Contains metadata as per the upstream feed of + the operating system and NVD. + installed_inventory_item_ids (Sequence[str]): + Corresponds to the ``INSTALLED_PACKAGE`` inventory item on + the VM. This field displays the inventory items affected by + this vulnerability. If the vulnerability report was not + updated after the VM inventory update, these values might + not display in VM inventory. For some distros, this field + may be empty. + available_inventory_item_ids (Sequence[str]): + Corresponds to the ``AVAILABLE_PACKAGE`` inventory item on + the VM. If the vulnerability report was not updated after + the VM inventory update, these values might not display in + VM inventory. If there is no available fix, the field is + empty. The ``inventory_item`` value specifies the latest + ``SoftwarePackage`` available to the VM that fixes the + vulnerability. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp for when the vulnerability was + first detected. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp for when the vulnerability was + last modified. + """ + + class Details(proto.Message): + r"""Contains metadata information for the vulnerability. This + information is collected from the upstream feed of the operating + system. + + Attributes: + cve (str): + The CVE of the vulnerability. CVE cannot be + empty and the combination of should be unique across + vulnerabilities for a VM. + cvss_v2_score (float): + The CVSS V2 score of this vulnerability. CVSS + V2 score is on a scale of 0 - 10 where 0 + indicates low severity and 10 indicates high + severity. + cvss_v3 (google.cloud.osconfig_v1alpha.types.CVSSv3): + The full description of the CVSSv3 for this + vulnerability from NVD. + severity (str): + Assigned severity/impact ranking from the + distro. + description (str): + The note or description describing the + vulnerability from the distro. + references (Sequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Details.Reference]): + Corresponds to the references attached to the + ``VulnerabilityDetails``. + """ + + class Reference(proto.Message): + r"""A reference for this vulnerability. + Attributes: + url (str): + The url of the reference. + """ + + url = proto.Field( + proto.STRING, + number=1, + ) + + cve = proto.Field( + proto.STRING, + number=1, + ) + cvss_v2_score = proto.Field( + proto.FLOAT, + number=2, + ) + cvss_v3 = proto.Field( + proto.MESSAGE, + number=3, + message='CVSSv3', + ) + severity = proto.Field( + proto.STRING, + number=4, + ) + description = proto.Field( + proto.STRING, + number=5, + ) + references = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='VulnerabilityReport.Vulnerability.Details.Reference', + ) + + details = proto.Field( + proto.MESSAGE, + number=1, + message='VulnerabilityReport.Vulnerability.Details', + ) + installed_inventory_item_ids = proto.RepeatedField( + proto.STRING, + number=2, + ) + available_inventory_item_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + vulnerabilities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Vulnerability, + ) + update_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GetVulnerabilityReportRequest(proto.Message): + r"""A request message for getting the vulnerability report for + the specified VM. + + Attributes: + name (str): + Required. API resource name for vulnerability resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, either + Compute Engine ``instance-id`` or ``instance-name`` can be + provided. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListVulnerabilityReportsRequest(proto.Message): + r"""A request message for listing vulnerability reports for all + VM instances in the specified location. + + Attributes: + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, only + ``-`` character is supported to list vulnerability reports + across VMs. + page_size (int): + The maximum number of results to return. + page_token (str): + A pagination token returned from a previous call to + ``ListVulnerabilityReports`` that indicates where this + listing should continue from. + filter (str): + If provided, this field specifies the criteria that must be + met by a ``vulnerabilityReport`` API resource to be included + in the response. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListVulnerabilityReportsResponse(proto.Message): + r"""A response message for listing vulnerability reports for all + VM instances in the specified location. + + Attributes: + vulnerability_reports (Sequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport]): + List of vulnerabilityReport objects. + next_page_token (str): + The pagination token to retrieve the next + page of vulnerabilityReports object. + """ + + @property + def raw_page(self): + return self + + vulnerability_reports = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VulnerabilityReport', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CVSSv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + For details, see https://www.first.org/cvss/specification- + document + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + https://www.first.org/cvss/specification- + document#Base-Metrics + exploitability_score (float): + The Exploitability sub-score equation is + derived from the Base Exploitability metrics. + https://www.first.org/cvss/specification- + document#2-1-Exploitability-Metrics + impact_score (float): + The Impact sub-score equation is derived from + the Base Impact metrics. + attack_vector (google.cloud.osconfig_v1alpha.types.CVSSv3.AttackVector): + This metric reflects the context by which + vulnerability exploitation is possible. + attack_complexity (google.cloud.osconfig_v1alpha.types.CVSSv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.osconfig_v1alpha.types.CVSSv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.osconfig_v1alpha.types.CVSSv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.osconfig_v1alpha.types.CVSSv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score = proto.Field( + proto.FLOAT, + number=1, + ) + exploitability_score = proto.Field( + proto.FLOAT, + number=2, + ) + impact_score = proto.Field( + proto.FLOAT, + number=3, + ) + attack_vector = proto.Field( + proto.ENUM, + number=5, + enum=AttackVector, + ) + attack_complexity = proto.Field( + proto.ENUM, + number=6, + enum=AttackComplexity, + ) + privileges_required = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py new file mode 100644 index 0000000..88bde29 --- /dev/null +++ b/owl-bot-staging/v1alpha/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/cloud/osconfig_v1alpha/', + '--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/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py new file mode 100644 index 0000000..2e964d4 --- /dev/null +++ b/owl-bot-staging/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py @@ -0,0 +1,187 @@ +#! /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 osconfigCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_os_policy_assignment': ('parent', 'os_policy_assignment', 'os_policy_assignment_id', ), + 'delete_os_policy_assignment': ('name', ), + 'get_instance_os_policies_compliance': ('name', ), + 'get_inventory': ('name', 'view', ), + 'get_os_policy_assignment': ('name', ), + 'get_vulnerability_report': ('name', ), + 'list_instance_os_policies_compliances': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_inventories': ('parent', 'view', 'page_size', 'page_token', 'filter', ), + 'list_os_policy_assignment_revisions': ('name', 'page_size', 'page_token', ), + 'list_os_policy_assignments': ('parent', 'page_size', 'page_token', ), + 'list_vulnerability_reports': ('parent', 'page_size', 'page_token', 'filter', ), + 'update_os_policy_assignment': ('os_policy_assignment', 'update_mask', ), + } + + 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=osconfigCallTransformer(), +): + """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 osconfig 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/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py new file mode 100644 index 0000000..903433f --- /dev/null +++ b/owl-bot-staging/v1alpha/setup.py @@ -0,0 +1,54 @@ +# -*- 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-cloud-osconfig', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.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', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/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/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/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/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/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/v1alpha/tests/unit/gapic/osconfig_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/__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/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py b/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py new file mode 100644 index 0000000..0da6262 --- /dev/null +++ b/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py @@ -0,0 +1,4846 @@ +# -*- 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 future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import OsConfigZonalServiceAsyncClient +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import OsConfigZonalServiceClient +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import pagers +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import transports +from google.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.osconfig_v1alpha.types import config_common +from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance +from google.cloud.osconfig_v1alpha.types import inventory +from google.cloud.osconfig_v1alpha.types import os_policy +from google.cloud.osconfig_v1alpha.types import os_policy_assignments +from google.cloud.osconfig_v1alpha.types import osconfig_common +from google.cloud.osconfig_v1alpha.types import vulnerability +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_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 OsConfigZonalServiceClient._get_default_mtls_endpoint(None) is None + assert OsConfigZonalServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OsConfigZonalServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OsConfigZonalServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OsConfigZonalServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OsConfigZonalServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + OsConfigZonalServiceClient, + OsConfigZonalServiceAsyncClient, +]) +def test_os_config_zonal_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 == 'osconfig.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.OsConfigZonalServiceGrpcTransport, "grpc"), + (transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_os_config_zonal_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + OsConfigZonalServiceClient, + OsConfigZonalServiceAsyncClient, +]) +def test_os_config_zonal_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 == 'osconfig.googleapis.com:443' + + +def test_os_config_zonal_service_client_get_transport_class(): + transport = OsConfigZonalServiceClient.get_transport_class() + available_transports = [ + transports.OsConfigZonalServiceGrpcTransport, + ] + assert transport in available_transports + + transport = OsConfigZonalServiceClient.get_transport_class("grpc") + assert transport == transports.OsConfigZonalServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc"), + (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(OsConfigZonalServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceClient)) +@mock.patch.object(OsConfigZonalServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceAsyncClient)) +def test_os_config_zonal_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(OsConfigZonalServiceClient, '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(OsConfigZonalServiceClient, '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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc", "true"), + (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc", "false"), + (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(OsConfigZonalServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceClient)) +@mock.patch.object(OsConfigZonalServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_os_config_zonal_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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + # 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, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc"), + (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_os_config_zonal_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, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc"), + (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_os_config_zonal_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, + always_use_jwt_access=True, + ) + + +def test_os_config_zonal_service_client_client_options_from_dict(): + with mock.patch('google.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OsConfigZonalServiceClient( + 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, + always_use_jwt_access=True, + ) + + +def test_create_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.CreateOSPolicyAssignmentRequest): + client = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_os_policy_assignment_from_dict(): + test_create_os_policy_assignment(request_type=dict) + + +def test_create_os_policy_assignment_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 = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + client.create_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.CreateOSPolicyAssignmentRequest): + client = OsConfigZonalServiceAsyncClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_async_from_dict(): + await test_create_os_policy_assignment_async(request_type=dict) + + +def test_create_os_policy_assignment_field_headers(): + client = OsConfigZonalServiceClient( + 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 = os_policy_assignments.CreateOSPolicyAssignmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_os_policy_assignment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_os_policy_assignment(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_os_policy_assignment_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = os_policy_assignments.CreateOSPolicyAssignmentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_os_policy_assignment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_os_policy_assignment(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_create_os_policy_assignment_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_os_policy_assignment( + parent='parent_value', + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + os_policy_assignment_id='os_policy_assignment_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') + assert args[0].os_policy_assignment_id == 'os_policy_assignment_id_value' + + +def test_create_os_policy_assignment_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_os_policy_assignment( + os_policy_assignments.CreateOSPolicyAssignmentRequest(), + parent='parent_value', + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + os_policy_assignment_id='os_policy_assignment_id_value', + ) + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_os_policy_assignment( + parent='parent_value', + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + os_policy_assignment_id='os_policy_assignment_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') + assert args[0].os_policy_assignment_id == 'os_policy_assignment_id_value' + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_os_policy_assignment( + os_policy_assignments.CreateOSPolicyAssignmentRequest(), + parent='parent_value', + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + os_policy_assignment_id='os_policy_assignment_id_value', + ) + + +def test_update_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.UpdateOSPolicyAssignmentRequest): + client = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_os_policy_assignment_from_dict(): + test_update_os_policy_assignment(request_type=dict) + + +def test_update_os_policy_assignment_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 = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + client.update_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.UpdateOSPolicyAssignmentRequest): + client = OsConfigZonalServiceAsyncClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_async_from_dict(): + await test_update_os_policy_assignment_async(request_type=dict) + + +def test_update_os_policy_assignment_field_headers(): + client = OsConfigZonalServiceClient( + 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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + request.os_policy_assignment.name = 'os_policy_assignment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_os_policy_assignment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_os_policy_assignment(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', + 'os_policy_assignment.name=os_policy_assignment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + request.os_policy_assignment.name = 'os_policy_assignment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_os_policy_assignment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_os_policy_assignment(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', + 'os_policy_assignment.name=os_policy_assignment.name/value', + ) in kw['metadata'] + + +def test_update_os_policy_assignment_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_os_policy_assignment( + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_os_policy_assignment_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_os_policy_assignment( + os_policy_assignments.UpdateOSPolicyAssignmentRequest(), + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_os_policy_assignment( + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_os_policy_assignment( + os_policy_assignments.UpdateOSPolicyAssignmentRequest(), + os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.GetOSPolicyAssignmentRequest): + client = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.OSPolicyAssignment( + name='name_value', + description='description_value', + revision_id='revision_id_value', + rollout_state=os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS, + baseline=True, + deleted=True, + reconciling=True, + uid='uid_value', + ) + response = client.get_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, os_policy_assignments.OSPolicyAssignment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.rollout_state == os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS + assert response.baseline is True + assert response.deleted is True + assert response.reconciling is True + assert response.uid == 'uid_value' + + +def test_get_os_policy_assignment_from_dict(): + test_get_os_policy_assignment(request_type=dict) + + +def test_get_os_policy_assignment_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 = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + client.get_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.GetOSPolicyAssignmentRequest): + client = OsConfigZonalServiceAsyncClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.OSPolicyAssignment( + name='name_value', + description='description_value', + revision_id='revision_id_value', + rollout_state=os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS, + baseline=True, + deleted=True, + reconciling=True, + uid='uid_value', + )) + response = await client.get_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, os_policy_assignments.OSPolicyAssignment) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.rollout_state == os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS + assert response.baseline is True + assert response.deleted is True + assert response.reconciling is True + assert response.uid == 'uid_value' + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_async_from_dict(): + await test_get_os_policy_assignment_async(request_type=dict) + + +def test_get_os_policy_assignment_field_headers(): + client = OsConfigZonalServiceClient( + 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 = os_policy_assignments.GetOSPolicyAssignmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment), + '__call__') as call: + call.return_value = os_policy_assignments.OSPolicyAssignment() + client.get_os_policy_assignment(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_os_policy_assignment_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = os_policy_assignments.GetOSPolicyAssignmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.OSPolicyAssignment()) + await client.get_os_policy_assignment(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_get_os_policy_assignment_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.OSPolicyAssignment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_os_policy_assignment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_os_policy_assignment_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_os_policy_assignment( + os_policy_assignments.GetOSPolicyAssignmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.OSPolicyAssignment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.OSPolicyAssignment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_os_policy_assignment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_os_policy_assignment( + os_policy_assignments.GetOSPolicyAssignmentRequest(), + name='name_value', + ) + + +def test_list_os_policy_assignments(transport: str = 'grpc', request_type=os_policy_assignments.ListOSPolicyAssignmentsRequest): + client = OsConfigZonalServiceClient( + 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_os_policy_assignments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_os_policy_assignments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_os_policy_assignments_from_dict(): + test_list_os_policy_assignments(request_type=dict) + + +def test_list_os_policy_assignments_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 = OsConfigZonalServiceClient( + 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_os_policy_assignments), + '__call__') as call: + client.list_os_policy_assignments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.ListOSPolicyAssignmentsRequest): + client = OsConfigZonalServiceAsyncClient( + 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_os_policy_assignments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_os_policy_assignments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_async_from_dict(): + await test_list_os_policy_assignments_async(request_type=dict) + + +def test_list_os_policy_assignments_field_headers(): + client = OsConfigZonalServiceClient( + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__') as call: + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() + client.list_os_policy_assignments(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_os_policy_assignments_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentsResponse()) + await client.list_os_policy_assignments(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_os_policy_assignments_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_os_policy_assignments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_os_policy_assignments_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_os_policy_assignments( + os_policy_assignments.ListOSPolicyAssignmentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_os_policy_assignments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_os_policy_assignments( + os_policy_assignments.ListOSPolicyAssignmentsRequest(), + parent='parent_value', + ) + + +def test_list_os_policy_assignments_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_os_policy_assignments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, os_policy_assignments.OSPolicyAssignment) + for i in results) + +def test_list_os_policy_assignments_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_os_policy_assignments(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_os_policy_assignments_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_os_policy_assignments(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, os_policy_assignments.OSPolicyAssignment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_os_policy_assignments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_os_policy_assignment_revisions(transport: str = 'grpc', request_type=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest): + client = OsConfigZonalServiceClient( + 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_os_policy_assignment_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_os_policy_assignment_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_os_policy_assignment_revisions_from_dict(): + test_list_os_policy_assignment_revisions(request_type=dict) + + +def test_list_os_policy_assignment_revisions_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 = OsConfigZonalServiceClient( + 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_os_policy_assignment_revisions), + '__call__') as call: + client.list_os_policy_assignment_revisions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest): + client = OsConfigZonalServiceAsyncClient( + 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_os_policy_assignment_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_os_policy_assignment_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentRevisionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_async_from_dict(): + await test_list_os_policy_assignment_revisions_async(request_type=dict) + + +def test_list_os_policy_assignment_revisions_field_headers(): + client = OsConfigZonalServiceClient( + 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__') as call: + call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse()) + await client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_os_policy_assignment_revisions( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_list_os_policy_assignment_revisions_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_os_policy_assignment_revisions( + os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_os_policy_assignment_revisions( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_os_policy_assignment_revisions( + os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(), + name='name_value', + ) + + +def test_list_os_policy_assignment_revisions_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.list_os_policy_assignment_revisions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, os_policy_assignments.OSPolicyAssignment) + for i in results) + +def test_list_os_policy_assignment_revisions_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_os_policy_assignment_revisions(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_os_policy_assignment_revisions_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_os_policy_assignment_revisions(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, os_policy_assignments.OSPolicyAssignment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='abc', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], + next_page_token='def', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token='ghi', + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_os_policy_assignment_revisions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.DeleteOSPolicyAssignmentRequest): + client = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_os_policy_assignment_from_dict(): + test_delete_os_policy_assignment(request_type=dict) + + +def test_delete_os_policy_assignment_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 = OsConfigZonalServiceClient( + 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_os_policy_assignment), + '__call__') as call: + client.delete_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.DeleteOSPolicyAssignmentRequest): + client = OsConfigZonalServiceAsyncClient( + 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_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_async_from_dict(): + await test_delete_os_policy_assignment_async(request_type=dict) + + +def test_delete_os_policy_assignment_field_headers(): + client = OsConfigZonalServiceClient( + 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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_os_policy_assignment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_os_policy_assignment(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_os_policy_assignment_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_os_policy_assignment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_os_policy_assignment(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_os_policy_assignment_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_os_policy_assignment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_delete_os_policy_assignment_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_os_policy_assignment( + os_policy_assignments.DeleteOSPolicyAssignmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_os_policy_assignment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_os_policy_assignment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_os_policy_assignment( + os_policy_assignments.DeleteOSPolicyAssignmentRequest(), + name='name_value', + ) + + +def test_get_instance_os_policies_compliance(transport: str = 'grpc', request_type=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest): + client = OsConfigZonalServiceClient( + 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_instance_os_policies_compliance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance( + name='name_value', + instance='instance_value', + state=config_common.OSPolicyComplianceState.COMPLIANT, + detailed_state='detailed_state_value', + detailed_state_reason='detailed_state_reason_value', + last_compliance_run_id='last_compliance_run_id_value', + ) + response = client.get_instance_os_policies_compliance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, instance_os_policies_compliance.InstanceOSPoliciesCompliance) + assert response.name == 'name_value' + assert response.instance == 'instance_value' + assert response.state == config_common.OSPolicyComplianceState.COMPLIANT + assert response.detailed_state == 'detailed_state_value' + assert response.detailed_state_reason == 'detailed_state_reason_value' + assert response.last_compliance_run_id == 'last_compliance_run_id_value' + + +def test_get_instance_os_policies_compliance_from_dict(): + test_get_instance_os_policies_compliance(request_type=dict) + + +def test_get_instance_os_policies_compliance_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 = OsConfigZonalServiceClient( + 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_instance_os_policies_compliance), + '__call__') as call: + client.get_instance_os_policies_compliance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() + + +@pytest.mark.asyncio +async def test_get_instance_os_policies_compliance_async(transport: str = 'grpc_asyncio', request_type=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest): + client = OsConfigZonalServiceAsyncClient( + 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_instance_os_policies_compliance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.InstanceOSPoliciesCompliance( + name='name_value', + instance='instance_value', + state=config_common.OSPolicyComplianceState.COMPLIANT, + detailed_state='detailed_state_value', + detailed_state_reason='detailed_state_reason_value', + last_compliance_run_id='last_compliance_run_id_value', + )) + response = await client.get_instance_os_policies_compliance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, instance_os_policies_compliance.InstanceOSPoliciesCompliance) + assert response.name == 'name_value' + assert response.instance == 'instance_value' + assert response.state == config_common.OSPolicyComplianceState.COMPLIANT + assert response.detailed_state == 'detailed_state_value' + assert response.detailed_state_reason == 'detailed_state_reason_value' + assert response.last_compliance_run_id == 'last_compliance_run_id_value' + + +@pytest.mark.asyncio +async def test_get_instance_os_policies_compliance_async_from_dict(): + await test_get_instance_os_policies_compliance_async(request_type=dict) + + +def test_get_instance_os_policies_compliance_field_headers(): + client = OsConfigZonalServiceClient( + 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 = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_os_policies_compliance), + '__call__') as call: + call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance() + client.get_instance_os_policies_compliance(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_instance_os_policies_compliance_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_os_policies_compliance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.InstanceOSPoliciesCompliance()) + await client.get_instance_os_policies_compliance(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_get_instance_os_policies_compliance_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_os_policies_compliance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance_os_policies_compliance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_instance_os_policies_compliance_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance_os_policies_compliance( + instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_instance_os_policies_compliance_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_os_policies_compliance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.InstanceOSPoliciesCompliance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance_os_policies_compliance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_instance_os_policies_compliance_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_instance_os_policies_compliance( + instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(), + name='name_value', + ) + + +def test_list_instance_os_policies_compliances(transport: str = 'grpc', request_type=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest): + client = OsConfigZonalServiceClient( + 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_instance_os_policies_compliances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_instance_os_policies_compliances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstanceOSPoliciesCompliancesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_instance_os_policies_compliances_from_dict(): + test_list_instance_os_policies_compliances(request_type=dict) + + +def test_list_instance_os_policies_compliances_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 = OsConfigZonalServiceClient( + 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_instance_os_policies_compliances), + '__call__') as call: + client.list_instance_os_policies_compliances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() + + +@pytest.mark.asyncio +async def test_list_instance_os_policies_compliances_async(transport: str = 'grpc_asyncio', request_type=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest): + client = OsConfigZonalServiceAsyncClient( + 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_instance_os_policies_compliances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_instance_os_policies_compliances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstanceOSPoliciesCompliancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_instance_os_policies_compliances_async_from_dict(): + await test_list_instance_os_policies_compliances_async(request_type=dict) + + +def test_list_instance_os_policies_compliances_field_headers(): + client = OsConfigZonalServiceClient( + 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__') as call: + call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse() + client.list_instance_os_policies_compliances(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_instance_os_policies_compliances_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse()) + await client.list_instance_os_policies_compliances(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_instance_os_policies_compliances_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instance_os_policies_compliances( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_instance_os_policies_compliances_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instance_os_policies_compliances( + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_instance_os_policies_compliances_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instance_os_policies_compliances( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_instance_os_policies_compliances_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_instance_os_policies_compliances( + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(), + parent='parent_value', + ) + + +def test_list_instance_os_policies_compliances_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='abc', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[], + next_page_token='def', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='ghi', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instance_os_policies_compliances(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, instance_os_policies_compliance.InstanceOSPoliciesCompliance) + for i in results) + +def test_list_instance_os_policies_compliances_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='abc', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[], + next_page_token='def', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='ghi', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instance_os_policies_compliances(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_instance_os_policies_compliances_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='abc', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[], + next_page_token='def', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='ghi', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instance_os_policies_compliances(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, instance_os_policies_compliance.InstanceOSPoliciesCompliance) + for i in responses) + +@pytest.mark.asyncio +async def test_list_instance_os_policies_compliances_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instance_os_policies_compliances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='abc', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[], + next_page_token='def', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + next_page_token='ghi', + ), + instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( + instance_os_policies_compliances=[ + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + instance_os_policies_compliance.InstanceOSPoliciesCompliance(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_instance_os_policies_compliances(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_inventory(transport: str = 'grpc', request_type=inventory.GetInventoryRequest): + client = OsConfigZonalServiceClient( + 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_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.Inventory( + name='name_value', + ) + response = client.get_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.GetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, inventory.Inventory) + assert response.name == 'name_value' + + +def test_get_inventory_from_dict(): + test_get_inventory(request_type=dict) + + +def test_get_inventory_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 = OsConfigZonalServiceClient( + 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_inventory), + '__call__') as call: + client.get_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.GetInventoryRequest() + + +@pytest.mark.asyncio +async def test_get_inventory_async(transport: str = 'grpc_asyncio', request_type=inventory.GetInventoryRequest): + client = OsConfigZonalServiceAsyncClient( + 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_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory( + name='name_value', + )) + response = await client.get_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.GetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, inventory.Inventory) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_inventory_async_from_dict(): + await test_get_inventory_async(request_type=dict) + + +def test_get_inventory_field_headers(): + client = OsConfigZonalServiceClient( + 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 = inventory.GetInventoryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_inventory), + '__call__') as call: + call.return_value = inventory.Inventory() + client.get_inventory(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_inventory_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = inventory.GetInventoryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_inventory), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory()) + await client.get_inventory(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_get_inventory_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.Inventory() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_inventory_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_inventory( + inventory.GetInventoryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_inventory_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_inventory), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.Inventory() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_inventory( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_inventory_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_inventory( + inventory.GetInventoryRequest(), + name='name_value', + ) + + +def test_list_inventories(transport: str = 'grpc', request_type=inventory.ListInventoriesRequest): + client = OsConfigZonalServiceClient( + 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_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.ListInventoriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.ListInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInventoriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_inventories_from_dict(): + test_list_inventories(request_type=dict) + + +def test_list_inventories_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 = OsConfigZonalServiceClient( + 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_inventories), + '__call__') as call: + client.list_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.ListInventoriesRequest() + + +@pytest.mark.asyncio +async def test_list_inventories_async(transport: str = 'grpc_asyncio', request_type=inventory.ListInventoriesRequest): + client = OsConfigZonalServiceAsyncClient( + 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_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(inventory.ListInventoriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.ListInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInventoriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_inventories_async_from_dict(): + await test_list_inventories_async(request_type=dict) + + +def test_list_inventories_field_headers(): + client = OsConfigZonalServiceClient( + 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 = inventory.ListInventoriesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__') as call: + call.return_value = inventory.ListInventoriesResponse() + client.list_inventories(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_inventories_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = inventory.ListInventoriesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.ListInventoriesResponse()) + await client.list_inventories(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_inventories_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.ListInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_inventories_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_inventories( + inventory.ListInventoriesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_inventories_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.ListInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.ListInventoriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_inventories( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_inventories_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_inventories( + inventory.ListInventoriesRequest(), + parent='parent_value', + ) + + +def test_list_inventories_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token='abc', + ), + inventory.ListInventoriesResponse( + inventories=[], + next_page_token='def', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + ], + next_page_token='ghi', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_inventories(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, inventory.Inventory) + for i in results) + +def test_list_inventories_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token='abc', + ), + inventory.ListInventoriesResponse( + inventories=[], + next_page_token='def', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + ], + next_page_token='ghi', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + ], + ), + RuntimeError, + ) + pages = list(client.list_inventories(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_inventories_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token='abc', + ), + inventory.ListInventoriesResponse( + inventories=[], + next_page_token='def', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + ], + next_page_token='ghi', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_inventories(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, inventory.Inventory) + for i in responses) + +@pytest.mark.asyncio +async def test_list_inventories_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token='abc', + ), + inventory.ListInventoriesResponse( + inventories=[], + next_page_token='def', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + ], + next_page_token='ghi', + ), + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_inventories(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_vulnerability_report(transport: str = 'grpc', request_type=vulnerability.GetVulnerabilityReportRequest): + client = OsConfigZonalServiceClient( + 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_vulnerability_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.VulnerabilityReport( + name='name_value', + ) + response = client.get_vulnerability_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.GetVulnerabilityReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, vulnerability.VulnerabilityReport) + assert response.name == 'name_value' + + +def test_get_vulnerability_report_from_dict(): + test_get_vulnerability_report(request_type=dict) + + +def test_get_vulnerability_report_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 = OsConfigZonalServiceClient( + 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_vulnerability_report), + '__call__') as call: + client.get_vulnerability_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.GetVulnerabilityReportRequest() + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_async(transport: str = 'grpc_asyncio', request_type=vulnerability.GetVulnerabilityReportRequest): + client = OsConfigZonalServiceAsyncClient( + 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_vulnerability_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.VulnerabilityReport( + name='name_value', + )) + response = await client.get_vulnerability_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.GetVulnerabilityReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, vulnerability.VulnerabilityReport) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_async_from_dict(): + await test_get_vulnerability_report_async(request_type=dict) + + +def test_get_vulnerability_report_field_headers(): + client = OsConfigZonalServiceClient( + 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 = vulnerability.GetVulnerabilityReportRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), + '__call__') as call: + call.return_value = vulnerability.VulnerabilityReport() + client.get_vulnerability_report(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_vulnerability_report_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = vulnerability.GetVulnerabilityReportRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.VulnerabilityReport()) + await client.get_vulnerability_report(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_get_vulnerability_report_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.VulnerabilityReport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_vulnerability_report( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_vulnerability_report_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_vulnerability_report( + vulnerability.GetVulnerabilityReportRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.VulnerabilityReport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.VulnerabilityReport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_vulnerability_report( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_vulnerability_report( + vulnerability.GetVulnerabilityReportRequest(), + name='name_value', + ) + + +def test_list_vulnerability_reports(transport: str = 'grpc', request_type=vulnerability.ListVulnerabilityReportsRequest): + client = OsConfigZonalServiceClient( + 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_vulnerability_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.ListVulnerabilityReportsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_vulnerability_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.ListVulnerabilityReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVulnerabilityReportsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_vulnerability_reports_from_dict(): + test_list_vulnerability_reports(request_type=dict) + + +def test_list_vulnerability_reports_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 = OsConfigZonalServiceClient( + 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_vulnerability_reports), + '__call__') as call: + client.list_vulnerability_reports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.ListVulnerabilityReportsRequest() + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_async(transport: str = 'grpc_asyncio', request_type=vulnerability.ListVulnerabilityReportsRequest): + client = OsConfigZonalServiceAsyncClient( + 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_vulnerability_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.ListVulnerabilityReportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_vulnerability_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.ListVulnerabilityReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVulnerabilityReportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_async_from_dict(): + await test_list_vulnerability_reports_async(request_type=dict) + + +def test_list_vulnerability_reports_field_headers(): + client = OsConfigZonalServiceClient( + 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 = vulnerability.ListVulnerabilityReportsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__') as call: + call.return_value = vulnerability.ListVulnerabilityReportsResponse() + client.list_vulnerability_reports(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_vulnerability_reports_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + 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 = vulnerability.ListVulnerabilityReportsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.ListVulnerabilityReportsResponse()) + await client.list_vulnerability_reports(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_vulnerability_reports_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.ListVulnerabilityReportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_vulnerability_reports( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +def test_list_vulnerability_reports_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_vulnerability_reports( + vulnerability.ListVulnerabilityReportsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.ListVulnerabilityReportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.ListVulnerabilityReportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_vulnerability_reports( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_vulnerability_reports( + vulnerability.ListVulnerabilityReportsRequest(), + parent='parent_value', + ) + + +def test_list_vulnerability_reports_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token='abc', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], + next_page_token='def', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + ], + next_page_token='ghi', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_vulnerability_reports(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, vulnerability.VulnerabilityReport) + for i in results) + +def test_list_vulnerability_reports_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token='abc', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], + next_page_token='def', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + ], + next_page_token='ghi', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_vulnerability_reports(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_vulnerability_reports_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token='abc', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], + next_page_token='def', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + ], + next_page_token='ghi', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_vulnerability_reports(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, vulnerability.VulnerabilityReport) + for i in responses) + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token='abc', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], + next_page_token='def', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + ], + next_page_token='ghi', + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_vulnerability_reports(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigZonalServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigZonalServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OsConfigZonalServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OsConfigZonalServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, +]) +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 = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OsConfigZonalServiceGrpcTransport, + ) + +def test_os_config_zonal_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OsConfigZonalServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_os_config_zonal_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OsConfigZonalServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_os_policy_assignment', + 'update_os_policy_assignment', + 'get_os_policy_assignment', + 'list_os_policy_assignments', + 'list_os_policy_assignment_revisions', + 'delete_os_policy_assignment', + 'get_instance_os_policies_compliance', + 'list_instance_os_policies_compliances', + 'get_inventory', + 'list_inventories', + 'get_vulnerability_report', + 'list_vulnerability_reports', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_os_config_zonal_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.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigZonalServiceTransport( + 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', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_os_config_zonal_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.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigZonalServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_os_config_zonal_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.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigZonalServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_os_config_zonal_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) + OsConfigZonalServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_os_config_zonal_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) + OsConfigZonalServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_os_config_zonal_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',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_os_config_zonal_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', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OsConfigZonalServiceGrpcTransport, grpc_helpers), + (transports.OsConfigZonalServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_os_config_zonal_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( + "osconfig.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="osconfig.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.OsConfigZonalServiceGrpcTransport, transports.OsConfigZonalServiceGrpcAsyncIOTransport]) +def test_os_config_zonal_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=None, + 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_os_config_zonal_service_host_no_port(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com'), + ) + assert client.transport._host == 'osconfig.googleapis.com:443' + + +def test_os_config_zonal_service_host_with_port(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com:8000'), + ) + assert client.transport._host == 'osconfig.googleapis.com:8000' + +def test_os_config_zonal_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OsConfigZonalServiceGrpcTransport( + 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_os_config_zonal_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OsConfigZonalServiceGrpcAsyncIOTransport( + 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.OsConfigZonalServiceGrpcTransport, transports.OsConfigZonalServiceGrpcAsyncIOTransport]) +def test_os_config_zonal_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=None, + 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.OsConfigZonalServiceGrpcTransport, transports.OsConfigZonalServiceGrpcAsyncIOTransport]) +def test_os_config_zonal_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=None, + 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_os_config_zonal_service_grpc_lro_client(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_os_config_zonal_service_grpc_lro_async_client(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_instance_path(): + project = "squid" + location = "clam" + instance = "whelk" + expected = "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + actual = OsConfigZonalServiceClient.instance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", + } + path = OsConfigZonalServiceClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_instance_path(path) + assert expected == actual + +def test_instance_os_policies_compliance_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" + expected = "projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}".format(project=project, location=location, instance=instance, ) + actual = OsConfigZonalServiceClient.instance_os_policies_compliance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_os_policies_compliance_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "instance": "abalone", + } + path = OsConfigZonalServiceClient.instance_os_policies_compliance_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_instance_os_policies_compliance_path(path) + assert expected == actual + +def test_inventory_path(): + project = "squid" + location = "clam" + instance = "whelk" + expected = "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) + actual = OsConfigZonalServiceClient.inventory_path(project, location, instance) + assert expected == actual + + +def test_parse_inventory_path(): + expected = { + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", + } + path = OsConfigZonalServiceClient.inventory_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_inventory_path(path) + assert expected == actual + +def test_os_policy_assignment_path(): + project = "cuttlefish" + location = "mussel" + os_policy_assignment = "winkle" + expected = "projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}".format(project=project, location=location, os_policy_assignment=os_policy_assignment, ) + actual = OsConfigZonalServiceClient.os_policy_assignment_path(project, location, os_policy_assignment) + assert expected == actual + + +def test_parse_os_policy_assignment_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "os_policy_assignment": "abalone", + } + path = OsConfigZonalServiceClient.os_policy_assignment_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_os_policy_assignment_path(path) + assert expected == actual + +def test_vulnerability_report_path(): + project = "squid" + location = "clam" + instance = "whelk" + expected = "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format(project=project, location=location, instance=instance, ) + actual = OsConfigZonalServiceClient.vulnerability_report_path(project, location, instance) + assert expected == actual + + +def test_parse_vulnerability_report_path(): + expected = { + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", + } + path = OsConfigZonalServiceClient.vulnerability_report_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_vulnerability_report_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OsConfigZonalServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = OsConfigZonalServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = OsConfigZonalServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = OsConfigZonalServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OsConfigZonalServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = OsConfigZonalServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = OsConfigZonalServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = OsConfigZonalServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = OsConfigZonalServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = OsConfigZonalServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.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.OsConfigZonalServiceTransport, '_prep_wrapped_messages') as prep: + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OsConfigZonalServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OsConfigZonalServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 2f61c00c808eae1a805b0fb87e5a42d5e3cdd060 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 30 Aug 2021 10:48:47 +0000 Subject: [PATCH 2/2] =?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/main/packages/owl-bot/README.md --- google/cloud/osconfig_v1/types/inventory.py | 42 + .../cloud/osconfig_v1alpha/types/inventory.py | 42 + 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 -- owl-bot-staging/v1/docs/index.rst | 7 - .../v1/docs/osconfig_v1/os_config_service.rst | 10 - .../v1/docs/osconfig_v1/services.rst | 6 - owl-bot-staging/v1/docs/osconfig_v1/types.rst | 7 - .../v1/google/cloud/osconfig/__init__.py | 91 - .../v1/google/cloud/osconfig/py.typed | 2 - .../v1/google/cloud/osconfig_v1/__init__.py | 92 - .../cloud/osconfig_v1/gapic_metadata.json | 113 - .../v1/google/cloud/osconfig_v1/py.typed | 2 - .../cloud/osconfig_v1/services/__init__.py | 15 - .../services/os_config_service/__init__.py | 22 - .../os_config_service/async_client.py | 896 --- .../services/os_config_service/client.py | 1107 ---- .../services/os_config_service/pagers.py | 385 -- .../os_config_service/transports/__init__.py | 33 - .../os_config_service/transports/base.py | 282 - .../os_config_service/transports/grpc.py | 470 -- .../transports/grpc_asyncio.py | 474 -- .../cloud/osconfig_v1/types/__init__.py | 94 - .../cloud/osconfig_v1/types/inventory.py | 520 -- .../osconfig_v1/types/osconfig_common.py | 52 - .../osconfig_v1/types/osconfig_service.py | 25 - .../osconfig_v1/types/patch_deployments.py | 439 -- .../cloud/osconfig_v1/types/patch_jobs.py | 1080 ---- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../v1/scripts/fixup_osconfig_v1_keywords.py | 184 - owl-bot-staging/v1/setup.py | 54 - 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/osconfig_v1/__init__.py | 16 - .../osconfig_v1/test_os_config_service.py | 3566 ------------ owl-bot-staging/v1alpha/.coveragerc | 17 - owl-bot-staging/v1alpha/MANIFEST.in | 2 - owl-bot-staging/v1alpha/README.rst | 49 - owl-bot-staging/v1alpha/docs/conf.py | 376 -- owl-bot-staging/v1alpha/docs/index.rst | 7 - .../os_config_zonal_service.rst | 10 - .../docs/osconfig_v1alpha/services.rst | 6 - .../v1alpha/docs/osconfig_v1alpha/types.rst | 7 - .../v1alpha/google/cloud/osconfig/__init__.py | 81 - .../v1alpha/google/cloud/osconfig/py.typed | 2 - .../google/cloud/osconfig_v1alpha/__init__.py | 82 - .../osconfig_v1alpha/gapic_metadata.json | 143 - .../google/cloud/osconfig_v1alpha/py.typed | 2 - .../osconfig_v1alpha/services/__init__.py | 15 - .../os_config_zonal_service/__init__.py | 22 - .../os_config_zonal_service/async_client.py | 1372 ----- .../os_config_zonal_service/client.py | 1599 ------ .../os_config_zonal_service/pagers.py | 631 --- .../transports/__init__.py | 33 - .../transports/base.py | 332 -- .../transports/grpc.py | 612 --- .../transports/grpc_asyncio.py | 616 --- .../cloud/osconfig_v1alpha/types/__init__.py | 90 - .../osconfig_v1alpha/types/config_common.py | 131 - .../types/instance_os_policies_compliance.py | 263 - .../cloud/osconfig_v1alpha/types/inventory.py | 670 --- .../cloud/osconfig_v1alpha/types/os_policy.py | 865 --- .../types/os_policy_assignments.py | 540 -- .../osconfig_v1alpha/types/osconfig_common.py | 52 - .../types/osconfig_zonal_service.py | 25 - .../osconfig_v1alpha/types/vulnerability.py | 451 -- owl-bot-staging/v1alpha/mypy.ini | 3 - owl-bot-staging/v1alpha/noxfile.py | 132 - .../fixup_osconfig_v1alpha_keywords.py | 187 - owl-bot-staging/v1alpha/setup.py | 54 - owl-bot-staging/v1alpha/tests/__init__.py | 16 - .../v1alpha/tests/unit/__init__.py | 16 - .../v1alpha/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/osconfig_v1alpha/__init__.py | 16 - .../test_os_config_zonal_service.py | 4846 ----------------- 79 files changed, 84 insertions(+), 25060 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/index.rst delete mode 100644 owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst delete mode 100644 owl-bot-staging/v1/docs/osconfig_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/osconfig_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py delete mode 100644 owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.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_osconfig_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/osconfig_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/test_os_config_service.py delete mode 100644 owl-bot-staging/v1alpha/.coveragerc delete mode 100644 owl-bot-staging/v1alpha/MANIFEST.in delete mode 100644 owl-bot-staging/v1alpha/README.rst delete mode 100644 owl-bot-staging/v1alpha/docs/conf.py delete mode 100644 owl-bot-staging/v1alpha/docs/index.rst delete mode 100644 owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst delete mode 100644 owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst delete mode 100644 owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_service.py delete mode 100644 owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py delete mode 100644 owl-bot-staging/v1alpha/mypy.ini delete mode 100644 owl-bot-staging/v1alpha/noxfile.py delete mode 100644 owl-bot-staging/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py delete mode 100644 owl-bot-staging/v1alpha/setup.py delete mode 100644 owl-bot-staging/v1alpha/tests/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/__init__.py delete mode 100644 owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py diff --git a/google/cloud/osconfig_v1/types/inventory.py b/google/cloud/osconfig_v1/types/inventory.py index d78bb46..e829fca 100644 --- a/google/cloud/osconfig_v1/types/inventory.py +++ b/google/cloud/osconfig_v1/types/inventory.py @@ -16,6 +16,7 @@ import proto # type: ignore from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore __protobuf__ = proto.module( @@ -164,6 +165,8 @@ class SoftwarePackage(proto.Message): for info in Windows Quick Fix Engineering. cos_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): Details of a COS package. + windows_application (google.cloud.osconfig_v1.types.Inventory.WindowsApplication): + Details of a Windows Application """ yum_package = proto.Field( @@ -211,6 +214,12 @@ class SoftwarePackage(proto.Message): oneof="details", message="Inventory.VersionedPackage", ) + windows_application = proto.Field( + proto.MESSAGE, + number=9, + oneof="details", + message="Inventory.WindowsApplication", + ) class VersionedPackage(proto.Message): r"""Information related to the a standard versioned package. @@ -343,6 +352,39 @@ class WindowsQuickFixEngineeringPackage(proto.Message): proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) + class WindowsApplication(proto.Message): + r"""Contains information about a Windows application as retrieved from + the Windows Registry. For more information about these fields, see + + `Windows Installer Properties for the Uninstall + Registry `__\ {: + class="external" } + + Attributes: + display_name (str): + The name of the application or product. + display_version (str): + The version of the product or application in + string format. + publisher (str): + The name of the manufacturer for the product + or application. + install_date (google.type.date_pb2.Date): + The last time this product received service. + The value of this property is replaced each time + a patch is applied or removed from the product + or the command-line option is used to repair the + product. + help_link (str): + The internet address for technical support. + """ + + display_name = proto.Field(proto.STRING, number=1,) + display_version = proto.Field(proto.STRING, number=2,) + publisher = proto.Field(proto.STRING, number=3,) + install_date = proto.Field(proto.MESSAGE, number=4, message=date_pb2.Date,) + help_link = proto.Field(proto.STRING, number=5,) + os_info = proto.Field(proto.MESSAGE, number=1, message=OsInfo,) items = proto.MapField(proto.STRING, proto.MESSAGE, number=2, message=Item,) diff --git a/google/cloud/osconfig_v1alpha/types/inventory.py b/google/cloud/osconfig_v1alpha/types/inventory.py index a5e4ae8..52972ef 100644 --- a/google/cloud/osconfig_v1alpha/types/inventory.py +++ b/google/cloud/osconfig_v1alpha/types/inventory.py @@ -16,6 +16,7 @@ import proto # type: ignore from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore __protobuf__ = proto.module( @@ -195,6 +196,8 @@ class SoftwarePackage(proto.Message): for info in Windows Quick Fix Engineering. cos_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): Details of a COS package. + windows_application (google.cloud.osconfig_v1alpha.types.Inventory.WindowsApplication): + Details of Windows Application. """ yum_package = proto.Field( @@ -242,6 +245,12 @@ class SoftwarePackage(proto.Message): oneof="details", message="Inventory.VersionedPackage", ) + windows_application = proto.Field( + proto.MESSAGE, + number=9, + oneof="details", + message="Inventory.WindowsApplication", + ) class VersionedPackage(proto.Message): r"""Information related to the a standard versioned package. @@ -374,6 +383,39 @@ class WindowsQuickFixEngineeringPackage(proto.Message): proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) + class WindowsApplication(proto.Message): + r"""Contains information about a Windows application as retrieved from + the Windows Registry. For more information about these fields, see + + `Windows Installer Properties for the Uninstall + Registry `__\ {: + class="external" } + + Attributes: + display_name (str): + The name of the application or product. + display_version (str): + The version of the product or application in + string format. + publisher (str): + The name of the manufacturer for the product + or application. + install_date (google.type.date_pb2.Date): + The last time this product received service. + The value of this property is replaced each time + a patch is applied or removed from the product + or the command-line option is used to repair the + product. + help_link (str): + The internet address for technical support. + """ + + display_name = proto.Field(proto.STRING, number=1,) + display_version = proto.Field(proto.STRING, number=2,) + publisher = proto.Field(proto.STRING, number=3,) + install_date = proto.Field(proto.MESSAGE, number=4, message=date_pb2.Date,) + help_link = proto.Field(proto.STRING, number=5,) + name = proto.Field(proto.STRING, number=3,) os_info = proto.Field(proto.MESSAGE, number=1, message=OsInfo,) items = proto.MapField(proto.STRING, proto.MESSAGE, number=2, message=Item,) diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index d146ff0..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/osconfig/__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 92df5fe..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/osconfig *.py -recursive-include google/cloud/osconfig_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index d649bbe..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Osconfig 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 Cloud Osconfig 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 9dc389a..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-cloud-osconfig 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-cloud-osconfig" -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 Cloud 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-cloud-osconfig-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-cloud-osconfig.tex", - u"google-cloud-osconfig Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-osconfig", - u"Google Cloud Osconfig Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-osconfig", - u"google-cloud-osconfig Documentation", - author, - "google-cloud-osconfig", - "GAPIC library for Google Cloud Osconfig 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/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index a469ba0..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - osconfig_v1/services - osconfig_v1/types diff --git a/owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst b/owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst deleted file mode 100644 index e082a4b..0000000 --- a/owl-bot-staging/v1/docs/osconfig_v1/os_config_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -OsConfigService ---------------------------------- - -.. automodule:: google.cloud.osconfig_v1.services.os_config_service - :members: - :inherited-members: - -.. automodule:: google.cloud.osconfig_v1.services.os_config_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/osconfig_v1/services.rst b/owl-bot-staging/v1/docs/osconfig_v1/services.rst deleted file mode 100644 index e0dad88..0000000 --- a/owl-bot-staging/v1/docs/osconfig_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Osconfig v1 API -========================================= -.. toctree:: - :maxdepth: 2 - - os_config_service diff --git a/owl-bot-staging/v1/docs/osconfig_v1/types.rst b/owl-bot-staging/v1/docs/osconfig_v1/types.rst deleted file mode 100644 index 5c7249d..0000000 --- a/owl-bot-staging/v1/docs/osconfig_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Osconfig v1 API -====================================== - -.. automodule:: google.cloud.osconfig_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/osconfig/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig/__init__.py deleted file mode 100644 index ceb94a0..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig/__init__.py +++ /dev/null @@ -1,91 +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.cloud.osconfig_v1.services.os_config_service.client import OsConfigServiceClient -from google.cloud.osconfig_v1.services.os_config_service.async_client import OsConfigServiceAsyncClient - -from google.cloud.osconfig_v1.types.inventory import Inventory -from google.cloud.osconfig_v1.types.osconfig_common import FixedOrPercent -from google.cloud.osconfig_v1.types.patch_deployments import CreatePatchDeploymentRequest -from google.cloud.osconfig_v1.types.patch_deployments import DeletePatchDeploymentRequest -from google.cloud.osconfig_v1.types.patch_deployments import GetPatchDeploymentRequest -from google.cloud.osconfig_v1.types.patch_deployments import ListPatchDeploymentsRequest -from google.cloud.osconfig_v1.types.patch_deployments import ListPatchDeploymentsResponse -from google.cloud.osconfig_v1.types.patch_deployments import MonthlySchedule -from google.cloud.osconfig_v1.types.patch_deployments import OneTimeSchedule -from google.cloud.osconfig_v1.types.patch_deployments import PatchDeployment -from google.cloud.osconfig_v1.types.patch_deployments import RecurringSchedule -from google.cloud.osconfig_v1.types.patch_deployments import WeekDayOfMonth -from google.cloud.osconfig_v1.types.patch_deployments import WeeklySchedule -from google.cloud.osconfig_v1.types.patch_jobs import AptSettings -from google.cloud.osconfig_v1.types.patch_jobs import CancelPatchJobRequest -from google.cloud.osconfig_v1.types.patch_jobs import ExecStep -from google.cloud.osconfig_v1.types.patch_jobs import ExecStepConfig -from google.cloud.osconfig_v1.types.patch_jobs import ExecutePatchJobRequest -from google.cloud.osconfig_v1.types.patch_jobs import GcsObject -from google.cloud.osconfig_v1.types.patch_jobs import GetPatchJobRequest -from google.cloud.osconfig_v1.types.patch_jobs import GooSettings -from google.cloud.osconfig_v1.types.patch_jobs import Instance -from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobInstanceDetailsRequest -from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobInstanceDetailsResponse -from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobsRequest -from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobsResponse -from google.cloud.osconfig_v1.types.patch_jobs import PatchConfig -from google.cloud.osconfig_v1.types.patch_jobs import PatchInstanceFilter -from google.cloud.osconfig_v1.types.patch_jobs import PatchJob -from google.cloud.osconfig_v1.types.patch_jobs import PatchJobInstanceDetails -from google.cloud.osconfig_v1.types.patch_jobs import PatchRollout -from google.cloud.osconfig_v1.types.patch_jobs import WindowsUpdateSettings -from google.cloud.osconfig_v1.types.patch_jobs import YumSettings -from google.cloud.osconfig_v1.types.patch_jobs import ZypperSettings - -__all__ = ('OsConfigServiceClient', - 'OsConfigServiceAsyncClient', - 'Inventory', - 'FixedOrPercent', - 'CreatePatchDeploymentRequest', - 'DeletePatchDeploymentRequest', - 'GetPatchDeploymentRequest', - 'ListPatchDeploymentsRequest', - 'ListPatchDeploymentsResponse', - 'MonthlySchedule', - 'OneTimeSchedule', - 'PatchDeployment', - 'RecurringSchedule', - 'WeekDayOfMonth', - 'WeeklySchedule', - 'AptSettings', - 'CancelPatchJobRequest', - 'ExecStep', - 'ExecStepConfig', - 'ExecutePatchJobRequest', - 'GcsObject', - 'GetPatchJobRequest', - 'GooSettings', - 'Instance', - 'ListPatchJobInstanceDetailsRequest', - 'ListPatchJobInstanceDetailsResponse', - 'ListPatchJobsRequest', - 'ListPatchJobsResponse', - 'PatchConfig', - 'PatchInstanceFilter', - 'PatchJob', - 'PatchJobInstanceDetails', - 'PatchRollout', - 'WindowsUpdateSettings', - 'YumSettings', - 'ZypperSettings', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig/py.typed b/owl-bot-staging/v1/google/cloud/osconfig/py.typed deleted file mode 100644 index e2df01b..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py deleted file mode 100644 index 3adda66..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/__init__.py +++ /dev/null @@ -1,92 +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.os_config_service import OsConfigServiceClient -from .services.os_config_service import OsConfigServiceAsyncClient - -from .types.inventory import Inventory -from .types.osconfig_common import FixedOrPercent -from .types.patch_deployments import CreatePatchDeploymentRequest -from .types.patch_deployments import DeletePatchDeploymentRequest -from .types.patch_deployments import GetPatchDeploymentRequest -from .types.patch_deployments import ListPatchDeploymentsRequest -from .types.patch_deployments import ListPatchDeploymentsResponse -from .types.patch_deployments import MonthlySchedule -from .types.patch_deployments import OneTimeSchedule -from .types.patch_deployments import PatchDeployment -from .types.patch_deployments import RecurringSchedule -from .types.patch_deployments import WeekDayOfMonth -from .types.patch_deployments import WeeklySchedule -from .types.patch_jobs import AptSettings -from .types.patch_jobs import CancelPatchJobRequest -from .types.patch_jobs import ExecStep -from .types.patch_jobs import ExecStepConfig -from .types.patch_jobs import ExecutePatchJobRequest -from .types.patch_jobs import GcsObject -from .types.patch_jobs import GetPatchJobRequest -from .types.patch_jobs import GooSettings -from .types.patch_jobs import Instance -from .types.patch_jobs import ListPatchJobInstanceDetailsRequest -from .types.patch_jobs import ListPatchJobInstanceDetailsResponse -from .types.patch_jobs import ListPatchJobsRequest -from .types.patch_jobs import ListPatchJobsResponse -from .types.patch_jobs import PatchConfig -from .types.patch_jobs import PatchInstanceFilter -from .types.patch_jobs import PatchJob -from .types.patch_jobs import PatchJobInstanceDetails -from .types.patch_jobs import PatchRollout -from .types.patch_jobs import WindowsUpdateSettings -from .types.patch_jobs import YumSettings -from .types.patch_jobs import ZypperSettings - -__all__ = ( - 'OsConfigServiceAsyncClient', -'AptSettings', -'CancelPatchJobRequest', -'CreatePatchDeploymentRequest', -'DeletePatchDeploymentRequest', -'ExecStep', -'ExecStepConfig', -'ExecutePatchJobRequest', -'FixedOrPercent', -'GcsObject', -'GetPatchDeploymentRequest', -'GetPatchJobRequest', -'GooSettings', -'Instance', -'Inventory', -'ListPatchDeploymentsRequest', -'ListPatchDeploymentsResponse', -'ListPatchJobInstanceDetailsRequest', -'ListPatchJobInstanceDetailsResponse', -'ListPatchJobsRequest', -'ListPatchJobsResponse', -'MonthlySchedule', -'OneTimeSchedule', -'OsConfigServiceClient', -'PatchConfig', -'PatchDeployment', -'PatchInstanceFilter', -'PatchJob', -'PatchJobInstanceDetails', -'PatchRollout', -'RecurringSchedule', -'WeekDayOfMonth', -'WeeklySchedule', -'WindowsUpdateSettings', -'YumSettings', -'ZypperSettings', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json deleted file mode 100644 index 8f824ed..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/gapic_metadata.json +++ /dev/null @@ -1,113 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.osconfig_v1", - "protoPackage": "google.cloud.osconfig.v1", - "schema": "1.0", - "services": { - "OsConfigService": { - "clients": { - "grpc": { - "libraryClient": "OsConfigServiceClient", - "rpcs": { - "CancelPatchJob": { - "methods": [ - "cancel_patch_job" - ] - }, - "CreatePatchDeployment": { - "methods": [ - "create_patch_deployment" - ] - }, - "DeletePatchDeployment": { - "methods": [ - "delete_patch_deployment" - ] - }, - "ExecutePatchJob": { - "methods": [ - "execute_patch_job" - ] - }, - "GetPatchDeployment": { - "methods": [ - "get_patch_deployment" - ] - }, - "GetPatchJob": { - "methods": [ - "get_patch_job" - ] - }, - "ListPatchDeployments": { - "methods": [ - "list_patch_deployments" - ] - }, - "ListPatchJobInstanceDetails": { - "methods": [ - "list_patch_job_instance_details" - ] - }, - "ListPatchJobs": { - "methods": [ - "list_patch_jobs" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OsConfigServiceAsyncClient", - "rpcs": { - "CancelPatchJob": { - "methods": [ - "cancel_patch_job" - ] - }, - "CreatePatchDeployment": { - "methods": [ - "create_patch_deployment" - ] - }, - "DeletePatchDeployment": { - "methods": [ - "delete_patch_deployment" - ] - }, - "ExecutePatchJob": { - "methods": [ - "execute_patch_job" - ] - }, - "GetPatchDeployment": { - "methods": [ - "get_patch_deployment" - ] - }, - "GetPatchJob": { - "methods": [ - "get_patch_job" - ] - }, - "ListPatchDeployments": { - "methods": [ - "list_patch_deployments" - ] - }, - "ListPatchJobInstanceDetails": { - "methods": [ - "list_patch_job_instance_details" - ] - }, - "ListPatchJobs": { - "methods": [ - "list_patch_jobs" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed b/owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed deleted file mode 100644 index e2df01b..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_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/cloud/osconfig_v1/services/os_config_service/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/__init__.py deleted file mode 100644 index 8948b2c..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_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 OsConfigServiceClient -from .async_client import OsConfigServiceAsyncClient - -__all__ = ( - 'OsConfigServiceClient', - 'OsConfigServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py deleted file mode 100644 index 3a919bd..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/async_client.py +++ /dev/null @@ -1,896 +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.cloud.osconfig_v1.services.os_config_service import pagers -from google.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OsConfigServiceGrpcAsyncIOTransport -from .client import OsConfigServiceClient - - -class OsConfigServiceAsyncClient: - """OS Config API - The OS Config service is a server-side component that you can - use to manage package installations and patch jobs for virtual - machine instances. - """ - - _client: OsConfigServiceClient - - DEFAULT_ENDPOINT = OsConfigServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = OsConfigServiceClient.DEFAULT_MTLS_ENDPOINT - - instance_path = staticmethod(OsConfigServiceClient.instance_path) - parse_instance_path = staticmethod(OsConfigServiceClient.parse_instance_path) - patch_deployment_path = staticmethod(OsConfigServiceClient.patch_deployment_path) - parse_patch_deployment_path = staticmethod(OsConfigServiceClient.parse_patch_deployment_path) - patch_job_path = staticmethod(OsConfigServiceClient.patch_job_path) - parse_patch_job_path = staticmethod(OsConfigServiceClient.parse_patch_job_path) - common_billing_account_path = staticmethod(OsConfigServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OsConfigServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OsConfigServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OsConfigServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OsConfigServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OsConfigServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OsConfigServiceClient.common_project_path) - parse_common_project_path = staticmethod(OsConfigServiceClient.parse_common_project_path) - common_location_path = staticmethod(OsConfigServiceClient.common_location_path) - parse_common_location_path = staticmethod(OsConfigServiceClient.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: - OsConfigServiceAsyncClient: The constructed client. - """ - return OsConfigServiceClient.from_service_account_info.__func__(OsConfigServiceAsyncClient, 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: - OsConfigServiceAsyncClient: The constructed client. - """ - return OsConfigServiceClient.from_service_account_file.__func__(OsConfigServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> OsConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OsConfigServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(OsConfigServiceClient).get_transport_class, type(OsConfigServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, OsConfigServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the os config 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, ~.OsConfigServiceTransport]): 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 = OsConfigServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def execute_patch_job(self, - request: patch_jobs.ExecutePatchJobRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_jobs.PatchJob: - r"""Patch VM instances by creating and running a patch - job. - - Args: - request (:class:`google.cloud.osconfig_v1.types.ExecutePatchJobRequest`): - The request object. A request message to initiate - patching across Compute Engine instances. - 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.cloud.osconfig_v1.types.PatchJob: - A high level representation of a patch job that is either in progress - or has completed. - - Instance details are not included in the job. To - paginate through instance details, use - ListPatchJobInstanceDetails. - - For more information about patch jobs, see [Creating - patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). - - """ - # Create or coerce a protobuf request object. - request = patch_jobs.ExecutePatchJobRequest(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.execute_patch_job, - 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, - ) - - # Done; return the response. - return response - - async def get_patch_job(self, - request: patch_jobs.GetPatchJobRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_jobs.PatchJob: - r"""Get the patch job. This can be used to track the - progress of an ongoing patch job or review the details - of completed jobs. - - Args: - request (:class:`google.cloud.osconfig_v1.types.GetPatchJobRequest`): - The request object. Request to get an active or - completed patch job. - name (:class:`str`): - Required. Name of the patch in the form - ``projects/*/patchJobs/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.types.PatchJob: - A high level representation of a patch job that is either in progress - or has completed. - - Instance details are not included in the job. To - paginate through instance details, use - ListPatchJobInstanceDetails. - - For more information about patch jobs, see [Creating - patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_jobs.GetPatchJobRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_patch_job, - 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 cancel_patch_job(self, - request: patch_jobs.CancelPatchJobRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_jobs.PatchJob: - r"""Cancel a patch job. The patch job must be active. - Canceled patch jobs cannot be restarted. - - Args: - request (:class:`google.cloud.osconfig_v1.types.CancelPatchJobRequest`): - The request object. Message for canceling a patch job. - 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.cloud.osconfig_v1.types.PatchJob: - A high level representation of a patch job that is either in progress - or has completed. - - Instance details are not included in the job. To - paginate through instance details, use - ListPatchJobInstanceDetails. - - For more information about patch jobs, see [Creating - patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). - - """ - # Create or coerce a protobuf request object. - request = patch_jobs.CancelPatchJobRequest(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.cancel_patch_job, - 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 list_patch_jobs(self, - request: patch_jobs.ListPatchJobsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPatchJobsAsyncPager: - r"""Get a list of patch jobs. - - Args: - request (:class:`google.cloud.osconfig_v1.types.ListPatchJobsRequest`): - The request object. A request message for listing patch - jobs. - parent (:class:`str`): - Required. In the form of ``projects/*`` - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobsAsyncPager: - A response message for listing patch - jobs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_jobs.ListPatchJobsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_patch_jobs, - 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.ListPatchJobsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_patch_job_instance_details(self, - request: patch_jobs.ListPatchJobInstanceDetailsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPatchJobInstanceDetailsAsyncPager: - r"""Get a list of instance details for a given patch job. - - Args: - request (:class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest`): - The request object. Request to list details for all - instances that are part of a patch job. - parent (:class:`str`): - Required. The parent for the instances are in the form - of ``projects/*/patchJobs/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobInstanceDetailsAsyncPager: - A response message for listing the - instances details for a patch job. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_jobs.ListPatchJobInstanceDetailsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_patch_job_instance_details, - 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.ListPatchJobInstanceDetailsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_patch_deployment(self, - request: patch_deployments.CreatePatchDeploymentRequest = None, - *, - parent: str = None, - patch_deployment: patch_deployments.PatchDeployment = None, - patch_deployment_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_deployments.PatchDeployment: - r"""Create an OS Config patch deployment. - - Args: - request (:class:`google.cloud.osconfig_v1.types.CreatePatchDeploymentRequest`): - The request object. A request message for creating a - patch deployment. - parent (:class:`str`): - Required. The project to apply this patch deployment to - in the form ``projects/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - patch_deployment (:class:`google.cloud.osconfig_v1.types.PatchDeployment`): - Required. The patch deployment to - create. - - This corresponds to the ``patch_deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - patch_deployment_id (:class:`str`): - Required. A name for the patch deployment in the - project. When creating a name the following rules apply: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the project. - - This corresponds to the ``patch_deployment_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.types.PatchDeployment: - Patch deployments are configurations that individual patch jobs use to - complete a patch. These configurations include - instance filter, package repository settings, and a - schedule. For more information about creating and - managing patch deployments, see [Scheduling patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, patch_deployment, patch_deployment_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_deployments.CreatePatchDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if patch_deployment is not None: - request.patch_deployment = patch_deployment - if patch_deployment_id is not None: - request.patch_deployment_id = patch_deployment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_patch_deployment, - 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, - ) - - # Done; return the response. - return response - - async def get_patch_deployment(self, - request: patch_deployments.GetPatchDeploymentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_deployments.PatchDeployment: - r"""Get an OS Config patch deployment. - - Args: - request (:class:`google.cloud.osconfig_v1.types.GetPatchDeploymentRequest`): - The request object. A request message for retrieving a - patch deployment. - name (:class:`str`): - Required. The resource name of the patch deployment in - the form ``projects/*/patchDeployments/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.types.PatchDeployment: - Patch deployments are configurations that individual patch jobs use to - complete a patch. These configurations include - instance filter, package repository settings, and a - schedule. For more information about creating and - managing patch deployments, see [Scheduling patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_deployments.GetPatchDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_patch_deployment, - 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 list_patch_deployments(self, - request: patch_deployments.ListPatchDeploymentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPatchDeploymentsAsyncPager: - r"""Get a page of OS Config patch deployments. - - Args: - request (:class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest`): - The request object. A request message for listing patch - deployments. - parent (:class:`str`): - Required. The resource name of the parent in the form - ``projects/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchDeploymentsAsyncPager: - A response message for listing patch - deployments. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_deployments.ListPatchDeploymentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_patch_deployments, - 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.ListPatchDeploymentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_patch_deployment(self, - request: patch_deployments.DeletePatchDeploymentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Delete an OS Config patch deployment. - - Args: - request (:class:`google.cloud.osconfig_v1.types.DeletePatchDeploymentRequest`): - The request object. A request message for deleting a - patch deployment. - name (:class:`str`): - Required. The resource name of the patch deployment in - the form ``projects/*/patchDeployments/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = patch_deployments.DeletePatchDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_patch_deployment, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-osconfig", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "OsConfigServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py deleted file mode 100644 index 42c6b69..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/client.py +++ /dev/null @@ -1,1107 +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.cloud.osconfig_v1.services.os_config_service import pagers -from google.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import OsConfigServiceGrpcTransport -from .transports.grpc_asyncio import OsConfigServiceGrpcAsyncIOTransport - - -class OsConfigServiceClientMeta(type): - """Metaclass for the OsConfigService 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[OsConfigServiceTransport]] - _transport_registry["grpc"] = OsConfigServiceGrpcTransport - _transport_registry["grpc_asyncio"] = OsConfigServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[OsConfigServiceTransport]: - """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 OsConfigServiceClient(metaclass=OsConfigServiceClientMeta): - """OS Config API - The OS Config service is a server-side component that you can - use to manage package installations and patch jobs for virtual - machine instances. - """ - - @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 = "osconfig.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: - OsConfigServiceClient: 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: - OsConfigServiceClient: 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) -> OsConfigServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OsConfigServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def instance_path(project: str,zone: str,instance: str,) -> str: - """Returns a fully-qualified instance string.""" - return "projects/{project}/zones/{zone}/instances/{instance}".format(project=project, zone=zone, instance=instance, ) - - @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: - """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/zones/(?P.+?)/instances/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def patch_deployment_path(project: str,patch_deployment: str,) -> str: - """Returns a fully-qualified patch_deployment string.""" - return "projects/{project}/patchDeployments/{patch_deployment}".format(project=project, patch_deployment=patch_deployment, ) - - @staticmethod - def parse_patch_deployment_path(path: str) -> Dict[str,str]: - """Parses a patch_deployment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/patchDeployments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def patch_job_path(project: str,patch_job: str,) -> str: - """Returns a fully-qualified patch_job string.""" - return "projects/{project}/patchJobs/{patch_job}".format(project=project, patch_job=patch_job, ) - - @staticmethod - def parse_patch_job_path(path: str) -> Dict[str,str]: - """Parses a patch_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/patchJobs/(?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, OsConfigServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the os config 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, OsConfigServiceTransport]): 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, OsConfigServiceTransport): - # transport is a OsConfigServiceTransport 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, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def execute_patch_job(self, - request: patch_jobs.ExecutePatchJobRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_jobs.PatchJob: - r"""Patch VM instances by creating and running a patch - job. - - Args: - request (google.cloud.osconfig_v1.types.ExecutePatchJobRequest): - The request object. A request message to initiate - patching across Compute Engine instances. - 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.cloud.osconfig_v1.types.PatchJob: - A high level representation of a patch job that is either in progress - or has completed. - - Instance details are not included in the job. To - paginate through instance details, use - ListPatchJobInstanceDetails. - - For more information about patch jobs, see [Creating - patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a patch_jobs.ExecutePatchJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_jobs.ExecutePatchJobRequest): - request = patch_jobs.ExecutePatchJobRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.execute_patch_job] - - # 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 get_patch_job(self, - request: patch_jobs.GetPatchJobRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_jobs.PatchJob: - r"""Get the patch job. This can be used to track the - progress of an ongoing patch job or review the details - of completed jobs. - - Args: - request (google.cloud.osconfig_v1.types.GetPatchJobRequest): - The request object. Request to get an active or - completed patch job. - name (str): - Required. Name of the patch in the form - ``projects/*/patchJobs/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.types.PatchJob: - A high level representation of a patch job that is either in progress - or has completed. - - Instance details are not included in the job. To - paginate through instance details, use - ListPatchJobInstanceDetails. - - For more information about patch jobs, see [Creating - patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_jobs.GetPatchJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_jobs.GetPatchJobRequest): - request = patch_jobs.GetPatchJobRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_patch_job] - - # 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 cancel_patch_job(self, - request: patch_jobs.CancelPatchJobRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_jobs.PatchJob: - r"""Cancel a patch job. The patch job must be active. - Canceled patch jobs cannot be restarted. - - Args: - request (google.cloud.osconfig_v1.types.CancelPatchJobRequest): - The request object. Message for canceling a patch job. - 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.cloud.osconfig_v1.types.PatchJob: - A high level representation of a patch job that is either in progress - or has completed. - - Instance details are not included in the job. To - paginate through instance details, use - ListPatchJobInstanceDetails. - - For more information about patch jobs, see [Creating - patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/create-patch-job). - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a patch_jobs.CancelPatchJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_jobs.CancelPatchJobRequest): - request = patch_jobs.CancelPatchJobRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_patch_job] - - # 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 list_patch_jobs(self, - request: patch_jobs.ListPatchJobsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPatchJobsPager: - r"""Get a list of patch jobs. - - Args: - request (google.cloud.osconfig_v1.types.ListPatchJobsRequest): - The request object. A request message for listing patch - jobs. - parent (str): - Required. In the form of ``projects/*`` - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobsPager: - A response message for listing patch - jobs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_jobs.ListPatchJobsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_jobs.ListPatchJobsRequest): - request = patch_jobs.ListPatchJobsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_patch_jobs] - - # 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.ListPatchJobsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_patch_job_instance_details(self, - request: patch_jobs.ListPatchJobInstanceDetailsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPatchJobInstanceDetailsPager: - r"""Get a list of instance details for a given patch job. - - Args: - request (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest): - The request object. Request to list details for all - instances that are part of a patch job. - parent (str): - Required. The parent for the instances are in the form - of ``projects/*/patchJobs/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchJobInstanceDetailsPager: - A response message for listing the - instances details for a patch job. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_jobs.ListPatchJobInstanceDetailsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_jobs.ListPatchJobInstanceDetailsRequest): - request = patch_jobs.ListPatchJobInstanceDetailsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_patch_job_instance_details] - - # 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.ListPatchJobInstanceDetailsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_patch_deployment(self, - request: patch_deployments.CreatePatchDeploymentRequest = None, - *, - parent: str = None, - patch_deployment: patch_deployments.PatchDeployment = None, - patch_deployment_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_deployments.PatchDeployment: - r"""Create an OS Config patch deployment. - - Args: - request (google.cloud.osconfig_v1.types.CreatePatchDeploymentRequest): - The request object. A request message for creating a - patch deployment. - parent (str): - Required. The project to apply this patch deployment to - in the form ``projects/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - patch_deployment (google.cloud.osconfig_v1.types.PatchDeployment): - Required. The patch deployment to - create. - - This corresponds to the ``patch_deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - patch_deployment_id (str): - Required. A name for the patch deployment in the - project. When creating a name the following rules apply: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the project. - - This corresponds to the ``patch_deployment_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.types.PatchDeployment: - Patch deployments are configurations that individual patch jobs use to - complete a patch. These configurations include - instance filter, package repository settings, and a - schedule. For more information about creating and - managing patch deployments, see [Scheduling patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, patch_deployment, patch_deployment_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_deployments.CreatePatchDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_deployments.CreatePatchDeploymentRequest): - request = patch_deployments.CreatePatchDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if patch_deployment is not None: - request.patch_deployment = patch_deployment - if patch_deployment_id is not None: - request.patch_deployment_id = patch_deployment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_patch_deployment] - - # 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 get_patch_deployment(self, - request: patch_deployments.GetPatchDeploymentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> patch_deployments.PatchDeployment: - r"""Get an OS Config patch deployment. - - Args: - request (google.cloud.osconfig_v1.types.GetPatchDeploymentRequest): - The request object. A request message for retrieving a - patch deployment. - name (str): - Required. The resource name of the patch deployment in - the form ``projects/*/patchDeployments/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.types.PatchDeployment: - Patch deployments are configurations that individual patch jobs use to - complete a patch. These configurations include - instance filter, package repository settings, and a - schedule. For more information about creating and - managing patch deployments, see [Scheduling patch - jobs](\ https://cloud.google.com/compute/docs/os-patch-management/schedule-patch-jobs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_deployments.GetPatchDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_deployments.GetPatchDeploymentRequest): - request = patch_deployments.GetPatchDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_patch_deployment] - - # 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 list_patch_deployments(self, - request: patch_deployments.ListPatchDeploymentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPatchDeploymentsPager: - r"""Get a page of OS Config patch deployments. - - Args: - request (google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest): - The request object. A request message for listing patch - deployments. - parent (str): - Required. The resource name of the parent in the form - ``projects/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1.services.os_config_service.pagers.ListPatchDeploymentsPager: - A response message for listing patch - deployments. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_deployments.ListPatchDeploymentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_deployments.ListPatchDeploymentsRequest): - request = patch_deployments.ListPatchDeploymentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_patch_deployments] - - # 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.ListPatchDeploymentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_patch_deployment(self, - request: patch_deployments.DeletePatchDeploymentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Delete an OS Config patch deployment. - - Args: - request (google.cloud.osconfig_v1.types.DeletePatchDeploymentRequest): - The request object. A request message for deleting a - patch deployment. - name (str): - Required. The resource name of the patch deployment in - the form ``projects/*/patchDeployments/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a patch_deployments.DeletePatchDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, patch_deployments.DeletePatchDeploymentRequest): - request = patch_deployments.DeletePatchDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_patch_deployment] - - # 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-osconfig", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "OsConfigServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py deleted file mode 100644 index 0598845..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/pagers.py +++ /dev/null @@ -1,385 +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.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs - - -class ListPatchJobsPager: - """A pager for iterating through ``list_patch_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``patch_jobs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPatchJobs`` requests and continue to iterate - through the ``patch_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` - 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[..., patch_jobs.ListPatchJobsResponse], - request: patch_jobs.ListPatchJobsRequest, - response: patch_jobs.ListPatchJobsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1.types.ListPatchJobsRequest): - The initial request object. - response (google.cloud.osconfig_v1.types.ListPatchJobsResponse): - 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 = patch_jobs.ListPatchJobsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[patch_jobs.ListPatchJobsResponse]: - 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[patch_jobs.PatchJob]: - for page in self.pages: - yield from page.patch_jobs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPatchJobsAsyncPager: - """A pager for iterating through ``list_patch_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``patch_jobs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPatchJobs`` requests and continue to iterate - through the ``patch_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobsResponse` - 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[patch_jobs.ListPatchJobsResponse]], - request: patch_jobs.ListPatchJobsRequest, - response: patch_jobs.ListPatchJobsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1.types.ListPatchJobsRequest): - The initial request object. - response (google.cloud.osconfig_v1.types.ListPatchJobsResponse): - 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 = patch_jobs.ListPatchJobsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[patch_jobs.ListPatchJobsResponse]: - 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[patch_jobs.PatchJob]: - async def async_generator(): - async for page in self.pages: - for response in page.patch_jobs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPatchJobInstanceDetailsPager: - """A pager for iterating through ``list_patch_job_instance_details`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``patch_job_instance_details`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPatchJobInstanceDetails`` requests and continue to iterate - through the ``patch_job_instance_details`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` - 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[..., patch_jobs.ListPatchJobInstanceDetailsResponse], - request: patch_jobs.ListPatchJobInstanceDetailsRequest, - response: patch_jobs.ListPatchJobInstanceDetailsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest): - The initial request object. - response (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse): - 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 = patch_jobs.ListPatchJobInstanceDetailsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[patch_jobs.ListPatchJobInstanceDetailsResponse]: - 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[patch_jobs.PatchJobInstanceDetails]: - for page in self.pages: - yield from page.patch_job_instance_details - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPatchJobInstanceDetailsAsyncPager: - """A pager for iterating through ``list_patch_job_instance_details`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``patch_job_instance_details`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPatchJobInstanceDetails`` requests and continue to iterate - through the ``patch_job_instance_details`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse` - 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[patch_jobs.ListPatchJobInstanceDetailsResponse]], - request: patch_jobs.ListPatchJobInstanceDetailsRequest, - response: patch_jobs.ListPatchJobInstanceDetailsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsRequest): - The initial request object. - response (google.cloud.osconfig_v1.types.ListPatchJobInstanceDetailsResponse): - 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 = patch_jobs.ListPatchJobInstanceDetailsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[patch_jobs.ListPatchJobInstanceDetailsResponse]: - 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[patch_jobs.PatchJobInstanceDetails]: - async def async_generator(): - async for page in self.pages: - for response in page.patch_job_instance_details: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPatchDeploymentsPager: - """A pager for iterating through ``list_patch_deployments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``patch_deployments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPatchDeployments`` requests and continue to iterate - through the ``patch_deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` - 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[..., patch_deployments.ListPatchDeploymentsResponse], - request: patch_deployments.ListPatchDeploymentsRequest, - response: patch_deployments.ListPatchDeploymentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest): - The initial request object. - response (google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse): - 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 = patch_deployments.ListPatchDeploymentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[patch_deployments.ListPatchDeploymentsResponse]: - 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[patch_deployments.PatchDeployment]: - for page in self.pages: - yield from page.patch_deployments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPatchDeploymentsAsyncPager: - """A pager for iterating through ``list_patch_deployments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``patch_deployments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPatchDeployments`` requests and continue to iterate - through the ``patch_deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse` - 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[patch_deployments.ListPatchDeploymentsResponse]], - request: patch_deployments.ListPatchDeploymentsRequest, - response: patch_deployments.ListPatchDeploymentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1.types.ListPatchDeploymentsRequest): - The initial request object. - response (google.cloud.osconfig_v1.types.ListPatchDeploymentsResponse): - 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 = patch_deployments.ListPatchDeploymentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[patch_deployments.ListPatchDeploymentsResponse]: - 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[patch_deployments.PatchDeployment]: - async def async_generator(): - async for page in self.pages: - for response in page.patch_deployments: - 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/cloud/osconfig_v1/services/os_config_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/__init__.py deleted file mode 100644 index 35e0b32..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_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 OsConfigServiceTransport -from .grpc import OsConfigServiceGrpcTransport -from .grpc_asyncio import OsConfigServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OsConfigServiceTransport]] -_transport_registry['grpc'] = OsConfigServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OsConfigServiceGrpcAsyncIOTransport - -__all__ = ( - 'OsConfigServiceTransport', - 'OsConfigServiceGrpcTransport', - 'OsConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py deleted file mode 100644 index 166b068..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/base.py +++ /dev/null @@ -1,282 +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.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-osconfig', - ).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 OsConfigServiceTransport(abc.ABC): - """Abstract transport class for OsConfigService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'osconfig.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 - - # 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.execute_patch_job: gapic_v1.method.wrap_method( - self.execute_patch_job, - default_timeout=None, - client_info=client_info, - ), - self.get_patch_job: gapic_v1.method.wrap_method( - self.get_patch_job, - default_timeout=None, - client_info=client_info, - ), - self.cancel_patch_job: gapic_v1.method.wrap_method( - self.cancel_patch_job, - default_timeout=None, - client_info=client_info, - ), - self.list_patch_jobs: gapic_v1.method.wrap_method( - self.list_patch_jobs, - default_timeout=None, - client_info=client_info, - ), - self.list_patch_job_instance_details: gapic_v1.method.wrap_method( - self.list_patch_job_instance_details, - default_timeout=None, - client_info=client_info, - ), - self.create_patch_deployment: gapic_v1.method.wrap_method( - self.create_patch_deployment, - default_timeout=None, - client_info=client_info, - ), - self.get_patch_deployment: gapic_v1.method.wrap_method( - self.get_patch_deployment, - default_timeout=None, - client_info=client_info, - ), - self.list_patch_deployments: gapic_v1.method.wrap_method( - self.list_patch_deployments, - default_timeout=None, - client_info=client_info, - ), - self.delete_patch_deployment: gapic_v1.method.wrap_method( - self.delete_patch_deployment, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def execute_patch_job(self) -> Callable[ - [patch_jobs.ExecutePatchJobRequest], - Union[ - patch_jobs.PatchJob, - Awaitable[patch_jobs.PatchJob] - ]]: - raise NotImplementedError() - - @property - def get_patch_job(self) -> Callable[ - [patch_jobs.GetPatchJobRequest], - Union[ - patch_jobs.PatchJob, - Awaitable[patch_jobs.PatchJob] - ]]: - raise NotImplementedError() - - @property - def cancel_patch_job(self) -> Callable[ - [patch_jobs.CancelPatchJobRequest], - Union[ - patch_jobs.PatchJob, - Awaitable[patch_jobs.PatchJob] - ]]: - raise NotImplementedError() - - @property - def list_patch_jobs(self) -> Callable[ - [patch_jobs.ListPatchJobsRequest], - Union[ - patch_jobs.ListPatchJobsResponse, - Awaitable[patch_jobs.ListPatchJobsResponse] - ]]: - raise NotImplementedError() - - @property - def list_patch_job_instance_details(self) -> Callable[ - [patch_jobs.ListPatchJobInstanceDetailsRequest], - Union[ - patch_jobs.ListPatchJobInstanceDetailsResponse, - Awaitable[patch_jobs.ListPatchJobInstanceDetailsResponse] - ]]: - raise NotImplementedError() - - @property - def create_patch_deployment(self) -> Callable[ - [patch_deployments.CreatePatchDeploymentRequest], - Union[ - patch_deployments.PatchDeployment, - Awaitable[patch_deployments.PatchDeployment] - ]]: - raise NotImplementedError() - - @property - def get_patch_deployment(self) -> Callable[ - [patch_deployments.GetPatchDeploymentRequest], - Union[ - patch_deployments.PatchDeployment, - Awaitable[patch_deployments.PatchDeployment] - ]]: - raise NotImplementedError() - - @property - def list_patch_deployments(self) -> Callable[ - [patch_deployments.ListPatchDeploymentsRequest], - Union[ - patch_deployments.ListPatchDeploymentsResponse, - Awaitable[patch_deployments.ListPatchDeploymentsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_patch_deployment(self) -> Callable[ - [patch_deployments.DeletePatchDeploymentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'OsConfigServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py deleted file mode 100644 index dc6df23..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# 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.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs -from google.protobuf import empty_pb2 # type: ignore -from .base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO - - -class OsConfigServiceGrpcTransport(OsConfigServiceTransport): - """gRPC backend transport for OsConfigService. - - OS Config API - The OS Config service is a server-side component that you can - use to manage package installations and patch jobs for virtual - machine instances. - - 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 = 'osconfig.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, - always_use_jwt_access: Optional[bool] = False, - ) -> 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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=always_use_jwt_access, - ) - - 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 = 'osconfig.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 execute_patch_job(self) -> Callable[ - [patch_jobs.ExecutePatchJobRequest], - patch_jobs.PatchJob]: - r"""Return a callable for the execute patch job method over gRPC. - - Patch VM instances by creating and running a patch - job. - - Returns: - Callable[[~.ExecutePatchJobRequest], - ~.PatchJob]: - 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 'execute_patch_job' not in self._stubs: - self._stubs['execute_patch_job'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ExecutePatchJob', - request_serializer=patch_jobs.ExecutePatchJobRequest.serialize, - response_deserializer=patch_jobs.PatchJob.deserialize, - ) - return self._stubs['execute_patch_job'] - - @property - def get_patch_job(self) -> Callable[ - [patch_jobs.GetPatchJobRequest], - patch_jobs.PatchJob]: - r"""Return a callable for the get patch job method over gRPC. - - Get the patch job. This can be used to track the - progress of an ongoing patch job or review the details - of completed jobs. - - Returns: - Callable[[~.GetPatchJobRequest], - ~.PatchJob]: - 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_patch_job' not in self._stubs: - self._stubs['get_patch_job'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/GetPatchJob', - request_serializer=patch_jobs.GetPatchJobRequest.serialize, - response_deserializer=patch_jobs.PatchJob.deserialize, - ) - return self._stubs['get_patch_job'] - - @property - def cancel_patch_job(self) -> Callable[ - [patch_jobs.CancelPatchJobRequest], - patch_jobs.PatchJob]: - r"""Return a callable for the cancel patch job method over gRPC. - - Cancel a patch job. The patch job must be active. - Canceled patch jobs cannot be restarted. - - Returns: - Callable[[~.CancelPatchJobRequest], - ~.PatchJob]: - 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 'cancel_patch_job' not in self._stubs: - self._stubs['cancel_patch_job'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/CancelPatchJob', - request_serializer=patch_jobs.CancelPatchJobRequest.serialize, - response_deserializer=patch_jobs.PatchJob.deserialize, - ) - return self._stubs['cancel_patch_job'] - - @property - def list_patch_jobs(self) -> Callable[ - [patch_jobs.ListPatchJobsRequest], - patch_jobs.ListPatchJobsResponse]: - r"""Return a callable for the list patch jobs method over gRPC. - - Get a list of patch jobs. - - Returns: - Callable[[~.ListPatchJobsRequest], - ~.ListPatchJobsResponse]: - 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_patch_jobs' not in self._stubs: - self._stubs['list_patch_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobs', - request_serializer=patch_jobs.ListPatchJobsRequest.serialize, - response_deserializer=patch_jobs.ListPatchJobsResponse.deserialize, - ) - return self._stubs['list_patch_jobs'] - - @property - def list_patch_job_instance_details(self) -> Callable[ - [patch_jobs.ListPatchJobInstanceDetailsRequest], - patch_jobs.ListPatchJobInstanceDetailsResponse]: - r"""Return a callable for the list patch job instance - details method over gRPC. - - Get a list of instance details for a given patch job. - - Returns: - Callable[[~.ListPatchJobInstanceDetailsRequest], - ~.ListPatchJobInstanceDetailsResponse]: - 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_patch_job_instance_details' not in self._stubs: - self._stubs['list_patch_job_instance_details'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobInstanceDetails', - request_serializer=patch_jobs.ListPatchJobInstanceDetailsRequest.serialize, - response_deserializer=patch_jobs.ListPatchJobInstanceDetailsResponse.deserialize, - ) - return self._stubs['list_patch_job_instance_details'] - - @property - def create_patch_deployment(self) -> Callable[ - [patch_deployments.CreatePatchDeploymentRequest], - patch_deployments.PatchDeployment]: - r"""Return a callable for the create patch deployment method over gRPC. - - Create an OS Config patch deployment. - - Returns: - Callable[[~.CreatePatchDeploymentRequest], - ~.PatchDeployment]: - 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_patch_deployment' not in self._stubs: - self._stubs['create_patch_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/CreatePatchDeployment', - request_serializer=patch_deployments.CreatePatchDeploymentRequest.serialize, - response_deserializer=patch_deployments.PatchDeployment.deserialize, - ) - return self._stubs['create_patch_deployment'] - - @property - def get_patch_deployment(self) -> Callable[ - [patch_deployments.GetPatchDeploymentRequest], - patch_deployments.PatchDeployment]: - r"""Return a callable for the get patch deployment method over gRPC. - - Get an OS Config patch deployment. - - Returns: - Callable[[~.GetPatchDeploymentRequest], - ~.PatchDeployment]: - 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_patch_deployment' not in self._stubs: - self._stubs['get_patch_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/GetPatchDeployment', - request_serializer=patch_deployments.GetPatchDeploymentRequest.serialize, - response_deserializer=patch_deployments.PatchDeployment.deserialize, - ) - return self._stubs['get_patch_deployment'] - - @property - def list_patch_deployments(self) -> Callable[ - [patch_deployments.ListPatchDeploymentsRequest], - patch_deployments.ListPatchDeploymentsResponse]: - r"""Return a callable for the list patch deployments method over gRPC. - - Get a page of OS Config patch deployments. - - Returns: - Callable[[~.ListPatchDeploymentsRequest], - ~.ListPatchDeploymentsResponse]: - 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_patch_deployments' not in self._stubs: - self._stubs['list_patch_deployments'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ListPatchDeployments', - request_serializer=patch_deployments.ListPatchDeploymentsRequest.serialize, - response_deserializer=patch_deployments.ListPatchDeploymentsResponse.deserialize, - ) - return self._stubs['list_patch_deployments'] - - @property - def delete_patch_deployment(self) -> Callable[ - [patch_deployments.DeletePatchDeploymentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete patch deployment method over gRPC. - - Delete an OS Config patch deployment. - - Returns: - Callable[[~.DeletePatchDeploymentRequest], - ~.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_patch_deployment' not in self._stubs: - self._stubs['delete_patch_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/DeletePatchDeployment', - request_serializer=patch_deployments.DeletePatchDeploymentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_patch_deployment'] - - -__all__ = ( - 'OsConfigServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py deleted file mode 100644 index e624b6b..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/services/os_config_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,474 +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.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs -from google.protobuf import empty_pb2 # type: ignore -from .base import OsConfigServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import OsConfigServiceGrpcTransport - - -class OsConfigServiceGrpcAsyncIOTransport(OsConfigServiceTransport): - """gRPC AsyncIO backend transport for OsConfigService. - - OS Config API - The OS Config service is a server-side component that you can - use to manage package installations and patch jobs for virtual - machine instances. - - 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 = 'osconfig.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 = 'osconfig.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, - always_use_jwt_access: Optional[bool] = False, - ) -> 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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=always_use_jwt_access, - ) - - 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 execute_patch_job(self) -> Callable[ - [patch_jobs.ExecutePatchJobRequest], - Awaitable[patch_jobs.PatchJob]]: - r"""Return a callable for the execute patch job method over gRPC. - - Patch VM instances by creating and running a patch - job. - - Returns: - Callable[[~.ExecutePatchJobRequest], - Awaitable[~.PatchJob]]: - 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 'execute_patch_job' not in self._stubs: - self._stubs['execute_patch_job'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ExecutePatchJob', - request_serializer=patch_jobs.ExecutePatchJobRequest.serialize, - response_deserializer=patch_jobs.PatchJob.deserialize, - ) - return self._stubs['execute_patch_job'] - - @property - def get_patch_job(self) -> Callable[ - [patch_jobs.GetPatchJobRequest], - Awaitable[patch_jobs.PatchJob]]: - r"""Return a callable for the get patch job method over gRPC. - - Get the patch job. This can be used to track the - progress of an ongoing patch job or review the details - of completed jobs. - - Returns: - Callable[[~.GetPatchJobRequest], - Awaitable[~.PatchJob]]: - 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_patch_job' not in self._stubs: - self._stubs['get_patch_job'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/GetPatchJob', - request_serializer=patch_jobs.GetPatchJobRequest.serialize, - response_deserializer=patch_jobs.PatchJob.deserialize, - ) - return self._stubs['get_patch_job'] - - @property - def cancel_patch_job(self) -> Callable[ - [patch_jobs.CancelPatchJobRequest], - Awaitable[patch_jobs.PatchJob]]: - r"""Return a callable for the cancel patch job method over gRPC. - - Cancel a patch job. The patch job must be active. - Canceled patch jobs cannot be restarted. - - Returns: - Callable[[~.CancelPatchJobRequest], - Awaitable[~.PatchJob]]: - 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 'cancel_patch_job' not in self._stubs: - self._stubs['cancel_patch_job'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/CancelPatchJob', - request_serializer=patch_jobs.CancelPatchJobRequest.serialize, - response_deserializer=patch_jobs.PatchJob.deserialize, - ) - return self._stubs['cancel_patch_job'] - - @property - def list_patch_jobs(self) -> Callable[ - [patch_jobs.ListPatchJobsRequest], - Awaitable[patch_jobs.ListPatchJobsResponse]]: - r"""Return a callable for the list patch jobs method over gRPC. - - Get a list of patch jobs. - - Returns: - Callable[[~.ListPatchJobsRequest], - Awaitable[~.ListPatchJobsResponse]]: - 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_patch_jobs' not in self._stubs: - self._stubs['list_patch_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobs', - request_serializer=patch_jobs.ListPatchJobsRequest.serialize, - response_deserializer=patch_jobs.ListPatchJobsResponse.deserialize, - ) - return self._stubs['list_patch_jobs'] - - @property - def list_patch_job_instance_details(self) -> Callable[ - [patch_jobs.ListPatchJobInstanceDetailsRequest], - Awaitable[patch_jobs.ListPatchJobInstanceDetailsResponse]]: - r"""Return a callable for the list patch job instance - details method over gRPC. - - Get a list of instance details for a given patch job. - - Returns: - Callable[[~.ListPatchJobInstanceDetailsRequest], - Awaitable[~.ListPatchJobInstanceDetailsResponse]]: - 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_patch_job_instance_details' not in self._stubs: - self._stubs['list_patch_job_instance_details'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ListPatchJobInstanceDetails', - request_serializer=patch_jobs.ListPatchJobInstanceDetailsRequest.serialize, - response_deserializer=patch_jobs.ListPatchJobInstanceDetailsResponse.deserialize, - ) - return self._stubs['list_patch_job_instance_details'] - - @property - def create_patch_deployment(self) -> Callable[ - [patch_deployments.CreatePatchDeploymentRequest], - Awaitable[patch_deployments.PatchDeployment]]: - r"""Return a callable for the create patch deployment method over gRPC. - - Create an OS Config patch deployment. - - Returns: - Callable[[~.CreatePatchDeploymentRequest], - Awaitable[~.PatchDeployment]]: - 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_patch_deployment' not in self._stubs: - self._stubs['create_patch_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/CreatePatchDeployment', - request_serializer=patch_deployments.CreatePatchDeploymentRequest.serialize, - response_deserializer=patch_deployments.PatchDeployment.deserialize, - ) - return self._stubs['create_patch_deployment'] - - @property - def get_patch_deployment(self) -> Callable[ - [patch_deployments.GetPatchDeploymentRequest], - Awaitable[patch_deployments.PatchDeployment]]: - r"""Return a callable for the get patch deployment method over gRPC. - - Get an OS Config patch deployment. - - Returns: - Callable[[~.GetPatchDeploymentRequest], - Awaitable[~.PatchDeployment]]: - 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_patch_deployment' not in self._stubs: - self._stubs['get_patch_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/GetPatchDeployment', - request_serializer=patch_deployments.GetPatchDeploymentRequest.serialize, - response_deserializer=patch_deployments.PatchDeployment.deserialize, - ) - return self._stubs['get_patch_deployment'] - - @property - def list_patch_deployments(self) -> Callable[ - [patch_deployments.ListPatchDeploymentsRequest], - Awaitable[patch_deployments.ListPatchDeploymentsResponse]]: - r"""Return a callable for the list patch deployments method over gRPC. - - Get a page of OS Config patch deployments. - - Returns: - Callable[[~.ListPatchDeploymentsRequest], - Awaitable[~.ListPatchDeploymentsResponse]]: - 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_patch_deployments' not in self._stubs: - self._stubs['list_patch_deployments'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/ListPatchDeployments', - request_serializer=patch_deployments.ListPatchDeploymentsRequest.serialize, - response_deserializer=patch_deployments.ListPatchDeploymentsResponse.deserialize, - ) - return self._stubs['list_patch_deployments'] - - @property - def delete_patch_deployment(self) -> Callable[ - [patch_deployments.DeletePatchDeploymentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete patch deployment method over gRPC. - - Delete an OS Config patch deployment. - - Returns: - Callable[[~.DeletePatchDeploymentRequest], - 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_patch_deployment' not in self._stubs: - self._stubs['delete_patch_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1.OsConfigService/DeletePatchDeployment', - request_serializer=patch_deployments.DeletePatchDeploymentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_patch_deployment'] - - -__all__ = ( - 'OsConfigServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py deleted file mode 100644 index 300a970..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/__init__.py +++ /dev/null @@ -1,94 +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 .inventory import ( - Inventory, -) -from .osconfig_common import ( - FixedOrPercent, -) -from .patch_deployments import ( - CreatePatchDeploymentRequest, - DeletePatchDeploymentRequest, - GetPatchDeploymentRequest, - ListPatchDeploymentsRequest, - ListPatchDeploymentsResponse, - MonthlySchedule, - OneTimeSchedule, - PatchDeployment, - RecurringSchedule, - WeekDayOfMonth, - WeeklySchedule, -) -from .patch_jobs import ( - AptSettings, - CancelPatchJobRequest, - ExecStep, - ExecStepConfig, - ExecutePatchJobRequest, - GcsObject, - GetPatchJobRequest, - GooSettings, - Instance, - ListPatchJobInstanceDetailsRequest, - ListPatchJobInstanceDetailsResponse, - ListPatchJobsRequest, - ListPatchJobsResponse, - PatchConfig, - PatchInstanceFilter, - PatchJob, - PatchJobInstanceDetails, - PatchRollout, - WindowsUpdateSettings, - YumSettings, - ZypperSettings, -) - -__all__ = ( - 'Inventory', - 'FixedOrPercent', - 'CreatePatchDeploymentRequest', - 'DeletePatchDeploymentRequest', - 'GetPatchDeploymentRequest', - 'ListPatchDeploymentsRequest', - 'ListPatchDeploymentsResponse', - 'MonthlySchedule', - 'OneTimeSchedule', - 'PatchDeployment', - 'RecurringSchedule', - 'WeekDayOfMonth', - 'WeeklySchedule', - 'AptSettings', - 'CancelPatchJobRequest', - 'ExecStep', - 'ExecStepConfig', - 'ExecutePatchJobRequest', - 'GcsObject', - 'GetPatchJobRequest', - 'GooSettings', - 'Instance', - 'ListPatchJobInstanceDetailsRequest', - 'ListPatchJobInstanceDetailsResponse', - 'ListPatchJobsRequest', - 'ListPatchJobsResponse', - 'PatchConfig', - 'PatchInstanceFilter', - 'PatchJob', - 'PatchJobInstanceDetails', - 'PatchRollout', - 'WindowsUpdateSettings', - 'YumSettings', - 'ZypperSettings', -) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py deleted file mode 100644 index 311a9dc..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/inventory.py +++ /dev/null @@ -1,520 +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 timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1', - manifest={ - 'Inventory', - }, -) - - -class Inventory(proto.Message): - r"""The inventory details of a VM. - Attributes: - os_info (google.cloud.osconfig_v1.types.Inventory.OsInfo): - Base level operating system information for - the VM. - items (Sequence[google.cloud.osconfig_v1.types.Inventory.ItemsEntry]): - Inventory items related to the VM keyed by an - opaque unique identifier for each inventory - item. The identifier is unique to each distinct - and addressable inventory item and will change, - when there is a new package version. - """ - - class OsInfo(proto.Message): - r"""Operating system information for the VM. - Attributes: - hostname (str): - The VM hostname. - long_name (str): - The operating system long name. - For example 'Debian GNU/Linux 9' or 'Microsoft - Window Server 2019 Datacenter'. - short_name (str): - The operating system short name. - For example, 'windows' or 'debian'. - version (str): - The version of the operating system. - architecture (str): - The system architecture of the operating - system. - kernel_version (str): - The kernel version of the operating system. - kernel_release (str): - The kernel release of the operating system. - osconfig_agent_version (str): - The current version of the OS Config agent - running on the VM. - """ - - hostname = proto.Field( - proto.STRING, - number=9, - ) - long_name = proto.Field( - proto.STRING, - number=2, - ) - short_name = proto.Field( - proto.STRING, - number=3, - ) - version = proto.Field( - proto.STRING, - number=4, - ) - architecture = proto.Field( - proto.STRING, - number=5, - ) - kernel_version = proto.Field( - proto.STRING, - number=6, - ) - kernel_release = proto.Field( - proto.STRING, - number=7, - ) - osconfig_agent_version = proto.Field( - proto.STRING, - number=8, - ) - - class Item(proto.Message): - r"""A single piece of inventory on a VM. - Attributes: - id (str): - Identifier for this item, unique across items - for this VM. - origin_type (google.cloud.osconfig_v1.types.Inventory.Item.OriginType): - The origin of this inventory item. - create_time (google.protobuf.timestamp_pb2.Timestamp): - When this inventory item was first detected. - update_time (google.protobuf.timestamp_pb2.Timestamp): - When this inventory item was last modified. - type_ (google.cloud.osconfig_v1.types.Inventory.Item.Type): - The specific type of inventory, correlating - to its specific details. - installed_package (google.cloud.osconfig_v1.types.Inventory.SoftwarePackage): - Software package present on the VM instance. - available_package (google.cloud.osconfig_v1.types.Inventory.SoftwarePackage): - Software package available to be installed on - the VM instance. - """ - class OriginType(proto.Enum): - r"""The origin of a specific inventory item.""" - ORIGIN_TYPE_UNSPECIFIED = 0 - INVENTORY_REPORT = 1 - - class Type(proto.Enum): - r"""The different types of inventory that are tracked on a VM.""" - TYPE_UNSPECIFIED = 0 - INSTALLED_PACKAGE = 1 - AVAILABLE_PACKAGE = 2 - - id = proto.Field( - proto.STRING, - number=1, - ) - origin_type = proto.Field( - proto.ENUM, - number=2, - enum='Inventory.Item.OriginType', - ) - create_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - type_ = proto.Field( - proto.ENUM, - number=5, - enum='Inventory.Item.Type', - ) - installed_package = proto.Field( - proto.MESSAGE, - number=6, - oneof='details', - message='Inventory.SoftwarePackage', - ) - available_package = proto.Field( - proto.MESSAGE, - number=7, - oneof='details', - message='Inventory.SoftwarePackage', - ) - - class SoftwarePackage(proto.Message): - r"""Software package information of the operating system. - Attributes: - yum_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): - Yum package info. For details about the yum package manager, - see - https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-yum. - apt_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): - Details of an APT package. - For details about the apt package manager, see - https://wiki.debian.org/Apt. - zypper_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): - Details of a Zypper package. For details about the Zypper - package manager, see - https://en.opensuse.org/SDB:Zypper_manual. - googet_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): - Details of a Googet package. - For details about the googet package manager, - see https://github.com/google/googet. - zypper_patch (google.cloud.osconfig_v1.types.Inventory.ZypperPatch): - Details of a Zypper patch. For details about the Zypper - package manager, see - https://en.opensuse.org/SDB:Zypper_manual. - wua_package (google.cloud.osconfig_v1.types.Inventory.WindowsUpdatePackage): - Details of a Windows Update package. See - https://docs.microsoft.com/en-us/windows/win32/api/_wua/ for - information about Windows Update. - qfe_package (google.cloud.osconfig_v1.types.Inventory.WindowsQuickFixEngineeringPackage): - Details of a Windows Quick Fix engineering - package. See - https://docs.microsoft.com/en- - us/windows/win32/cimwin32prov/win32-quickfixengineering - for info in Windows Quick Fix Engineering. - cos_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): - Details of a COS package. - windows_application (google.cloud.osconfig_v1.types.Inventory.WindowsApplication): - Details of a Windows Application - """ - - yum_package = proto.Field( - proto.MESSAGE, - number=1, - oneof='details', - message='Inventory.VersionedPackage', - ) - apt_package = proto.Field( - proto.MESSAGE, - number=2, - oneof='details', - message='Inventory.VersionedPackage', - ) - zypper_package = proto.Field( - proto.MESSAGE, - number=3, - oneof='details', - message='Inventory.VersionedPackage', - ) - googet_package = proto.Field( - proto.MESSAGE, - number=4, - oneof='details', - message='Inventory.VersionedPackage', - ) - zypper_patch = proto.Field( - proto.MESSAGE, - number=5, - oneof='details', - message='Inventory.ZypperPatch', - ) - wua_package = proto.Field( - proto.MESSAGE, - number=6, - oneof='details', - message='Inventory.WindowsUpdatePackage', - ) - qfe_package = proto.Field( - proto.MESSAGE, - number=7, - oneof='details', - message='Inventory.WindowsQuickFixEngineeringPackage', - ) - cos_package = proto.Field( - proto.MESSAGE, - number=8, - oneof='details', - message='Inventory.VersionedPackage', - ) - windows_application = proto.Field( - proto.MESSAGE, - number=9, - oneof='details', - message='Inventory.WindowsApplication', - ) - - class VersionedPackage(proto.Message): - r"""Information related to the a standard versioned package. - This includes package info for APT, Yum, Zypper, and Googet - package managers. - - Attributes: - package_name (str): - The name of the package. - architecture (str): - The system architecture this package is - intended for. - version (str): - The version of the package. - """ - - package_name = proto.Field( - proto.STRING, - number=4, - ) - architecture = proto.Field( - proto.STRING, - number=2, - ) - version = proto.Field( - proto.STRING, - number=3, - ) - - class WindowsUpdatePackage(proto.Message): - r"""Details related to a Windows Update package. Field data and names - are taken from Windows Update API IUpdate Interface: - https://docs.microsoft.com/en-us/windows/win32/api/_wua/ Descriptive - fields like title, and description are localized based on the locale - of the VM being updated. - - Attributes: - title (str): - The localized title of the update package. - description (str): - The localized description of the update - package. - categories (Sequence[google.cloud.osconfig_v1.types.Inventory.WindowsUpdatePackage.WindowsUpdateCategory]): - The categories that are associated with this - update package. - kb_article_ids (Sequence[str]): - A collection of Microsoft Knowledge Base - article IDs that are associated with the update - package. - support_url (str): - A hyperlink to the language-specific support - information for the update. - more_info_urls (Sequence[str]): - A collection of URLs that provide more - information about the update package. - update_id (str): - Gets the identifier of an update package. - Stays the same across revisions. - revision_number (int): - The revision number of this update package. - last_deployment_change_time (google.protobuf.timestamp_pb2.Timestamp): - The last published date of the update, in - (UTC) date and time. - """ - - class WindowsUpdateCategory(proto.Message): - r"""Categories specified by the Windows Update. - Attributes: - id (str): - The identifier of the windows update - category. - name (str): - The name of the windows update category. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - name = proto.Field( - proto.STRING, - number=2, - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - categories = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Inventory.WindowsUpdatePackage.WindowsUpdateCategory', - ) - kb_article_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - support_url = proto.Field( - proto.STRING, - number=11, - ) - more_info_urls = proto.RepeatedField( - proto.STRING, - number=5, - ) - update_id = proto.Field( - proto.STRING, - number=6, - ) - revision_number = proto.Field( - proto.INT32, - number=7, - ) - last_deployment_change_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - class ZypperPatch(proto.Message): - r"""Details related to a Zypper Patch. - Attributes: - patch_name (str): - The name of the patch. - category (str): - The category of the patch. - severity (str): - The severity specified for this patch - summary (str): - Any summary information provided about this - patch. - """ - - patch_name = proto.Field( - proto.STRING, - number=5, - ) - category = proto.Field( - proto.STRING, - number=2, - ) - severity = proto.Field( - proto.STRING, - number=3, - ) - summary = proto.Field( - proto.STRING, - number=4, - ) - - class WindowsQuickFixEngineeringPackage(proto.Message): - r"""Information related to a Quick Fix Engineering package. - Fields are taken from Windows QuickFixEngineering Interface and - match the source names: - https://docs.microsoft.com/en- - us/windows/win32/cimwin32prov/win32-quickfixengineering - - Attributes: - caption (str): - A short textual description of the QFE - update. - description (str): - A textual description of the QFE update. - hot_fix_id (str): - Unique identifier associated with a - particular QFE update. - install_time (google.protobuf.timestamp_pb2.Timestamp): - Date that the QFE update was installed. Mapped from - installed_on field. - """ - - caption = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - hot_fix_id = proto.Field( - proto.STRING, - number=3, - ) - install_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - class WindowsApplication(proto.Message): - r"""Contains information about a Windows application as retrieved from - the Windows Registry. For more information about these fields, see - - `Windows Installer Properties for the Uninstall - Registry `__\ {: - class="external" } - - Attributes: - display_name (str): - The name of the application or product. - display_version (str): - The version of the product or application in - string format. - publisher (str): - The name of the manufacturer for the product - or application. - install_date (google.type.date_pb2.Date): - The last time this product received service. - The value of this property is replaced each time - a patch is applied or removed from the product - or the command-line option is used to repair the - product. - help_link (str): - The internet address for technical support. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - display_version = proto.Field( - proto.STRING, - number=2, - ) - publisher = proto.Field( - proto.STRING, - number=3, - ) - install_date = proto.Field( - proto.MESSAGE, - number=4, - message=date_pb2.Date, - ) - help_link = proto.Field( - proto.STRING, - number=5, - ) - - os_info = proto.Field( - proto.MESSAGE, - number=1, - message=OsInfo, - ) - items = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=Item, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.py deleted file mode 100644 index 8d53f80..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_common.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.cloud.osconfig.v1', - manifest={ - 'FixedOrPercent', - }, -) - - -class FixedOrPercent(proto.Message): - r"""Message encapsulating a value that can be either absolute - ("fixed") or relative ("percent") to a value. - - Attributes: - fixed (int): - Specifies a fixed value. - percent (int): - Specifies the relative value defined as a - percentage, which will be multiplied by a - reference value. - """ - - fixed = proto.Field( - proto.INT32, - number=1, - oneof='mode', - ) - percent = proto.Field( - proto.INT32, - number=2, - oneof='mode', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_service.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_service.py deleted file mode 100644 index 9a1ec8c..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/osconfig_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.cloud.osconfig.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py deleted file mode 100644 index 73cad96..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_deployments.py +++ /dev/null @@ -1,439 +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.cloud.osconfig_v1.types import patch_jobs -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import dayofweek_pb2 # type: ignore -from google.type import timeofday_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1', - manifest={ - 'PatchDeployment', - 'OneTimeSchedule', - 'RecurringSchedule', - 'WeeklySchedule', - 'MonthlySchedule', - 'WeekDayOfMonth', - 'CreatePatchDeploymentRequest', - 'GetPatchDeploymentRequest', - 'ListPatchDeploymentsRequest', - 'ListPatchDeploymentsResponse', - 'DeletePatchDeploymentRequest', - }, -) - - -class PatchDeployment(proto.Message): - r"""Patch deployments are configurations that individual patch jobs use - to complete a patch. These configurations include instance filter, - package repository settings, and a schedule. For more information - about creating and managing patch deployments, see `Scheduling patch - jobs `__. - - Attributes: - name (str): - Unique name for the patch deployment resource in a project. - The patch deployment name is in the form: - ``projects/{project_id}/patchDeployments/{patch_deployment_id}``. - This field is ignored when you create a new patch - deployment. - description (str): - Optional. Description of the patch - deployment. Length of the description is limited - to 1024 characters. - instance_filter (google.cloud.osconfig_v1.types.PatchInstanceFilter): - Required. VM instances to patch. - patch_config (google.cloud.osconfig_v1.types.PatchConfig): - Optional. Patch configuration that is - applied. - duration (google.protobuf.duration_pb2.Duration): - Optional. Duration of the patch. After the - duration ends, the patch times out. - one_time_schedule (google.cloud.osconfig_v1.types.OneTimeSchedule): - Required. Schedule a one-time execution. - recurring_schedule (google.cloud.osconfig_v1.types.RecurringSchedule): - Required. Schedule recurring executions. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time the patch deployment was created. - Timestamp is in - `RFC3339 `__ text - format. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time the patch deployment was last updated. - Timestamp is in - `RFC3339 `__ text - format. - last_execute_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last time a patch job was started by this - deployment. Timestamp is in - `RFC3339 `__ text - format. - rollout (google.cloud.osconfig_v1.types.PatchRollout): - Optional. Rollout strategy of the patch job. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - instance_filter = proto.Field( - proto.MESSAGE, - number=3, - message=patch_jobs.PatchInstanceFilter, - ) - patch_config = proto.Field( - proto.MESSAGE, - number=4, - message=patch_jobs.PatchConfig, - ) - duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - one_time_schedule = proto.Field( - proto.MESSAGE, - number=6, - oneof='schedule', - message='OneTimeSchedule', - ) - recurring_schedule = proto.Field( - proto.MESSAGE, - number=7, - oneof='schedule', - message='RecurringSchedule', - ) - create_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - last_execute_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - rollout = proto.Field( - proto.MESSAGE, - number=11, - message=patch_jobs.PatchRollout, - ) - - -class OneTimeSchedule(proto.Message): - r"""Sets the time for a one time patch deployment. Timestamp is in - `RFC3339 `__ text format. - - Attributes: - execute_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The desired patch job execution - time. - """ - - execute_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - - -class RecurringSchedule(proto.Message): - r"""Sets the time for recurring patch deployments. - Attributes: - time_zone (google.type.datetime_pb2.TimeZone): - Required. Defines the time zone that ``time_of_day`` is - relative to. The rules for daylight saving time are - determined by the chosen time zone. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The time that the recurring schedule becomes - effective. Defaults to ``create_time`` of the patch - deployment. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The end time at which a recurring - patch deployment schedule is no longer active. - time_of_day (google.type.timeofday_pb2.TimeOfDay): - Required. Time of the day to run a recurring - deployment. - frequency (google.cloud.osconfig_v1.types.RecurringSchedule.Frequency): - Required. The frequency unit of this - recurring schedule. - weekly (google.cloud.osconfig_v1.types.WeeklySchedule): - Required. Schedule with weekly executions. - monthly (google.cloud.osconfig_v1.types.MonthlySchedule): - Required. Schedule with monthly executions. - last_execute_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the last patch job ran - successfully. - next_execute_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the next patch job is - scheduled to run. - """ - class Frequency(proto.Enum): - r"""Specifies the frequency of the recurring patch deployments.""" - FREQUENCY_UNSPECIFIED = 0 - WEEKLY = 1 - MONTHLY = 2 - - time_zone = proto.Field( - proto.MESSAGE, - number=1, - message=datetime_pb2.TimeZone, - ) - start_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - time_of_day = proto.Field( - proto.MESSAGE, - number=4, - message=timeofday_pb2.TimeOfDay, - ) - frequency = proto.Field( - proto.ENUM, - number=5, - enum=Frequency, - ) - weekly = proto.Field( - proto.MESSAGE, - number=6, - oneof='schedule_config', - message='WeeklySchedule', - ) - monthly = proto.Field( - proto.MESSAGE, - number=7, - oneof='schedule_config', - message='MonthlySchedule', - ) - last_execute_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - next_execute_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -class WeeklySchedule(proto.Message): - r"""Represents a weekly schedule. - Attributes: - day_of_week (google.type.dayofweek_pb2.DayOfWeek): - Required. Day of the week. - """ - - day_of_week = proto.Field( - proto.ENUM, - number=1, - enum=dayofweek_pb2.DayOfWeek, - ) - - -class MonthlySchedule(proto.Message): - r"""Represents a monthly schedule. An example of a valid monthly - schedule is "on the third Tuesday of the month" or "on the 15th - of the month". - - Attributes: - week_day_of_month (google.cloud.osconfig_v1.types.WeekDayOfMonth): - Required. Week day in a month. - month_day (int): - Required. One day of the month. 1-31 - indicates the 1st to the 31st day. -1 indicates - the last day of the month. Months without the - target day will be skipped. For example, a - schedule to run "every month on the 31st" will - not run in February, April, June, etc. - """ - - week_day_of_month = proto.Field( - proto.MESSAGE, - number=1, - oneof='day_of_month', - message='WeekDayOfMonth', - ) - month_day = proto.Field( - proto.INT32, - number=2, - oneof='day_of_month', - ) - - -class WeekDayOfMonth(proto.Message): - r"""Represents one week day in a month. An example is "the 4th - Sunday". - - Attributes: - week_ordinal (int): - Required. Week number in a month. 1-4 - indicates the 1st to 4th week of the month. -1 - indicates the last week of the month. - day_of_week (google.type.dayofweek_pb2.DayOfWeek): - Required. A day of the week. - """ - - week_ordinal = proto.Field( - proto.INT32, - number=1, - ) - day_of_week = proto.Field( - proto.ENUM, - number=2, - enum=dayofweek_pb2.DayOfWeek, - ) - - -class CreatePatchDeploymentRequest(proto.Message): - r"""A request message for creating a patch deployment. - Attributes: - parent (str): - Required. The project to apply this patch deployment to in - the form ``projects/*``. - patch_deployment_id (str): - Required. A name for the patch deployment in the project. - When creating a name the following rules apply: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the project. - patch_deployment (google.cloud.osconfig_v1.types.PatchDeployment): - Required. The patch deployment to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - patch_deployment_id = proto.Field( - proto.STRING, - number=2, - ) - patch_deployment = proto.Field( - proto.MESSAGE, - number=3, - message='PatchDeployment', - ) - - -class GetPatchDeploymentRequest(proto.Message): - r"""A request message for retrieving a patch deployment. - Attributes: - name (str): - Required. The resource name of the patch deployment in the - form ``projects/*/patchDeployments/*``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListPatchDeploymentsRequest(proto.Message): - r"""A request message for listing patch deployments. - Attributes: - parent (str): - Required. The resource name of the parent in the form - ``projects/*``. - page_size (int): - Optional. The maximum number of patch - deployments to return. Default is 100. - page_token (str): - Optional. A pagination token returned from a - previous call to ListPatchDeployments that - indicates where this listing should continue - from. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListPatchDeploymentsResponse(proto.Message): - r"""A response message for listing patch deployments. - Attributes: - patch_deployments (Sequence[google.cloud.osconfig_v1.types.PatchDeployment]): - The list of patch deployments. - next_page_token (str): - A pagination token that can be used to get - the next page of patch deployments. - """ - - @property - def raw_page(self): - return self - - patch_deployments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PatchDeployment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeletePatchDeploymentRequest(proto.Message): - r"""A request message for deleting a patch deployment. - Attributes: - name (str): - Required. The resource name of the patch deployment in the - form ``projects/*/patchDeployments/*``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.py b/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.py deleted file mode 100644 index cf6a700..0000000 --- a/owl-bot-staging/v1/google/cloud/osconfig_v1/types/patch_jobs.py +++ /dev/null @@ -1,1080 +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.cloud.osconfig_v1.types import osconfig_common -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1', - manifest={ - 'ExecutePatchJobRequest', - 'GetPatchJobRequest', - 'ListPatchJobInstanceDetailsRequest', - 'ListPatchJobInstanceDetailsResponse', - 'PatchJobInstanceDetails', - 'ListPatchJobsRequest', - 'ListPatchJobsResponse', - 'PatchJob', - 'PatchConfig', - 'Instance', - 'CancelPatchJobRequest', - 'AptSettings', - 'YumSettings', - 'GooSettings', - 'ZypperSettings', - 'WindowsUpdateSettings', - 'ExecStep', - 'ExecStepConfig', - 'GcsObject', - 'PatchInstanceFilter', - 'PatchRollout', - }, -) - - -class ExecutePatchJobRequest(proto.Message): - r"""A request message to initiate patching across Compute Engine - instances. - - Attributes: - parent (str): - Required. The project in which to run this patch in the form - ``projects/*`` - description (str): - Description of the patch job. Length of the - description is limited to 1024 characters. - instance_filter (google.cloud.osconfig_v1.types.PatchInstanceFilter): - Required. Instances to patch, either - explicitly or filtered by some criteria such as - zone or labels. - patch_config (google.cloud.osconfig_v1.types.PatchConfig): - Patch configuration being applied. If - omitted, instances are patched using the default - configurations. - duration (google.protobuf.duration_pb2.Duration): - Duration of the patch job. After the duration - ends, the patch job times out. - dry_run (bool): - If this patch is a dry-run only, instances - are contacted but will do nothing. - display_name (str): - Display name for this patch job. This does - not have to be unique. - rollout (google.cloud.osconfig_v1.types.PatchRollout): - Rollout strategy of the patch job. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - instance_filter = proto.Field( - proto.MESSAGE, - number=7, - message='PatchInstanceFilter', - ) - patch_config = proto.Field( - proto.MESSAGE, - number=4, - message='PatchConfig', - ) - duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - dry_run = proto.Field( - proto.BOOL, - number=6, - ) - display_name = proto.Field( - proto.STRING, - number=8, - ) - rollout = proto.Field( - proto.MESSAGE, - number=9, - message='PatchRollout', - ) - - -class GetPatchJobRequest(proto.Message): - r"""Request to get an active or completed patch job. - Attributes: - name (str): - Required. Name of the patch in the form - ``projects/*/patchJobs/*`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListPatchJobInstanceDetailsRequest(proto.Message): - r"""Request to list details for all instances that are part of a - patch job. - - Attributes: - parent (str): - Required. The parent for the instances are in the form of - ``projects/*/patchJobs/*``. - page_size (int): - The maximum number of instance details - records to return. Default is 100. - page_token (str): - A pagination token returned from a previous - call that indicates where this listing should - continue from. - filter (str): - A filter expression that filters results listed in the - response. This field supports filtering results by instance - zone, name, state, or ``failure_reason``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListPatchJobInstanceDetailsResponse(proto.Message): - r"""A response message for listing the instances details for a - patch job. - - Attributes: - patch_job_instance_details (Sequence[google.cloud.osconfig_v1.types.PatchJobInstanceDetails]): - A list of instance status. - next_page_token (str): - A pagination token that can be used to get - the next page of results. - """ - - @property - def raw_page(self): - return self - - patch_job_instance_details = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PatchJobInstanceDetails', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class PatchJobInstanceDetails(proto.Message): - r"""Patch details for a VM instance. For more information about - reviewing VM instance details, see `Listing all VM instance details - for a specific patch - job `__. - - Attributes: - name (str): - The instance name in the form - ``projects/*/zones/*/instances/*`` - instance_system_id (str): - The unique identifier for the instance. This - identifier is defined by the server. - state (google.cloud.osconfig_v1.types.Instance.PatchState): - Current state of instance patch. - failure_reason (str): - If the patch fails, this field provides the - reason. - attempt_count (int): - The number of times the agent that the agent - attempts to apply the patch. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - instance_system_id = proto.Field( - proto.STRING, - number=2, - ) - state = proto.Field( - proto.ENUM, - number=3, - enum='Instance.PatchState', - ) - failure_reason = proto.Field( - proto.STRING, - number=4, - ) - attempt_count = proto.Field( - proto.INT64, - number=5, - ) - - -class ListPatchJobsRequest(proto.Message): - r"""A request message for listing patch jobs. - Attributes: - parent (str): - Required. In the form of ``projects/*`` - page_size (int): - The maximum number of instance status to - return. - page_token (str): - A pagination token returned from a previous - call that indicates where this listing should - continue from. - filter (str): - If provided, this field specifies the criteria that must be - met by patch jobs to be included in the response. Currently, - filtering is only available on the patch_deployment field. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListPatchJobsResponse(proto.Message): - r"""A response message for listing patch jobs. - Attributes: - patch_jobs (Sequence[google.cloud.osconfig_v1.types.PatchJob]): - The list of patch jobs. - next_page_token (str): - A pagination token that can be used to get - the next page of results. - """ - - @property - def raw_page(self): - return self - - patch_jobs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='PatchJob', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class PatchJob(proto.Message): - r"""A high level representation of a patch job that is either in - progress or has completed. - - Instance details are not included in the job. To paginate through - instance details, use ListPatchJobInstanceDetails. - - For more information about patch jobs, see `Creating patch - jobs `__. - - Attributes: - name (str): - Unique identifier for this patch job in the form - ``projects/*/patchJobs/*`` - display_name (str): - Display name for this patch job. This is not - a unique identifier. - description (str): - Description of the patch job. Length of the - description is limited to 1024 characters. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time this patch job was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Last time this patch job was updated. - state (google.cloud.osconfig_v1.types.PatchJob.State): - The current state of the PatchJob. - instance_filter (google.cloud.osconfig_v1.types.PatchInstanceFilter): - Instances to patch. - patch_config (google.cloud.osconfig_v1.types.PatchConfig): - Patch configuration being applied. - duration (google.protobuf.duration_pb2.Duration): - Duration of the patch job. After the duration - ends, the patch job times out. - instance_details_summary (google.cloud.osconfig_v1.types.PatchJob.InstanceDetailsSummary): - Summary of instance details. - dry_run (bool): - If this patch job is a dry run, the agent - reports that it has finished without running any - updates on the VM instance. - error_message (str): - If this patch job failed, this message - provides information about the failure. - percent_complete (float): - Reflects the overall progress of the patch - job in the range of 0.0 being no progress to - 100.0 being complete. - patch_deployment (str): - Output only. Name of the patch deployment - that created this patch job. - rollout (google.cloud.osconfig_v1.types.PatchRollout): - Rollout strategy being applied. - """ - class State(proto.Enum): - r"""Enumeration of the various states a patch job passes through - as it executes. - """ - STATE_UNSPECIFIED = 0 - STARTED = 1 - INSTANCE_LOOKUP = 2 - PATCHING = 3 - SUCCEEDED = 4 - COMPLETED_WITH_ERRORS = 5 - CANCELED = 6 - TIMED_OUT = 7 - - class InstanceDetailsSummary(proto.Message): - r"""A summary of the current patch state across all instances that this - patch job affects. Contains counts of instances in different states. - These states map to ``InstancePatchState``. List patch job instance - details to see the specific states of each instance. - - Attributes: - pending_instance_count (int): - Number of instances pending patch job. - inactive_instance_count (int): - Number of instances that are inactive. - notified_instance_count (int): - Number of instances notified about patch job. - started_instance_count (int): - Number of instances that have started. - downloading_patches_instance_count (int): - Number of instances that are downloading - patches. - applying_patches_instance_count (int): - Number of instances that are applying - patches. - rebooting_instance_count (int): - Number of instances rebooting. - succeeded_instance_count (int): - Number of instances that have completed - successfully. - succeeded_reboot_required_instance_count (int): - Number of instances that require reboot. - failed_instance_count (int): - Number of instances that failed. - acked_instance_count (int): - Number of instances that have acked and will - start shortly. - timed_out_instance_count (int): - Number of instances that exceeded the time - out while applying the patch. - pre_patch_step_instance_count (int): - Number of instances that are running the pre- - atch step. - post_patch_step_instance_count (int): - Number of instances that are running the - post-patch step. - no_agent_detected_instance_count (int): - Number of instances that do not appear to be - running the agent. Check to ensure that the - agent is installed, running, and able to - communicate with the service. - """ - - pending_instance_count = proto.Field( - proto.INT64, - number=1, - ) - inactive_instance_count = proto.Field( - proto.INT64, - number=2, - ) - notified_instance_count = proto.Field( - proto.INT64, - number=3, - ) - started_instance_count = proto.Field( - proto.INT64, - number=4, - ) - downloading_patches_instance_count = proto.Field( - proto.INT64, - number=5, - ) - applying_patches_instance_count = proto.Field( - proto.INT64, - number=6, - ) - rebooting_instance_count = proto.Field( - proto.INT64, - number=7, - ) - succeeded_instance_count = proto.Field( - proto.INT64, - number=8, - ) - succeeded_reboot_required_instance_count = proto.Field( - proto.INT64, - number=9, - ) - failed_instance_count = proto.Field( - proto.INT64, - number=10, - ) - acked_instance_count = proto.Field( - proto.INT64, - number=11, - ) - timed_out_instance_count = proto.Field( - proto.INT64, - number=12, - ) - pre_patch_step_instance_count = proto.Field( - proto.INT64, - number=13, - ) - post_patch_step_instance_count = proto.Field( - proto.INT64, - number=14, - ) - no_agent_detected_instance_count = proto.Field( - proto.INT64, - number=15, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=14, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.ENUM, - number=5, - enum=State, - ) - instance_filter = proto.Field( - proto.MESSAGE, - number=13, - message='PatchInstanceFilter', - ) - patch_config = proto.Field( - proto.MESSAGE, - number=7, - message='PatchConfig', - ) - duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - instance_details_summary = proto.Field( - proto.MESSAGE, - number=9, - message=InstanceDetailsSummary, - ) - dry_run = proto.Field( - proto.BOOL, - number=10, - ) - error_message = proto.Field( - proto.STRING, - number=11, - ) - percent_complete = proto.Field( - proto.DOUBLE, - number=12, - ) - patch_deployment = proto.Field( - proto.STRING, - number=15, - ) - rollout = proto.Field( - proto.MESSAGE, - number=16, - message='PatchRollout', - ) - - -class PatchConfig(proto.Message): - r"""Patch configuration specifications. Contains details on how - to apply the patch(es) to a VM instance. - - Attributes: - reboot_config (google.cloud.osconfig_v1.types.PatchConfig.RebootConfig): - Post-patch reboot settings. - apt (google.cloud.osconfig_v1.types.AptSettings): - Apt update settings. Use this setting to override the - default ``apt`` patch rules. - yum (google.cloud.osconfig_v1.types.YumSettings): - Yum update settings. Use this setting to override the - default ``yum`` patch rules. - goo (google.cloud.osconfig_v1.types.GooSettings): - Goo update settings. Use this setting to override the - default ``goo`` patch rules. - zypper (google.cloud.osconfig_v1.types.ZypperSettings): - Zypper update settings. Use this setting to override the - default ``zypper`` patch rules. - windows_update (google.cloud.osconfig_v1.types.WindowsUpdateSettings): - Windows update settings. Use this override - the default windows patch rules. - pre_step (google.cloud.osconfig_v1.types.ExecStep): - The ``ExecStep`` to run before the patch update. - post_step (google.cloud.osconfig_v1.types.ExecStep): - The ``ExecStep`` to run after the patch update. - """ - class RebootConfig(proto.Enum): - r"""Post-patch reboot settings.""" - REBOOT_CONFIG_UNSPECIFIED = 0 - DEFAULT = 1 - ALWAYS = 2 - NEVER = 3 - - reboot_config = proto.Field( - proto.ENUM, - number=1, - enum=RebootConfig, - ) - apt = proto.Field( - proto.MESSAGE, - number=3, - message='AptSettings', - ) - yum = proto.Field( - proto.MESSAGE, - number=4, - message='YumSettings', - ) - goo = proto.Field( - proto.MESSAGE, - number=5, - message='GooSettings', - ) - zypper = proto.Field( - proto.MESSAGE, - number=6, - message='ZypperSettings', - ) - windows_update = proto.Field( - proto.MESSAGE, - number=7, - message='WindowsUpdateSettings', - ) - pre_step = proto.Field( - proto.MESSAGE, - number=8, - message='ExecStep', - ) - post_step = proto.Field( - proto.MESSAGE, - number=9, - message='ExecStep', - ) - - -class Instance(proto.Message): - r"""Namespace for instance state enums. """ - class PatchState(proto.Enum): - r"""Patch state of an instance.""" - PATCH_STATE_UNSPECIFIED = 0 - PENDING = 1 - INACTIVE = 2 - NOTIFIED = 3 - STARTED = 4 - DOWNLOADING_PATCHES = 5 - APPLYING_PATCHES = 6 - REBOOTING = 7 - SUCCEEDED = 8 - SUCCEEDED_REBOOT_REQUIRED = 9 - FAILED = 10 - ACKED = 11 - TIMED_OUT = 12 - RUNNING_PRE_PATCH_STEP = 13 - RUNNING_POST_PATCH_STEP = 14 - NO_AGENT_DETECTED = 15 - - -class CancelPatchJobRequest(proto.Message): - r"""Message for canceling a patch job. - Attributes: - name (str): - Required. Name of the patch in the form - ``projects/*/patchJobs/*`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class AptSettings(proto.Message): - r"""Apt patching is completed by executing - ``apt-get update && apt-get upgrade``. Additional options can be set - to control how this is executed. - - Attributes: - type_ (google.cloud.osconfig_v1.types.AptSettings.Type): - By changing the type to DIST, the patching is performed - using ``apt-get dist-upgrade`` instead. - excludes (Sequence[str]): - List of packages to exclude from update. - These packages will be excluded - exclusive_packages (Sequence[str]): - An exclusive list of packages to be updated. - These are the only packages that will be - updated. If these packages are not installed, - they will be ignored. This field cannot be - specified with any other patch configuration - fields. - """ - class Type(proto.Enum): - r"""Apt patch type.""" - TYPE_UNSPECIFIED = 0 - DIST = 1 - UPGRADE = 2 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - excludes = proto.RepeatedField( - proto.STRING, - number=2, - ) - exclusive_packages = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class YumSettings(proto.Message): - r"""Yum patching is performed by executing ``yum update``. Additional - options can be set to control how this is executed. - - Note that not all settings are supported on all platforms. - - Attributes: - security (bool): - Adds the ``--security`` flag to ``yum update``. Not - supported on all platforms. - minimal (bool): - Will cause patch to run ``yum update-minimal`` instead. - excludes (Sequence[str]): - List of packages to exclude from update. These packages are - excluded by using the yum ``--exclude`` flag. - exclusive_packages (Sequence[str]): - An exclusive list of packages to be updated. - These are the only packages that will be - updated. If these packages are not installed, - they will be ignored. This field must not be - specified with any other patch configuration - fields. - """ - - security = proto.Field( - proto.BOOL, - number=1, - ) - minimal = proto.Field( - proto.BOOL, - number=2, - ) - excludes = proto.RepeatedField( - proto.STRING, - number=3, - ) - exclusive_packages = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class GooSettings(proto.Message): - r"""Googet patching is performed by running ``googet update``. """ - - -class ZypperSettings(proto.Message): - r"""Zypper patching is performed by running ``zypper patch``. See also - https://en.opensuse.org/SDB:Zypper_manual. - - Attributes: - with_optional (bool): - Adds the ``--with-optional`` flag to ``zypper patch``. - with_update (bool): - Adds the ``--with-update`` flag, to ``zypper patch``. - categories (Sequence[str]): - Install only patches with these categories. - Common categories include security, recommended, - and feature. - severities (Sequence[str]): - Install only patches with these severities. - Common severities include critical, important, - moderate, and low. - excludes (Sequence[str]): - List of patches to exclude from update. - exclusive_patches (Sequence[str]): - An exclusive list of patches to be updated. These are the - only patches that will be installed using 'zypper patch - patch:' command. This field must not be used - with any other patch configuration fields. - """ - - with_optional = proto.Field( - proto.BOOL, - number=1, - ) - with_update = proto.Field( - proto.BOOL, - number=2, - ) - categories = proto.RepeatedField( - proto.STRING, - number=3, - ) - severities = proto.RepeatedField( - proto.STRING, - number=4, - ) - excludes = proto.RepeatedField( - proto.STRING, - number=5, - ) - exclusive_patches = proto.RepeatedField( - proto.STRING, - number=6, - ) - - -class WindowsUpdateSettings(proto.Message): - r"""Windows patching is performed using the Windows Update Agent. - Attributes: - classifications (Sequence[google.cloud.osconfig_v1.types.WindowsUpdateSettings.Classification]): - Only apply updates of these windows update - classifications. If empty, all updates are - applied. - excludes (Sequence[str]): - List of KBs to exclude from update. - exclusive_patches (Sequence[str]): - An exclusive list of kbs to be updated. These - are the only patches that will be updated. This - field must not be used with other patch - configurations. - """ - class Classification(proto.Enum): - r"""Microsoft Windows update classifications as defined in [1] - https://support.microsoft.com/en-us/help/824684/description-of-the-standard-terminology-that-is-used-to-describe-micro - """ - CLASSIFICATION_UNSPECIFIED = 0 - CRITICAL = 1 - SECURITY = 2 - DEFINITION = 3 - DRIVER = 4 - FEATURE_PACK = 5 - SERVICE_PACK = 6 - TOOL = 7 - UPDATE_ROLLUP = 8 - UPDATE = 9 - - classifications = proto.RepeatedField( - proto.ENUM, - number=1, - enum=Classification, - ) - excludes = proto.RepeatedField( - proto.STRING, - number=2, - ) - exclusive_patches = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ExecStep(proto.Message): - r"""A step that runs an executable for a PatchJob. - Attributes: - linux_exec_step_config (google.cloud.osconfig_v1.types.ExecStepConfig): - The ExecStepConfig for all Linux VMs targeted - by the PatchJob. - windows_exec_step_config (google.cloud.osconfig_v1.types.ExecStepConfig): - The ExecStepConfig for all Windows VMs - targeted by the PatchJob. - """ - - linux_exec_step_config = proto.Field( - proto.MESSAGE, - number=1, - message='ExecStepConfig', - ) - windows_exec_step_config = proto.Field( - proto.MESSAGE, - number=2, - message='ExecStepConfig', - ) - - -class ExecStepConfig(proto.Message): - r"""Common configurations for an ExecStep. - Attributes: - local_path (str): - An absolute path to the executable on the VM. - gcs_object (google.cloud.osconfig_v1.types.GcsObject): - A Cloud Storage object containing the - executable. - allowed_success_codes (Sequence[int]): - Defaults to [0]. A list of possible return values that the - execution can return to indicate a success. - interpreter (google.cloud.osconfig_v1.types.ExecStepConfig.Interpreter): - The script interpreter to use to run the script. If no - interpreter is specified the script will be executed - directly, which will likely only succeed for scripts with - [shebang lines] - (https://en.wikipedia.org/wiki/Shebang_(Unix)). - """ - class Interpreter(proto.Enum): - r"""The interpreter used to execute the a file.""" - INTERPRETER_UNSPECIFIED = 0 - SHELL = 1 - POWERSHELL = 2 - - local_path = proto.Field( - proto.STRING, - number=1, - oneof='executable', - ) - gcs_object = proto.Field( - proto.MESSAGE, - number=2, - oneof='executable', - message='GcsObject', - ) - allowed_success_codes = proto.RepeatedField( - proto.INT32, - number=3, - ) - interpreter = proto.Field( - proto.ENUM, - number=4, - enum=Interpreter, - ) - - -class GcsObject(proto.Message): - r"""Cloud Storage object representation. - Attributes: - bucket (str): - Required. Bucket of the Cloud Storage object. - object_ (str): - Required. Name of the Cloud Storage object. - generation_number (int): - Required. Generation number of the Cloud - Storage object. This is used to ensure that the - ExecStep specified by this PatchJob does not - change. - """ - - bucket = proto.Field( - proto.STRING, - number=1, - ) - object_ = proto.Field( - proto.STRING, - number=2, - ) - generation_number = proto.Field( - proto.INT64, - number=3, - ) - - -class PatchInstanceFilter(proto.Message): - r"""A filter to target VM instances for patching. The targeted - VMs must meet all criteria specified. So if both labels and - zones are specified, the patch job targets only VMs with those - labels and in those zones. - - Attributes: - all_ (bool): - Target all VM instances in the project. If - true, no other criteria is permitted. - group_labels (Sequence[google.cloud.osconfig_v1.types.PatchInstanceFilter.GroupLabel]): - Targets VM instances matching ANY of these - GroupLabels. This allows targeting of disparate - groups of VM instances. - zones (Sequence[str]): - Targets VM instances in ANY of these zones. - Leave empty to target VM instances in any zone. - instances (Sequence[str]): - Targets any of the VM instances specified. Instances are - specified by their URI in the form - ``zones/[ZONE]/instances/[INSTANCE_NAME]``, - ``projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]``, - or - ``https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]`` - instance_name_prefixes (Sequence[str]): - Targets VMs whose name starts with one of - these prefixes. Similar to labels, this is - another way to group VMs when targeting configs, - for example prefix="prod-". - """ - - class GroupLabel(proto.Message): - r"""Targets a group of VM instances by using their `assigned - labels `__. - Labels are key-value pairs. A ``GroupLabel`` is a combination of - labels that is used to target VMs for a patch job. - - For example, a patch job can target VMs that have the following - ``GroupLabel``: ``{"env":"test", "app":"web"}``. This means that the - patch job is applied to VMs that have both the labels ``env=test`` - and ``app=web``. - - Attributes: - labels (Sequence[google.cloud.osconfig_v1.types.PatchInstanceFilter.GroupLabel.LabelsEntry]): - Compute Engine instance labels that must be - present for a VM instance to be targeted by this - filter. - """ - - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - - all_ = proto.Field( - proto.BOOL, - number=1, - ) - group_labels = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=GroupLabel, - ) - zones = proto.RepeatedField( - proto.STRING, - number=3, - ) - instances = proto.RepeatedField( - proto.STRING, - number=4, - ) - instance_name_prefixes = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class PatchRollout(proto.Message): - r"""Patch rollout configuration specifications. Contains details - on the concurrency control when applying patch(es) to all - targeted VMs. - - Attributes: - mode (google.cloud.osconfig_v1.types.PatchRollout.Mode): - Mode of the patch rollout. - disruption_budget (google.cloud.osconfig_v1.types.FixedOrPercent): - The maximum number (or percentage) of VMs per zone to - disrupt at any given moment. The number of VMs calculated - from multiplying the percentage by the total number of VMs - in a zone is rounded up. - - During patching, a VM is considered disrupted from the time - the agent is notified to begin until patching has completed. - This disruption time includes the time to complete reboot - and any post-patch steps. - - A VM contributes to the disruption budget if its patching - operation fails either when applying the patches, running - pre or post patch steps, or if it fails to respond with a - success notification before timing out. VMs that are not - running or do not have an active agent do not count toward - this disruption budget. - - For zone-by-zone rollouts, if the disruption budget in a - zone is exceeded, the patch job stops, because continuing to - the next zone requires completion of the patch process in - the previous zone. - - For example, if the disruption budget has a fixed value of - ``10``, and 8 VMs fail to patch in the current zone, the - patch job continues to patch 2 VMs at a time until the zone - is completed. When that zone is completed successfully, - patching begins with 10 VMs at a time in the next zone. If - 10 VMs in the next zone fail to patch, the patch job stops. - """ - class Mode(proto.Enum): - r"""Type of the rollout.""" - MODE_UNSPECIFIED = 0 - ZONE_BY_ZONE = 1 - CONCURRENT_ZONES = 2 - - mode = proto.Field( - proto.ENUM, - number=1, - enum=Mode, - ) - disruption_budget = proto.Field( - proto.MESSAGE, - number=2, - message=osconfig_common.FixedOrPercent, - ) - - -__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 7a59b05..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/cloud/osconfig_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_osconfig_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_osconfig_v1_keywords.py deleted file mode 100644 index b5accfb..0000000 --- a/owl-bot-staging/v1/scripts/fixup_osconfig_v1_keywords.py +++ /dev/null @@ -1,184 +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 osconfigCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'cancel_patch_job': ('name', ), - 'create_patch_deployment': ('parent', 'patch_deployment_id', 'patch_deployment', ), - 'delete_patch_deployment': ('name', ), - 'execute_patch_job': ('parent', 'instance_filter', 'description', 'patch_config', 'duration', 'dry_run', 'display_name', 'rollout', ), - 'get_patch_deployment': ('name', ), - 'get_patch_job': ('name', ), - 'list_patch_deployments': ('parent', 'page_size', 'page_token', ), - 'list_patch_job_instance_details': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_patch_jobs': ('parent', 'page_size', 'page_token', 'filter', ), - } - - 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=osconfigCallTransformer(), -): - """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 osconfig 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 903433f..0000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +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-cloud-osconfig', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.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', - 'Programming Language :: Python :: 3.9', - '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/osconfig_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/osconfig_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/osconfig_v1/test_os_config_service.py b/owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/test_os_config_service.py deleted file mode 100644 index 3071b5a..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/osconfig_v1/test_os_config_service.py +++ /dev/null @@ -1,3566 +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.cloud.osconfig_v1.services.os_config_service import OsConfigServiceAsyncClient -from google.cloud.osconfig_v1.services.os_config_service import OsConfigServiceClient -from google.cloud.osconfig_v1.services.os_config_service import pagers -from google.cloud.osconfig_v1.services.os_config_service import transports -from google.cloud.osconfig_v1.services.os_config_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.osconfig_v1.types import osconfig_common -from google.cloud.osconfig_v1.types import patch_deployments -from google.cloud.osconfig_v1.types import patch_jobs -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import datetime_pb2 # type: ignore -from google.type import dayofweek_pb2 # type: ignore -from google.type import timeofday_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 OsConfigServiceClient._get_default_mtls_endpoint(None) is None - assert OsConfigServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OsConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OsConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OsConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OsConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - OsConfigServiceClient, - OsConfigServiceAsyncClient, -]) -def test_os_config_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 == 'osconfig.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.OsConfigServiceGrpcTransport, "grpc"), - (transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_os_config_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - OsConfigServiceClient, - OsConfigServiceAsyncClient, -]) -def test_os_config_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 == 'osconfig.googleapis.com:443' - - -def test_os_config_service_client_get_transport_class(): - transport = OsConfigServiceClient.get_transport_class() - available_transports = [ - transports.OsConfigServiceGrpcTransport, - ] - assert transport in available_transports - - transport = OsConfigServiceClient.get_transport_class("grpc") - assert transport == transports.OsConfigServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"), - (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(OsConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceClient)) -@mock.patch.object(OsConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceAsyncClient)) -def test_os_config_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(OsConfigServiceClient, '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(OsConfigServiceClient, '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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc", "true"), - (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc", "false"), - (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(OsConfigServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceClient)) -@mock.patch.object(OsConfigServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_os_config_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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"), - (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_os_config_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, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"), - (OsConfigServiceAsyncClient, transports.OsConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_os_config_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, - always_use_jwt_access=True, - ) - - -def test_os_config_service_client_client_options_from_dict(): - with mock.patch('google.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = OsConfigServiceClient( - 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, - always_use_jwt_access=True, - ) - - -def test_execute_patch_job(transport: str = 'grpc', request_type=patch_jobs.ExecutePatchJobRequest): - client = OsConfigServiceClient( - 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.execute_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.PatchJob( - name='name_value', - display_name='display_name_value', - description='description_value', - state=patch_jobs.PatchJob.State.STARTED, - dry_run=True, - error_message='error_message_value', - percent_complete=0.1705, - patch_deployment='patch_deployment_value', - ) - response = client.execute_patch_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ExecutePatchJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_jobs.PatchJob) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == patch_jobs.PatchJob.State.STARTED - assert response.dry_run is True - assert response.error_message == 'error_message_value' - assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) - assert response.patch_deployment == 'patch_deployment_value' - - -def test_execute_patch_job_from_dict(): - test_execute_patch_job(request_type=dict) - - -def test_execute_patch_job_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 = OsConfigServiceClient( - 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.execute_patch_job), - '__call__') as call: - client.execute_patch_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ExecutePatchJobRequest() - - -@pytest.mark.asyncio -async def test_execute_patch_job_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.ExecutePatchJobRequest): - client = OsConfigServiceAsyncClient( - 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.execute_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob( - name='name_value', - display_name='display_name_value', - description='description_value', - state=patch_jobs.PatchJob.State.STARTED, - dry_run=True, - error_message='error_message_value', - percent_complete=0.1705, - patch_deployment='patch_deployment_value', - )) - response = await client.execute_patch_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ExecutePatchJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_jobs.PatchJob) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == patch_jobs.PatchJob.State.STARTED - assert response.dry_run is True - assert response.error_message == 'error_message_value' - assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) - assert response.patch_deployment == 'patch_deployment_value' - - -@pytest.mark.asyncio -async def test_execute_patch_job_async_from_dict(): - await test_execute_patch_job_async(request_type=dict) - - -def test_execute_patch_job_field_headers(): - client = OsConfigServiceClient( - 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 = patch_jobs.ExecutePatchJobRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_patch_job), - '__call__') as call: - call.return_value = patch_jobs.PatchJob() - client.execute_patch_job(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_execute_patch_job_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_jobs.ExecutePatchJobRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_patch_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) - await client.execute_patch_job(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_get_patch_job(transport: str = 'grpc', request_type=patch_jobs.GetPatchJobRequest): - client = OsConfigServiceClient( - 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_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.PatchJob( - name='name_value', - display_name='display_name_value', - description='description_value', - state=patch_jobs.PatchJob.State.STARTED, - dry_run=True, - error_message='error_message_value', - percent_complete=0.1705, - patch_deployment='patch_deployment_value', - ) - response = client.get_patch_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.GetPatchJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_jobs.PatchJob) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == patch_jobs.PatchJob.State.STARTED - assert response.dry_run is True - assert response.error_message == 'error_message_value' - assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) - assert response.patch_deployment == 'patch_deployment_value' - - -def test_get_patch_job_from_dict(): - test_get_patch_job(request_type=dict) - - -def test_get_patch_job_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 = OsConfigServiceClient( - 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_patch_job), - '__call__') as call: - client.get_patch_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.GetPatchJobRequest() - - -@pytest.mark.asyncio -async def test_get_patch_job_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.GetPatchJobRequest): - client = OsConfigServiceAsyncClient( - 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_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob( - name='name_value', - display_name='display_name_value', - description='description_value', - state=patch_jobs.PatchJob.State.STARTED, - dry_run=True, - error_message='error_message_value', - percent_complete=0.1705, - patch_deployment='patch_deployment_value', - )) - response = await client.get_patch_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.GetPatchJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_jobs.PatchJob) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == patch_jobs.PatchJob.State.STARTED - assert response.dry_run is True - assert response.error_message == 'error_message_value' - assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) - assert response.patch_deployment == 'patch_deployment_value' - - -@pytest.mark.asyncio -async def test_get_patch_job_async_from_dict(): - await test_get_patch_job_async(request_type=dict) - - -def test_get_patch_job_field_headers(): - client = OsConfigServiceClient( - 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 = patch_jobs.GetPatchJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_job), - '__call__') as call: - call.return_value = patch_jobs.PatchJob() - client.get_patch_job(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_patch_job_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_jobs.GetPatchJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) - await client.get_patch_job(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_get_patch_job_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.PatchJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_patch_job( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_patch_job_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_patch_job( - patch_jobs.GetPatchJobRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_patch_job_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.PatchJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_patch_job( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_patch_job_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_patch_job( - patch_jobs.GetPatchJobRequest(), - name='name_value', - ) - - -def test_cancel_patch_job(transport: str = 'grpc', request_type=patch_jobs.CancelPatchJobRequest): - client = OsConfigServiceClient( - 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.cancel_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.PatchJob( - name='name_value', - display_name='display_name_value', - description='description_value', - state=patch_jobs.PatchJob.State.STARTED, - dry_run=True, - error_message='error_message_value', - percent_complete=0.1705, - patch_deployment='patch_deployment_value', - ) - response = client.cancel_patch_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.CancelPatchJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_jobs.PatchJob) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == patch_jobs.PatchJob.State.STARTED - assert response.dry_run is True - assert response.error_message == 'error_message_value' - assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) - assert response.patch_deployment == 'patch_deployment_value' - - -def test_cancel_patch_job_from_dict(): - test_cancel_patch_job(request_type=dict) - - -def test_cancel_patch_job_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 = OsConfigServiceClient( - 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.cancel_patch_job), - '__call__') as call: - client.cancel_patch_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.CancelPatchJobRequest() - - -@pytest.mark.asyncio -async def test_cancel_patch_job_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.CancelPatchJobRequest): - client = OsConfigServiceAsyncClient( - 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.cancel_patch_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob( - name='name_value', - display_name='display_name_value', - description='description_value', - state=patch_jobs.PatchJob.State.STARTED, - dry_run=True, - error_message='error_message_value', - percent_complete=0.1705, - patch_deployment='patch_deployment_value', - )) - response = await client.cancel_patch_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.CancelPatchJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_jobs.PatchJob) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == patch_jobs.PatchJob.State.STARTED - assert response.dry_run is True - assert response.error_message == 'error_message_value' - assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6) - assert response.patch_deployment == 'patch_deployment_value' - - -@pytest.mark.asyncio -async def test_cancel_patch_job_async_from_dict(): - await test_cancel_patch_job_async(request_type=dict) - - -def test_cancel_patch_job_field_headers(): - client = OsConfigServiceClient( - 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 = patch_jobs.CancelPatchJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_patch_job), - '__call__') as call: - call.return_value = patch_jobs.PatchJob() - client.cancel_patch_job(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_cancel_patch_job_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_jobs.CancelPatchJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.cancel_patch_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob()) - await client.cancel_patch_job(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_list_patch_jobs(transport: str = 'grpc', request_type=patch_jobs.ListPatchJobsRequest): - client = OsConfigServiceClient( - 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_patch_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.ListPatchJobsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_patch_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ListPatchJobsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPatchJobsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_patch_jobs_from_dict(): - test_list_patch_jobs(request_type=dict) - - -def test_list_patch_jobs_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 = OsConfigServiceClient( - 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_patch_jobs), - '__call__') as call: - client.list_patch_jobs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ListPatchJobsRequest() - - -@pytest.mark.asyncio -async def test_list_patch_jobs_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.ListPatchJobsRequest): - client = OsConfigServiceAsyncClient( - 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_patch_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_patch_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ListPatchJobsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPatchJobsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_patch_jobs_async_from_dict(): - await test_list_patch_jobs_async(request_type=dict) - - -def test_list_patch_jobs_field_headers(): - client = OsConfigServiceClient( - 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 = patch_jobs.ListPatchJobsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__') as call: - call.return_value = patch_jobs.ListPatchJobsResponse() - client.list_patch_jobs(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_patch_jobs_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_jobs.ListPatchJobsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobsResponse()) - await client.list_patch_jobs(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_patch_jobs_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.ListPatchJobsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_patch_jobs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_patch_jobs_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_patch_jobs( - patch_jobs.ListPatchJobsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_patch_jobs_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.ListPatchJobsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_patch_jobs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_patch_jobs_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_patch_jobs( - patch_jobs.ListPatchJobsRequest(), - parent='parent_value', - ) - - -def test_list_patch_jobs_pager(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_patch_jobs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, patch_jobs.PatchJob) - for i in results) - -def test_list_patch_jobs_pages(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - ), - RuntimeError, - ) - pages = list(client.list_patch_jobs(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_patch_jobs_async_pager(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_patch_jobs(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, patch_jobs.PatchJob) - for i in responses) - -@pytest.mark.asyncio -async def test_list_patch_jobs_async_pages(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobsResponse( - patch_jobs=[ - patch_jobs.PatchJob(), - patch_jobs.PatchJob(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_patch_jobs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_patch_job_instance_details(transport: str = 'grpc', request_type=patch_jobs.ListPatchJobInstanceDetailsRequest): - client = OsConfigServiceClient( - 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_patch_job_instance_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_patch_job_instance_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ListPatchJobInstanceDetailsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPatchJobInstanceDetailsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_patch_job_instance_details_from_dict(): - test_list_patch_job_instance_details(request_type=dict) - - -def test_list_patch_job_instance_details_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 = OsConfigServiceClient( - 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_patch_job_instance_details), - '__call__') as call: - client.list_patch_job_instance_details() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ListPatchJobInstanceDetailsRequest() - - -@pytest.mark.asyncio -async def test_list_patch_job_instance_details_async(transport: str = 'grpc_asyncio', request_type=patch_jobs.ListPatchJobInstanceDetailsRequest): - client = OsConfigServiceAsyncClient( - 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_patch_job_instance_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobInstanceDetailsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_patch_job_instance_details(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_jobs.ListPatchJobInstanceDetailsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPatchJobInstanceDetailsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_patch_job_instance_details_async_from_dict(): - await test_list_patch_job_instance_details_async(request_type=dict) - - -def test_list_patch_job_instance_details_field_headers(): - client = OsConfigServiceClient( - 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 = patch_jobs.ListPatchJobInstanceDetailsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__') as call: - call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse() - client.list_patch_job_instance_details(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_patch_job_instance_details_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_jobs.ListPatchJobInstanceDetailsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobInstanceDetailsResponse()) - await client.list_patch_job_instance_details(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_patch_job_instance_details_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_patch_job_instance_details( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_patch_job_instance_details_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_patch_job_instance_details( - patch_jobs.ListPatchJobInstanceDetailsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_patch_job_instance_details_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.ListPatchJobInstanceDetailsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_patch_job_instance_details( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_patch_job_instance_details_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_patch_job_instance_details( - patch_jobs.ListPatchJobInstanceDetailsRequest(), - parent='parent_value', - ) - - -def test_list_patch_job_instance_details_pager(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_patch_job_instance_details(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, patch_jobs.PatchJobInstanceDetails) - for i in results) - -def test_list_patch_job_instance_details_pages(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - ), - RuntimeError, - ) - pages = list(client.list_patch_job_instance_details(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_patch_job_instance_details_async_pager(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_patch_job_instance_details(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, patch_jobs.PatchJobInstanceDetails) - for i in responses) - -@pytest.mark.asyncio -async def test_list_patch_job_instance_details_async_pages(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_job_instance_details), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='abc', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[], - next_page_token='def', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - ], - next_page_token='ghi', - ), - patch_jobs.ListPatchJobInstanceDetailsResponse( - patch_job_instance_details=[ - patch_jobs.PatchJobInstanceDetails(), - patch_jobs.PatchJobInstanceDetails(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_patch_job_instance_details(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_create_patch_deployment(transport: str = 'grpc', request_type=patch_deployments.CreatePatchDeploymentRequest): - client = OsConfigServiceClient( - 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_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.PatchDeployment( - name='name_value', - description='description_value', - one_time_schedule=patch_deployments.OneTimeSchedule(execute_time=timestamp_pb2.Timestamp(seconds=751)), - ) - response = client.create_patch_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.CreatePatchDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_deployments.PatchDeployment) - assert response.name == 'name_value' - assert response.description == 'description_value' - - -def test_create_patch_deployment_from_dict(): - test_create_patch_deployment(request_type=dict) - - -def test_create_patch_deployment_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 = OsConfigServiceClient( - 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_patch_deployment), - '__call__') as call: - client.create_patch_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.CreatePatchDeploymentRequest() - - -@pytest.mark.asyncio -async def test_create_patch_deployment_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.CreatePatchDeploymentRequest): - client = OsConfigServiceAsyncClient( - 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_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment( - name='name_value', - description='description_value', - )) - response = await client.create_patch_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.CreatePatchDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_deployments.PatchDeployment) - assert response.name == 'name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_patch_deployment_async_from_dict(): - await test_create_patch_deployment_async(request_type=dict) - - -def test_create_patch_deployment_field_headers(): - client = OsConfigServiceClient( - 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 = patch_deployments.CreatePatchDeploymentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_patch_deployment), - '__call__') as call: - call.return_value = patch_deployments.PatchDeployment() - client.create_patch_deployment(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_patch_deployment_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_deployments.CreatePatchDeploymentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_patch_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) - await client.create_patch_deployment(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_create_patch_deployment_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.PatchDeployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_patch_deployment( - parent='parent_value', - patch_deployment=patch_deployments.PatchDeployment(name='name_value'), - patch_deployment_id='patch_deployment_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].patch_deployment == patch_deployments.PatchDeployment(name='name_value') - assert args[0].patch_deployment_id == 'patch_deployment_id_value' - - -def test_create_patch_deployment_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_patch_deployment( - patch_deployments.CreatePatchDeploymentRequest(), - parent='parent_value', - patch_deployment=patch_deployments.PatchDeployment(name='name_value'), - patch_deployment_id='patch_deployment_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_patch_deployment_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.PatchDeployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_patch_deployment( - parent='parent_value', - patch_deployment=patch_deployments.PatchDeployment(name='name_value'), - patch_deployment_id='patch_deployment_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].patch_deployment == patch_deployments.PatchDeployment(name='name_value') - assert args[0].patch_deployment_id == 'patch_deployment_id_value' - - -@pytest.mark.asyncio -async def test_create_patch_deployment_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_patch_deployment( - patch_deployments.CreatePatchDeploymentRequest(), - parent='parent_value', - patch_deployment=patch_deployments.PatchDeployment(name='name_value'), - patch_deployment_id='patch_deployment_id_value', - ) - - -def test_get_patch_deployment(transport: str = 'grpc', request_type=patch_deployments.GetPatchDeploymentRequest): - client = OsConfigServiceClient( - 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_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.PatchDeployment( - name='name_value', - description='description_value', - one_time_schedule=patch_deployments.OneTimeSchedule(execute_time=timestamp_pb2.Timestamp(seconds=751)), - ) - response = client.get_patch_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.GetPatchDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_deployments.PatchDeployment) - assert response.name == 'name_value' - assert response.description == 'description_value' - - -def test_get_patch_deployment_from_dict(): - test_get_patch_deployment(request_type=dict) - - -def test_get_patch_deployment_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 = OsConfigServiceClient( - 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_patch_deployment), - '__call__') as call: - client.get_patch_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.GetPatchDeploymentRequest() - - -@pytest.mark.asyncio -async def test_get_patch_deployment_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.GetPatchDeploymentRequest): - client = OsConfigServiceAsyncClient( - 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_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment( - name='name_value', - description='description_value', - )) - response = await client.get_patch_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.GetPatchDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, patch_deployments.PatchDeployment) - assert response.name == 'name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_patch_deployment_async_from_dict(): - await test_get_patch_deployment_async(request_type=dict) - - -def test_get_patch_deployment_field_headers(): - client = OsConfigServiceClient( - 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 = patch_deployments.GetPatchDeploymentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_deployment), - '__call__') as call: - call.return_value = patch_deployments.PatchDeployment() - client.get_patch_deployment(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_patch_deployment_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_deployments.GetPatchDeploymentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) - await client.get_patch_deployment(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_get_patch_deployment_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.PatchDeployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_patch_deployment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_patch_deployment_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_patch_deployment( - patch_deployments.GetPatchDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_patch_deployment_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.PatchDeployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.PatchDeployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_patch_deployment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_patch_deployment_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_patch_deployment( - patch_deployments.GetPatchDeploymentRequest(), - name='name_value', - ) - - -def test_list_patch_deployments(transport: str = 'grpc', request_type=patch_deployments.ListPatchDeploymentsRequest): - client = OsConfigServiceClient( - 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_patch_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.ListPatchDeploymentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_patch_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.ListPatchDeploymentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPatchDeploymentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_patch_deployments_from_dict(): - test_list_patch_deployments(request_type=dict) - - -def test_list_patch_deployments_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 = OsConfigServiceClient( - 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_patch_deployments), - '__call__') as call: - client.list_patch_deployments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.ListPatchDeploymentsRequest() - - -@pytest.mark.asyncio -async def test_list_patch_deployments_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.ListPatchDeploymentsRequest): - client = OsConfigServiceAsyncClient( - 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_patch_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.ListPatchDeploymentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_patch_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.ListPatchDeploymentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPatchDeploymentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_patch_deployments_async_from_dict(): - await test_list_patch_deployments_async(request_type=dict) - - -def test_list_patch_deployments_field_headers(): - client = OsConfigServiceClient( - 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 = patch_deployments.ListPatchDeploymentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__') as call: - call.return_value = patch_deployments.ListPatchDeploymentsResponse() - client.list_patch_deployments(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_patch_deployments_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_deployments.ListPatchDeploymentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.ListPatchDeploymentsResponse()) - await client.list_patch_deployments(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_patch_deployments_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.ListPatchDeploymentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_patch_deployments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_patch_deployments_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_patch_deployments( - patch_deployments.ListPatchDeploymentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_patch_deployments_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = patch_deployments.ListPatchDeploymentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_deployments.ListPatchDeploymentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_patch_deployments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_patch_deployments_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_patch_deployments( - patch_deployments.ListPatchDeploymentsRequest(), - parent='parent_value', - ) - - -def test_list_patch_deployments_pager(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - next_page_token='abc', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[], - next_page_token='def', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - ], - next_page_token='ghi', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_patch_deployments(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, patch_deployments.PatchDeployment) - for i in results) - -def test_list_patch_deployments_pages(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - next_page_token='abc', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[], - next_page_token='def', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - ], - next_page_token='ghi', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_patch_deployments(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_patch_deployments_async_pager(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - next_page_token='abc', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[], - next_page_token='def', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - ], - next_page_token='ghi', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_patch_deployments(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, patch_deployments.PatchDeployment) - for i in responses) - -@pytest.mark.asyncio -async def test_list_patch_deployments_async_pages(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_patch_deployments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - next_page_token='abc', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[], - next_page_token='def', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - ], - next_page_token='ghi', - ), - patch_deployments.ListPatchDeploymentsResponse( - patch_deployments=[ - patch_deployments.PatchDeployment(), - patch_deployments.PatchDeployment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_patch_deployments(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_patch_deployment(transport: str = 'grpc', request_type=patch_deployments.DeletePatchDeploymentRequest): - client = OsConfigServiceClient( - 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_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_patch_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.DeletePatchDeploymentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_patch_deployment_from_dict(): - test_delete_patch_deployment(request_type=dict) - - -def test_delete_patch_deployment_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 = OsConfigServiceClient( - 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_patch_deployment), - '__call__') as call: - client.delete_patch_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.DeletePatchDeploymentRequest() - - -@pytest.mark.asyncio -async def test_delete_patch_deployment_async(transport: str = 'grpc_asyncio', request_type=patch_deployments.DeletePatchDeploymentRequest): - client = OsConfigServiceAsyncClient( - 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_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_patch_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == patch_deployments.DeletePatchDeploymentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_patch_deployment_async_from_dict(): - await test_delete_patch_deployment_async(request_type=dict) - - -def test_delete_patch_deployment_field_headers(): - client = OsConfigServiceClient( - 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 = patch_deployments.DeletePatchDeploymentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_patch_deployment), - '__call__') as call: - call.return_value = None - client.delete_patch_deployment(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_patch_deployment_field_headers_async(): - client = OsConfigServiceAsyncClient( - 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 = patch_deployments.DeletePatchDeploymentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_patch_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_patch_deployment(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_patch_deployment_flattened(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_patch_deployment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_patch_deployment_flattened_error(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_patch_deployment( - patch_deployments.DeletePatchDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_patch_deployment_flattened_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_patch_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_patch_deployment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_patch_deployment_flattened_error_async(): - client = OsConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_patch_deployment( - patch_deployments.DeletePatchDeploymentRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OsConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.OsConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.OsConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OsConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = OsConfigServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OsConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.OsConfigServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.OsConfigServiceGrpcTransport, - transports.OsConfigServiceGrpcAsyncIOTransport, -]) -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 = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.OsConfigServiceGrpcTransport, - ) - -def test_os_config_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.OsConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_os_config_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.OsConfigServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'execute_patch_job', - 'get_patch_job', - 'cancel_patch_job', - 'list_patch_jobs', - 'list_patch_job_instance_details', - 'create_patch_deployment', - 'get_patch_deployment', - 'list_patch_deployments', - 'delete_patch_deployment', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_os_config_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.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OsConfigServiceTransport( - 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', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_os_config_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.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OsConfigServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_os_config_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.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OsConfigServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_os_config_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) - OsConfigServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_os_config_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) - OsConfigServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.OsConfigServiceGrpcTransport, - transports.OsConfigServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_os_config_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',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.OsConfigServiceGrpcTransport, - transports.OsConfigServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_os_config_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', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.OsConfigServiceGrpcTransport, grpc_helpers), - (transports.OsConfigServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_os_config_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( - "osconfig.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="osconfig.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.OsConfigServiceGrpcTransport, transports.OsConfigServiceGrpcAsyncIOTransport]) -def test_os_config_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=None, - 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_os_config_service_host_no_port(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com'), - ) - assert client.transport._host == 'osconfig.googleapis.com:443' - - -def test_os_config_service_host_with_port(): - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com:8000'), - ) - assert client.transport._host == 'osconfig.googleapis.com:8000' - -def test_os_config_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OsConfigServiceGrpcTransport( - 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_os_config_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OsConfigServiceGrpcAsyncIOTransport( - 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.OsConfigServiceGrpcTransport, transports.OsConfigServiceGrpcAsyncIOTransport]) -def test_os_config_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=None, - 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.OsConfigServiceGrpcTransport, transports.OsConfigServiceGrpcAsyncIOTransport]) -def test_os_config_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=None, - 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_instance_path(): - project = "squid" - zone = "clam" - instance = "whelk" - expected = "projects/{project}/zones/{zone}/instances/{instance}".format(project=project, zone=zone, instance=instance, ) - actual = OsConfigServiceClient.instance_path(project, zone, instance) - assert expected == actual - - -def test_parse_instance_path(): - expected = { - "project": "octopus", - "zone": "oyster", - "instance": "nudibranch", - } - path = OsConfigServiceClient.instance_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_instance_path(path) - assert expected == actual - -def test_patch_deployment_path(): - project = "cuttlefish" - patch_deployment = "mussel" - expected = "projects/{project}/patchDeployments/{patch_deployment}".format(project=project, patch_deployment=patch_deployment, ) - actual = OsConfigServiceClient.patch_deployment_path(project, patch_deployment) - assert expected == actual - - -def test_parse_patch_deployment_path(): - expected = { - "project": "winkle", - "patch_deployment": "nautilus", - } - path = OsConfigServiceClient.patch_deployment_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_patch_deployment_path(path) - assert expected == actual - -def test_patch_job_path(): - project = "scallop" - patch_job = "abalone" - expected = "projects/{project}/patchJobs/{patch_job}".format(project=project, patch_job=patch_job, ) - actual = OsConfigServiceClient.patch_job_path(project, patch_job) - assert expected == actual - - -def test_parse_patch_job_path(): - expected = { - "project": "squid", - "patch_job": "clam", - } - path = OsConfigServiceClient.patch_job_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_patch_job_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OsConfigServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = OsConfigServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = OsConfigServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = OsConfigServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OsConfigServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = OsConfigServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = OsConfigServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = OsConfigServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = OsConfigServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = OsConfigServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigServiceClient.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.OsConfigServiceTransport, '_prep_wrapped_messages') as prep: - client = OsConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.OsConfigServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = OsConfigServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1alpha/.coveragerc b/owl-bot-staging/v1alpha/.coveragerc deleted file mode 100644 index d146ff0..0000000 --- a/owl-bot-staging/v1alpha/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/osconfig/__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/v1alpha/MANIFEST.in b/owl-bot-staging/v1alpha/MANIFEST.in deleted file mode 100644 index 5e29933..0000000 --- a/owl-bot-staging/v1alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/osconfig *.py -recursive-include google/cloud/osconfig_v1alpha *.py diff --git a/owl-bot-staging/v1alpha/README.rst b/owl-bot-staging/v1alpha/README.rst deleted file mode 100644 index d649bbe..0000000 --- a/owl-bot-staging/v1alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Osconfig 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 Cloud Osconfig 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/v1alpha/docs/conf.py b/owl-bot-staging/v1alpha/docs/conf.py deleted file mode 100644 index 9dc389a..0000000 --- a/owl-bot-staging/v1alpha/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-cloud-osconfig 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-cloud-osconfig" -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 Cloud 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-cloud-osconfig-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-cloud-osconfig.tex", - u"google-cloud-osconfig Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-osconfig", - u"Google Cloud Osconfig Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-osconfig", - u"google-cloud-osconfig Documentation", - author, - "google-cloud-osconfig", - "GAPIC library for Google Cloud Osconfig 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/v1alpha/docs/index.rst b/owl-bot-staging/v1alpha/docs/index.rst deleted file mode 100644 index b4b9003..0000000 --- a/owl-bot-staging/v1alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - osconfig_v1alpha/services - osconfig_v1alpha/types diff --git a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst deleted file mode 100644 index c4cbbee..0000000 --- a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/os_config_zonal_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -OsConfigZonalService --------------------------------------- - -.. automodule:: google.cloud.osconfig_v1alpha.services.os_config_zonal_service - :members: - :inherited-members: - -.. automodule:: google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst deleted file mode 100644 index 2f77a4c..0000000 --- a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Osconfig v1alpha API -============================================== -.. toctree:: - :maxdepth: 2 - - os_config_zonal_service diff --git a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst b/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst deleted file mode 100644 index 84add7e..0000000 --- a/owl-bot-staging/v1alpha/docs/osconfig_v1alpha/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Osconfig v1alpha API -=========================================== - -.. automodule:: google.cloud.osconfig_v1alpha.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py deleted file mode 100644 index e241de9..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig/__init__.py +++ /dev/null @@ -1,81 +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.cloud.osconfig_v1alpha.services.os_config_zonal_service.client import OsConfigZonalServiceClient -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service.async_client import OsConfigZonalServiceAsyncClient - -from google.cloud.osconfig_v1alpha.types.config_common import OSPolicyResourceCompliance -from google.cloud.osconfig_v1alpha.types.config_common import OSPolicyResourceConfigStep -from google.cloud.osconfig_v1alpha.types.config_common import OSPolicyComplianceState -from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import GetInstanceOSPoliciesComplianceRequest -from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import InstanceOSPoliciesCompliance -from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesRequest -from google.cloud.osconfig_v1alpha.types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesResponse -from google.cloud.osconfig_v1alpha.types.inventory import GetInventoryRequest -from google.cloud.osconfig_v1alpha.types.inventory import Inventory -from google.cloud.osconfig_v1alpha.types.inventory import ListInventoriesRequest -from google.cloud.osconfig_v1alpha.types.inventory import ListInventoriesResponse -from google.cloud.osconfig_v1alpha.types.inventory import InventoryView -from google.cloud.osconfig_v1alpha.types.os_policy import OSPolicy -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import CreateOSPolicyAssignmentRequest -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import DeleteOSPolicyAssignmentRequest -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import GetOSPolicyAssignmentRequest -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentRevisionsRequest -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentRevisionsResponse -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentsRequest -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import ListOSPolicyAssignmentsResponse -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import OSPolicyAssignment -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import OSPolicyAssignmentOperationMetadata -from google.cloud.osconfig_v1alpha.types.os_policy_assignments import UpdateOSPolicyAssignmentRequest -from google.cloud.osconfig_v1alpha.types.osconfig_common import FixedOrPercent -from google.cloud.osconfig_v1alpha.types.vulnerability import CVSSv3 -from google.cloud.osconfig_v1alpha.types.vulnerability import GetVulnerabilityReportRequest -from google.cloud.osconfig_v1alpha.types.vulnerability import ListVulnerabilityReportsRequest -from google.cloud.osconfig_v1alpha.types.vulnerability import ListVulnerabilityReportsResponse -from google.cloud.osconfig_v1alpha.types.vulnerability import VulnerabilityReport - -__all__ = ('OsConfigZonalServiceClient', - 'OsConfigZonalServiceAsyncClient', - 'OSPolicyResourceCompliance', - 'OSPolicyResourceConfigStep', - 'OSPolicyComplianceState', - 'GetInstanceOSPoliciesComplianceRequest', - 'InstanceOSPoliciesCompliance', - 'ListInstanceOSPoliciesCompliancesRequest', - 'ListInstanceOSPoliciesCompliancesResponse', - 'GetInventoryRequest', - 'Inventory', - 'ListInventoriesRequest', - 'ListInventoriesResponse', - 'InventoryView', - 'OSPolicy', - 'CreateOSPolicyAssignmentRequest', - 'DeleteOSPolicyAssignmentRequest', - 'GetOSPolicyAssignmentRequest', - 'ListOSPolicyAssignmentRevisionsRequest', - 'ListOSPolicyAssignmentRevisionsResponse', - 'ListOSPolicyAssignmentsRequest', - 'ListOSPolicyAssignmentsResponse', - 'OSPolicyAssignment', - 'OSPolicyAssignmentOperationMetadata', - 'UpdateOSPolicyAssignmentRequest', - 'FixedOrPercent', - 'CVSSv3', - 'GetVulnerabilityReportRequest', - 'ListVulnerabilityReportsRequest', - 'ListVulnerabilityReportsResponse', - 'VulnerabilityReport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed b/owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed deleted file mode 100644 index e2df01b..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py deleted file mode 100644 index 3de3d41..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/__init__.py +++ /dev/null @@ -1,82 +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.os_config_zonal_service import OsConfigZonalServiceClient -from .services.os_config_zonal_service import OsConfigZonalServiceAsyncClient - -from .types.config_common import OSPolicyResourceCompliance -from .types.config_common import OSPolicyResourceConfigStep -from .types.config_common import OSPolicyComplianceState -from .types.instance_os_policies_compliance import GetInstanceOSPoliciesComplianceRequest -from .types.instance_os_policies_compliance import InstanceOSPoliciesCompliance -from .types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesRequest -from .types.instance_os_policies_compliance import ListInstanceOSPoliciesCompliancesResponse -from .types.inventory import GetInventoryRequest -from .types.inventory import Inventory -from .types.inventory import ListInventoriesRequest -from .types.inventory import ListInventoriesResponse -from .types.inventory import InventoryView -from .types.os_policy import OSPolicy -from .types.os_policy_assignments import CreateOSPolicyAssignmentRequest -from .types.os_policy_assignments import DeleteOSPolicyAssignmentRequest -from .types.os_policy_assignments import GetOSPolicyAssignmentRequest -from .types.os_policy_assignments import ListOSPolicyAssignmentRevisionsRequest -from .types.os_policy_assignments import ListOSPolicyAssignmentRevisionsResponse -from .types.os_policy_assignments import ListOSPolicyAssignmentsRequest -from .types.os_policy_assignments import ListOSPolicyAssignmentsResponse -from .types.os_policy_assignments import OSPolicyAssignment -from .types.os_policy_assignments import OSPolicyAssignmentOperationMetadata -from .types.os_policy_assignments import UpdateOSPolicyAssignmentRequest -from .types.osconfig_common import FixedOrPercent -from .types.vulnerability import CVSSv3 -from .types.vulnerability import GetVulnerabilityReportRequest -from .types.vulnerability import ListVulnerabilityReportsRequest -from .types.vulnerability import ListVulnerabilityReportsResponse -from .types.vulnerability import VulnerabilityReport - -__all__ = ( - 'OsConfigZonalServiceAsyncClient', -'CVSSv3', -'CreateOSPolicyAssignmentRequest', -'DeleteOSPolicyAssignmentRequest', -'FixedOrPercent', -'GetInstanceOSPoliciesComplianceRequest', -'GetInventoryRequest', -'GetOSPolicyAssignmentRequest', -'GetVulnerabilityReportRequest', -'InstanceOSPoliciesCompliance', -'Inventory', -'InventoryView', -'ListInstanceOSPoliciesCompliancesRequest', -'ListInstanceOSPoliciesCompliancesResponse', -'ListInventoriesRequest', -'ListInventoriesResponse', -'ListOSPolicyAssignmentRevisionsRequest', -'ListOSPolicyAssignmentRevisionsResponse', -'ListOSPolicyAssignmentsRequest', -'ListOSPolicyAssignmentsResponse', -'ListVulnerabilityReportsRequest', -'ListVulnerabilityReportsResponse', -'OSPolicy', -'OSPolicyAssignment', -'OSPolicyAssignmentOperationMetadata', -'OSPolicyComplianceState', -'OSPolicyResourceCompliance', -'OSPolicyResourceConfigStep', -'OsConfigZonalServiceClient', -'UpdateOSPolicyAssignmentRequest', -'VulnerabilityReport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json deleted file mode 100644 index 7429575..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/gapic_metadata.json +++ /dev/null @@ -1,143 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.osconfig_v1alpha", - "protoPackage": "google.cloud.osconfig.v1alpha", - "schema": "1.0", - "services": { - "OsConfigZonalService": { - "clients": { - "grpc": { - "libraryClient": "OsConfigZonalServiceClient", - "rpcs": { - "CreateOSPolicyAssignment": { - "methods": [ - "create_os_policy_assignment" - ] - }, - "DeleteOSPolicyAssignment": { - "methods": [ - "delete_os_policy_assignment" - ] - }, - "GetInstanceOSPoliciesCompliance": { - "methods": [ - "get_instance_os_policies_compliance" - ] - }, - "GetInventory": { - "methods": [ - "get_inventory" - ] - }, - "GetOSPolicyAssignment": { - "methods": [ - "get_os_policy_assignment" - ] - }, - "GetVulnerabilityReport": { - "methods": [ - "get_vulnerability_report" - ] - }, - "ListInstanceOSPoliciesCompliances": { - "methods": [ - "list_instance_os_policies_compliances" - ] - }, - "ListInventories": { - "methods": [ - "list_inventories" - ] - }, - "ListOSPolicyAssignmentRevisions": { - "methods": [ - "list_os_policy_assignment_revisions" - ] - }, - "ListOSPolicyAssignments": { - "methods": [ - "list_os_policy_assignments" - ] - }, - "ListVulnerabilityReports": { - "methods": [ - "list_vulnerability_reports" - ] - }, - "UpdateOSPolicyAssignment": { - "methods": [ - "update_os_policy_assignment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OsConfigZonalServiceAsyncClient", - "rpcs": { - "CreateOSPolicyAssignment": { - "methods": [ - "create_os_policy_assignment" - ] - }, - "DeleteOSPolicyAssignment": { - "methods": [ - "delete_os_policy_assignment" - ] - }, - "GetInstanceOSPoliciesCompliance": { - "methods": [ - "get_instance_os_policies_compliance" - ] - }, - "GetInventory": { - "methods": [ - "get_inventory" - ] - }, - "GetOSPolicyAssignment": { - "methods": [ - "get_os_policy_assignment" - ] - }, - "GetVulnerabilityReport": { - "methods": [ - "get_vulnerability_report" - ] - }, - "ListInstanceOSPoliciesCompliances": { - "methods": [ - "list_instance_os_policies_compliances" - ] - }, - "ListInventories": { - "methods": [ - "list_inventories" - ] - }, - "ListOSPolicyAssignmentRevisions": { - "methods": [ - "list_os_policy_assignment_revisions" - ] - }, - "ListOSPolicyAssignments": { - "methods": [ - "list_os_policy_assignments" - ] - }, - "ListVulnerabilityReports": { - "methods": [ - "list_vulnerability_reports" - ] - }, - "UpdateOSPolicyAssignment": { - "methods": [ - "update_os_policy_assignment" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed deleted file mode 100644 index e2df01b..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-osconfig package uses inline types. diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/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/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/__init__.py deleted file mode 100644 index aa429a5..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_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 OsConfigZonalServiceClient -from .async_client import OsConfigZonalServiceAsyncClient - -__all__ = ( - 'OsConfigZonalServiceClient', - 'OsConfigZonalServiceAsyncClient', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py deleted file mode 100644 index 0835ba2..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py +++ /dev/null @@ -1,1372 +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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import pagers -from google.cloud.osconfig_v1alpha.types import config_common -from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import vulnerability -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport -from .client import OsConfigZonalServiceClient - - -class OsConfigZonalServiceAsyncClient: - """Zonal OS Config API - The OS Config service is the server-side component that allows - users to manage package installations and patch jobs for Compute - Engine VM instances. - """ - - _client: OsConfigZonalServiceClient - - DEFAULT_ENDPOINT = OsConfigZonalServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = OsConfigZonalServiceClient.DEFAULT_MTLS_ENDPOINT - - instance_path = staticmethod(OsConfigZonalServiceClient.instance_path) - parse_instance_path = staticmethod(OsConfigZonalServiceClient.parse_instance_path) - instance_os_policies_compliance_path = staticmethod(OsConfigZonalServiceClient.instance_os_policies_compliance_path) - parse_instance_os_policies_compliance_path = staticmethod(OsConfigZonalServiceClient.parse_instance_os_policies_compliance_path) - inventory_path = staticmethod(OsConfigZonalServiceClient.inventory_path) - parse_inventory_path = staticmethod(OsConfigZonalServiceClient.parse_inventory_path) - os_policy_assignment_path = staticmethod(OsConfigZonalServiceClient.os_policy_assignment_path) - parse_os_policy_assignment_path = staticmethod(OsConfigZonalServiceClient.parse_os_policy_assignment_path) - vulnerability_report_path = staticmethod(OsConfigZonalServiceClient.vulnerability_report_path) - parse_vulnerability_report_path = staticmethod(OsConfigZonalServiceClient.parse_vulnerability_report_path) - common_billing_account_path = staticmethod(OsConfigZonalServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OsConfigZonalServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OsConfigZonalServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OsConfigZonalServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OsConfigZonalServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OsConfigZonalServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OsConfigZonalServiceClient.common_project_path) - parse_common_project_path = staticmethod(OsConfigZonalServiceClient.parse_common_project_path) - common_location_path = staticmethod(OsConfigZonalServiceClient.common_location_path) - parse_common_location_path = staticmethod(OsConfigZonalServiceClient.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: - OsConfigZonalServiceAsyncClient: The constructed client. - """ - return OsConfigZonalServiceClient.from_service_account_info.__func__(OsConfigZonalServiceAsyncClient, 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: - OsConfigZonalServiceAsyncClient: The constructed client. - """ - return OsConfigZonalServiceClient.from_service_account_file.__func__(OsConfigZonalServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> OsConfigZonalServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OsConfigZonalServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(OsConfigZonalServiceClient).get_transport_class, type(OsConfigZonalServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, OsConfigZonalServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the os config zonal 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, ~.OsConfigZonalServiceTransport]): 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 = OsConfigZonalServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_os_policy_assignment(self, - request: os_policy_assignments.CreateOSPolicyAssignmentRequest = None, - *, - parent: str = None, - os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, - os_policy_assignment_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create an OS policy assignment. - - This method also creates the first revision of the OS policy - assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.CreateOSPolicyAssignmentRequest`): - The request object. A request message to create an OS - policy assignment - parent (:class:`str`): - Required. The parent resource name in - the form: - projects/{project}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - os_policy_assignment (:class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment`): - Required. The OS policy assignment to - be created. - - This corresponds to the ``os_policy_assignment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - os_policy_assignment_id (:class:`str`): - Required. The logical name of the OS policy assignment - in the project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the project. - - This corresponds to the ``os_policy_assignment_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to - apply a set of OS policies to a dynamically targeted - group of Compute Engine VM instances. - - An OS policy is used to define the desired state - configuration for a Compute Engine VM instance - through a set of configuration resources that provide - capabilities such as installing or removing software - packages, or executing a script. - - For more information, see [OS policy and OS policy - assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, os_policy_assignment, os_policy_assignment_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = os_policy_assignments.CreateOSPolicyAssignmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if os_policy_assignment is not None: - request.os_policy_assignment = os_policy_assignment - if os_policy_assignment_id is not None: - request.os_policy_assignment_id = os_policy_assignment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_os_policy_assignment, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - os_policy_assignments.OSPolicyAssignment, - metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, - ) - - # Done; return the response. - return response - - async def update_os_policy_assignment(self, - request: os_policy_assignments.UpdateOSPolicyAssignmentRequest = None, - *, - os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Update an existing OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.UpdateOSPolicyAssignmentRequest`): - The request object. A request message to update an OS - policy assignment - os_policy_assignment (:class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment`): - Required. The updated OS policy - assignment. - - This corresponds to the ``os_policy_assignment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask that controls - which fields of the assignment should be - updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to - apply a set of OS policies to a dynamically targeted - group of Compute Engine VM instances. - - An OS policy is used to define the desired state - configuration for a Compute Engine VM instance - through a set of configuration resources that provide - capabilities such as installing or removing software - packages, or executing a script. - - For more information, see [OS policy and OS policy - assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([os_policy_assignment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = os_policy_assignments.UpdateOSPolicyAssignmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if os_policy_assignment is not None: - request.os_policy_assignment = os_policy_assignment - if update_mask is not None: - request.update_mask = update_mask - - # 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_os_policy_assignment, - 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(( - ("os_policy_assignment.name", request.os_policy_assignment.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - os_policy_assignments.OSPolicyAssignment, - metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_os_policy_assignment(self, - request: os_policy_assignments.GetOSPolicyAssignmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> os_policy_assignments.OSPolicyAssignment: - r"""Retrieve an existing OS policy assignment. - - This method always returns the latest revision. In order to - retrieve a previous revision of the assignment, also provide the - revision ID in the ``name`` parameter. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.GetOSPolicyAssignmentRequest`): - The request object. A request message to get an OS - policy assignment - name (:class:`str`): - Required. The resource name of OS policy assignment. - - Format: - ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.OSPolicyAssignment: - OS policy assignment is an API resource that is used to - apply a set of OS policies to a dynamically targeted - group of Compute Engine VM instances. - - An OS policy is used to define the desired state - configuration for a Compute Engine VM instance - through a set of configuration resources that provide - capabilities such as installing or removing software - packages, or executing a script. - - For more information, see [OS policy and OS policy - assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = os_policy_assignments.GetOSPolicyAssignmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_os_policy_assignment, - 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 list_os_policy_assignments(self, - request: os_policy_assignments.ListOSPolicyAssignmentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListOSPolicyAssignmentsAsyncPager: - r"""List the OS policy assignments under the parent - resource. - For each OS policy assignment, the latest revision is - returned. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest`): - The request object. A request message to list OS policy - assignments for a parent resource - parent (:class:`str`): - Required. The parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentsAsyncPager: - A response message for listing all - assignments under given parent. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_os_policy_assignments, - 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.ListOSPolicyAssignmentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_os_policy_assignment_revisions(self, - request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListOSPolicyAssignmentRevisionsAsyncPager: - r"""List the OS policy assignment revisions for a given - OS policy assignment. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest`): - The request object. A request message to list revisions - for a OS policy assignment - name (:class:`str`): - Required. The name of the OS policy - assignment to list revisions for. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentRevisionsAsyncPager: - A response message for listing all - revisions for a OS policy assignment. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_os_policy_assignment_revisions, - 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListOSPolicyAssignmentRevisionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_os_policy_assignment(self, - request: os_policy_assignments.DeleteOSPolicyAssignmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Delete the OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - If the LRO completes and is not cancelled, all revisions - associated with the OS policy assignment are deleted. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.DeleteOSPolicyAssignmentRequest`): - The request object. A request message for deleting a OS - policy assignment. - name (:class:`str`): - Required. The name of the OS policy - assignment to be deleted - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = os_policy_assignments.DeleteOSPolicyAssignmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_os_policy_assignment, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_instance_os_policies_compliance(self, - request: instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instance_os_policies_compliance.InstanceOSPoliciesCompliance: - r"""Get OS policies compliance data for the specified - Compute Engine VM instance. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.GetInstanceOSPoliciesComplianceRequest`): - The request object. A request message for getting OS - policies compliance data for the given Compute Engine VM - instance. - name (:class:`str`): - Required. API resource name for instance OS policies - compliance resource. - - Format: - ``projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}`` - - For ``{project}``, either Compute Engine project-number - or project-id can be provided. For ``{instance}``, - either Compute Engine VM instance-id or instance-name - can be provided. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance: - This API resource represents the OS policies compliance data for a Compute - Engine virtual machine (VM) instance at a given point - in time. - - A Compute Engine VM can have multiple OS policy - assignments, and each assignment can have multiple OS - policies. As a result, multiple OS policies could be - applied to a single VM. - - You can use this API resource to determine both the - compliance state of your VM as well as the compliance - state of an individual OS policy. - - For more information, see [View - compliance](\ https://cloud.google.com/compute/docs/os-configuration-management/view-compliance). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_instance_os_policies_compliance, - 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 list_instance_os_policies_compliances(self, - request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInstanceOSPoliciesCompliancesAsyncPager: - r"""List OS policies compliance data for all Compute - Engine VM instances in the specified zone. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest`): - The request object. A request message for listing OS - policies compliance data for all Compute Engine VMs in - the given location. - parent (:class:`str`): - Required. The parent resource name. - - Format: ``projects/{project}/locations/{location}`` - - For ``{project}``, either Compute Engine project-number - or project-id can be provided. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInstanceOSPoliciesCompliancesAsyncPager: - A response message for listing OS - policies compliance data for all Compute - Engine VMs in the given location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_instance_os_policies_compliances, - 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.ListInstanceOSPoliciesCompliancesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_inventory(self, - request: inventory.GetInventoryRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> inventory.Inventory: - r"""Get inventory data for the specified VM instance. If the VM has - no associated inventory, the message ``NOT_FOUND`` is returned. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.GetInventoryRequest`): - The request object. A request message for getting - inventory data for the specified VM. - name (:class:`str`): - Required. API resource name for inventory resource. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}/inventory`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, - either Compute Engine ``instance-id`` or - ``instance-name`` can be provided. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.Inventory: - This API resource represents the available inventory data for a - Compute Engine virtual machine (VM) instance at a - given point in time. - - You can use this API resource to determine the - inventory data of your VM. - - For more information, see [Information provided by OS - inventory - management](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = inventory.GetInventoryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_inventory, - 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 list_inventories(self, - request: inventory.ListInventoriesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInventoriesAsyncPager: - r"""List inventory data for all VM instances in the - specified zone. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.ListInventoriesRequest`): - The request object. A request message for listing - inventory data for all VMs in the specified location. - parent (:class:`str`): - Required. The parent resource name. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, only - hyphen or dash character is supported to list - inventories across VMs. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInventoriesAsyncPager: - A response message for listing - inventory data for all VMs in a - specified location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = inventory.ListInventoriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_inventories, - 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.ListInventoriesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_vulnerability_report(self, - request: vulnerability.GetVulnerabilityReportRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vulnerability.VulnerabilityReport: - r"""Gets the vulnerability report for the specified VM - instance. Only VMs with inventory data have - vulnerability reports associated with them. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.GetVulnerabilityReportRequest`): - The request object. A request message for getting the - vulnerability report for the specified VM. - name (:class:`str`): - Required. API resource name for vulnerability resource. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, - either Compute Engine ``instance-id`` or - ``instance-name`` can be provided. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.VulnerabilityReport: - This API resource represents the vulnerability report for a specified - Compute Engine virtual machine (VM) instance at a - given point in time. - - For more information, see [Vulnerability - reports](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#vulnerability-reports). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = vulnerability.GetVulnerabilityReportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_vulnerability_report, - 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 list_vulnerability_reports(self, - request: vulnerability.ListVulnerabilityReportsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVulnerabilityReportsAsyncPager: - r"""List vulnerability reports for all VM instances in - the specified zone. - - Args: - request (:class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest`): - The request object. A request message for listing - vulnerability reports for all VM instances in the - specified location. - parent (:class:`str`): - Required. The parent resource name. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, only - ``-`` character is supported to list vulnerability - reports across VMs. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListVulnerabilityReportsAsyncPager: - A response message for listing - vulnerability reports for all VM - instances in the specified location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = vulnerability.ListVulnerabilityReportsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_vulnerability_reports, - 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.ListVulnerabilityReportsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-osconfig", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "OsConfigZonalServiceAsyncClient", -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py deleted file mode 100644 index e538314..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py +++ /dev/null @@ -1,1599 +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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import pagers -from google.cloud.osconfig_v1alpha.types import config_common -from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import vulnerability -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import OsConfigZonalServiceGrpcTransport -from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport - - -class OsConfigZonalServiceClientMeta(type): - """Metaclass for the OsConfigZonalService 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[OsConfigZonalServiceTransport]] - _transport_registry["grpc"] = OsConfigZonalServiceGrpcTransport - _transport_registry["grpc_asyncio"] = OsConfigZonalServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[OsConfigZonalServiceTransport]: - """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 OsConfigZonalServiceClient(metaclass=OsConfigZonalServiceClientMeta): - """Zonal OS Config API - The OS Config service is the server-side component that allows - users to manage package installations and patch jobs for Compute - Engine VM instances. - """ - - @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 = "osconfig.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: - OsConfigZonalServiceClient: 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: - OsConfigZonalServiceClient: 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) -> OsConfigZonalServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OsConfigZonalServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def instance_path(project: str,location: str,instance: str,) -> str: - """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) - - @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: - """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def instance_os_policies_compliance_path(project: str,location: str,instance: str,) -> str: - """Returns a fully-qualified instance_os_policies_compliance string.""" - return "projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}".format(project=project, location=location, instance=instance, ) - - @staticmethod - def parse_instance_os_policies_compliance_path(path: str) -> Dict[str,str]: - """Parses a instance_os_policies_compliance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instanceOSPoliciesCompliances/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def inventory_path(project: str,location: str,instance: str,) -> str: - """Returns a fully-qualified inventory string.""" - return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) - - @staticmethod - def parse_inventory_path(path: str) -> Dict[str,str]: - """Parses a inventory path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) - return m.groupdict() if m else {} - - @staticmethod - def os_policy_assignment_path(project: str,location: str,os_policy_assignment: str,) -> str: - """Returns a fully-qualified os_policy_assignment string.""" - return "projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}".format(project=project, location=location, os_policy_assignment=os_policy_assignment, ) - - @staticmethod - def parse_os_policy_assignment_path(path: str) -> Dict[str,str]: - """Parses a os_policy_assignment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/osPolicyAssignments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def vulnerability_report_path(project: str,location: str,instance: str,) -> str: - """Returns a fully-qualified vulnerability_report string.""" - return "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format(project=project, location=location, instance=instance, ) - - @staticmethod - def parse_vulnerability_report_path(path: str) -> Dict[str,str]: - """Parses a vulnerability_report path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/vulnerabilityReport$", 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, OsConfigZonalServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the os config zonal 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, OsConfigZonalServiceTransport]): 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, OsConfigZonalServiceTransport): - # transport is a OsConfigZonalServiceTransport 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, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_os_policy_assignment(self, - request: os_policy_assignments.CreateOSPolicyAssignmentRequest = None, - *, - parent: str = None, - os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, - os_policy_assignment_id: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create an OS policy assignment. - - This method also creates the first revision of the OS policy - assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Args: - request (google.cloud.osconfig_v1alpha.types.CreateOSPolicyAssignmentRequest): - The request object. A request message to create an OS - policy assignment - parent (str): - Required. The parent resource name in - the form: - projects/{project}/locations/{location} - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): - Required. The OS policy assignment to - be created. - - This corresponds to the ``os_policy_assignment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - os_policy_assignment_id (str): - Required. The logical name of the OS policy assignment - in the project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the project. - - This corresponds to the ``os_policy_assignment_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to - apply a set of OS policies to a dynamically targeted - group of Compute Engine VM instances. - - An OS policy is used to define the desired state - configuration for a Compute Engine VM instance - through a set of configuration resources that provide - capabilities such as installing or removing software - packages, or executing a script. - - For more information, see [OS policy and OS policy - assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, os_policy_assignment, os_policy_assignment_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a os_policy_assignments.CreateOSPolicyAssignmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, os_policy_assignments.CreateOSPolicyAssignmentRequest): - request = os_policy_assignments.CreateOSPolicyAssignmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if os_policy_assignment is not None: - request.os_policy_assignment = os_policy_assignment - if os_policy_assignment_id is not None: - request.os_policy_assignment_id = os_policy_assignment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_os_policy_assignment] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - os_policy_assignments.OSPolicyAssignment, - metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, - ) - - # Done; return the response. - return response - - def update_os_policy_assignment(self, - request: os_policy_assignments.UpdateOSPolicyAssignmentRequest = None, - *, - os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Update an existing OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Args: - request (google.cloud.osconfig_v1alpha.types.UpdateOSPolicyAssignmentRequest): - The request object. A request message to update an OS - policy assignment - os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): - Required. The updated OS policy - assignment. - - This corresponds to the ``os_policy_assignment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask that controls - which fields of the assignment should be - updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.osconfig_v1alpha.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to - apply a set of OS policies to a dynamically targeted - group of Compute Engine VM instances. - - An OS policy is used to define the desired state - configuration for a Compute Engine VM instance - through a set of configuration resources that provide - capabilities such as installing or removing software - packages, or executing a script. - - For more information, see [OS policy and OS policy - assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([os_policy_assignment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a os_policy_assignments.UpdateOSPolicyAssignmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, os_policy_assignments.UpdateOSPolicyAssignmentRequest): - request = os_policy_assignments.UpdateOSPolicyAssignmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if os_policy_assignment is not None: - request.os_policy_assignment = os_policy_assignment - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_os_policy_assignment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("os_policy_assignment.name", request.os_policy_assignment.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - os_policy_assignments.OSPolicyAssignment, - metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, - ) - - # Done; return the response. - return response - - def get_os_policy_assignment(self, - request: os_policy_assignments.GetOSPolicyAssignmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> os_policy_assignments.OSPolicyAssignment: - r"""Retrieve an existing OS policy assignment. - - This method always returns the latest revision. In order to - retrieve a previous revision of the assignment, also provide the - revision ID in the ``name`` parameter. - - Args: - request (google.cloud.osconfig_v1alpha.types.GetOSPolicyAssignmentRequest): - The request object. A request message to get an OS - policy assignment - name (str): - Required. The resource name of OS policy assignment. - - Format: - ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.OSPolicyAssignment: - OS policy assignment is an API resource that is used to - apply a set of OS policies to a dynamically targeted - group of Compute Engine VM instances. - - An OS policy is used to define the desired state - configuration for a Compute Engine VM instance - through a set of configuration resources that provide - capabilities such as installing or removing software - packages, or executing a script. - - For more information, see [OS policy and OS policy - assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a os_policy_assignments.GetOSPolicyAssignmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, os_policy_assignments.GetOSPolicyAssignmentRequest): - request = os_policy_assignments.GetOSPolicyAssignmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_os_policy_assignment] - - # 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 list_os_policy_assignments(self, - request: os_policy_assignments.ListOSPolicyAssignmentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListOSPolicyAssignmentsPager: - r"""List the OS policy assignments under the parent - resource. - For each OS policy assignment, the latest revision is - returned. - - Args: - request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest): - The request object. A request message to list OS policy - assignments for a parent resource - parent (str): - Required. The parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentsPager: - A response message for listing all - assignments under given parent. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a os_policy_assignments.ListOSPolicyAssignmentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, os_policy_assignments.ListOSPolicyAssignmentsRequest): - request = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_os_policy_assignments] - - # 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.ListOSPolicyAssignmentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_os_policy_assignment_revisions(self, - request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListOSPolicyAssignmentRevisionsPager: - r"""List the OS policy assignment revisions for a given - OS policy assignment. - - Args: - request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest): - The request object. A request message to list revisions - for a OS policy assignment - name (str): - Required. The name of the OS policy - assignment to list revisions for. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentRevisionsPager: - A response message for listing all - revisions for a OS policy assignment. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest): - request = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_os_policy_assignment_revisions] - - # 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListOSPolicyAssignmentRevisionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_os_policy_assignment(self, - request: os_policy_assignments.DeleteOSPolicyAssignmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Delete the OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - If the LRO completes and is not cancelled, all revisions - associated with the OS policy assignment are deleted. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Args: - request (google.cloud.osconfig_v1alpha.types.DeleteOSPolicyAssignmentRequest): - The request object. A request message for deleting a OS - policy assignment. - name (str): - Required. The name of the OS policy - assignment to be deleted - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a os_policy_assignments.DeleteOSPolicyAssignmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, os_policy_assignments.DeleteOSPolicyAssignmentRequest): - request = os_policy_assignments.DeleteOSPolicyAssignmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_os_policy_assignment] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, - ) - - # Done; return the response. - return response - - def get_instance_os_policies_compliance(self, - request: instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instance_os_policies_compliance.InstanceOSPoliciesCompliance: - r"""Get OS policies compliance data for the specified - Compute Engine VM instance. - - Args: - request (google.cloud.osconfig_v1alpha.types.GetInstanceOSPoliciesComplianceRequest): - The request object. A request message for getting OS - policies compliance data for the given Compute Engine VM - instance. - name (str): - Required. API resource name for instance OS policies - compliance resource. - - Format: - ``projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}`` - - For ``{project}``, either Compute Engine project-number - or project-id can be provided. For ``{instance}``, - either Compute Engine VM instance-id or instance-name - can be provided. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance: - This API resource represents the OS policies compliance data for a Compute - Engine virtual machine (VM) instance at a given point - in time. - - A Compute Engine VM can have multiple OS policy - assignments, and each assignment can have multiple OS - policies. As a result, multiple OS policies could be - applied to a single VM. - - You can use this API resource to determine both the - compliance state of your VM as well as the compliance - state of an individual OS policy. - - For more information, see [View - compliance](\ https://cloud.google.com/compute/docs/os-configuration-management/view-compliance). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest): - request = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_instance_os_policies_compliance] - - # 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 list_instance_os_policies_compliances(self, - request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInstanceOSPoliciesCompliancesPager: - r"""List OS policies compliance data for all Compute - Engine VM instances in the specified zone. - - Args: - request (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest): - The request object. A request message for listing OS - policies compliance data for all Compute Engine VMs in - the given location. - parent (str): - Required. The parent resource name. - - Format: ``projects/{project}/locations/{location}`` - - For ``{project}``, either Compute Engine project-number - or project-id can be provided. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInstanceOSPoliciesCompliancesPager: - A response message for listing OS - policies compliance data for all Compute - Engine VMs in the given location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest): - request = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_instance_os_policies_compliances] - - # 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.ListInstanceOSPoliciesCompliancesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_inventory(self, - request: inventory.GetInventoryRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> inventory.Inventory: - r"""Get inventory data for the specified VM instance. If the VM has - no associated inventory, the message ``NOT_FOUND`` is returned. - - Args: - request (google.cloud.osconfig_v1alpha.types.GetInventoryRequest): - The request object. A request message for getting - inventory data for the specified VM. - name (str): - Required. API resource name for inventory resource. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}/inventory`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, - either Compute Engine ``instance-id`` or - ``instance-name`` can be provided. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.Inventory: - This API resource represents the available inventory data for a - Compute Engine virtual machine (VM) instance at a - given point in time. - - You can use this API resource to determine the - inventory data of your VM. - - For more information, see [Information provided by OS - inventory - management](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a inventory.GetInventoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, inventory.GetInventoryRequest): - request = inventory.GetInventoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_inventory] - - # 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 list_inventories(self, - request: inventory.ListInventoriesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInventoriesPager: - r"""List inventory data for all VM instances in the - specified zone. - - Args: - request (google.cloud.osconfig_v1alpha.types.ListInventoriesRequest): - The request object. A request message for listing - inventory data for all VMs in the specified location. - parent (str): - Required. The parent resource name. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, only - hyphen or dash character is supported to list - inventories across VMs. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListInventoriesPager: - A response message for listing - inventory data for all VMs in a - specified location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a inventory.ListInventoriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, inventory.ListInventoriesRequest): - request = inventory.ListInventoriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_inventories] - - # 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.ListInventoriesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_vulnerability_report(self, - request: vulnerability.GetVulnerabilityReportRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vulnerability.VulnerabilityReport: - r"""Gets the vulnerability report for the specified VM - instance. Only VMs with inventory data have - vulnerability reports associated with them. - - Args: - request (google.cloud.osconfig_v1alpha.types.GetVulnerabilityReportRequest): - The request object. A request message for getting the - vulnerability report for the specified VM. - name (str): - Required. API resource name for vulnerability resource. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, - either Compute Engine ``instance-id`` or - ``instance-name`` can be provided. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.types.VulnerabilityReport: - This API resource represents the vulnerability report for a specified - Compute Engine virtual machine (VM) instance at a - given point in time. - - For more information, see [Vulnerability - reports](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#vulnerability-reports). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a vulnerability.GetVulnerabilityReportRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, vulnerability.GetVulnerabilityReportRequest): - request = vulnerability.GetVulnerabilityReportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_vulnerability_report] - - # 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 list_vulnerability_reports(self, - request: vulnerability.ListVulnerabilityReportsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVulnerabilityReportsPager: - r"""List vulnerability reports for all VM instances in - the specified zone. - - Args: - request (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest): - The request object. A request message for listing - vulnerability reports for all VM instances in the - specified location. - parent (str): - Required. The parent resource name. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, only - ``-`` character is supported to list vulnerability - reports across VMs. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.osconfig_v1alpha.services.os_config_zonal_service.pagers.ListVulnerabilityReportsPager: - A response message for listing - vulnerability reports for all VM - instances in the specified location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a vulnerability.ListVulnerabilityReportsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, vulnerability.ListVulnerabilityReportsRequest): - request = vulnerability.ListVulnerabilityReportsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_vulnerability_reports] - - # 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.ListVulnerabilityReportsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-osconfig", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "OsConfigZonalServiceClient", -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py deleted file mode 100644 index 8c83011..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/pagers.py +++ /dev/null @@ -1,631 +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.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import vulnerability - - -class ListOSPolicyAssignmentsPager: - """A pager for iterating through ``list_os_policy_assignments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``os_policy_assignments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOSPolicyAssignments`` requests and continue to iterate - through the ``os_policy_assignments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` - 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[..., os_policy_assignments.ListOSPolicyAssignmentsResponse], - request: os_policy_assignments.ListOSPolicyAssignmentsRequest, - response: os_policy_assignments.ListOSPolicyAssignmentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse): - 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[os_policy_assignments.ListOSPolicyAssignmentsResponse]: - 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[os_policy_assignments.OSPolicyAssignment]: - for page in self.pages: - yield from page.os_policy_assignments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOSPolicyAssignmentsAsyncPager: - """A pager for iterating through ``list_os_policy_assignments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``os_policy_assignments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOSPolicyAssignments`` requests and continue to iterate - through the ``os_policy_assignments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse` - 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[os_policy_assignments.ListOSPolicyAssignmentsResponse]], - request: os_policy_assignments.ListOSPolicyAssignmentsRequest, - response: os_policy_assignments.ListOSPolicyAssignmentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentsResponse): - 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[os_policy_assignments.ListOSPolicyAssignmentsResponse]: - 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[os_policy_assignments.OSPolicyAssignment]: - async def async_generator(): - async for page in self.pages: - for response in page.os_policy_assignments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOSPolicyAssignmentRevisionsPager: - """A pager for iterating through ``list_os_policy_assignment_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``os_policy_assignments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOSPolicyAssignmentRevisions`` requests and continue to iterate - through the ``os_policy_assignments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` - 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[..., os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse], - request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, - response: os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse): - 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: - 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[os_policy_assignments.OSPolicyAssignment]: - for page in self.pages: - yield from page.os_policy_assignments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOSPolicyAssignmentRevisionsAsyncPager: - """A pager for iterating through ``list_os_policy_assignment_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``os_policy_assignments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOSPolicyAssignmentRevisions`` requests and continue to iterate - through the ``os_policy_assignments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse` - 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[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]], - request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, - response: os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListOSPolicyAssignmentRevisionsResponse): - 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: - 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[os_policy_assignments.OSPolicyAssignment]: - async def async_generator(): - async for page in self.pages: - for response in page.os_policy_assignments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInstanceOSPoliciesCompliancesPager: - """A pager for iterating through ``list_instance_os_policies_compliances`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``instance_os_policies_compliances`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListInstanceOSPoliciesCompliances`` requests and continue to iterate - through the ``instance_os_policies_compliances`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` - 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[..., instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse], - request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest, - response: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse): - 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]: - 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[instance_os_policies_compliance.InstanceOSPoliciesCompliance]: - for page in self.pages: - yield from page.instance_os_policies_compliances - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInstanceOSPoliciesCompliancesAsyncPager: - """A pager for iterating through ``list_instance_os_policies_compliances`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``instance_os_policies_compliances`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListInstanceOSPoliciesCompliances`` requests and continue to iterate - through the ``instance_os_policies_compliances`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse` - 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[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]], - request: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest, - response: instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListInstanceOSPoliciesCompliancesResponse): - 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]: - 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[instance_os_policies_compliance.InstanceOSPoliciesCompliance]: - async def async_generator(): - async for page in self.pages: - for response in page.instance_os_policies_compliances: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInventoriesPager: - """A pager for iterating through ``list_inventories`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``inventories`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListInventories`` requests and continue to iterate - through the ``inventories`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` - 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[..., inventory.ListInventoriesResponse], - request: inventory.ListInventoriesRequest, - response: inventory.ListInventoriesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListInventoriesRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListInventoriesResponse): - 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 = inventory.ListInventoriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[inventory.ListInventoriesResponse]: - 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[inventory.Inventory]: - for page in self.pages: - yield from page.inventories - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInventoriesAsyncPager: - """A pager for iterating through ``list_inventories`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``inventories`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListInventories`` requests and continue to iterate - through the ``inventories`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListInventoriesResponse` - 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[inventory.ListInventoriesResponse]], - request: inventory.ListInventoriesRequest, - response: inventory.ListInventoriesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListInventoriesRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListInventoriesResponse): - 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 = inventory.ListInventoriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[inventory.ListInventoriesResponse]: - 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[inventory.Inventory]: - async def async_generator(): - async for page in self.pages: - for response in page.inventories: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVulnerabilityReportsPager: - """A pager for iterating through ``list_vulnerability_reports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``vulnerability_reports`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListVulnerabilityReports`` requests and continue to iterate - through the ``vulnerability_reports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` - 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[..., vulnerability.ListVulnerabilityReportsResponse], - request: vulnerability.ListVulnerabilityReportsRequest, - response: vulnerability.ListVulnerabilityReportsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse): - 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 = vulnerability.ListVulnerabilityReportsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[vulnerability.ListVulnerabilityReportsResponse]: - 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[vulnerability.VulnerabilityReport]: - for page in self.pages: - yield from page.vulnerability_reports - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVulnerabilityReportsAsyncPager: - """A pager for iterating through ``list_vulnerability_reports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``vulnerability_reports`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListVulnerabilityReports`` requests and continue to iterate - through the ``vulnerability_reports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse` - 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[vulnerability.ListVulnerabilityReportsResponse]], - request: vulnerability.ListVulnerabilityReportsRequest, - response: vulnerability.ListVulnerabilityReportsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsRequest): - The initial request object. - response (google.cloud.osconfig_v1alpha.types.ListVulnerabilityReportsResponse): - 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 = vulnerability.ListVulnerabilityReportsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[vulnerability.ListVulnerabilityReportsResponse]: - 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[vulnerability.VulnerabilityReport]: - async def async_generator(): - async for page in self.pages: - for response in page.vulnerability_reports: - 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/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/__init__.py deleted file mode 100644 index 81d3d8a..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_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 OsConfigZonalServiceTransport -from .grpc import OsConfigZonalServiceGrpcTransport -from .grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OsConfigZonalServiceTransport]] -_transport_registry['grpc'] = OsConfigZonalServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OsConfigZonalServiceGrpcAsyncIOTransport - -__all__ = ( - 'OsConfigZonalServiceTransport', - 'OsConfigZonalServiceGrpcTransport', - 'OsConfigZonalServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py deleted file mode 100644 index 9ecb8d2..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/base.py +++ /dev/null @@ -1,332 +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.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import vulnerability -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-osconfig', - ).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 OsConfigZonalServiceTransport(abc.ABC): - """Abstract transport class for OsConfigZonalService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'osconfig.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 - - # 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_os_policy_assignment: gapic_v1.method.wrap_method( - self.create_os_policy_assignment, - default_timeout=None, - client_info=client_info, - ), - self.update_os_policy_assignment: gapic_v1.method.wrap_method( - self.update_os_policy_assignment, - default_timeout=None, - client_info=client_info, - ), - self.get_os_policy_assignment: gapic_v1.method.wrap_method( - self.get_os_policy_assignment, - default_timeout=None, - client_info=client_info, - ), - self.list_os_policy_assignments: gapic_v1.method.wrap_method( - self.list_os_policy_assignments, - default_timeout=None, - client_info=client_info, - ), - self.list_os_policy_assignment_revisions: gapic_v1.method.wrap_method( - self.list_os_policy_assignment_revisions, - default_timeout=None, - client_info=client_info, - ), - self.delete_os_policy_assignment: gapic_v1.method.wrap_method( - self.delete_os_policy_assignment, - default_timeout=None, - client_info=client_info, - ), - self.get_instance_os_policies_compliance: gapic_v1.method.wrap_method( - self.get_instance_os_policies_compliance, - default_timeout=None, - client_info=client_info, - ), - self.list_instance_os_policies_compliances: gapic_v1.method.wrap_method( - self.list_instance_os_policies_compliances, - default_timeout=None, - client_info=client_info, - ), - self.get_inventory: gapic_v1.method.wrap_method( - self.get_inventory, - default_timeout=None, - client_info=client_info, - ), - self.list_inventories: gapic_v1.method.wrap_method( - self.list_inventories, - default_timeout=None, - client_info=client_info, - ), - self.get_vulnerability_report: gapic_v1.method.wrap_method( - self.get_vulnerability_report, - default_timeout=None, - client_info=client_info, - ), - self.list_vulnerability_reports: gapic_v1.method.wrap_method( - self.list_vulnerability_reports, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.CreateOSPolicyAssignmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.UpdateOSPolicyAssignmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.GetOSPolicyAssignmentRequest], - Union[ - os_policy_assignments.OSPolicyAssignment, - Awaitable[os_policy_assignments.OSPolicyAssignment] - ]]: - raise NotImplementedError() - - @property - def list_os_policy_assignments(self) -> Callable[ - [os_policy_assignments.ListOSPolicyAssignmentsRequest], - Union[ - os_policy_assignments.ListOSPolicyAssignmentsResponse, - Awaitable[os_policy_assignments.ListOSPolicyAssignmentsResponse] - ]]: - raise NotImplementedError() - - @property - def list_os_policy_assignment_revisions(self) -> Callable[ - [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], - Union[ - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, - Awaitable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.DeleteOSPolicyAssignmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_instance_os_policies_compliance(self) -> Callable[ - [instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest], - Union[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance, - Awaitable[instance_os_policies_compliance.InstanceOSPoliciesCompliance] - ]]: - raise NotImplementedError() - - @property - def list_instance_os_policies_compliances(self) -> Callable[ - [instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest], - Union[ - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse, - Awaitable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse] - ]]: - raise NotImplementedError() - - @property - def get_inventory(self) -> Callable[ - [inventory.GetInventoryRequest], - Union[ - inventory.Inventory, - Awaitable[inventory.Inventory] - ]]: - raise NotImplementedError() - - @property - def list_inventories(self) -> Callable[ - [inventory.ListInventoriesRequest], - Union[ - inventory.ListInventoriesResponse, - Awaitable[inventory.ListInventoriesResponse] - ]]: - raise NotImplementedError() - - @property - def get_vulnerability_report(self) -> Callable[ - [vulnerability.GetVulnerabilityReportRequest], - Union[ - vulnerability.VulnerabilityReport, - Awaitable[vulnerability.VulnerabilityReport] - ]]: - raise NotImplementedError() - - @property - def list_vulnerability_reports(self) -> Callable[ - [vulnerability.ListVulnerabilityReportsRequest], - Union[ - vulnerability.ListVulnerabilityReportsResponse, - Awaitable[vulnerability.ListVulnerabilityReportsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'OsConfigZonalServiceTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py deleted file mode 100644 index 0086218..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc.py +++ /dev/null @@ -1,612 +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 operations_v1 # 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.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import vulnerability -from google.longrunning import operations_pb2 # type: ignore -from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO - - -class OsConfigZonalServiceGrpcTransport(OsConfigZonalServiceTransport): - """gRPC backend transport for OsConfigZonalService. - - Zonal OS Config API - The OS Config service is the server-side component that allows - users to manage package installations and patch jobs for Compute - Engine VM instances. - - 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 = 'osconfig.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, - always_use_jwt_access: Optional[bool] = False, - ) -> 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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] = {} - self._operations_client = None - - 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=always_use_jwt_access, - ) - - 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 = 'osconfig.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.CreateOSPolicyAssignmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create os policy assignment method over gRPC. - - Create an OS policy assignment. - - This method also creates the first revision of the OS policy - assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Returns: - Callable[[~.CreateOSPolicyAssignmentRequest], - ~.Operation]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['create_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/CreateOSPolicyAssignment', - request_serializer=os_policy_assignments.CreateOSPolicyAssignmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_os_policy_assignment'] - - @property - def update_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.UpdateOSPolicyAssignmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update os policy assignment method over gRPC. - - Update an existing OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Returns: - Callable[[~.UpdateOSPolicyAssignmentRequest], - ~.Operation]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['update_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/UpdateOSPolicyAssignment', - request_serializer=os_policy_assignments.UpdateOSPolicyAssignmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_os_policy_assignment'] - - @property - def get_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.GetOSPolicyAssignmentRequest], - os_policy_assignments.OSPolicyAssignment]: - r"""Return a callable for the get os policy assignment method over gRPC. - - Retrieve an existing OS policy assignment. - - This method always returns the latest revision. In order to - retrieve a previous revision of the assignment, also provide the - revision ID in the ``name`` parameter. - - Returns: - Callable[[~.GetOSPolicyAssignmentRequest], - ~.OSPolicyAssignment]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['get_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetOSPolicyAssignment', - request_serializer=os_policy_assignments.GetOSPolicyAssignmentRequest.serialize, - response_deserializer=os_policy_assignments.OSPolicyAssignment.deserialize, - ) - return self._stubs['get_os_policy_assignment'] - - @property - def list_os_policy_assignments(self) -> Callable[ - [os_policy_assignments.ListOSPolicyAssignmentsRequest], - os_policy_assignments.ListOSPolicyAssignmentsResponse]: - r"""Return a callable for the list os policy assignments method over gRPC. - - List the OS policy assignments under the parent - resource. - For each OS policy assignment, the latest revision is - returned. - - Returns: - Callable[[~.ListOSPolicyAssignmentsRequest], - ~.ListOSPolicyAssignmentsResponse]: - 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_os_policy_assignments' not in self._stubs: - self._stubs['list_os_policy_assignments'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignments', - request_serializer=os_policy_assignments.ListOSPolicyAssignmentsRequest.serialize, - response_deserializer=os_policy_assignments.ListOSPolicyAssignmentsResponse.deserialize, - ) - return self._stubs['list_os_policy_assignments'] - - @property - def list_os_policy_assignment_revisions(self) -> Callable[ - [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: - r"""Return a callable for the list os policy assignment - revisions method over gRPC. - - List the OS policy assignment revisions for a given - OS policy assignment. - - Returns: - Callable[[~.ListOSPolicyAssignmentRevisionsRequest], - ~.ListOSPolicyAssignmentRevisionsResponse]: - 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_os_policy_assignment_revisions' not in self._stubs: - self._stubs['list_os_policy_assignment_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignmentRevisions', - request_serializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest.serialize, - response_deserializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse.deserialize, - ) - return self._stubs['list_os_policy_assignment_revisions'] - - @property - def delete_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.DeleteOSPolicyAssignmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete os policy assignment method over gRPC. - - Delete the OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - If the LRO completes and is not cancelled, all revisions - associated with the OS policy assignment are deleted. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Returns: - Callable[[~.DeleteOSPolicyAssignmentRequest], - ~.Operation]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['delete_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/DeleteOSPolicyAssignment', - request_serializer=os_policy_assignments.DeleteOSPolicyAssignmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_os_policy_assignment'] - - @property - def get_instance_os_policies_compliance(self) -> Callable[ - [instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest], - instance_os_policies_compliance.InstanceOSPoliciesCompliance]: - r"""Return a callable for the get instance os policies - compliance method over gRPC. - - Get OS policies compliance data for the specified - Compute Engine VM instance. - - Returns: - Callable[[~.GetInstanceOSPoliciesComplianceRequest], - ~.InstanceOSPoliciesCompliance]: - 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_instance_os_policies_compliance' not in self._stubs: - self._stubs['get_instance_os_policies_compliance'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInstanceOSPoliciesCompliance', - request_serializer=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest.serialize, - response_deserializer=instance_os_policies_compliance.InstanceOSPoliciesCompliance.deserialize, - ) - return self._stubs['get_instance_os_policies_compliance'] - - @property - def list_instance_os_policies_compliances(self) -> Callable[ - [instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest], - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]: - r"""Return a callable for the list instance os policies - compliances method over gRPC. - - List OS policies compliance data for all Compute - Engine VM instances in the specified zone. - - Returns: - Callable[[~.ListInstanceOSPoliciesCompliancesRequest], - ~.ListInstanceOSPoliciesCompliancesResponse]: - 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_instance_os_policies_compliances' not in self._stubs: - self._stubs['list_instance_os_policies_compliances'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInstanceOSPoliciesCompliances', - request_serializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest.serialize, - response_deserializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse.deserialize, - ) - return self._stubs['list_instance_os_policies_compliances'] - - @property - def get_inventory(self) -> Callable[ - [inventory.GetInventoryRequest], - inventory.Inventory]: - r"""Return a callable for the get inventory method over gRPC. - - Get inventory data for the specified VM instance. If the VM has - no associated inventory, the message ``NOT_FOUND`` is returned. - - Returns: - Callable[[~.GetInventoryRequest], - ~.Inventory]: - 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_inventory' not in self._stubs: - self._stubs['get_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInventory', - request_serializer=inventory.GetInventoryRequest.serialize, - response_deserializer=inventory.Inventory.deserialize, - ) - return self._stubs['get_inventory'] - - @property - def list_inventories(self) -> Callable[ - [inventory.ListInventoriesRequest], - inventory.ListInventoriesResponse]: - r"""Return a callable for the list inventories method over gRPC. - - List inventory data for all VM instances in the - specified zone. - - Returns: - Callable[[~.ListInventoriesRequest], - ~.ListInventoriesResponse]: - 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_inventories' not in self._stubs: - self._stubs['list_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInventories', - request_serializer=inventory.ListInventoriesRequest.serialize, - response_deserializer=inventory.ListInventoriesResponse.deserialize, - ) - return self._stubs['list_inventories'] - - @property - def get_vulnerability_report(self) -> Callable[ - [vulnerability.GetVulnerabilityReportRequest], - vulnerability.VulnerabilityReport]: - r"""Return a callable for the get vulnerability report method over gRPC. - - Gets the vulnerability report for the specified VM - instance. Only VMs with inventory data have - vulnerability reports associated with them. - - Returns: - Callable[[~.GetVulnerabilityReportRequest], - ~.VulnerabilityReport]: - 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_vulnerability_report' not in self._stubs: - self._stubs['get_vulnerability_report'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetVulnerabilityReport', - request_serializer=vulnerability.GetVulnerabilityReportRequest.serialize, - response_deserializer=vulnerability.VulnerabilityReport.deserialize, - ) - return self._stubs['get_vulnerability_report'] - - @property - def list_vulnerability_reports(self) -> Callable[ - [vulnerability.ListVulnerabilityReportsRequest], - vulnerability.ListVulnerabilityReportsResponse]: - r"""Return a callable for the list vulnerability reports method over gRPC. - - List vulnerability reports for all VM instances in - the specified zone. - - Returns: - Callable[[~.ListVulnerabilityReportsRequest], - ~.ListVulnerabilityReportsResponse]: - 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_vulnerability_reports' not in self._stubs: - self._stubs['list_vulnerability_reports'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListVulnerabilityReports', - request_serializer=vulnerability.ListVulnerabilityReportsRequest.serialize, - response_deserializer=vulnerability.ListVulnerabilityReportsResponse.deserialize, - ) - return self._stubs['list_vulnerability_reports'] - - -__all__ = ( - 'OsConfigZonalServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py deleted file mode 100644 index 0507441..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,616 +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.api_core import operations_v1 # 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.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import vulnerability -from google.longrunning import operations_pb2 # type: ignore -from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import OsConfigZonalServiceGrpcTransport - - -class OsConfigZonalServiceGrpcAsyncIOTransport(OsConfigZonalServiceTransport): - """gRPC AsyncIO backend transport for OsConfigZonalService. - - Zonal OS Config API - The OS Config service is the server-side component that allows - users to manage package installations and patch jobs for Compute - Engine VM instances. - - 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 = 'osconfig.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 = 'osconfig.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, - always_use_jwt_access: Optional[bool] = False, - ) -> 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. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - 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] = {} - self._operations_client = None - - 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=always_use_jwt_access, - ) - - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.CreateOSPolicyAssignmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create os policy assignment method over gRPC. - - Create an OS policy assignment. - - This method also creates the first revision of the OS policy - assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Returns: - Callable[[~.CreateOSPolicyAssignmentRequest], - Awaitable[~.Operation]]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['create_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/CreateOSPolicyAssignment', - request_serializer=os_policy_assignments.CreateOSPolicyAssignmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_os_policy_assignment'] - - @property - def update_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.UpdateOSPolicyAssignmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update os policy assignment method over gRPC. - - Update an existing OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Returns: - Callable[[~.UpdateOSPolicyAssignmentRequest], - Awaitable[~.Operation]]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['update_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/UpdateOSPolicyAssignment', - request_serializer=os_policy_assignments.UpdateOSPolicyAssignmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_os_policy_assignment'] - - @property - def get_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.GetOSPolicyAssignmentRequest], - Awaitable[os_policy_assignments.OSPolicyAssignment]]: - r"""Return a callable for the get os policy assignment method over gRPC. - - Retrieve an existing OS policy assignment. - - This method always returns the latest revision. In order to - retrieve a previous revision of the assignment, also provide the - revision ID in the ``name`` parameter. - - Returns: - Callable[[~.GetOSPolicyAssignmentRequest], - Awaitable[~.OSPolicyAssignment]]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['get_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetOSPolicyAssignment', - request_serializer=os_policy_assignments.GetOSPolicyAssignmentRequest.serialize, - response_deserializer=os_policy_assignments.OSPolicyAssignment.deserialize, - ) - return self._stubs['get_os_policy_assignment'] - - @property - def list_os_policy_assignments(self) -> Callable[ - [os_policy_assignments.ListOSPolicyAssignmentsRequest], - Awaitable[os_policy_assignments.ListOSPolicyAssignmentsResponse]]: - r"""Return a callable for the list os policy assignments method over gRPC. - - List the OS policy assignments under the parent - resource. - For each OS policy assignment, the latest revision is - returned. - - Returns: - Callable[[~.ListOSPolicyAssignmentsRequest], - Awaitable[~.ListOSPolicyAssignmentsResponse]]: - 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_os_policy_assignments' not in self._stubs: - self._stubs['list_os_policy_assignments'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignments', - request_serializer=os_policy_assignments.ListOSPolicyAssignmentsRequest.serialize, - response_deserializer=os_policy_assignments.ListOSPolicyAssignmentsResponse.deserialize, - ) - return self._stubs['list_os_policy_assignments'] - - @property - def list_os_policy_assignment_revisions(self) -> Callable[ - [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], - Awaitable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]]: - r"""Return a callable for the list os policy assignment - revisions method over gRPC. - - List the OS policy assignment revisions for a given - OS policy assignment. - - Returns: - Callable[[~.ListOSPolicyAssignmentRevisionsRequest], - Awaitable[~.ListOSPolicyAssignmentRevisionsResponse]]: - 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_os_policy_assignment_revisions' not in self._stubs: - self._stubs['list_os_policy_assignment_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListOSPolicyAssignmentRevisions', - request_serializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest.serialize, - response_deserializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse.deserialize, - ) - return self._stubs['list_os_policy_assignment_revisions'] - - @property - def delete_os_policy_assignment(self) -> Callable[ - [os_policy_assignments.DeleteOSPolicyAssignmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete os policy assignment method over gRPC. - - Delete the OS policy assignment. - - This method creates a new revision of the OS policy assignment. - - This method returns a long running operation (LRO) that contains - the rollout details. The rollout can be cancelled by cancelling - the LRO. - - If the LRO completes and is not cancelled, all revisions - associated with the OS policy assignment are deleted. - - For more information, see `Method: - projects.locations.osPolicyAssignments.operations.cancel `__. - - Returns: - Callable[[~.DeleteOSPolicyAssignmentRequest], - Awaitable[~.Operation]]: - 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_os_policy_assignment' not in self._stubs: - self._stubs['delete_os_policy_assignment'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/DeleteOSPolicyAssignment', - request_serializer=os_policy_assignments.DeleteOSPolicyAssignmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_os_policy_assignment'] - - @property - def get_instance_os_policies_compliance(self) -> Callable[ - [instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest], - Awaitable[instance_os_policies_compliance.InstanceOSPoliciesCompliance]]: - r"""Return a callable for the get instance os policies - compliance method over gRPC. - - Get OS policies compliance data for the specified - Compute Engine VM instance. - - Returns: - Callable[[~.GetInstanceOSPoliciesComplianceRequest], - Awaitable[~.InstanceOSPoliciesCompliance]]: - 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_instance_os_policies_compliance' not in self._stubs: - self._stubs['get_instance_os_policies_compliance'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInstanceOSPoliciesCompliance', - request_serializer=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest.serialize, - response_deserializer=instance_os_policies_compliance.InstanceOSPoliciesCompliance.deserialize, - ) - return self._stubs['get_instance_os_policies_compliance'] - - @property - def list_instance_os_policies_compliances(self) -> Callable[ - [instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest], - Awaitable[instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse]]: - r"""Return a callable for the list instance os policies - compliances method over gRPC. - - List OS policies compliance data for all Compute - Engine VM instances in the specified zone. - - Returns: - Callable[[~.ListInstanceOSPoliciesCompliancesRequest], - Awaitable[~.ListInstanceOSPoliciesCompliancesResponse]]: - 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_instance_os_policies_compliances' not in self._stubs: - self._stubs['list_instance_os_policies_compliances'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInstanceOSPoliciesCompliances', - request_serializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest.serialize, - response_deserializer=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse.deserialize, - ) - return self._stubs['list_instance_os_policies_compliances'] - - @property - def get_inventory(self) -> Callable[ - [inventory.GetInventoryRequest], - Awaitable[inventory.Inventory]]: - r"""Return a callable for the get inventory method over gRPC. - - Get inventory data for the specified VM instance. If the VM has - no associated inventory, the message ``NOT_FOUND`` is returned. - - Returns: - Callable[[~.GetInventoryRequest], - Awaitable[~.Inventory]]: - 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_inventory' not in self._stubs: - self._stubs['get_inventory'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetInventory', - request_serializer=inventory.GetInventoryRequest.serialize, - response_deserializer=inventory.Inventory.deserialize, - ) - return self._stubs['get_inventory'] - - @property - def list_inventories(self) -> Callable[ - [inventory.ListInventoriesRequest], - Awaitable[inventory.ListInventoriesResponse]]: - r"""Return a callable for the list inventories method over gRPC. - - List inventory data for all VM instances in the - specified zone. - - Returns: - Callable[[~.ListInventoriesRequest], - Awaitable[~.ListInventoriesResponse]]: - 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_inventories' not in self._stubs: - self._stubs['list_inventories'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListInventories', - request_serializer=inventory.ListInventoriesRequest.serialize, - response_deserializer=inventory.ListInventoriesResponse.deserialize, - ) - return self._stubs['list_inventories'] - - @property - def get_vulnerability_report(self) -> Callable[ - [vulnerability.GetVulnerabilityReportRequest], - Awaitable[vulnerability.VulnerabilityReport]]: - r"""Return a callable for the get vulnerability report method over gRPC. - - Gets the vulnerability report for the specified VM - instance. Only VMs with inventory data have - vulnerability reports associated with them. - - Returns: - Callable[[~.GetVulnerabilityReportRequest], - Awaitable[~.VulnerabilityReport]]: - 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_vulnerability_report' not in self._stubs: - self._stubs['get_vulnerability_report'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/GetVulnerabilityReport', - request_serializer=vulnerability.GetVulnerabilityReportRequest.serialize, - response_deserializer=vulnerability.VulnerabilityReport.deserialize, - ) - return self._stubs['get_vulnerability_report'] - - @property - def list_vulnerability_reports(self) -> Callable[ - [vulnerability.ListVulnerabilityReportsRequest], - Awaitable[vulnerability.ListVulnerabilityReportsResponse]]: - r"""Return a callable for the list vulnerability reports method over gRPC. - - List vulnerability reports for all VM instances in - the specified zone. - - Returns: - Callable[[~.ListVulnerabilityReportsRequest], - Awaitable[~.ListVulnerabilityReportsResponse]]: - 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_vulnerability_reports' not in self._stubs: - self._stubs['list_vulnerability_reports'] = self.grpc_channel.unary_unary( - '/google.cloud.osconfig.v1alpha.OsConfigZonalService/ListVulnerabilityReports', - request_serializer=vulnerability.ListVulnerabilityReportsRequest.serialize, - response_deserializer=vulnerability.ListVulnerabilityReportsResponse.deserialize, - ) - return self._stubs['list_vulnerability_reports'] - - -__all__ = ( - 'OsConfigZonalServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py deleted file mode 100644 index d2d0699..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/__init__.py +++ /dev/null @@ -1,90 +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 .config_common import ( - OSPolicyResourceCompliance, - OSPolicyResourceConfigStep, - OSPolicyComplianceState, -) -from .instance_os_policies_compliance import ( - GetInstanceOSPoliciesComplianceRequest, - InstanceOSPoliciesCompliance, - ListInstanceOSPoliciesCompliancesRequest, - ListInstanceOSPoliciesCompliancesResponse, -) -from .inventory import ( - GetInventoryRequest, - Inventory, - ListInventoriesRequest, - ListInventoriesResponse, - InventoryView, -) -from .os_policy import ( - OSPolicy, -) -from .os_policy_assignments import ( - CreateOSPolicyAssignmentRequest, - DeleteOSPolicyAssignmentRequest, - GetOSPolicyAssignmentRequest, - ListOSPolicyAssignmentRevisionsRequest, - ListOSPolicyAssignmentRevisionsResponse, - ListOSPolicyAssignmentsRequest, - ListOSPolicyAssignmentsResponse, - OSPolicyAssignment, - OSPolicyAssignmentOperationMetadata, - UpdateOSPolicyAssignmentRequest, -) -from .osconfig_common import ( - FixedOrPercent, -) -from .vulnerability import ( - CVSSv3, - GetVulnerabilityReportRequest, - ListVulnerabilityReportsRequest, - ListVulnerabilityReportsResponse, - VulnerabilityReport, -) - -__all__ = ( - 'OSPolicyResourceCompliance', - 'OSPolicyResourceConfigStep', - 'OSPolicyComplianceState', - 'GetInstanceOSPoliciesComplianceRequest', - 'InstanceOSPoliciesCompliance', - 'ListInstanceOSPoliciesCompliancesRequest', - 'ListInstanceOSPoliciesCompliancesResponse', - 'GetInventoryRequest', - 'Inventory', - 'ListInventoriesRequest', - 'ListInventoriesResponse', - 'InventoryView', - 'OSPolicy', - 'CreateOSPolicyAssignmentRequest', - 'DeleteOSPolicyAssignmentRequest', - 'GetOSPolicyAssignmentRequest', - 'ListOSPolicyAssignmentRevisionsRequest', - 'ListOSPolicyAssignmentRevisionsResponse', - 'ListOSPolicyAssignmentsRequest', - 'ListOSPolicyAssignmentsResponse', - 'OSPolicyAssignment', - 'OSPolicyAssignmentOperationMetadata', - 'UpdateOSPolicyAssignmentRequest', - 'FixedOrPercent', - 'CVSSv3', - 'GetVulnerabilityReportRequest', - 'ListVulnerabilityReportsRequest', - 'ListVulnerabilityReportsResponse', - 'VulnerabilityReport', -) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py deleted file mode 100644 index 0bb9fda..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/config_common.py +++ /dev/null @@ -1,131 +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.cloud.osconfig.v1alpha', - manifest={ - 'OSPolicyComplianceState', - 'OSPolicyResourceConfigStep', - 'OSPolicyResourceCompliance', - }, -) - - -class OSPolicyComplianceState(proto.Enum): - r"""Supported OSPolicy compliance states.""" - OS_POLICY_COMPLIANCE_STATE_UNSPECIFIED = 0 - COMPLIANT = 1 - NON_COMPLIANT = 2 - UNKNOWN = 3 - NO_OS_POLICIES_APPLICABLE = 4 - - -class OSPolicyResourceConfigStep(proto.Message): - r"""Step performed by the OS Config agent for configuring an - ``OSPolicyResource`` to its desired state. - - Attributes: - type_ (google.cloud.osconfig_v1alpha.types.OSPolicyResourceConfigStep.Type): - Configuration step type. - outcome (google.cloud.osconfig_v1alpha.types.OSPolicyResourceConfigStep.Outcome): - Outcome of the configuration step. - error_message (str): - An error message recorded during the - execution of this step. Only populated when - outcome is FAILED. - """ - class Type(proto.Enum): - r"""Supported configuration step types""" - TYPE_UNSPECIFIED = 0 - VALIDATION = 1 - DESIRED_STATE_CHECK = 2 - DESIRED_STATE_ENFORCEMENT = 3 - DESIRED_STATE_CHECK_POST_ENFORCEMENT = 4 - - class Outcome(proto.Enum): - r"""Supported outcomes for a configuration step.""" - OUTCOME_UNSPECIFIED = 0 - SUCCEEDED = 1 - FAILED = 2 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - outcome = proto.Field( - proto.ENUM, - number=2, - enum=Outcome, - ) - error_message = proto.Field( - proto.STRING, - number=3, - ) - - -class OSPolicyResourceCompliance(proto.Message): - r"""Compliance data for an OS policy resource. - Attributes: - os_policy_resource_id (str): - The id of the OS policy resource. - config_steps (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyResourceConfigStep]): - Ordered list of configuration steps taken by - the agent for the OS policy resource. - state (google.cloud.osconfig_v1alpha.types.OSPolicyComplianceState): - Compliance state of the OS policy resource. - exec_resource_output (google.cloud.osconfig_v1alpha.types.OSPolicyResourceCompliance.ExecResourceOutput): - ExecResource specific output. - """ - - class ExecResourceOutput(proto.Message): - r"""ExecResource specific output. - Attributes: - enforcement_output (bytes): - Output from Enforcement phase output file (if - run). Output size is limited to 100K bytes. - """ - - enforcement_output = proto.Field( - proto.BYTES, - number=2, - ) - - os_policy_resource_id = proto.Field( - proto.STRING, - number=1, - ) - config_steps = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='OSPolicyResourceConfigStep', - ) - state = proto.Field( - proto.ENUM, - number=3, - enum='OSPolicyComplianceState', - ) - exec_resource_output = proto.Field( - proto.MESSAGE, - number=4, - oneof='output', - message=ExecResourceOutput, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py deleted file mode 100644 index b95ca34..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/instance_os_policies_compliance.py +++ /dev/null @@ -1,263 +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.cloud.osconfig_v1alpha.types import config_common -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1alpha', - manifest={ - 'InstanceOSPoliciesCompliance', - 'GetInstanceOSPoliciesComplianceRequest', - 'ListInstanceOSPoliciesCompliancesRequest', - 'ListInstanceOSPoliciesCompliancesResponse', - }, -) - - -class InstanceOSPoliciesCompliance(proto.Message): - r"""This API resource represents the OS policies compliance data for a - Compute Engine virtual machine (VM) instance at a given point in - time. - - A Compute Engine VM can have multiple OS policy assignments, and - each assignment can have multiple OS policies. As a result, multiple - OS policies could be applied to a single VM. - - You can use this API resource to determine both the compliance state - of your VM as well as the compliance state of an individual OS - policy. - - For more information, see `View - compliance `__. - - Attributes: - name (str): - Output only. The ``InstanceOSPoliciesCompliance`` API - resource name. - - Format: - ``projects/{project_number}/locations/{location}/instanceOSPoliciesCompliances/{instance_id}`` - instance (str): - Output only. The Compute Engine VM instance - name. - state (google.cloud.osconfig_v1alpha.types.OSPolicyComplianceState): - Output only. Compliance state of the VM. - detailed_state (str): - Output only. Detailed compliance state of the VM. This field - is populated only when compliance state is ``UNKNOWN``. - - It may contain one of the following values: - - - ``no-compliance-data``: Compliance data is not available - for this VM. - - ``no-agent-detected``: OS Config agent is not detected - for this VM. - - ``config-not-supported-by-agent``: The version of the OS - Config agent running on this VM does not support - configuration management. - - ``inactive``: VM is not running. - - ``internal-service-errors``: There were internal service - errors encountered while enforcing compliance. - - ``agent-errors``: OS config agent encountered errors - while enforcing compliance. - detailed_state_reason (str): - Output only. The reason for the ``detailed_state`` of the VM - (if any). - os_policy_compliances (Sequence[google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance.OSPolicyCompliance]): - Output only. Compliance data for each ``OSPolicy`` that is - applied to the VM. - last_compliance_check_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp of the last compliance - check for the VM. - last_compliance_run_id (str): - Output only. Unique identifier for the last - compliance run. This id will be logged by the OS - config agent during a compliance run and can be - used for debugging and tracing purpose. - """ - - class OSPolicyCompliance(proto.Message): - r"""Compliance data for an OS policy - Attributes: - os_policy_id (str): - The OS policy id - os_policy_assignment (str): - Reference to the ``OSPolicyAssignment`` API resource that - the ``OSPolicy`` belongs to. - - Format: - ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id@revision_id}`` - state (google.cloud.osconfig_v1alpha.types.OSPolicyComplianceState): - Compliance state of the OS policy. - os_policy_resource_compliances (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyResourceCompliance]): - Compliance data for each ``OSPolicyResource`` that is - applied to the VM. - """ - - os_policy_id = proto.Field( - proto.STRING, - number=1, - ) - os_policy_assignment = proto.Field( - proto.STRING, - number=2, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=config_common.OSPolicyComplianceState, - ) - os_policy_resource_compliances = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=config_common.OSPolicyResourceCompliance, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - instance = proto.Field( - proto.STRING, - number=2, - ) - state = proto.Field( - proto.ENUM, - number=3, - enum=config_common.OSPolicyComplianceState, - ) - detailed_state = proto.Field( - proto.STRING, - number=4, - ) - detailed_state_reason = proto.Field( - proto.STRING, - number=5, - ) - os_policy_compliances = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=OSPolicyCompliance, - ) - last_compliance_check_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - last_compliance_run_id = proto.Field( - proto.STRING, - number=8, - ) - - -class GetInstanceOSPoliciesComplianceRequest(proto.Message): - r"""A request message for getting OS policies compliance data for - the given Compute Engine VM instance. - - Attributes: - name (str): - Required. API resource name for instance OS policies - compliance resource. - - Format: - ``projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}`` - - For ``{project}``, either Compute Engine project-number or - project-id can be provided. For ``{instance}``, either - Compute Engine VM instance-id or instance-name can be - provided. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListInstanceOSPoliciesCompliancesRequest(proto.Message): - r"""A request message for listing OS policies compliance data for - all Compute Engine VMs in the given location. - - Attributes: - parent (str): - Required. The parent resource name. - - Format: ``projects/{project}/locations/{location}`` - - For ``{project}``, either Compute Engine project-number or - project-id can be provided. - page_size (int): - The maximum number of results to return. - page_token (str): - A pagination token returned from a previous call to - ``ListInstanceOSPoliciesCompliances`` that indicates where - this listing should continue from. - filter (str): - If provided, this field specifies the criteria that must be - met by a ``InstanceOSPoliciesCompliance`` API resource to be - included in the response. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListInstanceOSPoliciesCompliancesResponse(proto.Message): - r"""A response message for listing OS policies compliance data - for all Compute Engine VMs in the given location. - - Attributes: - instance_os_policies_compliances (Sequence[google.cloud.osconfig_v1alpha.types.InstanceOSPoliciesCompliance]): - List of instance OS policies compliance - objects. - next_page_token (str): - The pagination token to retrieve the next - page of instance OS policies compliance objects. - """ - - @property - def raw_page(self): - return self - - instance_os_policies_compliances = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='InstanceOSPoliciesCompliance', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py deleted file mode 100644 index dc5f595..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/inventory.py +++ /dev/null @@ -1,670 +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 timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1alpha', - manifest={ - 'InventoryView', - 'Inventory', - 'GetInventoryRequest', - 'ListInventoriesRequest', - 'ListInventoriesResponse', - }, -) - - -class InventoryView(proto.Enum): - r"""The view for inventory objects.""" - INVENTORY_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - -class Inventory(proto.Message): - r"""This API resource represents the available inventory data for a - Compute Engine virtual machine (VM) instance at a given point in - time. - - You can use this API resource to determine the inventory data of - your VM. - - For more information, see `Information provided by OS inventory - management `__. - - Attributes: - name (str): - Output only. The ``Inventory`` API resource name. - - Format: - ``projects/{project_number}/locations/{location}/instances/{instance_id}/inventory`` - os_info (google.cloud.osconfig_v1alpha.types.Inventory.OsInfo): - Output only. Base level operating system - information for the VM. - items (Sequence[google.cloud.osconfig_v1alpha.types.Inventory.ItemsEntry]): - Output only. Inventory items related to the - VM keyed by an opaque unique identifier for each - inventory item. The identifier is unique to each - distinct and addressable inventory item and will - change, when there is a new package version. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp of the last reported - inventory for the VM. - """ - - class OsInfo(proto.Message): - r"""Operating system information for the VM. - Attributes: - hostname (str): - The VM hostname. - long_name (str): - The operating system long name. - For example 'Debian GNU/Linux 9' or 'Microsoft - Window Server 2019 Datacenter'. - short_name (str): - The operating system short name. - For example, 'windows' or 'debian'. - version (str): - The version of the operating system. - architecture (str): - The system architecture of the operating - system. - kernel_version (str): - The kernel version of the operating system. - kernel_release (str): - The kernel release of the operating system. - osconfig_agent_version (str): - The current version of the OS Config agent - running on the VM. - """ - - hostname = proto.Field( - proto.STRING, - number=9, - ) - long_name = proto.Field( - proto.STRING, - number=2, - ) - short_name = proto.Field( - proto.STRING, - number=3, - ) - version = proto.Field( - proto.STRING, - number=4, - ) - architecture = proto.Field( - proto.STRING, - number=5, - ) - kernel_version = proto.Field( - proto.STRING, - number=6, - ) - kernel_release = proto.Field( - proto.STRING, - number=7, - ) - osconfig_agent_version = proto.Field( - proto.STRING, - number=8, - ) - - class Item(proto.Message): - r"""A single piece of inventory on a VM. - Attributes: - id (str): - Identifier for this item, unique across items - for this VM. - origin_type (google.cloud.osconfig_v1alpha.types.Inventory.Item.OriginType): - The origin of this inventory item. - create_time (google.protobuf.timestamp_pb2.Timestamp): - When this inventory item was first detected. - update_time (google.protobuf.timestamp_pb2.Timestamp): - When this inventory item was last modified. - type_ (google.cloud.osconfig_v1alpha.types.Inventory.Item.Type): - The specific type of inventory, correlating - to its specific details. - installed_package (google.cloud.osconfig_v1alpha.types.Inventory.SoftwarePackage): - Software package present on the VM instance. - available_package (google.cloud.osconfig_v1alpha.types.Inventory.SoftwarePackage): - Software package available to be installed on - the VM instance. - """ - class OriginType(proto.Enum): - r"""The origin of a specific inventory item.""" - ORIGIN_TYPE_UNSPECIFIED = 0 - INVENTORY_REPORT = 1 - - class Type(proto.Enum): - r"""The different types of inventory that are tracked on a VM.""" - TYPE_UNSPECIFIED = 0 - INSTALLED_PACKAGE = 1 - AVAILABLE_PACKAGE = 2 - - id = proto.Field( - proto.STRING, - number=1, - ) - origin_type = proto.Field( - proto.ENUM, - number=2, - enum='Inventory.Item.OriginType', - ) - create_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - type_ = proto.Field( - proto.ENUM, - number=5, - enum='Inventory.Item.Type', - ) - installed_package = proto.Field( - proto.MESSAGE, - number=6, - oneof='details', - message='Inventory.SoftwarePackage', - ) - available_package = proto.Field( - proto.MESSAGE, - number=7, - oneof='details', - message='Inventory.SoftwarePackage', - ) - - class SoftwarePackage(proto.Message): - r"""Software package information of the operating system. - Attributes: - yum_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): - Yum package info. For details about the yum package manager, - see - https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-yum. - apt_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): - Details of an APT package. - For details about the apt package manager, see - https://wiki.debian.org/Apt. - zypper_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): - Details of a Zypper package. For details about the Zypper - package manager, see - https://en.opensuse.org/SDB:Zypper_manual. - googet_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): - Details of a Googet package. - For details about the googet package manager, - see https://github.com/google/googet. - zypper_patch (google.cloud.osconfig_v1alpha.types.Inventory.ZypperPatch): - Details of a Zypper patch. For details about the Zypper - package manager, see - https://en.opensuse.org/SDB:Zypper_manual. - wua_package (google.cloud.osconfig_v1alpha.types.Inventory.WindowsUpdatePackage): - Details of a Windows Update package. See - https://docs.microsoft.com/en-us/windows/win32/api/_wua/ for - information about Windows Update. - qfe_package (google.cloud.osconfig_v1alpha.types.Inventory.WindowsQuickFixEngineeringPackage): - Details of a Windows Quick Fix engineering - package. See - https://docs.microsoft.com/en- - us/windows/win32/cimwin32prov/win32-quickfixengineering - for info in Windows Quick Fix Engineering. - cos_package (google.cloud.osconfig_v1alpha.types.Inventory.VersionedPackage): - Details of a COS package. - windows_application (google.cloud.osconfig_v1alpha.types.Inventory.WindowsApplication): - Details of Windows Application. - """ - - yum_package = proto.Field( - proto.MESSAGE, - number=1, - oneof='details', - message='Inventory.VersionedPackage', - ) - apt_package = proto.Field( - proto.MESSAGE, - number=2, - oneof='details', - message='Inventory.VersionedPackage', - ) - zypper_package = proto.Field( - proto.MESSAGE, - number=3, - oneof='details', - message='Inventory.VersionedPackage', - ) - googet_package = proto.Field( - proto.MESSAGE, - number=4, - oneof='details', - message='Inventory.VersionedPackage', - ) - zypper_patch = proto.Field( - proto.MESSAGE, - number=5, - oneof='details', - message='Inventory.ZypperPatch', - ) - wua_package = proto.Field( - proto.MESSAGE, - number=6, - oneof='details', - message='Inventory.WindowsUpdatePackage', - ) - qfe_package = proto.Field( - proto.MESSAGE, - number=7, - oneof='details', - message='Inventory.WindowsQuickFixEngineeringPackage', - ) - cos_package = proto.Field( - proto.MESSAGE, - number=8, - oneof='details', - message='Inventory.VersionedPackage', - ) - windows_application = proto.Field( - proto.MESSAGE, - number=9, - oneof='details', - message='Inventory.WindowsApplication', - ) - - class VersionedPackage(proto.Message): - r"""Information related to the a standard versioned package. - This includes package info for APT, Yum, Zypper, and Googet - package managers. - - Attributes: - package_name (str): - The name of the package. - architecture (str): - The system architecture this package is - intended for. - version (str): - The version of the package. - """ - - package_name = proto.Field( - proto.STRING, - number=4, - ) - architecture = proto.Field( - proto.STRING, - number=2, - ) - version = proto.Field( - proto.STRING, - number=3, - ) - - class ZypperPatch(proto.Message): - r"""Details related to a Zypper Patch. - Attributes: - patch_name (str): - The name of the patch. - category (str): - The category of the patch. - severity (str): - The severity specified for this patch - summary (str): - Any summary information provided about this - patch. - """ - - patch_name = proto.Field( - proto.STRING, - number=5, - ) - category = proto.Field( - proto.STRING, - number=2, - ) - severity = proto.Field( - proto.STRING, - number=3, - ) - summary = proto.Field( - proto.STRING, - number=4, - ) - - class WindowsUpdatePackage(proto.Message): - r"""Details related to a Windows Update package. Field data and names - are taken from Windows Update API IUpdate Interface: - https://docs.microsoft.com/en-us/windows/win32/api/_wua/ Descriptive - fields like title, and description are localized based on the locale - of the VM being updated. - - Attributes: - title (str): - The localized title of the update package. - description (str): - The localized description of the update - package. - categories (Sequence[google.cloud.osconfig_v1alpha.types.Inventory.WindowsUpdatePackage.WindowsUpdateCategory]): - The categories that are associated with this - update package. - kb_article_ids (Sequence[str]): - A collection of Microsoft Knowledge Base - article IDs that are associated with the update - package. - support_url (str): - A hyperlink to the language-specific support - information for the update. - more_info_urls (Sequence[str]): - A collection of URLs that provide more - information about the update package. - update_id (str): - Gets the identifier of an update package. - Stays the same across revisions. - revision_number (int): - The revision number of this update package. - last_deployment_change_time (google.protobuf.timestamp_pb2.Timestamp): - The last published date of the update, in - (UTC) date and time. - """ - - class WindowsUpdateCategory(proto.Message): - r"""Categories specified by the Windows Update. - Attributes: - id (str): - The identifier of the windows update - category. - name (str): - The name of the windows update category. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - name = proto.Field( - proto.STRING, - number=2, - ) - - title = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - categories = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Inventory.WindowsUpdatePackage.WindowsUpdateCategory', - ) - kb_article_ids = proto.RepeatedField( - proto.STRING, - number=4, - ) - support_url = proto.Field( - proto.STRING, - number=11, - ) - more_info_urls = proto.RepeatedField( - proto.STRING, - number=5, - ) - update_id = proto.Field( - proto.STRING, - number=6, - ) - revision_number = proto.Field( - proto.INT32, - number=7, - ) - last_deployment_change_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - class WindowsQuickFixEngineeringPackage(proto.Message): - r"""Information related to a Quick Fix Engineering package. - Fields are taken from Windows QuickFixEngineering Interface and - match the source names: - https://docs.microsoft.com/en- - us/windows/win32/cimwin32prov/win32-quickfixengineering - - Attributes: - caption (str): - A short textual description of the QFE - update. - description (str): - A textual description of the QFE update. - hot_fix_id (str): - Unique identifier associated with a - particular QFE update. - install_time (google.protobuf.timestamp_pb2.Timestamp): - Date that the QFE update was installed. Mapped from - installed_on field. - """ - - caption = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - hot_fix_id = proto.Field( - proto.STRING, - number=3, - ) - install_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - class WindowsApplication(proto.Message): - r"""Contains information about a Windows application as retrieved from - the Windows Registry. For more information about these fields, see - - `Windows Installer Properties for the Uninstall - Registry `__\ {: - class="external" } - - Attributes: - display_name (str): - The name of the application or product. - display_version (str): - The version of the product or application in - string format. - publisher (str): - The name of the manufacturer for the product - or application. - install_date (google.type.date_pb2.Date): - The last time this product received service. - The value of this property is replaced each time - a patch is applied or removed from the product - or the command-line option is used to repair the - product. - help_link (str): - The internet address for technical support. - """ - - display_name = proto.Field( - proto.STRING, - number=1, - ) - display_version = proto.Field( - proto.STRING, - number=2, - ) - publisher = proto.Field( - proto.STRING, - number=3, - ) - install_date = proto.Field( - proto.MESSAGE, - number=4, - message=date_pb2.Date, - ) - help_link = proto.Field( - proto.STRING, - number=5, - ) - - name = proto.Field( - proto.STRING, - number=3, - ) - os_info = proto.Field( - proto.MESSAGE, - number=1, - message=OsInfo, - ) - items = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=Item, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class GetInventoryRequest(proto.Message): - r"""A request message for getting inventory data for the - specified VM. - - Attributes: - name (str): - Required. API resource name for inventory resource. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}/inventory`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, either - Compute Engine ``instance-id`` or ``instance-name`` can be - provided. - view (google.cloud.osconfig_v1alpha.types.InventoryView): - Inventory view indicating what information - should be included in the inventory resource. If - unspecified, the default view is BASIC. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=2, - enum='InventoryView', - ) - - -class ListInventoriesRequest(proto.Message): - r"""A request message for listing inventory data for all VMs in - the specified location. - - Attributes: - parent (str): - Required. The parent resource name. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, only - hyphen or dash character is supported to list inventories - across VMs. - view (google.cloud.osconfig_v1alpha.types.InventoryView): - Inventory view indicating what information - should be included in the inventory resource. If - unspecified, the default view is BASIC. - page_size (int): - The maximum number of results to return. - page_token (str): - A pagination token returned from a previous call to - ``ListInventories`` that indicates where this listing should - continue from. - filter (str): - If provided, this field specifies the criteria that must be - met by a ``Inventory`` API resource to be included in the - response. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=2, - enum='InventoryView', - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - - -class ListInventoriesResponse(proto.Message): - r"""A response message for listing inventory data for all VMs in - a specified location. - - Attributes: - inventories (Sequence[google.cloud.osconfig_v1alpha.types.Inventory]): - List of inventory objects. - next_page_token (str): - The pagination token to retrieve the next - page of inventory objects. - """ - - @property - def raw_page(self): - return self - - inventories = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Inventory', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py deleted file mode 100644 index c8cc8c2..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy.py +++ /dev/null @@ -1,865 +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.cloud.osconfig.v1alpha', - manifest={ - 'OSPolicy', - }, -) - - -class OSPolicy(proto.Message): - r"""An OS policy defines the desired state configuration for a - VM. - - Attributes: - id (str): - Required. The id of the OS policy with the following - restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the assignment. - description (str): - Policy description. - Length of the description is limited to 1024 - characters. - mode (google.cloud.osconfig_v1alpha.types.OSPolicy.Mode): - Required. Policy mode - resource_groups (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicy.ResourceGroup]): - Required. List of resource groups for the policy. For a - particular VM, resource groups are evaluated in the order - specified and the first resource group that is applicable is - selected and the rest are ignored. - - If none of the resource groups are applicable for a VM, the - VM is considered to be non-compliant w.r.t this policy. This - behavior can be toggled by the flag - ``allow_no_resource_group_match`` - allow_no_resource_group_match (bool): - This flag determines the OS policy compliance status when - none of the resource groups within the policy are applicable - for a VM. Set this value to ``true`` if the policy needs to - be reported as compliant even if the policy has nothing to - validate or enforce. - """ - class Mode(proto.Enum): - r"""Policy mode""" - MODE_UNSPECIFIED = 0 - VALIDATION = 1 - ENFORCEMENT = 2 - - class OSFilter(proto.Message): - r"""The ``OSFilter`` is used to specify the OS filtering criteria for - the resource group. - - Attributes: - os_short_name (str): - This should match OS short name emitted by - the OS inventory agent. An empty value matches - any OS. - os_version (str): - This value should match the version emitted by the OS - inventory agent. Prefix matches are supported if asterisk(*) - is provided as the last character. For example, to match all - versions with a major version of ``7``, specify the - following value for this field ``7.*`` - """ - - os_short_name = proto.Field( - proto.STRING, - number=1, - ) - os_version = proto.Field( - proto.STRING, - number=2, - ) - - class Resource(proto.Message): - r"""An OS policy resource is used to define the desired state - configuration and provides a specific functionality like - installing/removing packages, executing a script etc. - - The system ensures that resources are always in their desired - state by taking necessary actions if they have drifted from - their desired state. - - Attributes: - id (str): - Required. The id of the resource with the following - restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the OS policy. - pkg (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource): - Package resource - repository (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource): - Package repository resource - exec_ (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource): - Exec resource - file (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.FileResource): - File resource - """ - - class File(proto.Message): - r"""A remote or local file. - Attributes: - remote (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File.Remote): - A generic remote file. - gcs (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File.Gcs): - A Cloud Storage object. - local_path (str): - A local path within the VM to use. - allow_insecure (bool): - Defaults to false. When false, files are - subject to validations based on the file type: - Remote: A checksum must be specified. - Cloud Storage: An object generation number must - be specified. - """ - - class Remote(proto.Message): - r"""Specifies a file available via some URI. - Attributes: - uri (str): - Required. URI from which to fetch the object. It should - contain both the protocol and path following the format - ``{protocol}://{location}``. - sha256_checksum (str): - SHA256 checksum of the remote file. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - sha256_checksum = proto.Field( - proto.STRING, - number=2, - ) - - class Gcs(proto.Message): - r"""Specifies a file available as a Cloud Storage Object. - Attributes: - bucket (str): - Required. Bucket of the Cloud Storage object. - object_ (str): - Required. Name of the Cloud Storage object. - generation (int): - Generation number of the Cloud Storage - object. - """ - - bucket = proto.Field( - proto.STRING, - number=1, - ) - object_ = proto.Field( - proto.STRING, - number=2, - ) - generation = proto.Field( - proto.INT64, - number=3, - ) - - remote = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message='OSPolicy.Resource.File.Remote', - ) - gcs = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='OSPolicy.Resource.File.Gcs', - ) - local_path = proto.Field( - proto.STRING, - number=3, - oneof='type', - ) - allow_insecure = proto.Field( - proto.BOOL, - number=4, - ) - - class PackageResource(proto.Message): - r"""A resource that manages a system package. - Attributes: - desired_state (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.DesiredState): - Required. The desired state the agent should - maintain for this package. - apt (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.APT): - A package managed by Apt. - deb (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.Deb): - A deb package file. - yum (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.YUM): - A package managed by YUM. - zypper (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.Zypper): - A package managed by Zypper. - rpm (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.RPM): - An rpm package file. - googet (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.GooGet): - A package managed by GooGet. - msi (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.PackageResource.MSI): - An MSI package. - """ - class DesiredState(proto.Enum): - r"""The desired state that the OS Config agent maintains on the - VM. - """ - DESIRED_STATE_UNSPECIFIED = 0 - INSTALLED = 1 - REMOVED = 2 - - class Deb(proto.Message): - r"""A deb package file. dpkg packages only support INSTALLED - state. - - Attributes: - source (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): - Required. A deb package. - pull_deps (bool): - Whether dependencies should also be installed. - - - install when false: ``dpkg -i package`` - - install when true: - ``apt-get update && apt-get -y install package.deb`` - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message='OSPolicy.Resource.File', - ) - pull_deps = proto.Field( - proto.BOOL, - number=2, - ) - - class APT(proto.Message): - r"""A package managed by APT. - - - install: ``apt-get update && apt-get -y install [name]`` - - remove: ``apt-get -y remove [name]`` - - Attributes: - name (str): - Required. Package name. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - class RPM(proto.Message): - r"""An RPM package file. RPM packages only support INSTALLED - state. - - Attributes: - source (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): - Required. An rpm package. - pull_deps (bool): - Whether dependencies should also be installed. - - - install when false: - ``rpm --upgrade --replacepkgs package.rpm`` - - install when true: ``yum -y install package.rpm`` or - ``zypper -y install package.rpm`` - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message='OSPolicy.Resource.File', - ) - pull_deps = proto.Field( - proto.BOOL, - number=2, - ) - - class YUM(proto.Message): - r"""A package managed by YUM. - - - install: ``yum -y install package`` - - remove: ``yum -y remove package`` - - Attributes: - name (str): - Required. Package name. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - class Zypper(proto.Message): - r"""A package managed by Zypper. - - - install: ``zypper -y install package`` - - remove: ``zypper -y rm package`` - - Attributes: - name (str): - Required. Package name. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - class GooGet(proto.Message): - r"""A package managed by GooGet. - - - install: ``googet -noconfirm install package`` - - remove: ``googet -noconfirm remove package`` - - Attributes: - name (str): - Required. Package name. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - class MSI(proto.Message): - r"""An MSI package. MSI packages only support INSTALLED state. - Attributes: - source (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): - Required. The MSI package. - properties (Sequence[str]): - Additional properties to use during installation. This - should be in the format of Property=Setting. Appended to the - defaults of ``ACTION=INSTALL REBOOT=ReallySuppress``. - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message='OSPolicy.Resource.File', - ) - properties = proto.RepeatedField( - proto.STRING, - number=2, - ) - - desired_state = proto.Field( - proto.ENUM, - number=1, - enum='OSPolicy.Resource.PackageResource.DesiredState', - ) - apt = proto.Field( - proto.MESSAGE, - number=2, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.APT', - ) - deb = proto.Field( - proto.MESSAGE, - number=3, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.Deb', - ) - yum = proto.Field( - proto.MESSAGE, - number=4, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.YUM', - ) - zypper = proto.Field( - proto.MESSAGE, - number=5, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.Zypper', - ) - rpm = proto.Field( - proto.MESSAGE, - number=6, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.RPM', - ) - googet = proto.Field( - proto.MESSAGE, - number=7, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.GooGet', - ) - msi = proto.Field( - proto.MESSAGE, - number=8, - oneof='system_package', - message='OSPolicy.Resource.PackageResource.MSI', - ) - - class RepositoryResource(proto.Message): - r"""A resource that manages a package repository. - Attributes: - apt (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.AptRepository): - An Apt Repository. - yum (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.YumRepository): - A Yum Repository. - zypper (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.ZypperRepository): - A Zypper Repository. - goo (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.GooRepository): - A Goo Repository. - """ - - class AptRepository(proto.Message): - r"""Represents a single apt package repository. These will be added to a - repo file that will be managed at - ``/etc/apt/sources.list.d/google_osconfig.list``. - - Attributes: - archive_type (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType): - Required. Type of archive files in this - repository. - uri (str): - Required. URI for this repository. - distribution (str): - Required. Distribution of this repository. - components (Sequence[str]): - Required. List of components for this - repository. Must contain at least one item. - gpg_key (str): - URI of the key file for this repository. The agent maintains - a keyring at - ``/etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg``. - """ - class ArchiveType(proto.Enum): - r"""Type of archive.""" - ARCHIVE_TYPE_UNSPECIFIED = 0 - DEB = 1 - DEB_SRC = 2 - - archive_type = proto.Field( - proto.ENUM, - number=1, - enum='OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType', - ) - uri = proto.Field( - proto.STRING, - number=2, - ) - distribution = proto.Field( - proto.STRING, - number=3, - ) - components = proto.RepeatedField( - proto.STRING, - number=4, - ) - gpg_key = proto.Field( - proto.STRING, - number=5, - ) - - class YumRepository(proto.Message): - r"""Represents a single yum package repository. These are added to a - repo file that is managed at - ``/etc/yum.repos.d/google_osconfig.repo``. - - Attributes: - id (str): - Required. A one word, unique name for this repository. This - is the ``repo id`` in the yum config file and also the - ``display_name`` if ``display_name`` is omitted. This id is - also used as the unique identifier when checking for - resource conflicts. - display_name (str): - The display name of the repository. - base_url (str): - Required. The location of the repository - directory. - gpg_keys (Sequence[str]): - URIs of GPG keys. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - base_url = proto.Field( - proto.STRING, - number=3, - ) - gpg_keys = proto.RepeatedField( - proto.STRING, - number=4, - ) - - class ZypperRepository(proto.Message): - r"""Represents a single zypper package repository. These are added to a - repo file that is managed at - ``/etc/zypp/repos.d/google_osconfig.repo``. - - Attributes: - id (str): - Required. A one word, unique name for this repository. This - is the ``repo id`` in the zypper config file and also the - ``display_name`` if ``display_name`` is omitted. This id is - also used as the unique identifier when checking for - GuestPolicy conflicts. - display_name (str): - The display name of the repository. - base_url (str): - Required. The location of the repository - directory. - gpg_keys (Sequence[str]): - URIs of GPG keys. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - base_url = proto.Field( - proto.STRING, - number=3, - ) - gpg_keys = proto.RepeatedField( - proto.STRING, - number=4, - ) - - class GooRepository(proto.Message): - r"""Represents a Goo package repository. These are added to a repo file - that is managed at - ``C:/ProgramData/GooGet/repos/google_osconfig.repo``. - - Attributes: - name (str): - Required. The name of the repository. - url (str): - Required. The url of the repository. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - url = proto.Field( - proto.STRING, - number=2, - ) - - apt = proto.Field( - proto.MESSAGE, - number=1, - oneof='repository', - message='OSPolicy.Resource.RepositoryResource.AptRepository', - ) - yum = proto.Field( - proto.MESSAGE, - number=2, - oneof='repository', - message='OSPolicy.Resource.RepositoryResource.YumRepository', - ) - zypper = proto.Field( - proto.MESSAGE, - number=3, - oneof='repository', - message='OSPolicy.Resource.RepositoryResource.ZypperRepository', - ) - goo = proto.Field( - proto.MESSAGE, - number=4, - oneof='repository', - message='OSPolicy.Resource.RepositoryResource.GooRepository', - ) - - class ExecResource(proto.Message): - r"""A resource that allows executing scripts on the VM. - - The ``ExecResource`` has 2 stages: ``validate`` and ``enforce`` and - both stages accept a script as an argument to execute. - - When the ``ExecResource`` is applied by the agent, it first executes - the script in the ``validate`` stage. The ``validate`` stage can - signal that the ``ExecResource`` is already in the desired state by - returning an exit code of ``100``. If the ``ExecResource`` is not in - the desired state, it should return an exit code of ``101``. Any - other exit code returned by this stage is considered an error. - - If the ``ExecResource`` is not in the desired state based on the - exit code from the ``validate`` stage, the agent proceeds to execute - the script from the ``enforce`` stage. If the ``ExecResource`` is - already in the desired state, the ``enforce`` stage will not be run. - Similar to ``validate`` stage, the ``enforce`` stage should return - an exit code of ``100`` to indicate that the resource in now in its - desired state. Any other exit code is considered an error. - - NOTE: An exit code of ``100`` was chosen over ``0`` (and ``101`` vs - ``1``) to have an explicit indicator of ``in desired state``, - ``not in desired state`` and errors. Because, for example, - Powershell will always return an exit code of ``0`` unless an - ``exit`` statement is provided in the script. So, for reasons of - consistency and being explicit, exit codes ``100`` and ``101`` were - chosen. - - Attributes: - validate (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource.Exec): - Required. What to run to validate this - resource is in the desired state. An exit code - of 100 indicates "in desired state", and exit - code of 101 indicates "not in desired state". - Any other exit code indicates a failure running - validate. - enforce (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource.Exec): - What to run to bring this resource into the - desired state. An exit code of 100 indicates - "success", any other exit code indicates a - failure running enforce. - """ - - class Exec(proto.Message): - r"""A file or script to execute. - Attributes: - file (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): - A remote or local file. - script (str): - An inline script. - The size of the script is limited to 1024 - characters. - args (Sequence[str]): - Optional arguments to pass to the source - during execution. - interpreter (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.ExecResource.Exec.Interpreter): - Required. The script interpreter to use. - output_file_path (str): - Only recorded for enforce Exec. - Path to an output file (that is created by this - Exec) whose content will be recorded in - OSPolicyResourceCompliance after a successful - run. Absence or failure to read this file will - result in this ExecResource being non-compliant. - Output file size is limited to 100K bytes. - """ - class Interpreter(proto.Enum): - r"""The interpreter to use.""" - INTERPRETER_UNSPECIFIED = 0 - NONE = 1 - SHELL = 2 - POWERSHELL = 3 - - file = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='OSPolicy.Resource.File', - ) - script = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - args = proto.RepeatedField( - proto.STRING, - number=3, - ) - interpreter = proto.Field( - proto.ENUM, - number=4, - enum='OSPolicy.Resource.ExecResource.Exec.Interpreter', - ) - output_file_path = proto.Field( - proto.STRING, - number=5, - ) - - validate = proto.Field( - proto.MESSAGE, - number=1, - message='OSPolicy.Resource.ExecResource.Exec', - ) - enforce = proto.Field( - proto.MESSAGE, - number=2, - message='OSPolicy.Resource.ExecResource.Exec', - ) - - class FileResource(proto.Message): - r"""A resource that manages the state of a file. - Attributes: - file (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.File): - A remote or local source. - content (str): - A a file with this content. - The size of the content is limited to 1024 - characters. - path (str): - Required. The absolute path of the file - within the VM. - state (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.FileResource.DesiredState): - Required. Desired state of the file. - permissions (str): - Consists of three octal digits which - represent, in order, the permissions of the - owner, group, and other users for the file - (similarly to the numeric mode used in the linux - chmod utility). Each digit represents a three - bit number with the 4 bit corresponding to the - read permissions, the 2 bit corresponds to the - write bit, and the one bit corresponds to the - execute permission. Default behavior is 755. - - Below are some examples of permissions and their - associated values: read, write, and execute: 7 - read and execute: 5 - read and write: 6 - read only: 4 - """ - class DesiredState(proto.Enum): - r"""Desired state of the file.""" - DESIRED_STATE_UNSPECIFIED = 0 - PRESENT = 1 - ABSENT = 2 - CONTENTS_MATCH = 3 - - file = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='OSPolicy.Resource.File', - ) - content = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - path = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum='OSPolicy.Resource.FileResource.DesiredState', - ) - permissions = proto.Field( - proto.STRING, - number=5, - ) - - id = proto.Field( - proto.STRING, - number=1, - ) - pkg = proto.Field( - proto.MESSAGE, - number=2, - oneof='resource_type', - message='OSPolicy.Resource.PackageResource', - ) - repository = proto.Field( - proto.MESSAGE, - number=3, - oneof='resource_type', - message='OSPolicy.Resource.RepositoryResource', - ) - exec_ = proto.Field( - proto.MESSAGE, - number=4, - oneof='resource_type', - message='OSPolicy.Resource.ExecResource', - ) - file = proto.Field( - proto.MESSAGE, - number=5, - oneof='resource_type', - message='OSPolicy.Resource.FileResource', - ) - - class ResourceGroup(proto.Message): - r"""Resource groups provide a mechanism to group OS policy resources. - - Resource groups enable OS policy authors to create a single OS - policy to be applied to VMs running different operating Systems. - - When the OS policy is applied to a target VM, the appropriate - resource group within the OS policy is selected based on the - ``OSFilter`` specified within the resource group. - - Attributes: - os_filter (google.cloud.osconfig_v1alpha.types.OSPolicy.OSFilter): - Used to specify the OS filter for a resource - group - resources (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicy.Resource]): - Required. List of resources configured for - this resource group. The resources are executed - in the exact order specified here. - """ - - os_filter = proto.Field( - proto.MESSAGE, - number=1, - message='OSPolicy.OSFilter', - ) - resources = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='OSPolicy.Resource', - ) - - id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - mode = proto.Field( - proto.ENUM, - number=3, - enum=Mode, - ) - resource_groups = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=ResourceGroup, - ) - allow_no_resource_group_match = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py deleted file mode 100644 index 2314d05..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/os_policy_assignments.py +++ /dev/null @@ -1,540 +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.cloud.osconfig_v1alpha.types import os_policy -from google.cloud.osconfig_v1alpha.types import osconfig_common -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1alpha', - manifest={ - 'OSPolicyAssignment', - 'OSPolicyAssignmentOperationMetadata', - 'CreateOSPolicyAssignmentRequest', - 'UpdateOSPolicyAssignmentRequest', - 'GetOSPolicyAssignmentRequest', - 'ListOSPolicyAssignmentsRequest', - 'ListOSPolicyAssignmentsResponse', - 'ListOSPolicyAssignmentRevisionsRequest', - 'ListOSPolicyAssignmentRevisionsResponse', - 'DeleteOSPolicyAssignmentRequest', - }, -) - - -class OSPolicyAssignment(proto.Message): - r"""OS policy assignment is an API resource that is used to apply a set - of OS policies to a dynamically targeted group of Compute Engine VM - instances. - - An OS policy is used to define the desired state configuration for a - Compute Engine VM instance through a set of configuration resources - that provide capabilities such as installing or removing software - packages, or executing a script. - - For more information, see `OS policy and OS policy - assignment `__. - - Attributes: - name (str): - Resource name. - - Format: - ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id}`` - - This field is ignored when you create an OS policy - assignment. - description (str): - OS policy assignment description. - Length of the description is limited to 1024 - characters. - os_policies (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicy]): - Required. List of OS policies to be applied - to the VMs. - instance_filter (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.InstanceFilter): - Required. Filter to select VMs. - rollout (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.Rollout): - Required. Rollout to deploy the OS policy assignment. A - rollout is triggered in the following situations: - - 1) OSPolicyAssignment is created. - 2) OSPolicyAssignment is updated and the update contains - changes to one of the following fields: - - - instance_filter - - os_policies - - 3) OSPolicyAssignment is deleted. - revision_id (str): - Output only. The assignment revision ID - A new revision is committed whenever a rollout - is triggered for a OS policy assignment - revision_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp that the revision - was created. - rollout_state (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.RolloutState): - Output only. OS policy assignment rollout - state - baseline (bool): - Output only. Indicates that this revision has been - successfully rolled out in this zone and new VMs will be - assigned OS policies from this revision. - - For a given OS policy assignment, there is only one revision - with a value of ``true`` for this field. - deleted (bool): - Output only. Indicates that this revision - deletes the OS policy assignment. - reconciling (bool): - Output only. Indicates that reconciliation is in progress - for the revision. This value is ``true`` when the - ``rollout_state`` is one of: - - - IN_PROGRESS - - CANCELLING - uid (str): - Output only. Server generated unique id for - the OS policy assignment resource. - """ - class RolloutState(proto.Enum): - r"""OS policy assignment rollout state""" - ROLLOUT_STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - CANCELLING = 2 - CANCELLED = 3 - SUCCEEDED = 4 - - class LabelSet(proto.Message): - r"""Message representing label set. - - - A label is a key value pair set for a VM. - - A LabelSet is a set of labels. - - Labels within a LabelSet are ANDed. In other words, a LabelSet is - applicable for a VM only if it matches all the labels in the - LabelSet. - - Example: A LabelSet with 2 labels: ``env=prod`` and - ``type=webserver`` will only be applicable for those VMs with - both labels present. - - Attributes: - labels (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.LabelSet.LabelsEntry]): - Labels are identified by key/value pairs in - this map. A VM should contain all the key/value - pairs specified in this map to be selected. - """ - - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - - class InstanceFilter(proto.Message): - r"""Message to represent the filters to select VMs for an - assignment - - Attributes: - all_ (bool): - Target all VMs in the project. If true, no - other criteria is permitted. - os_short_names (Sequence[str]): - A VM is included if it's OS short name - matches with any of the values provided in this - list. - inclusion_labels (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.LabelSet]): - List of label sets used for VM inclusion. - - If the list has more than one ``LabelSet``, the VM is - included if any of the label sets are applicable for the VM. - exclusion_labels (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment.LabelSet]): - List of label sets used for VM exclusion. - If the list has more than one label set, the VM - is excluded if any of the label sets are - applicable for the VM. - - This filter is applied last in the filtering - chain and therefore a VM is guaranteed to be - excluded if it satisfies one of the below label - sets. - """ - - all_ = proto.Field( - proto.BOOL, - number=1, - ) - os_short_names = proto.RepeatedField( - proto.STRING, - number=2, - ) - inclusion_labels = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='OSPolicyAssignment.LabelSet', - ) - exclusion_labels = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='OSPolicyAssignment.LabelSet', - ) - - class Rollout(proto.Message): - r"""Message to configure the rollout at the zonal level for the - OS policy assignment. - - Attributes: - disruption_budget (google.cloud.osconfig_v1alpha.types.FixedOrPercent): - Required. The maximum number (or percentage) - of VMs per zone to disrupt at any given moment. - min_wait_duration (google.protobuf.duration_pb2.Duration): - Required. This determines the minimum duration of time to - wait after the configuration changes are applied through the - current rollout. A VM continues to count towards the - ``disruption_budget`` at least until this duration of time - has passed after configuration changes are applied. - """ - - disruption_budget = proto.Field( - proto.MESSAGE, - number=1, - message=osconfig_common.FixedOrPercent, - ) - min_wait_duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - os_policies = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=os_policy.OSPolicy, - ) - instance_filter = proto.Field( - proto.MESSAGE, - number=4, - message=InstanceFilter, - ) - rollout = proto.Field( - proto.MESSAGE, - number=5, - message=Rollout, - ) - revision_id = proto.Field( - proto.STRING, - number=6, - ) - revision_create_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - rollout_state = proto.Field( - proto.ENUM, - number=9, - enum=RolloutState, - ) - baseline = proto.Field( - proto.BOOL, - number=10, - ) - deleted = proto.Field( - proto.BOOL, - number=11, - ) - reconciling = proto.Field( - proto.BOOL, - number=12, - ) - uid = proto.Field( - proto.STRING, - number=13, - ) - - -class OSPolicyAssignmentOperationMetadata(proto.Message): - r"""OS policy assignment operation metadata provided by OS policy - assignment API methods that return long running operations. - - Attributes: - os_policy_assignment (str): - Reference to the ``OSPolicyAssignment`` API resource. - - Format: - ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id@revision_id}`` - api_method (google.cloud.osconfig_v1alpha.types.OSPolicyAssignmentOperationMetadata.APIMethod): - The OS policy assignment API method. - rollout_state (google.cloud.osconfig_v1alpha.types.OSPolicyAssignmentOperationMetadata.RolloutState): - State of the rollout - rollout_start_time (google.protobuf.timestamp_pb2.Timestamp): - Rollout start time - rollout_update_time (google.protobuf.timestamp_pb2.Timestamp): - Rollout update time - """ - class APIMethod(proto.Enum): - r"""The OS policy assignment API method.""" - API_METHOD_UNSPECIFIED = 0 - CREATE = 1 - UPDATE = 2 - DELETE = 3 - - class RolloutState(proto.Enum): - r"""State of the rollout""" - ROLLOUT_STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - CANCELLING = 2 - CANCELLED = 3 - SUCCEEDED = 4 - - os_policy_assignment = proto.Field( - proto.STRING, - number=1, - ) - api_method = proto.Field( - proto.ENUM, - number=2, - enum=APIMethod, - ) - rollout_state = proto.Field( - proto.ENUM, - number=3, - enum=RolloutState, - ) - rollout_start_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - rollout_update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class CreateOSPolicyAssignmentRequest(proto.Message): - r"""A request message to create an OS policy assignment - Attributes: - parent (str): - Required. The parent resource name in the - form: projects/{project}/locations/{location} - os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): - Required. The OS policy assignment to be - created. - os_policy_assignment_id (str): - Required. The logical name of the OS policy assignment in - the project with the following restrictions: - - - Must contain only lowercase letters, numbers, and - hyphens. - - Must start with a letter. - - Must be between 1-63 characters. - - Must end with a number or a letter. - - Must be unique within the project. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - os_policy_assignment = proto.Field( - proto.MESSAGE, - number=2, - message='OSPolicyAssignment', - ) - os_policy_assignment_id = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateOSPolicyAssignmentRequest(proto.Message): - r"""A request message to update an OS policy assignment - Attributes: - os_policy_assignment (google.cloud.osconfig_v1alpha.types.OSPolicyAssignment): - Required. The updated OS policy assignment. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask that controls which - fields of the assignment should be updated. - """ - - os_policy_assignment = proto.Field( - proto.MESSAGE, - number=1, - message='OSPolicyAssignment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetOSPolicyAssignmentRequest(proto.Message): - r"""A request message to get an OS policy assignment - Attributes: - name (str): - Required. The resource name of OS policy assignment. - - Format: - ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListOSPolicyAssignmentsRequest(proto.Message): - r"""A request message to list OS policy assignments for a parent - resource - - Attributes: - parent (str): - Required. The parent resource name. - page_size (int): - The maximum number of assignments to return. - page_token (str): - A pagination token returned from a previous call to - ``ListOSPolicyAssignments`` that indicates where this - listing should continue from. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListOSPolicyAssignmentsResponse(proto.Message): - r"""A response message for listing all assignments under given - parent. - - Attributes: - os_policy_assignments (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment]): - The list of assignments - next_page_token (str): - The pagination token to retrieve the next - page of OS policy assignments. - """ - - @property - def raw_page(self): - return self - - os_policy_assignments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='OSPolicyAssignment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListOSPolicyAssignmentRevisionsRequest(proto.Message): - r"""A request message to list revisions for a OS policy - assignment - - Attributes: - name (str): - Required. The name of the OS policy - assignment to list revisions for. - page_size (int): - The maximum number of revisions to return. - page_token (str): - A pagination token returned from a previous call to - ``ListOSPolicyAssignmentRevisions`` that indicates where - this listing should continue from. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListOSPolicyAssignmentRevisionsResponse(proto.Message): - r"""A response message for listing all revisions for a OS policy - assignment. - - Attributes: - os_policy_assignments (Sequence[google.cloud.osconfig_v1alpha.types.OSPolicyAssignment]): - The OS policy assignment revisions - next_page_token (str): - The pagination token to retrieve the next - page of OS policy assignment revisions. - """ - - @property - def raw_page(self): - return self - - os_policy_assignments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='OSPolicyAssignment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteOSPolicyAssignmentRequest(proto.Message): - r"""A request message for deleting a OS policy assignment. - Attributes: - name (str): - Required. The name of the OS policy - assignment to be deleted - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.py deleted file mode 100644 index ac13f0e..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_common.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.cloud.osconfig.v1alpha', - manifest={ - 'FixedOrPercent', - }, -) - - -class FixedOrPercent(proto.Message): - r"""Message encapsulating a value that can be either absolute - ("fixed") or relative ("percent") to a value. - - Attributes: - fixed (int): - Specifies a fixed value. - percent (int): - Specifies the relative value defined as a - percentage, which will be multiplied by a - reference value. - """ - - fixed = proto.Field( - proto.INT32, - number=1, - oneof='mode', - ) - percent = proto.Field( - proto.INT32, - number=2, - oneof='mode', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_service.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_service.py deleted file mode 100644 index 0956e1b..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/osconfig_zonal_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.cloud.osconfig.v1alpha', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py b/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py deleted file mode 100644 index 3f59e94..0000000 --- a/owl-bot-staging/v1alpha/google/cloud/osconfig_v1alpha/types/vulnerability.py +++ /dev/null @@ -1,451 +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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.osconfig.v1alpha', - manifest={ - 'VulnerabilityReport', - 'GetVulnerabilityReportRequest', - 'ListVulnerabilityReportsRequest', - 'ListVulnerabilityReportsResponse', - 'CVSSv3', - }, -) - - -class VulnerabilityReport(proto.Message): - r"""This API resource represents the vulnerability report for a - specified Compute Engine virtual machine (VM) instance at a given - point in time. - - For more information, see `Vulnerability - reports `__. - - Attributes: - name (str): - Output only. The ``vulnerabilityReport`` API resource name. - - Format: - ``projects/{project_number}/locations/{location}/instances/{instance_id}/vulnerabilityReport`` - vulnerabilities (Sequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability]): - Output only. List of vulnerabilities - affecting the VM. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp for when the last - vulnerability report was generated for the VM. - """ - - class Vulnerability(proto.Message): - r"""A vulnerability affecting the VM instance. - Attributes: - details (google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Details): - Contains metadata as per the upstream feed of - the operating system and NVD. - installed_inventory_item_ids (Sequence[str]): - Corresponds to the ``INSTALLED_PACKAGE`` inventory item on - the VM. This field displays the inventory items affected by - this vulnerability. If the vulnerability report was not - updated after the VM inventory update, these values might - not display in VM inventory. For some distros, this field - may be empty. - available_inventory_item_ids (Sequence[str]): - Corresponds to the ``AVAILABLE_PACKAGE`` inventory item on - the VM. If the vulnerability report was not updated after - the VM inventory update, these values might not display in - VM inventory. If there is no available fix, the field is - empty. The ``inventory_item`` value specifies the latest - ``SoftwarePackage`` available to the VM that fixes the - vulnerability. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp for when the vulnerability was - first detected. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp for when the vulnerability was - last modified. - """ - - class Details(proto.Message): - r"""Contains metadata information for the vulnerability. This - information is collected from the upstream feed of the operating - system. - - Attributes: - cve (str): - The CVE of the vulnerability. CVE cannot be - empty and the combination of should be unique across - vulnerabilities for a VM. - cvss_v2_score (float): - The CVSS V2 score of this vulnerability. CVSS - V2 score is on a scale of 0 - 10 where 0 - indicates low severity and 10 indicates high - severity. - cvss_v3 (google.cloud.osconfig_v1alpha.types.CVSSv3): - The full description of the CVSSv3 for this - vulnerability from NVD. - severity (str): - Assigned severity/impact ranking from the - distro. - description (str): - The note or description describing the - vulnerability from the distro. - references (Sequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Details.Reference]): - Corresponds to the references attached to the - ``VulnerabilityDetails``. - """ - - class Reference(proto.Message): - r"""A reference for this vulnerability. - Attributes: - url (str): - The url of the reference. - """ - - url = proto.Field( - proto.STRING, - number=1, - ) - - cve = proto.Field( - proto.STRING, - number=1, - ) - cvss_v2_score = proto.Field( - proto.FLOAT, - number=2, - ) - cvss_v3 = proto.Field( - proto.MESSAGE, - number=3, - message='CVSSv3', - ) - severity = proto.Field( - proto.STRING, - number=4, - ) - description = proto.Field( - proto.STRING, - number=5, - ) - references = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='VulnerabilityReport.Vulnerability.Details.Reference', - ) - - details = proto.Field( - proto.MESSAGE, - number=1, - message='VulnerabilityReport.Vulnerability.Details', - ) - installed_inventory_item_ids = proto.RepeatedField( - proto.STRING, - number=2, - ) - available_inventory_item_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - vulnerabilities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Vulnerability, - ) - update_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class GetVulnerabilityReportRequest(proto.Message): - r"""A request message for getting the vulnerability report for - the specified VM. - - Attributes: - name (str): - Required. API resource name for vulnerability resource. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, either - Compute Engine ``instance-id`` or ``instance-name`` can be - provided. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListVulnerabilityReportsRequest(proto.Message): - r"""A request message for listing vulnerability reports for all - VM instances in the specified location. - - Attributes: - parent (str): - Required. The parent resource name. - - Format: - ``projects/{project}/locations/{location}/instances/{instance}`` - - For ``{project}``, either ``project-number`` or - ``project-id`` can be provided. For ``{instance}``, only - ``-`` character is supported to list vulnerability reports - across VMs. - page_size (int): - The maximum number of results to return. - page_token (str): - A pagination token returned from a previous call to - ``ListVulnerabilityReports`` that indicates where this - listing should continue from. - filter (str): - If provided, this field specifies the criteria that must be - met by a ``vulnerabilityReport`` API resource to be included - in the response. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListVulnerabilityReportsResponse(proto.Message): - r"""A response message for listing vulnerability reports for all - VM instances in the specified location. - - Attributes: - vulnerability_reports (Sequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport]): - List of vulnerabilityReport objects. - next_page_token (str): - The pagination token to retrieve the next - page of vulnerabilityReports object. - """ - - @property - def raw_page(self): - return self - - vulnerability_reports = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VulnerabilityReport', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CVSSv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - For details, see https://www.first.org/cvss/specification- - document - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - https://www.first.org/cvss/specification- - document#Base-Metrics - exploitability_score (float): - The Exploitability sub-score equation is - derived from the Base Exploitability metrics. - https://www.first.org/cvss/specification- - document#2-1-Exploitability-Metrics - impact_score (float): - The Impact sub-score equation is derived from - the Base Impact metrics. - attack_vector (google.cloud.osconfig_v1alpha.types.CVSSv3.AttackVector): - This metric reflects the context by which - vulnerability exploitation is possible. - attack_complexity (google.cloud.osconfig_v1alpha.types.CVSSv3.AttackComplexity): - This metric describes the conditions beyond - the attacker's control that must exist in order - to exploit the vulnerability. - privileges_required (google.cloud.osconfig_v1alpha.types.CVSSv3.PrivilegesRequired): - This metric describes the level of privileges - an attacker must possess before successfully - exploiting the vulnerability. - user_interaction (google.cloud.osconfig_v1alpha.types.CVSSv3.UserInteraction): - This metric captures the requirement for a - human user, other than the attacker, to - participate in the successful compromise of the - vulnerable component. - scope (google.cloud.osconfig_v1alpha.types.CVSSv3.Scope): - The Scope metric captures whether a - vulnerability in one vulnerable component - impacts resources in components beyond its - security scope. - confidentiality_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact): - This metric measures the impact to the - confidentiality of the information resources - managed by a software component due to a - successfully exploited vulnerability. - integrity_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact): - This metric measures the impact to integrity - of a successfully exploited vulnerability. - availability_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact): - This metric measures the impact to the - availability of the impacted component resulting - from a successfully exploited vulnerability. - """ - class AttackVector(proto.Enum): - r"""This metric reflects the context by which vulnerability - exploitation is possible. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r"""This metric describes the conditions beyond the attacker's - control that must exist in order to exploit the vulnerability. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r"""This metric describes the level of privileges an attacker - must possess before successfully exploiting the vulnerability. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r"""This metric captures the requirement for a human user, other - than the attacker, to participate in the successful compromise - of the vulnerable component. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r"""The Scope metric captures whether a vulnerability in one - vulnerable component impacts resources in components beyond its - security scope. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r"""The Impact metrics capture the effects of a successfully - exploited vulnerability on the component that suffers the worst - outcome that is most directly and predictably associated with - the attack. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score = proto.Field( - proto.FLOAT, - number=1, - ) - exploitability_score = proto.Field( - proto.FLOAT, - number=2, - ) - impact_score = proto.Field( - proto.FLOAT, - number=3, - ) - attack_vector = proto.Field( - proto.ENUM, - number=5, - enum=AttackVector, - ) - attack_complexity = proto.Field( - proto.ENUM, - number=6, - enum=AttackComplexity, - ) - privileges_required = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1alpha/mypy.ini b/owl-bot-staging/v1alpha/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1alpha/noxfile.py b/owl-bot-staging/v1alpha/noxfile.py deleted file mode 100644 index 88bde29..0000000 --- a/owl-bot-staging/v1alpha/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/cloud/osconfig_v1alpha/', - '--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/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py b/owl-bot-staging/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py deleted file mode 100644 index 2e964d4..0000000 --- a/owl-bot-staging/v1alpha/scripts/fixup_osconfig_v1alpha_keywords.py +++ /dev/null @@ -1,187 +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 osconfigCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_os_policy_assignment': ('parent', 'os_policy_assignment', 'os_policy_assignment_id', ), - 'delete_os_policy_assignment': ('name', ), - 'get_instance_os_policies_compliance': ('name', ), - 'get_inventory': ('name', 'view', ), - 'get_os_policy_assignment': ('name', ), - 'get_vulnerability_report': ('name', ), - 'list_instance_os_policies_compliances': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_inventories': ('parent', 'view', 'page_size', 'page_token', 'filter', ), - 'list_os_policy_assignment_revisions': ('name', 'page_size', 'page_token', ), - 'list_os_policy_assignments': ('parent', 'page_size', 'page_token', ), - 'list_vulnerability_reports': ('parent', 'page_size', 'page_token', 'filter', ), - 'update_os_policy_assignment': ('os_policy_assignment', 'update_mask', ), - } - - 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=osconfigCallTransformer(), -): - """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 osconfig 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/v1alpha/setup.py b/owl-bot-staging/v1alpha/setup.py deleted file mode 100644 index 903433f..0000000 --- a/owl-bot-staging/v1alpha/setup.py +++ /dev/null @@ -1,54 +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-cloud-osconfig', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.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', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1alpha/tests/__init__.py b/owl-bot-staging/v1alpha/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/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/v1alpha/tests/unit/__init__.py b/owl-bot-staging/v1alpha/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/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/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/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/v1alpha/tests/unit/gapic/osconfig_v1alpha/__init__.py b/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/__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/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py b/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py deleted file mode 100644 index 0da6262..0000000 --- a/owl-bot-staging/v1alpha/tests/unit/gapic/osconfig_v1alpha/test_os_config_zonal_service.py +++ /dev/null @@ -1,4846 +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 future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import OsConfigZonalServiceAsyncClient -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import OsConfigZonalServiceClient -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import pagers -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import transports -from google.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.osconfig_v1alpha.types import config_common -from google.cloud.osconfig_v1alpha.types import instance_os_policies_compliance -from google.cloud.osconfig_v1alpha.types import inventory -from google.cloud.osconfig_v1alpha.types import os_policy -from google.cloud.osconfig_v1alpha.types import os_policy_assignments -from google.cloud.osconfig_v1alpha.types import osconfig_common -from google.cloud.osconfig_v1alpha.types import vulnerability -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_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 OsConfigZonalServiceClient._get_default_mtls_endpoint(None) is None - assert OsConfigZonalServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OsConfigZonalServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OsConfigZonalServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OsConfigZonalServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OsConfigZonalServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - OsConfigZonalServiceClient, - OsConfigZonalServiceAsyncClient, -]) -def test_os_config_zonal_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 == 'osconfig.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.OsConfigZonalServiceGrpcTransport, "grpc"), - (transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_os_config_zonal_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - OsConfigZonalServiceClient, - OsConfigZonalServiceAsyncClient, -]) -def test_os_config_zonal_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 == 'osconfig.googleapis.com:443' - - -def test_os_config_zonal_service_client_get_transport_class(): - transport = OsConfigZonalServiceClient.get_transport_class() - available_transports = [ - transports.OsConfigZonalServiceGrpcTransport, - ] - assert transport in available_transports - - transport = OsConfigZonalServiceClient.get_transport_class("grpc") - assert transport == transports.OsConfigZonalServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc"), - (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(OsConfigZonalServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceClient)) -@mock.patch.object(OsConfigZonalServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceAsyncClient)) -def test_os_config_zonal_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(OsConfigZonalServiceClient, '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(OsConfigZonalServiceClient, '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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc", "true"), - (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc", "false"), - (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(OsConfigZonalServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceClient)) -@mock.patch.object(OsConfigZonalServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OsConfigZonalServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_os_config_zonal_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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - # 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, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc"), - (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_os_config_zonal_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, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OsConfigZonalServiceClient, transports.OsConfigZonalServiceGrpcTransport, "grpc"), - (OsConfigZonalServiceAsyncClient, transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_os_config_zonal_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, - always_use_jwt_access=True, - ) - - -def test_os_config_zonal_service_client_client_options_from_dict(): - with mock.patch('google.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = OsConfigZonalServiceClient( - 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, - always_use_jwt_access=True, - ) - - -def test_create_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.CreateOSPolicyAssignmentRequest): - client = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_os_policy_assignment_from_dict(): - test_create_os_policy_assignment(request_type=dict) - - -def test_create_os_policy_assignment_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 = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - client.create_os_policy_assignment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() - - -@pytest.mark.asyncio -async def test_create_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.CreateOSPolicyAssignmentRequest): - client = OsConfigZonalServiceAsyncClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_os_policy_assignment_async_from_dict(): - await test_create_os_policy_assignment_async(request_type=dict) - - -def test_create_os_policy_assignment_field_headers(): - client = OsConfigZonalServiceClient( - 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 = os_policy_assignments.CreateOSPolicyAssignmentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_os_policy_assignment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_os_policy_assignment(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_os_policy_assignment_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = os_policy_assignments.CreateOSPolicyAssignmentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_os_policy_assignment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_os_policy_assignment(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_create_os_policy_assignment_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_os_policy_assignment( - parent='parent_value', - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - os_policy_assignment_id='os_policy_assignment_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') - assert args[0].os_policy_assignment_id == 'os_policy_assignment_id_value' - - -def test_create_os_policy_assignment_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_os_policy_assignment( - os_policy_assignments.CreateOSPolicyAssignmentRequest(), - parent='parent_value', - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - os_policy_assignment_id='os_policy_assignment_id_value', - ) - - -@pytest.mark.asyncio -async def test_create_os_policy_assignment_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_os_policy_assignment( - parent='parent_value', - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - os_policy_assignment_id='os_policy_assignment_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') - assert args[0].os_policy_assignment_id == 'os_policy_assignment_id_value' - - -@pytest.mark.asyncio -async def test_create_os_policy_assignment_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_os_policy_assignment( - os_policy_assignments.CreateOSPolicyAssignmentRequest(), - parent='parent_value', - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - os_policy_assignment_id='os_policy_assignment_id_value', - ) - - -def test_update_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.UpdateOSPolicyAssignmentRequest): - client = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_os_policy_assignment_from_dict(): - test_update_os_policy_assignment(request_type=dict) - - -def test_update_os_policy_assignment_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 = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - client.update_os_policy_assignment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() - - -@pytest.mark.asyncio -async def test_update_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.UpdateOSPolicyAssignmentRequest): - client = OsConfigZonalServiceAsyncClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_os_policy_assignment_async_from_dict(): - await test_update_os_policy_assignment_async(request_type=dict) - - -def test_update_os_policy_assignment_field_headers(): - client = OsConfigZonalServiceClient( - 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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest() - - request.os_policy_assignment.name = 'os_policy_assignment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_os_policy_assignment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_os_policy_assignment(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', - 'os_policy_assignment.name=os_policy_assignment.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_os_policy_assignment_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest() - - request.os_policy_assignment.name = 'os_policy_assignment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_os_policy_assignment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_os_policy_assignment(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', - 'os_policy_assignment.name=os_policy_assignment.name/value', - ) in kw['metadata'] - - -def test_update_os_policy_assignment_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_os_policy_assignment( - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_os_policy_assignment_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_os_policy_assignment( - os_policy_assignments.UpdateOSPolicyAssignmentRequest(), - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_os_policy_assignment_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_os_policy_assignment( - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_os_policy_assignment_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_os_policy_assignment( - os_policy_assignments.UpdateOSPolicyAssignmentRequest(), - os_policy_assignment=os_policy_assignments.OSPolicyAssignment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.GetOSPolicyAssignmentRequest): - client = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.OSPolicyAssignment( - name='name_value', - description='description_value', - revision_id='revision_id_value', - rollout_state=os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS, - baseline=True, - deleted=True, - reconciling=True, - uid='uid_value', - ) - response = client.get_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, os_policy_assignments.OSPolicyAssignment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.rollout_state == os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS - assert response.baseline is True - assert response.deleted is True - assert response.reconciling is True - assert response.uid == 'uid_value' - - -def test_get_os_policy_assignment_from_dict(): - test_get_os_policy_assignment(request_type=dict) - - -def test_get_os_policy_assignment_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 = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - client.get_os_policy_assignment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() - - -@pytest.mark.asyncio -async def test_get_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.GetOSPolicyAssignmentRequest): - client = OsConfigZonalServiceAsyncClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.OSPolicyAssignment( - name='name_value', - description='description_value', - revision_id='revision_id_value', - rollout_state=os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS, - baseline=True, - deleted=True, - reconciling=True, - uid='uid_value', - )) - response = await client.get_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, os_policy_assignments.OSPolicyAssignment) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.rollout_state == os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS - assert response.baseline is True - assert response.deleted is True - assert response.reconciling is True - assert response.uid == 'uid_value' - - -@pytest.mark.asyncio -async def test_get_os_policy_assignment_async_from_dict(): - await test_get_os_policy_assignment_async(request_type=dict) - - -def test_get_os_policy_assignment_field_headers(): - client = OsConfigZonalServiceClient( - 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 = os_policy_assignments.GetOSPolicyAssignmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_os_policy_assignment), - '__call__') as call: - call.return_value = os_policy_assignments.OSPolicyAssignment() - client.get_os_policy_assignment(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_os_policy_assignment_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = os_policy_assignments.GetOSPolicyAssignmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_os_policy_assignment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.OSPolicyAssignment()) - await client.get_os_policy_assignment(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_get_os_policy_assignment_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.OSPolicyAssignment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_os_policy_assignment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_os_policy_assignment_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_os_policy_assignment( - os_policy_assignments.GetOSPolicyAssignmentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_os_policy_assignment_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.OSPolicyAssignment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.OSPolicyAssignment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_os_policy_assignment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_os_policy_assignment_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_os_policy_assignment( - os_policy_assignments.GetOSPolicyAssignmentRequest(), - name='name_value', - ) - - -def test_list_os_policy_assignments(transport: str = 'grpc', request_type=os_policy_assignments.ListOSPolicyAssignmentsRequest): - client = OsConfigZonalServiceClient( - 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_os_policy_assignments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_os_policy_assignments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOSPolicyAssignmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_os_policy_assignments_from_dict(): - test_list_os_policy_assignments(request_type=dict) - - -def test_list_os_policy_assignments_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 = OsConfigZonalServiceClient( - 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_os_policy_assignments), - '__call__') as call: - client.list_os_policy_assignments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() - - -@pytest.mark.asyncio -async def test_list_os_policy_assignments_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.ListOSPolicyAssignmentsRequest): - client = OsConfigZonalServiceAsyncClient( - 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_os_policy_assignments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_os_policy_assignments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOSPolicyAssignmentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_os_policy_assignments_async_from_dict(): - await test_list_os_policy_assignments_async(request_type=dict) - - -def test_list_os_policy_assignments_field_headers(): - client = OsConfigZonalServiceClient( - 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__') as call: - call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() - client.list_os_policy_assignments(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_os_policy_assignments_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentsResponse()) - await client.list_os_policy_assignments(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_os_policy_assignments_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_os_policy_assignments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_os_policy_assignments_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_os_policy_assignments( - os_policy_assignments.ListOSPolicyAssignmentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_os_policy_assignments_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_os_policy_assignments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_os_policy_assignments_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_os_policy_assignments( - os_policy_assignments.ListOSPolicyAssignmentsRequest(), - parent='parent_value', - ) - - -def test_list_os_policy_assignments_pager(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_os_policy_assignments(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, os_policy_assignments.OSPolicyAssignment) - for i in results) - -def test_list_os_policy_assignments_pages(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_os_policy_assignments(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_os_policy_assignments_async_pager(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_os_policy_assignments(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, os_policy_assignments.OSPolicyAssignment) - for i in responses) - -@pytest.mark.asyncio -async def test_list_os_policy_assignments_async_pages(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_os_policy_assignments(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_os_policy_assignment_revisions(transport: str = 'grpc', request_type=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest): - client = OsConfigZonalServiceClient( - 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_os_policy_assignment_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_os_policy_assignment_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOSPolicyAssignmentRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_os_policy_assignment_revisions_from_dict(): - test_list_os_policy_assignment_revisions(request_type=dict) - - -def test_list_os_policy_assignment_revisions_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 = OsConfigZonalServiceClient( - 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_os_policy_assignment_revisions), - '__call__') as call: - client.list_os_policy_assignment_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() - - -@pytest.mark.asyncio -async def test_list_os_policy_assignment_revisions_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest): - client = OsConfigZonalServiceAsyncClient( - 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_os_policy_assignment_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_os_policy_assignment_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOSPolicyAssignmentRevisionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_os_policy_assignment_revisions_async_from_dict(): - await test_list_os_policy_assignment_revisions_async(request_type=dict) - - -def test_list_os_policy_assignment_revisions_field_headers(): - client = OsConfigZonalServiceClient( - 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__') as call: - call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() - client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse()) - await client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_os_policy_assignment_revisions( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_list_os_policy_assignment_revisions_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_os_policy_assignment_revisions( - os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_list_os_policy_assignment_revisions_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_os_policy_assignment_revisions( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_list_os_policy_assignment_revisions_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_os_policy_assignment_revisions( - os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(), - name='name_value', - ) - - -def test_list_os_policy_assignment_revisions_pager(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.list_os_policy_assignment_revisions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, os_policy_assignments.OSPolicyAssignment) - for i in results) - -def test_list_os_policy_assignment_revisions_pages(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_os_policy_assignment_revisions(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_os_policy_assignment_revisions_async_pager(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_os_policy_assignment_revisions(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, os_policy_assignments.OSPolicyAssignment) - for i in responses) - -@pytest.mark.asyncio -async def test_list_os_policy_assignment_revisions_async_pages(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_os_policy_assignment_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='abc', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[], - next_page_token='def', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - ], - next_page_token='ghi', - ), - os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( - os_policy_assignments=[ - os_policy_assignments.OSPolicyAssignment(), - os_policy_assignments.OSPolicyAssignment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_os_policy_assignment_revisions(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_os_policy_assignment(transport: str = 'grpc', request_type=os_policy_assignments.DeleteOSPolicyAssignmentRequest): - client = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_os_policy_assignment_from_dict(): - test_delete_os_policy_assignment(request_type=dict) - - -def test_delete_os_policy_assignment_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 = OsConfigZonalServiceClient( - 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_os_policy_assignment), - '__call__') as call: - client.delete_os_policy_assignment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() - - -@pytest.mark.asyncio -async def test_delete_os_policy_assignment_async(transport: str = 'grpc_asyncio', request_type=os_policy_assignments.DeleteOSPolicyAssignmentRequest): - client = OsConfigZonalServiceAsyncClient( - 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_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_os_policy_assignment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_os_policy_assignment_async_from_dict(): - await test_delete_os_policy_assignment_async(request_type=dict) - - -def test_delete_os_policy_assignment_field_headers(): - client = OsConfigZonalServiceClient( - 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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_os_policy_assignment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_os_policy_assignment(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_os_policy_assignment_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_os_policy_assignment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_os_policy_assignment(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_os_policy_assignment_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_os_policy_assignment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_delete_os_policy_assignment_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_os_policy_assignment( - os_policy_assignments.DeleteOSPolicyAssignmentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_os_policy_assignment_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_os_policy_assignment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_os_policy_assignment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_os_policy_assignment_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_os_policy_assignment( - os_policy_assignments.DeleteOSPolicyAssignmentRequest(), - name='name_value', - ) - - -def test_get_instance_os_policies_compliance(transport: str = 'grpc', request_type=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest): - client = OsConfigZonalServiceClient( - 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_instance_os_policies_compliance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance( - name='name_value', - instance='instance_value', - state=config_common.OSPolicyComplianceState.COMPLIANT, - detailed_state='detailed_state_value', - detailed_state_reason='detailed_state_reason_value', - last_compliance_run_id='last_compliance_run_id_value', - ) - response = client.get_instance_os_policies_compliance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, instance_os_policies_compliance.InstanceOSPoliciesCompliance) - assert response.name == 'name_value' - assert response.instance == 'instance_value' - assert response.state == config_common.OSPolicyComplianceState.COMPLIANT - assert response.detailed_state == 'detailed_state_value' - assert response.detailed_state_reason == 'detailed_state_reason_value' - assert response.last_compliance_run_id == 'last_compliance_run_id_value' - - -def test_get_instance_os_policies_compliance_from_dict(): - test_get_instance_os_policies_compliance(request_type=dict) - - -def test_get_instance_os_policies_compliance_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 = OsConfigZonalServiceClient( - 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_instance_os_policies_compliance), - '__call__') as call: - client.get_instance_os_policies_compliance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() - - -@pytest.mark.asyncio -async def test_get_instance_os_policies_compliance_async(transport: str = 'grpc_asyncio', request_type=instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest): - client = OsConfigZonalServiceAsyncClient( - 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_instance_os_policies_compliance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.InstanceOSPoliciesCompliance( - name='name_value', - instance='instance_value', - state=config_common.OSPolicyComplianceState.COMPLIANT, - detailed_state='detailed_state_value', - detailed_state_reason='detailed_state_reason_value', - last_compliance_run_id='last_compliance_run_id_value', - )) - response = await client.get_instance_os_policies_compliance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, instance_os_policies_compliance.InstanceOSPoliciesCompliance) - assert response.name == 'name_value' - assert response.instance == 'instance_value' - assert response.state == config_common.OSPolicyComplianceState.COMPLIANT - assert response.detailed_state == 'detailed_state_value' - assert response.detailed_state_reason == 'detailed_state_reason_value' - assert response.last_compliance_run_id == 'last_compliance_run_id_value' - - -@pytest.mark.asyncio -async def test_get_instance_os_policies_compliance_async_from_dict(): - await test_get_instance_os_policies_compliance_async(request_type=dict) - - -def test_get_instance_os_policies_compliance_field_headers(): - client = OsConfigZonalServiceClient( - 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 = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_os_policies_compliance), - '__call__') as call: - call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance() - client.get_instance_os_policies_compliance(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_instance_os_policies_compliance_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_os_policies_compliance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.InstanceOSPoliciesCompliance()) - await client.get_instance_os_policies_compliance(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_get_instance_os_policies_compliance_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_os_policies_compliance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_instance_os_policies_compliance( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_instance_os_policies_compliance_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_instance_os_policies_compliance( - instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_instance_os_policies_compliance_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_os_policies_compliance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance_os_policies_compliance.InstanceOSPoliciesCompliance() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.InstanceOSPoliciesCompliance()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_instance_os_policies_compliance( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_instance_os_policies_compliance_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_instance_os_policies_compliance( - instance_os_policies_compliance.GetInstanceOSPoliciesComplianceRequest(), - name='name_value', - ) - - -def test_list_instance_os_policies_compliances(transport: str = 'grpc', request_type=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest): - client = OsConfigZonalServiceClient( - 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_instance_os_policies_compliances), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_instance_os_policies_compliances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstanceOSPoliciesCompliancesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_instance_os_policies_compliances_from_dict(): - test_list_instance_os_policies_compliances(request_type=dict) - - -def test_list_instance_os_policies_compliances_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 = OsConfigZonalServiceClient( - 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_instance_os_policies_compliances), - '__call__') as call: - client.list_instance_os_policies_compliances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() - - -@pytest.mark.asyncio -async def test_list_instance_os_policies_compliances_async(transport: str = 'grpc_asyncio', request_type=instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest): - client = OsConfigZonalServiceAsyncClient( - 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_instance_os_policies_compliances), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_instance_os_policies_compliances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstanceOSPoliciesCompliancesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_instance_os_policies_compliances_async_from_dict(): - await test_list_instance_os_policies_compliances_async(request_type=dict) - - -def test_list_instance_os_policies_compliances_field_headers(): - client = OsConfigZonalServiceClient( - 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__') as call: - call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse() - client.list_instance_os_policies_compliances(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_instance_os_policies_compliances_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse()) - await client.list_instance_os_policies_compliances(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_instance_os_policies_compliances_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_instance_os_policies_compliances( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_instance_os_policies_compliances_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_instance_os_policies_compliances( - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_instance_os_policies_compliances_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_instance_os_policies_compliances( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_instance_os_policies_compliances_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_instance_os_policies_compliances( - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesRequest(), - parent='parent_value', - ) - - -def test_list_instance_os_policies_compliances_pager(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='abc', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[], - next_page_token='def', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='ghi', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_instance_os_policies_compliances(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, instance_os_policies_compliance.InstanceOSPoliciesCompliance) - for i in results) - -def test_list_instance_os_policies_compliances_pages(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='abc', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[], - next_page_token='def', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='ghi', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - ), - RuntimeError, - ) - pages = list(client.list_instance_os_policies_compliances(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_instance_os_policies_compliances_async_pager(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='abc', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[], - next_page_token='def', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='ghi', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_instance_os_policies_compliances(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, instance_os_policies_compliance.InstanceOSPoliciesCompliance) - for i in responses) - -@pytest.mark.asyncio -async def test_list_instance_os_policies_compliances_async_pages(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instance_os_policies_compliances), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='abc', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[], - next_page_token='def', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - next_page_token='ghi', - ), - instance_os_policies_compliance.ListInstanceOSPoliciesCompliancesResponse( - instance_os_policies_compliances=[ - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - instance_os_policies_compliance.InstanceOSPoliciesCompliance(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_instance_os_policies_compliances(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_inventory(transport: str = 'grpc', request_type=inventory.GetInventoryRequest): - client = OsConfigZonalServiceClient( - 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_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = inventory.Inventory( - name='name_value', - ) - response = client.get_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == inventory.GetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, inventory.Inventory) - assert response.name == 'name_value' - - -def test_get_inventory_from_dict(): - test_get_inventory(request_type=dict) - - -def test_get_inventory_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 = OsConfigZonalServiceClient( - 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_inventory), - '__call__') as call: - client.get_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == inventory.GetInventoryRequest() - - -@pytest.mark.asyncio -async def test_get_inventory_async(transport: str = 'grpc_asyncio', request_type=inventory.GetInventoryRequest): - client = OsConfigZonalServiceAsyncClient( - 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_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory( - name='name_value', - )) - response = await client.get_inventory(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == inventory.GetInventoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, inventory.Inventory) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_inventory_async_from_dict(): - await test_get_inventory_async(request_type=dict) - - -def test_get_inventory_field_headers(): - client = OsConfigZonalServiceClient( - 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 = inventory.GetInventoryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_inventory), - '__call__') as call: - call.return_value = inventory.Inventory() - client.get_inventory(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_inventory_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = inventory.GetInventoryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_inventory), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory()) - await client.get_inventory(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_get_inventory_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = inventory.Inventory() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_inventory_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_inventory( - inventory.GetInventoryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_inventory_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_inventory), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = inventory.Inventory() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_inventory( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_inventory_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_inventory( - inventory.GetInventoryRequest(), - name='name_value', - ) - - -def test_list_inventories(transport: str = 'grpc', request_type=inventory.ListInventoriesRequest): - client = OsConfigZonalServiceClient( - 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_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = inventory.ListInventoriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == inventory.ListInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInventoriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_inventories_from_dict(): - test_list_inventories(request_type=dict) - - -def test_list_inventories_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 = OsConfigZonalServiceClient( - 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_inventories), - '__call__') as call: - client.list_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == inventory.ListInventoriesRequest() - - -@pytest.mark.asyncio -async def test_list_inventories_async(transport: str = 'grpc_asyncio', request_type=inventory.ListInventoriesRequest): - client = OsConfigZonalServiceAsyncClient( - 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_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(inventory.ListInventoriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == inventory.ListInventoriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInventoriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_inventories_async_from_dict(): - await test_list_inventories_async(request_type=dict) - - -def test_list_inventories_field_headers(): - client = OsConfigZonalServiceClient( - 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 = inventory.ListInventoriesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__') as call: - call.return_value = inventory.ListInventoriesResponse() - client.list_inventories(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_inventories_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = inventory.ListInventoriesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.ListInventoriesResponse()) - await client.list_inventories(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_inventories_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = inventory.ListInventoriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_inventories_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_inventories( - inventory.ListInventoriesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_inventories_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = inventory.ListInventoriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.ListInventoriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_inventories( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_inventories_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_inventories( - inventory.ListInventoriesRequest(), - parent='parent_value', - ) - - -def test_list_inventories_pager(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - inventory.Inventory(), - ], - next_page_token='abc', - ), - inventory.ListInventoriesResponse( - inventories=[], - next_page_token='def', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - ], - next_page_token='ghi', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_inventories(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, inventory.Inventory) - for i in results) - -def test_list_inventories_pages(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - inventory.Inventory(), - ], - next_page_token='abc', - ), - inventory.ListInventoriesResponse( - inventories=[], - next_page_token='def', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - ], - next_page_token='ghi', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - ], - ), - RuntimeError, - ) - pages = list(client.list_inventories(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_inventories_async_pager(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - inventory.Inventory(), - ], - next_page_token='abc', - ), - inventory.ListInventoriesResponse( - inventories=[], - next_page_token='def', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - ], - next_page_token='ghi', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_inventories(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, inventory.Inventory) - for i in responses) - -@pytest.mark.asyncio -async def test_list_inventories_async_pages(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_inventories), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - inventory.Inventory(), - ], - next_page_token='abc', - ), - inventory.ListInventoriesResponse( - inventories=[], - next_page_token='def', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - ], - next_page_token='ghi', - ), - inventory.ListInventoriesResponse( - inventories=[ - inventory.Inventory(), - inventory.Inventory(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_inventories(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_vulnerability_report(transport: str = 'grpc', request_type=vulnerability.GetVulnerabilityReportRequest): - client = OsConfigZonalServiceClient( - 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_vulnerability_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vulnerability.VulnerabilityReport( - name='name_value', - ) - response = client.get_vulnerability_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == vulnerability.GetVulnerabilityReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, vulnerability.VulnerabilityReport) - assert response.name == 'name_value' - - -def test_get_vulnerability_report_from_dict(): - test_get_vulnerability_report(request_type=dict) - - -def test_get_vulnerability_report_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 = OsConfigZonalServiceClient( - 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_vulnerability_report), - '__call__') as call: - client.get_vulnerability_report() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vulnerability.GetVulnerabilityReportRequest() - - -@pytest.mark.asyncio -async def test_get_vulnerability_report_async(transport: str = 'grpc_asyncio', request_type=vulnerability.GetVulnerabilityReportRequest): - client = OsConfigZonalServiceAsyncClient( - 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_vulnerability_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.VulnerabilityReport( - name='name_value', - )) - response = await client.get_vulnerability_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == vulnerability.GetVulnerabilityReportRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, vulnerability.VulnerabilityReport) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_vulnerability_report_async_from_dict(): - await test_get_vulnerability_report_async(request_type=dict) - - -def test_get_vulnerability_report_field_headers(): - client = OsConfigZonalServiceClient( - 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 = vulnerability.GetVulnerabilityReportRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vulnerability_report), - '__call__') as call: - call.return_value = vulnerability.VulnerabilityReport() - client.get_vulnerability_report(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_vulnerability_report_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = vulnerability.GetVulnerabilityReportRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vulnerability_report), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.VulnerabilityReport()) - await client.get_vulnerability_report(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_get_vulnerability_report_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vulnerability_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vulnerability.VulnerabilityReport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_vulnerability_report( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_vulnerability_report_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_vulnerability_report( - vulnerability.GetVulnerabilityReportRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_vulnerability_report_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vulnerability_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vulnerability.VulnerabilityReport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.VulnerabilityReport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_vulnerability_report( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_vulnerability_report_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_vulnerability_report( - vulnerability.GetVulnerabilityReportRequest(), - name='name_value', - ) - - -def test_list_vulnerability_reports(transport: str = 'grpc', request_type=vulnerability.ListVulnerabilityReportsRequest): - client = OsConfigZonalServiceClient( - 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_vulnerability_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vulnerability.ListVulnerabilityReportsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_vulnerability_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == vulnerability.ListVulnerabilityReportsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVulnerabilityReportsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_vulnerability_reports_from_dict(): - test_list_vulnerability_reports(request_type=dict) - - -def test_list_vulnerability_reports_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 = OsConfigZonalServiceClient( - 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_vulnerability_reports), - '__call__') as call: - client.list_vulnerability_reports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vulnerability.ListVulnerabilityReportsRequest() - - -@pytest.mark.asyncio -async def test_list_vulnerability_reports_async(transport: str = 'grpc_asyncio', request_type=vulnerability.ListVulnerabilityReportsRequest): - client = OsConfigZonalServiceAsyncClient( - 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_vulnerability_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.ListVulnerabilityReportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_vulnerability_reports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == vulnerability.ListVulnerabilityReportsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVulnerabilityReportsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_vulnerability_reports_async_from_dict(): - await test_list_vulnerability_reports_async(request_type=dict) - - -def test_list_vulnerability_reports_field_headers(): - client = OsConfigZonalServiceClient( - 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 = vulnerability.ListVulnerabilityReportsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__') as call: - call.return_value = vulnerability.ListVulnerabilityReportsResponse() - client.list_vulnerability_reports(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_vulnerability_reports_field_headers_async(): - client = OsConfigZonalServiceAsyncClient( - 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 = vulnerability.ListVulnerabilityReportsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.ListVulnerabilityReportsResponse()) - await client.list_vulnerability_reports(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_vulnerability_reports_flattened(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vulnerability.ListVulnerabilityReportsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_vulnerability_reports( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -def test_list_vulnerability_reports_flattened_error(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_vulnerability_reports( - vulnerability.ListVulnerabilityReportsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_vulnerability_reports_flattened_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vulnerability.ListVulnerabilityReportsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vulnerability.ListVulnerabilityReportsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_vulnerability_reports( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_vulnerability_reports_flattened_error_async(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_vulnerability_reports( - vulnerability.ListVulnerabilityReportsRequest(), - parent='parent_value', - ) - - -def test_list_vulnerability_reports_pager(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - next_page_token='abc', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[], - next_page_token='def', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - ], - next_page_token='ghi', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_vulnerability_reports(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, vulnerability.VulnerabilityReport) - for i in results) - -def test_list_vulnerability_reports_pages(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - next_page_token='abc', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[], - next_page_token='def', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - ], - next_page_token='ghi', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - ), - RuntimeError, - ) - pages = list(client.list_vulnerability_reports(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_vulnerability_reports_async_pager(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - next_page_token='abc', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[], - next_page_token='def', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - ], - next_page_token='ghi', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_vulnerability_reports(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, vulnerability.VulnerabilityReport) - for i in responses) - -@pytest.mark.asyncio -async def test_list_vulnerability_reports_async_pages(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vulnerability_reports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - next_page_token='abc', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[], - next_page_token='def', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - ], - next_page_token='ghi', - ), - vulnerability.ListVulnerabilityReportsResponse( - vulnerability_reports=[ - vulnerability.VulnerabilityReport(), - vulnerability.VulnerabilityReport(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_vulnerability_reports(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OsConfigZonalServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.OsConfigZonalServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsConfigZonalServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.OsConfigZonalServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsConfigZonalServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OsConfigZonalServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = OsConfigZonalServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OsConfigZonalServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.OsConfigZonalServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.OsConfigZonalServiceGrpcTransport, - transports.OsConfigZonalServiceGrpcAsyncIOTransport, -]) -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 = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.OsConfigZonalServiceGrpcTransport, - ) - -def test_os_config_zonal_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.OsConfigZonalServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_os_config_zonal_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.OsConfigZonalServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_os_policy_assignment', - 'update_os_policy_assignment', - 'get_os_policy_assignment', - 'list_os_policy_assignments', - 'list_os_policy_assignment_revisions', - 'delete_os_policy_assignment', - 'get_instance_os_policies_compliance', - 'list_instance_os_policies_compliances', - 'get_inventory', - 'list_inventories', - 'get_vulnerability_report', - 'list_vulnerability_reports', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_os_config_zonal_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.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OsConfigZonalServiceTransport( - 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', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_os_config_zonal_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.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OsConfigZonalServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_os_config_zonal_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.cloud.osconfig_v1alpha.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OsConfigZonalServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_os_config_zonal_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) - OsConfigZonalServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_os_config_zonal_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) - OsConfigZonalServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.OsConfigZonalServiceGrpcTransport, - transports.OsConfigZonalServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_os_config_zonal_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',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.OsConfigZonalServiceGrpcTransport, - transports.OsConfigZonalServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_os_config_zonal_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', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.OsConfigZonalServiceGrpcTransport, grpc_helpers), - (transports.OsConfigZonalServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_os_config_zonal_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( - "osconfig.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="osconfig.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.OsConfigZonalServiceGrpcTransport, transports.OsConfigZonalServiceGrpcAsyncIOTransport]) -def test_os_config_zonal_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=None, - 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_os_config_zonal_service_host_no_port(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com'), - ) - assert client.transport._host == 'osconfig.googleapis.com:443' - - -def test_os_config_zonal_service_host_with_port(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='osconfig.googleapis.com:8000'), - ) - assert client.transport._host == 'osconfig.googleapis.com:8000' - -def test_os_config_zonal_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OsConfigZonalServiceGrpcTransport( - 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_os_config_zonal_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OsConfigZonalServiceGrpcAsyncIOTransport( - 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.OsConfigZonalServiceGrpcTransport, transports.OsConfigZonalServiceGrpcAsyncIOTransport]) -def test_os_config_zonal_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=None, - 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.OsConfigZonalServiceGrpcTransport, transports.OsConfigZonalServiceGrpcAsyncIOTransport]) -def test_os_config_zonal_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=None, - 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_os_config_zonal_service_grpc_lro_client(): - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_os_config_zonal_service_grpc_lro_async_client(): - client = OsConfigZonalServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_instance_path(): - project = "squid" - location = "clam" - instance = "whelk" - expected = "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) - actual = OsConfigZonalServiceClient.instance_path(project, location, instance) - assert expected == actual - - -def test_parse_instance_path(): - expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", - } - path = OsConfigZonalServiceClient.instance_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_instance_path(path) - assert expected == actual - -def test_instance_os_policies_compliance_path(): - project = "cuttlefish" - location = "mussel" - instance = "winkle" - expected = "projects/{project}/locations/{location}/instanceOSPoliciesCompliances/{instance}".format(project=project, location=location, instance=instance, ) - actual = OsConfigZonalServiceClient.instance_os_policies_compliance_path(project, location, instance) - assert expected == actual - - -def test_parse_instance_os_policies_compliance_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "instance": "abalone", - } - path = OsConfigZonalServiceClient.instance_os_policies_compliance_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_instance_os_policies_compliance_path(path) - assert expected == actual - -def test_inventory_path(): - project = "squid" - location = "clam" - instance = "whelk" - expected = "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) - actual = OsConfigZonalServiceClient.inventory_path(project, location, instance) - assert expected == actual - - -def test_parse_inventory_path(): - expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", - } - path = OsConfigZonalServiceClient.inventory_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_inventory_path(path) - assert expected == actual - -def test_os_policy_assignment_path(): - project = "cuttlefish" - location = "mussel" - os_policy_assignment = "winkle" - expected = "projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}".format(project=project, location=location, os_policy_assignment=os_policy_assignment, ) - actual = OsConfigZonalServiceClient.os_policy_assignment_path(project, location, os_policy_assignment) - assert expected == actual - - -def test_parse_os_policy_assignment_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "os_policy_assignment": "abalone", - } - path = OsConfigZonalServiceClient.os_policy_assignment_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_os_policy_assignment_path(path) - assert expected == actual - -def test_vulnerability_report_path(): - project = "squid" - location = "clam" - instance = "whelk" - expected = "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format(project=project, location=location, instance=instance, ) - actual = OsConfigZonalServiceClient.vulnerability_report_path(project, location, instance) - assert expected == actual - - -def test_parse_vulnerability_report_path(): - expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", - } - path = OsConfigZonalServiceClient.vulnerability_report_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_vulnerability_report_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OsConfigZonalServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = OsConfigZonalServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = OsConfigZonalServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = OsConfigZonalServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OsConfigZonalServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = OsConfigZonalServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = OsConfigZonalServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = OsConfigZonalServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = OsConfigZonalServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = OsConfigZonalServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = OsConfigZonalServiceClient.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.OsConfigZonalServiceTransport, '_prep_wrapped_messages') as prep: - client = OsConfigZonalServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.OsConfigZonalServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = OsConfigZonalServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info)