- On January 1, 2020 this library will no longer support Python 2 on the latest released version. - Previously released library versions will continue to be available. For more information please + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.
{% block body %} {% endblock %} diff --git a/docs/conf.py b/docs/conf.py index 8e0733f4..e00dd301 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,6 +20,10 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ @@ -38,21 +42,18 @@ "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", + "recommonmark", ] # autodoc/autosummary flags autoclass_content = "both" -autodoc_default_flags = ["members"] +autodoc_default_options = {"members": True} 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'] @@ -93,7 +94,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -340,7 +346,7 @@ intersphinx_mapping = { "python": ("http://python.readthedocs.org/en/latest/", None), "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.io/grpc/python/", None), } diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index bbcbba23..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Scheduler API -============================== - -.. automodule:: google.cloud.scheduler_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 024654cf..00000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Scheduler API Client -==================================== - -.. automodule:: google.cloud.scheduler_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst deleted file mode 100644 index b28e8ef3..00000000 --- a/docs/gapic/v1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Scheduler API -============================== - -.. automodule:: google.cloud.scheduler_v1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst deleted file mode 100644 index 81ca2a36..00000000 --- a/docs/gapic/v1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Scheduler API Client -==================================== - -.. automodule:: google.cloud.scheduler_v1beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 8b86e0b9..2cf2d5af 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,25 +1,41 @@ .. include:: README.rst +.. include:: multiprocessing.rst + This package includes clients for multiple versions of the Cloud Scheduler API. By default, you will get ``v1``, the latest stable version. +v1 +------------- .. toctree:: - :maxdepth: 2 + :maxdepth: 2 - gapic/v1/api - gapic/v1/types + scheduler_v1/services + scheduler_v1/types Previous beta release ``v1beta1`` is provided as well. -An API and type reference is provided for ``v1beta1``: +v1beta1 +------------- +.. toctree:: + :maxdepth: 2 + + scheduler_v1beta1/services + scheduler_v1beta1/types + + + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. .. toctree:: :maxdepth: 2 - gapic/v1beta1/api - gapic/v1beta1/types - + UPGRADING + Changelog --------- diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst new file mode 100644 index 00000000..1cb29d4c --- /dev/null +++ b/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpcio` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.Pool` or + :class:`multiprocessing.Process`. diff --git a/docs/scheduler_v1/services.rst b/docs/scheduler_v1/services.rst new file mode 100644 index 00000000..114d6268 --- /dev/null +++ b/docs/scheduler_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Scheduler v1 API +========================================== + +.. automodule:: google.cloud.scheduler_v1.services.cloud_scheduler + :members: + :inherited-members: diff --git a/docs/scheduler_v1/types.rst b/docs/scheduler_v1/types.rst new file mode 100644 index 00000000..b9c1233f --- /dev/null +++ b/docs/scheduler_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Scheduler v1 API +======================================= + +.. automodule:: google.cloud.scheduler_v1.types + :members: diff --git a/docs/scheduler_v1beta1/services.rst b/docs/scheduler_v1beta1/services.rst new file mode 100644 index 00000000..48b0abf9 --- /dev/null +++ b/docs/scheduler_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Scheduler v1beta1 API +=============================================== + +.. automodule:: google.cloud.scheduler_v1beta1.services.cloud_scheduler + :members: + :inherited-members: diff --git a/docs/scheduler_v1beta1/types.rst b/docs/scheduler_v1beta1/types.rst new file mode 100644 index 00000000..af3eaf33 --- /dev/null +++ b/docs/scheduler_v1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Scheduler v1beta1 API +============================================ + +.. automodule:: google.cloud.scheduler_v1beta1.types + :members: diff --git a/google/cloud/scheduler/__init__.py b/google/cloud/scheduler/__init__.py new file mode 100644 index 00000000..f894ce91 --- /dev/null +++ b/google/cloud/scheduler/__init__.py @@ -0,0 +1,64 @@ +# -*- 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.scheduler_v1.services.cloud_scheduler.async_client import ( + CloudSchedulerAsyncClient, +) +from google.cloud.scheduler_v1.services.cloud_scheduler.client import ( + CloudSchedulerClient, +) +from google.cloud.scheduler_v1.types.cloudscheduler import CreateJobRequest +from google.cloud.scheduler_v1.types.cloudscheduler import DeleteJobRequest +from google.cloud.scheduler_v1.types.cloudscheduler import GetJobRequest +from google.cloud.scheduler_v1.types.cloudscheduler import ListJobsRequest +from google.cloud.scheduler_v1.types.cloudscheduler import ListJobsResponse +from google.cloud.scheduler_v1.types.cloudscheduler import PauseJobRequest +from google.cloud.scheduler_v1.types.cloudscheduler import ResumeJobRequest +from google.cloud.scheduler_v1.types.cloudscheduler import RunJobRequest +from google.cloud.scheduler_v1.types.cloudscheduler import UpdateJobRequest +from google.cloud.scheduler_v1.types.job import Job +from google.cloud.scheduler_v1.types.job import RetryConfig +from google.cloud.scheduler_v1.types.target import AppEngineHttpTarget +from google.cloud.scheduler_v1.types.target import AppEngineRouting +from google.cloud.scheduler_v1.types.target import HttpMethod +from google.cloud.scheduler_v1.types.target import HttpTarget +from google.cloud.scheduler_v1.types.target import OAuthToken +from google.cloud.scheduler_v1.types.target import OidcToken +from google.cloud.scheduler_v1.types.target import PubsubTarget + +__all__ = ( + "AppEngineHttpTarget", + "AppEngineRouting", + "CloudSchedulerAsyncClient", + "CloudSchedulerClient", + "CreateJobRequest", + "DeleteJobRequest", + "GetJobRequest", + "HttpMethod", + "HttpTarget", + "Job", + "ListJobsRequest", + "ListJobsResponse", + "OAuthToken", + "OidcToken", + "PauseJobRequest", + "PubsubTarget", + "ResumeJobRequest", + "RetryConfig", + "RunJobRequest", + "UpdateJobRequest", +) diff --git a/google/cloud/scheduler/py.typed b/google/cloud/scheduler/py.typed new file mode 100644 index 00000000..ca4d524b --- /dev/null +++ b/google/cloud/scheduler/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-scheduler package uses inline types. diff --git a/google/cloud/scheduler_v1/__init__.py b/google/cloud/scheduler_v1/__init__.py index e8f1301b..f2d528ea 100644 --- a/google/cloud/scheduler_v1/__init__.py +++ b/google/cloud/scheduler_v1/__init__.py @@ -1,41 +1,59 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.scheduler_v1 import types -from google.cloud.scheduler_v1.gapic import cloud_scheduler_client -from google.cloud.scheduler_v1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7." - "More details about Python 2 support for Google Cloud Client Libraries" - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class CloudSchedulerClient(cloud_scheduler_client.CloudSchedulerClient): - __doc__ = cloud_scheduler_client.CloudSchedulerClient.__doc__ - enums = enums - - -__all__ = ("enums", "types", "CloudSchedulerClient") +from .services.cloud_scheduler import CloudSchedulerClient +from .types.cloudscheduler import CreateJobRequest +from .types.cloudscheduler import DeleteJobRequest +from .types.cloudscheduler import GetJobRequest +from .types.cloudscheduler import ListJobsRequest +from .types.cloudscheduler import ListJobsResponse +from .types.cloudscheduler import PauseJobRequest +from .types.cloudscheduler import ResumeJobRequest +from .types.cloudscheduler import RunJobRequest +from .types.cloudscheduler import UpdateJobRequest +from .types.job import Job +from .types.job import RetryConfig +from .types.target import AppEngineHttpTarget +from .types.target import AppEngineRouting +from .types.target import HttpMethod +from .types.target import HttpTarget +from .types.target import OAuthToken +from .types.target import OidcToken +from .types.target import PubsubTarget + + +__all__ = ( + "AppEngineHttpTarget", + "AppEngineRouting", + "CreateJobRequest", + "DeleteJobRequest", + "GetJobRequest", + "HttpMethod", + "HttpTarget", + "Job", + "ListJobsRequest", + "ListJobsResponse", + "OAuthToken", + "OidcToken", + "PauseJobRequest", + "PubsubTarget", + "ResumeJobRequest", + "RetryConfig", + "RunJobRequest", + "UpdateJobRequest", + "CloudSchedulerClient", +) diff --git a/google/cloud/scheduler_v1/gapic/cloud_scheduler_client.py b/google/cloud/scheduler_v1/gapic/cloud_scheduler_client.py deleted file mode 100644 index b7eda181..00000000 --- a/google/cloud/scheduler_v1/gapic/cloud_scheduler_client.py +++ /dev/null @@ -1,847 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.scheduler.v1 CloudScheduler API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.scheduler_v1.gapic import cloud_scheduler_client_config -from google.cloud.scheduler_v1.gapic import enums -from google.cloud.scheduler_v1.gapic.transports import cloud_scheduler_grpc_transport -from google.cloud.scheduler_v1.proto import cloudscheduler_pb2 -from google.cloud.scheduler_v1.proto import cloudscheduler_pb2_grpc -from google.cloud.scheduler_v1.proto import job_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-scheduler" -).version - - -class CloudSchedulerClient(object): - """ - The Cloud Scheduler API allows external entities to reliably - schedule asynchronous jobs. - """ - - SERVICE_ADDRESS = "cloudscheduler.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.scheduler.v1.CloudScheduler" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CloudSchedulerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def job_path(cls, project, location, job): - """Return a fully-qualified job string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/jobs/{job}", - project=project, - location=location, - job=job, - ) - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.CloudSchedulerGrpcTransport, - Callable[[~.Credentials, type], ~.CloudSchedulerGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = cloud_scheduler_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=cloud_scheduler_grpc_transport.CloudSchedulerGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = cloud_scheduler_grpc_transport.CloudSchedulerGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME] - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_jobs( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists jobs. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_jobs(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_jobs(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.scheduler_v1.types.Job` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_jobs" not in self._inner_api_calls: - self._inner_api_calls[ - "list_jobs" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_jobs, - default_retry=self._method_configs["ListJobs"].retry, - default_timeout=self._method_configs["ListJobs"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.ListJobsRequest(parent=parent, page_size=page_size) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_jobs"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="jobs", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a job. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.get_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_job" not in self._inner_api_calls: - self._inner_api_calls[ - "get_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_job, - default_retry=self._method_configs["GetJob"].retry, - default_timeout=self._method_configs["GetJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.GetJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_job( - self, - parent, - job, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a job. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `job`: - >>> job = {} - >>> - >>> response = client.create_job(parent, job) - - Args: - parent (str): Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - job (Union[dict, ~google.cloud.scheduler_v1.types.Job]): Required. The job to add. The user can optionally specify a name for the - job in ``name``. ``name`` cannot be the same as an existing job. If a - name is not specified then the system will generate a random unique name - that will be returned (``name``) in the response. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.scheduler_v1.types.Job` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_job" not in self._inner_api_calls: - self._inner_api_calls[ - "create_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_job, - default_retry=self._method_configs["CreateJob"].retry, - default_timeout=self._method_configs["CreateJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.CreateJobRequest(parent=parent, job=job) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_job( - self, - job, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a job. - - If successful, the updated ``Job`` is returned. If the job does not - exist, ``NOT_FOUND`` is returned. - - If UpdateJob does not successfully return, it is possible for the job to - be in an ``Job.State.UPDATE_FAILED`` state. A job in this state may not - be executed. If this happens, retry the UpdateJob request until a - successful response is received. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> # TODO: Initialize `job`: - >>> job = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_job(job, update_mask) - - Args: - job (Union[dict, ~google.cloud.scheduler_v1.types.Job]): Required. The new job properties. ``name`` must be specified. - - Output only fields cannot be modified using UpdateJob. Any value - specified for an output only field will be ignored. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.scheduler_v1.types.Job` - update_mask (Union[dict, ~google.cloud.scheduler_v1.types.FieldMask]): A mask used to specify which fields of the job are being updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.scheduler_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_job" not in self._inner_api_calls: - self._inner_api_calls[ - "update_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_job, - default_retry=self._method_configs["UpdateJob"].retry, - default_timeout=self._method_configs["UpdateJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.UpdateJobRequest(job=job, update_mask=update_mask) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("job.name", job.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a job. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> client.delete_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_job" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_job, - default_retry=self._method_configs["DeleteJob"].retry, - default_timeout=self._method_configs["DeleteJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.DeleteJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def pause_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Pauses a job. - - If a job is paused then the system will stop executing the job until it - is re-enabled via ``ResumeJob``. The state of the job is stored in - ``state``; if paused it will be set to ``Job.State.PAUSED``. A job must - be in ``Job.State.ENABLED`` to be paused. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.pause_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "pause_job" not in self._inner_api_calls: - self._inner_api_calls[ - "pause_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.pause_job, - default_retry=self._method_configs["PauseJob"].retry, - default_timeout=self._method_configs["PauseJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.PauseJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["pause_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def resume_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Resume a job. - - This method reenables a job after it has been ``Job.State.PAUSED``. The - state of a job is stored in ``Job.state``; after calling this method it - will be set to ``Job.State.ENABLED``. A job must be in - ``Job.State.PAUSED`` to be resumed. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.resume_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "resume_job" not in self._inner_api_calls: - self._inner_api_calls[ - "resume_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.resume_job, - default_retry=self._method_configs["ResumeJob"].retry, - default_timeout=self._method_configs["ResumeJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.ResumeJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["resume_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def run_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Forces a job to run now. - - When this method is called, Cloud Scheduler will dispatch the job, even - if the job is already running. - - Example: - >>> from google.cloud import scheduler_v1 - >>> - >>> client = scheduler_v1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.run_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "run_job" not in self._inner_api_calls: - self._inner_api_calls[ - "run_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.run_job, - default_retry=self._method_configs["RunJob"].retry, - default_timeout=self._method_configs["RunJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.RunJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["run_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/scheduler_v1/gapic/cloud_scheduler_client_config.py b/google/cloud/scheduler_v1/gapic/cloud_scheduler_client_config.py deleted file mode 100644 index da963b9d..00000000 --- a/google/cloud/scheduler_v1/gapic/cloud_scheduler_client_config.py +++ /dev/null @@ -1,63 +0,0 @@ -config = { - "interfaces": { - "google.cloud.scheduler.v1.CloudScheduler": { - "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "ListJobs": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "GetJob": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "CreateJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "UpdateJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "DeleteJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "PauseJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ResumeJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "RunJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - }, - } - } -} diff --git a/google/cloud/scheduler_v1/gapic/enums.py b/google/cloud/scheduler_v1/gapic/enums.py deleted file mode 100644 index 746acde6..00000000 --- a/google/cloud/scheduler_v1/gapic/enums.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class HttpMethod(enum.IntEnum): - """ - The HTTP method used to execute the job. - - Attributes: - HTTP_METHOD_UNSPECIFIED (int): HTTP method unspecified. Defaults to POST. - POST (int): HTTP POST - GET (int): HTTP GET - HEAD (int): HTTP HEAD - PUT (int): HTTP PUT - DELETE (int): HTTP DELETE - PATCH (int): HTTP PATCH - OPTIONS (int): HTTP OPTIONS - """ - - HTTP_METHOD_UNSPECIFIED = 0 - POST = 1 - GET = 2 - HEAD = 3 - PUT = 4 - DELETE = 5 - PATCH = 6 - OPTIONS = 7 - - -class Job(object): - class State(enum.IntEnum): - """ - State of the job. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ENABLED (int): The job is executing normally. - PAUSED (int): The job is paused by the user. It will not execute. A user can - intentionally pause the job using ``PauseJobRequest``. - DISABLED (int): The job is disabled by the system due to error. The user - cannot directly set a job to be disabled. - UPDATE_FAILED (int): The job state resulting from a failed ``CloudScheduler.UpdateJob`` - operation. To recover a job from this state, retry - ``CloudScheduler.UpdateJob`` until a successful response is received. - """ - - STATE_UNSPECIFIED = 0 - ENABLED = 1 - PAUSED = 2 - DISABLED = 3 - UPDATE_FAILED = 4 diff --git a/google/cloud/scheduler_v1/gapic/transports/__init__.py b/google/cloud/scheduler_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/scheduler_v1/gapic/transports/cloud_scheduler_grpc_transport.py b/google/cloud/scheduler_v1/gapic/transports/cloud_scheduler_grpc_transport.py deleted file mode 100644 index 5b14b6c8..00000000 --- a/google/cloud/scheduler_v1/gapic/transports/cloud_scheduler_grpc_transport.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.scheduler_v1.proto import cloudscheduler_pb2_grpc - - -class CloudSchedulerGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.scheduler.v1 CloudScheduler API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - channel=None, - credentials=None, - address="cloudscheduler.googleapis.com:443", - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive." - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "cloud_scheduler_stub": cloudscheduler_pb2_grpc.CloudSchedulerStub(channel) - } - - @classmethod - def create_channel( - cls, address="cloudscheduler.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_jobs(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.list_jobs`. - - Lists jobs. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].ListJobs - - @property - def get_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.get_job`. - - Gets a job. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].GetJob - - @property - def create_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.create_job`. - - Creates a job. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].CreateJob - - @property - def update_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.update_job`. - - Updates a job. - - If successful, the updated ``Job`` is returned. If the job does not - exist, ``NOT_FOUND`` is returned. - - If UpdateJob does not successfully return, it is possible for the job to - be in an ``Job.State.UPDATE_FAILED`` state. A job in this state may not - be executed. If this happens, retry the UpdateJob request until a - successful response is received. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].UpdateJob - - @property - def delete_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.delete_job`. - - Deletes a job. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].DeleteJob - - @property - def pause_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.pause_job`. - - Pauses a job. - - If a job is paused then the system will stop executing the job until it - is re-enabled via ``ResumeJob``. The state of the job is stored in - ``state``; if paused it will be set to ``Job.State.PAUSED``. A job must - be in ``Job.State.ENABLED`` to be paused. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].PauseJob - - @property - def resume_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.resume_job`. - - Resume a job. - - This method reenables a job after it has been ``Job.State.PAUSED``. The - state of a job is stored in ``Job.state``; after calling this method it - will be set to ``Job.State.ENABLED``. A job must be in - ``Job.State.PAUSED`` to be resumed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].ResumeJob - - @property - def run_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.run_job`. - - Forces a job to run now. - - When this method is called, Cloud Scheduler will dispatch the job, even - if the job is already running. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].RunJob diff --git a/google/cloud/scheduler_v1/proto/__init__.py b/google/cloud/scheduler_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/scheduler_v1/proto/cloudscheduler_pb2.py b/google/cloud/scheduler_v1/proto/cloudscheduler_pb2.py deleted file mode 100644 index b604f9ce..00000000 --- a/google/cloud/scheduler_v1/proto/cloudscheduler_pb2.py +++ /dev/null @@ -1,845 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/scheduler_v1/proto/cloudscheduler.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.scheduler_v1.proto import ( - job_pb2 as google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/scheduler_v1/proto/cloudscheduler.proto", - package="google.cloud.scheduler.v1", - syntax="proto3", - serialized_options=_b( - "\n\035com.google.cloud.scheduler.v1B\016SchedulerProtoP\001ZBgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1;scheduler\242\002\tSCHEDULER" - ), - serialized_pb=_b( - '\n4google/cloud/scheduler_v1/proto/cloudscheduler.proto\x12\x19google.cloud.scheduler.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a)google/cloud/scheduler_v1/proto/job.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto"s\n\x0fListJobsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\x12!cloudscheduler.googleapis.com/Job\x12\x11\n\tpage_size\x18\x05 \x01(\x05\x12\x12\n\npage_token\x18\x06 \x01(\t"Y\n\x10ListJobsResponse\x12,\n\x04jobs\x18\x01 \x03(\x0b\x32\x1e.google.cloud.scheduler.v1.Job\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"H\n\rGetJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"\x7f\n\x10\x43reateJobRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\x12!cloudscheduler.googleapis.com/Job\x12\x30\n\x03job\x18\x02 \x01(\x0b\x32\x1e.google.cloud.scheduler.v1.JobB\x03\xe0\x41\x02"z\n\x10UpdateJobRequest\x12\x30\n\x03job\x18\x01 \x01(\x0b\x32\x1e.google.cloud.scheduler.v1.JobB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"K\n\x10\x44\x65leteJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"J\n\x0fPauseJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"K\n\x10ResumeJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"H\n\rRunJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job2\xb3\n\n\x0e\x43loudScheduler\x12\x9e\x01\n\x08ListJobs\x12*.google.cloud.scheduler.v1.ListJobsRequest\x1a+.google.cloud.scheduler.v1.ListJobsResponse"9\x82\xd3\xe4\x93\x02*\x12(/v1/{parent=projects/*/locations/*}/jobs\xda\x41\x06parent\x12\x8b\x01\n\x06GetJob\x12(.google.cloud.scheduler.v1.GetJobRequest\x1a\x1e.google.cloud.scheduler.v1.Job"7\x82\xd3\xe4\x93\x02*\x12(/v1/{name=projects/*/locations/*/jobs/*}\xda\x41\x04name\x12\x9c\x01\n\tCreateJob\x12+.google.cloud.scheduler.v1.CreateJobRequest\x1a\x1e.google.cloud.scheduler.v1.Job"B\x82\xd3\xe4\x93\x02/"(/v1/{parent=projects/*/locations/*}/jobs:\x03job\xda\x41\nparent,job\x12\xa5\x01\n\tUpdateJob\x12+.google.cloud.scheduler.v1.UpdateJobRequest\x1a\x1e.google.cloud.scheduler.v1.Job"K\x82\xd3\xe4\x93\x02\x33\x32,/v1/{job.name=projects/*/locations/*/jobs/*}:\x03job\xda\x41\x0fjob,update_mask\x12\x89\x01\n\tDeleteJob\x12+.google.cloud.scheduler.v1.DeleteJobRequest\x1a\x16.google.protobuf.Empty"7\x82\xd3\xe4\x93\x02**(/v1/{name=projects/*/locations/*/jobs/*}\xda\x41\x04name\x12\x98\x01\n\x08PauseJob\x12*.google.cloud.scheduler.v1.PauseJobRequest\x1a\x1e.google.cloud.scheduler.v1.Job"@\x82\xd3\xe4\x93\x02\x33"./v1/{name=projects/*/locations/*/jobs/*}:pause:\x01*\xda\x41\x04name\x12\x9b\x01\n\tResumeJob\x12+.google.cloud.scheduler.v1.ResumeJobRequest\x1a\x1e.google.cloud.scheduler.v1.Job"A\x82\xd3\xe4\x93\x02\x34"//v1/{name=projects/*/locations/*/jobs/*}:resume:\x01*\xda\x41\x04name\x12\x92\x01\n\x06RunJob\x12(.google.cloud.scheduler.v1.RunJobRequest\x1a\x1e.google.cloud.scheduler.v1.Job">\x82\xd3\xe4\x93\x02\x31",/v1/{name=projects/*/locations/*/jobs/*}:run:\x01*\xda\x41\x04name\x1aQ\xca\x41\x1d\x63loudscheduler.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\x81\x01\n\x1d\x63om.google.cloud.scheduler.v1B\x0eSchedulerProtoP\x01ZBgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1;scheduler\xa2\x02\tSCHEDULERb\x06proto3' - ), - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - ], -) - - -_LISTJOBSREQUEST = _descriptor.Descriptor( - name="ListJobsRequest", - full_name="google.cloud.scheduler.v1.ListJobsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.scheduler.v1.ListJobsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\022!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.scheduler.v1.ListJobsRequest.page_size", - index=1, - number=5, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.scheduler.v1.ListJobsRequest.page_token", - index=2, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=304, - serialized_end=419, -) - - -_LISTJOBSRESPONSE = _descriptor.Descriptor( - name="ListJobsResponse", - full_name="google.cloud.scheduler.v1.ListJobsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="jobs", - full_name="google.cloud.scheduler.v1.ListJobsResponse.jobs", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.scheduler.v1.ListJobsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=421, - serialized_end=510, -) - - -_GETJOBREQUEST = _descriptor.Descriptor( - name="GetJobRequest", - full_name="google.cloud.scheduler.v1.GetJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1.GetJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=512, - serialized_end=584, -) - - -_CREATEJOBREQUEST = _descriptor.Descriptor( - name="CreateJobRequest", - full_name="google.cloud.scheduler.v1.CreateJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.scheduler.v1.CreateJobRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\022!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="job", - full_name="google.cloud.scheduler.v1.CreateJobRequest.job", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\340A\002"), - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=586, - serialized_end=713, -) - - -_UPDATEJOBREQUEST = _descriptor.Descriptor( - name="UpdateJobRequest", - full_name="google.cloud.scheduler.v1.UpdateJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="job", - full_name="google.cloud.scheduler.v1.UpdateJobRequest.job", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\340A\002"), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.scheduler.v1.UpdateJobRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\340A\002"), - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=715, - serialized_end=837, -) - - -_DELETEJOBREQUEST = _descriptor.Descriptor( - name="DeleteJobRequest", - full_name="google.cloud.scheduler.v1.DeleteJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1.DeleteJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=839, - serialized_end=914, -) - - -_PAUSEJOBREQUEST = _descriptor.Descriptor( - name="PauseJobRequest", - full_name="google.cloud.scheduler.v1.PauseJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1.PauseJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=916, - serialized_end=990, -) - - -_RESUMEJOBREQUEST = _descriptor.Descriptor( - name="ResumeJobRequest", - full_name="google.cloud.scheduler.v1.ResumeJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1.ResumeJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=992, - serialized_end=1067, -) - - -_RUNJOBREQUEST = _descriptor.Descriptor( - name="RunJobRequest", - full_name="google.cloud.scheduler.v1.RunJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1.RunJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1069, - serialized_end=1141, -) - -_LISTJOBSRESPONSE.fields_by_name[ - "jobs" -].message_type = google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB -_CREATEJOBREQUEST.fields_by_name[ - "job" -].message_type = google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB -_UPDATEJOBREQUEST.fields_by_name[ - "job" -].message_type = google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB -_UPDATEJOBREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -DESCRIPTOR.message_types_by_name["ListJobsRequest"] = _LISTJOBSREQUEST -DESCRIPTOR.message_types_by_name["ListJobsResponse"] = _LISTJOBSRESPONSE -DESCRIPTOR.message_types_by_name["GetJobRequest"] = _GETJOBREQUEST -DESCRIPTOR.message_types_by_name["CreateJobRequest"] = _CREATEJOBREQUEST -DESCRIPTOR.message_types_by_name["UpdateJobRequest"] = _UPDATEJOBREQUEST -DESCRIPTOR.message_types_by_name["DeleteJobRequest"] = _DELETEJOBREQUEST -DESCRIPTOR.message_types_by_name["PauseJobRequest"] = _PAUSEJOBREQUEST -DESCRIPTOR.message_types_by_name["ResumeJobRequest"] = _RESUMEJOBREQUEST -DESCRIPTOR.message_types_by_name["RunJobRequest"] = _RUNJOBREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListJobsRequest = _reflection.GeneratedProtocolMessageType( - "ListJobsRequest", - (_message.Message,), - dict( - DESCRIPTOR=_LISTJOBSREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for listing jobs using - [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. - Attributes: - parent: - Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - page_size: - Requested page size. The maximum page size is 500. If - unspecified, the page size will be the maximum. Fewer jobs - than requested might be returned, even if more jobs exist; use - next\_page\_token to determine if more jobs exist. - page_token: - A token identifying a page of results the server will return. - To request the first page results, page\_token must be empty. - To request the next page of results, page\_token must be the - value of [next\_page\_token][google.cloud.scheduler.v1.ListJob - sResponse.next\_page\_token] returned from the previous call - to - [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. - It is an error to switch the value of - [filter][google.cloud.scheduler.v1.ListJobsRequest.filter] or - [order\_by][google.cloud.scheduler.v1.ListJobsRequest.order\_b - y] while iterating through pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.ListJobsRequest) - ), -) -_sym_db.RegisterMessage(ListJobsRequest) - -ListJobsResponse = _reflection.GeneratedProtocolMessageType( - "ListJobsResponse", - (_message.Message,), - dict( - DESCRIPTOR=_LISTJOBSRESPONSE, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Response message for listing jobs using - [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. - Attributes: - jobs: - The list of jobs. - next_page_token: - A token to retrieve next page of results. Pass this value in - the [page\_token][google.cloud.scheduler.v1.ListJobsRequest.pa - ge\_token] field in the subsequent call to - [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] - to retrieve the next page of results. If this is empty it - indicates that there are no more results through which to - paginate. The page token is valid for only 2 hours. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.ListJobsResponse) - ), -) -_sym_db.RegisterMessage(ListJobsResponse) - -GetJobRequest = _reflection.GeneratedProtocolMessageType( - "GetJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_GETJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [GetJob][google.cloud.scheduler.v1.CloudScheduler.GetJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.GetJobRequest) - ), -) -_sym_db.RegisterMessage(GetJobRequest) - -CreateJobRequest = _reflection.GeneratedProtocolMessageType( - "CreateJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_CREATEJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob]. - Attributes: - parent: - Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - job: - Required. The job to add. The user can optionally specify a - name for the job in - [name][google.cloud.scheduler.v1.Job.name]. - [name][google.cloud.scheduler.v1.Job.name] cannot be the same - as an existing job. If a name is not specified then the system - will generate a random unique name that will be returned - ([name][google.cloud.scheduler.v1.Job.name]) in the response. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.CreateJobRequest) - ), -) -_sym_db.RegisterMessage(CreateJobRequest) - -UpdateJobRequest = _reflection.GeneratedProtocolMessageType( - "UpdateJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_UPDATEJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. - Attributes: - job: - Required. The new job properties. - [name][google.cloud.scheduler.v1.Job.name] must be specified. - Output only fields cannot be modified using UpdateJob. Any - value specified for an output only field will be ignored. - update_mask: - A mask used to specify which fields of the job are being - updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.UpdateJobRequest) - ), -) -_sym_db.RegisterMessage(UpdateJobRequest) - -DeleteJobRequest = _reflection.GeneratedProtocolMessageType( - "DeleteJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_DELETEJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for deleting a job using - [DeleteJob][google.cloud.scheduler.v1.CloudScheduler.DeleteJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.DeleteJobRequest) - ), -) -_sym_db.RegisterMessage(DeleteJobRequest) - -PauseJobRequest = _reflection.GeneratedProtocolMessageType( - "PauseJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_PAUSEJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [PauseJob][google.cloud.scheduler.v1.CloudScheduler.PauseJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.PauseJobRequest) - ), -) -_sym_db.RegisterMessage(PauseJobRequest) - -ResumeJobRequest = _reflection.GeneratedProtocolMessageType( - "ResumeJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_RESUMEJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.ResumeJobRequest) - ), -) -_sym_db.RegisterMessage(ResumeJobRequest) - -RunJobRequest = _reflection.GeneratedProtocolMessageType( - "RunJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_RUNJOBREQUEST, - __module__="google.cloud.scheduler_v1.proto.cloudscheduler_pb2", - __doc__="""Request message for forcing a job to run now using - [RunJob][google.cloud.scheduler.v1.CloudScheduler.RunJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.RunJobRequest) - ), -) -_sym_db.RegisterMessage(RunJobRequest) - - -DESCRIPTOR._options = None -_LISTJOBSREQUEST.fields_by_name["parent"]._options = None -_GETJOBREQUEST.fields_by_name["name"]._options = None -_CREATEJOBREQUEST.fields_by_name["parent"]._options = None -_CREATEJOBREQUEST.fields_by_name["job"]._options = None -_UPDATEJOBREQUEST.fields_by_name["job"]._options = None -_UPDATEJOBREQUEST.fields_by_name["update_mask"]._options = None -_DELETEJOBREQUEST.fields_by_name["name"]._options = None -_PAUSEJOBREQUEST.fields_by_name["name"]._options = None -_RESUMEJOBREQUEST.fields_by_name["name"]._options = None -_RUNJOBREQUEST.fields_by_name["name"]._options = None - -_CLOUDSCHEDULER = _descriptor.ServiceDescriptor( - name="CloudScheduler", - full_name="google.cloud.scheduler.v1.CloudScheduler", - file=DESCRIPTOR, - index=0, - serialized_options=_b( - "\312A\035cloudscheduler.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform" - ), - serialized_start=1144, - serialized_end=2475, - methods=[ - _descriptor.MethodDescriptor( - name="ListJobs", - full_name="google.cloud.scheduler.v1.CloudScheduler.ListJobs", - index=0, - containing_service=None, - input_type=_LISTJOBSREQUEST, - output_type=_LISTJOBSRESPONSE, - serialized_options=_b( - "\202\323\344\223\002*\022(/v1/{parent=projects/*/locations/*}/jobs\332A\006parent" - ), - ), - _descriptor.MethodDescriptor( - name="GetJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.GetJob", - index=1, - containing_service=None, - input_type=_GETJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - "\202\323\344\223\002*\022(/v1/{name=projects/*/locations/*/jobs/*}\332A\004name" - ), - ), - _descriptor.MethodDescriptor( - name="CreateJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.CreateJob", - index=2, - containing_service=None, - input_type=_CREATEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\002/"(/v1/{parent=projects/*/locations/*}/jobs:\003job\332A\nparent,job' - ), - ), - _descriptor.MethodDescriptor( - name="UpdateJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.UpdateJob", - index=3, - containing_service=None, - input_type=_UPDATEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - "\202\323\344\223\00232,/v1/{job.name=projects/*/locations/*/jobs/*}:\003job\332A\017job,update_mask" - ), - ), - _descriptor.MethodDescriptor( - name="DeleteJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.DeleteJob", - index=4, - containing_service=None, - input_type=_DELETEJOBREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=_b( - "\202\323\344\223\002**(/v1/{name=projects/*/locations/*/jobs/*}\332A\004name" - ), - ), - _descriptor.MethodDescriptor( - name="PauseJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.PauseJob", - index=5, - containing_service=None, - input_type=_PAUSEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0023"./v1/{name=projects/*/locations/*/jobs/*}:pause:\001*\332A\004name' - ), - ), - _descriptor.MethodDescriptor( - name="ResumeJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.ResumeJob", - index=6, - containing_service=None, - input_type=_RESUMEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0024"//v1/{name=projects/*/locations/*/jobs/*}:resume:\001*\332A\004name' - ), - ), - _descriptor.MethodDescriptor( - name="RunJob", - full_name="google.cloud.scheduler.v1.CloudScheduler.RunJob", - index=7, - containing_service=None, - input_type=_RUNJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0021",/v1/{name=projects/*/locations/*/jobs/*}:run:\001*\332A\004name' - ), - ), - ], -) -_sym_db.RegisterServiceDescriptor(_CLOUDSCHEDULER) - -DESCRIPTOR.services_by_name["CloudScheduler"] = _CLOUDSCHEDULER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/scheduler_v1/proto/cloudscheduler_pb2_grpc.py b/google/cloud/scheduler_v1/proto/cloudscheduler_pb2_grpc.py deleted file mode 100644 index 7a55cab6..00000000 --- a/google/cloud/scheduler_v1/proto/cloudscheduler_pb2_grpc.py +++ /dev/null @@ -1,196 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -from google.cloud.scheduler_v1.proto import ( - cloudscheduler_pb2 as google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2, -) -from google.cloud.scheduler_v1.proto import ( - job_pb2 as google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class CloudSchedulerStub(object): - """The Cloud Scheduler API allows external entities to reliably - schedule asynchronous jobs. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListJobs = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/ListJobs", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.ListJobsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.ListJobsResponse.FromString, - ) - self.GetJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/GetJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.GetJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.CreateJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/CreateJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.CreateJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.UpdateJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/UpdateJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.UpdateJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.DeleteJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/DeleteJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.DeleteJobRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.PauseJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/PauseJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.PauseJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.ResumeJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/ResumeJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.ResumeJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.RunJob = channel.unary_unary( - "/google.cloud.scheduler.v1.CloudScheduler/RunJob", - request_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.RunJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.FromString, - ) - - -class CloudSchedulerServicer(object): - """The Cloud Scheduler API allows external entities to reliably - schedule asynchronous jobs. - """ - - def ListJobs(self, request, context): - """Lists jobs. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetJob(self, request, context): - """Gets a job. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateJob(self, request, context): - """Creates a job. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateJob(self, request, context): - """Updates a job. - - If successful, the updated [Job][google.cloud.scheduler.v1.Job] is returned. If the job does - not exist, `NOT_FOUND` is returned. - - If UpdateJob does not successfully return, it is possible for the - job to be in an [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1.Job.State.UPDATE_FAILED] state. A job in this state may - not be executed. If this happens, retry the UpdateJob request - until a successful response is received. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteJob(self, request, context): - """Deletes a job. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def PauseJob(self, request, context): - """Pauses a job. - - If a job is paused then the system will stop executing the job - until it is re-enabled via [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. The - state of the job is stored in [state][google.cloud.scheduler.v1.Job.state]; if paused it - will be set to [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. A job must be in [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED] - to be paused. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ResumeJob(self, request, context): - """Resume a job. - - This method reenables a job after it has been [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. The - state of a job is stored in [Job.state][google.cloud.scheduler.v1.Job.state]; after calling this method it - will be set to [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED]. A job must be in - [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED] to be resumed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RunJob(self, request, context): - """Forces a job to run now. - - When this method is called, Cloud Scheduler will dispatch the job, even - if the job is already running. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_CloudSchedulerServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListJobs": grpc.unary_unary_rpc_method_handler( - servicer.ListJobs, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.ListJobsRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.ListJobsResponse.SerializeToString, - ), - "GetJob": grpc.unary_unary_rpc_method_handler( - servicer.GetJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.GetJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "CreateJob": grpc.unary_unary_rpc_method_handler( - servicer.CreateJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.CreateJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "UpdateJob": grpc.unary_unary_rpc_method_handler( - servicer.UpdateJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.UpdateJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "DeleteJob": grpc.unary_unary_rpc_method_handler( - servicer.DeleteJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.DeleteJobRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "PauseJob": grpc.unary_unary_rpc_method_handler( - servicer.PauseJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.PauseJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "ResumeJob": grpc.unary_unary_rpc_method_handler( - servicer.ResumeJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.ResumeJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "RunJob": grpc.unary_unary_rpc_method_handler( - servicer.RunJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_cloudscheduler__pb2.RunJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.scheduler.v1.CloudScheduler", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/google/cloud/scheduler_v1/proto/job_pb2.py b/google/cloud/scheduler_v1/proto/job_pb2.py deleted file mode 100644 index 55d509c0..00000000 --- a/google/cloud/scheduler_v1/proto/job_pb2.py +++ /dev/null @@ -1,701 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/scheduler_v1/proto/job.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.scheduler_v1.proto import ( - target_pb2 as google_dot_cloud_dot_scheduler__v1_dot_proto_dot_target__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/scheduler_v1/proto/job.proto", - package="google.cloud.scheduler.v1", - syntax="proto3", - serialized_options=_b( - "\n\035com.google.cloud.scheduler.v1B\010JobProtoP\001ZBgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1;scheduler" - ), - serialized_pb=_b( - '\n)google/cloud/scheduler_v1/proto/job.proto\x12\x19google.cloud.scheduler.v1\x1a\x19google/api/resource.proto\x1a,google/cloud/scheduler_v1/proto/target.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\x1a\x1cgoogle/api/annotations.proto"\xcb\x06\n\x03Job\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12@\n\rpubsub_target\x18\x04 \x01(\x0b\x32\'.google.cloud.scheduler.v1.PubsubTargetH\x00\x12P\n\x16\x61pp_engine_http_target\x18\x05 \x01(\x0b\x32..google.cloud.scheduler.v1.AppEngineHttpTargetH\x00\x12<\n\x0bhttp_target\x18\x06 \x01(\x0b\x32%.google.cloud.scheduler.v1.HttpTargetH\x00\x12\x10\n\x08schedule\x18\x14 \x01(\t\x12\x11\n\ttime_zone\x18\x15 \x01(\t\x12\x34\n\x10user_update_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x05state\x18\n \x01(\x0e\x32$.google.cloud.scheduler.v1.Job.State\x12"\n\x06status\x18\x0b \x01(\x0b\x32\x12.google.rpc.Status\x12\x31\n\rschedule_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x35\n\x11last_attempt_time\x18\x12 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12<\n\x0cretry_config\x18\x13 \x01(\x0b\x32&.google.cloud.scheduler.v1.RetryConfig\x12\x33\n\x10\x61ttempt_deadline\x18\x16 \x01(\x0b\x32\x19.google.protobuf.Duration"X\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x45NABLED\x10\x01\x12\n\n\x06PAUSED\x10\x02\x12\x0c\n\x08\x44ISABLED\x10\x03\x12\x11\n\rUPDATE_FAILED\x10\x04:Z\xea\x41W\n!cloudscheduler.googleapis.com/Job\x12\x32projects/{project}/locations/{location}/jobs/{job}B\x08\n\x06target"\xe2\x01\n\x0bRetryConfig\x12\x13\n\x0bretry_count\x18\x01 \x01(\x05\x12\x35\n\x12max_retry_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14min_backoff_duration\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14max_backoff_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x15\n\rmax_doublings\x18\x05 \x01(\x05\x42o\n\x1d\x63om.google.cloud.scheduler.v1B\x08JobProtoP\x01ZBgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1;schedulerb\x06proto3' - ), - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_scheduler__v1_dot_proto_dot_target__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_JOB_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.scheduler.v1.Job.State", - filename=None, - file=DESCRIPTOR, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - ), - _descriptor.EnumValueDescriptor( - name="ENABLED", index=1, number=1, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="PAUSED", index=2, number=2, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="DISABLED", index=3, number=3, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="UPDATE_FAILED", index=4, number=4, serialized_options=None, type=None - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=919, - serialized_end=1007, -) -_sym_db.RegisterEnumDescriptor(_JOB_STATE) - - -_JOB = _descriptor.Descriptor( - name="Job", - full_name="google.cloud.scheduler.v1.Job", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1.Job.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.scheduler.v1.Job.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="pubsub_target", - full_name="google.cloud.scheduler.v1.Job.pubsub_target", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="app_engine_http_target", - full_name="google.cloud.scheduler.v1.Job.app_engine_http_target", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="http_target", - full_name="google.cloud.scheduler.v1.Job.http_target", - index=4, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="schedule", - full_name="google.cloud.scheduler.v1.Job.schedule", - index=5, - number=20, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="time_zone", - full_name="google.cloud.scheduler.v1.Job.time_zone", - index=6, - number=21, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="user_update_time", - full_name="google.cloud.scheduler.v1.Job.user_update_time", - index=7, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.scheduler.v1.Job.state", - index=8, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="status", - full_name="google.cloud.scheduler.v1.Job.status", - index=9, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="schedule_time", - full_name="google.cloud.scheduler.v1.Job.schedule_time", - index=10, - number=17, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="last_attempt_time", - full_name="google.cloud.scheduler.v1.Job.last_attempt_time", - index=11, - number=18, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="retry_config", - full_name="google.cloud.scheduler.v1.Job.retry_config", - index=12, - number=19, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="attempt_deadline", - full_name="google.cloud.scheduler.v1.Job.attempt_deadline", - index=13, - number=22, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_JOB_STATE], - serialized_options=_b( - "\352AW\n!cloudscheduler.googleapis.com/Job\0222projects/{project}/locations/{location}/jobs/{job}" - ), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="target", - full_name="google.cloud.scheduler.v1.Job.target", - index=0, - containing_type=None, - fields=[], - ) - ], - serialized_start=266, - serialized_end=1109, -) - - -_RETRYCONFIG = _descriptor.Descriptor( - name="RetryConfig", - full_name="google.cloud.scheduler.v1.RetryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="retry_count", - full_name="google.cloud.scheduler.v1.RetryConfig.retry_count", - index=0, - number=1, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="max_retry_duration", - full_name="google.cloud.scheduler.v1.RetryConfig.max_retry_duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="min_backoff_duration", - full_name="google.cloud.scheduler.v1.RetryConfig.min_backoff_duration", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="max_backoff_duration", - full_name="google.cloud.scheduler.v1.RetryConfig.max_backoff_duration", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="max_doublings", - full_name="google.cloud.scheduler.v1.RetryConfig.max_doublings", - index=4, - number=5, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1112, - serialized_end=1338, -) - -_JOB.fields_by_name[ - "pubsub_target" -].message_type = ( - google_dot_cloud_dot_scheduler__v1_dot_proto_dot_target__pb2._PUBSUBTARGET -) -_JOB.fields_by_name[ - "app_engine_http_target" -].message_type = ( - google_dot_cloud_dot_scheduler__v1_dot_proto_dot_target__pb2._APPENGINEHTTPTARGET -) -_JOB.fields_by_name[ - "http_target" -].message_type = ( - google_dot_cloud_dot_scheduler__v1_dot_proto_dot_target__pb2._HTTPTARGET -) -_JOB.fields_by_name[ - "user_update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_JOB.fields_by_name["state"].enum_type = _JOB_STATE -_JOB.fields_by_name["status"].message_type = google_dot_rpc_dot_status__pb2._STATUS -_JOB.fields_by_name[ - "schedule_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_JOB.fields_by_name[ - "last_attempt_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_JOB.fields_by_name["retry_config"].message_type = _RETRYCONFIG -_JOB.fields_by_name[ - "attempt_deadline" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_JOB_STATE.containing_type = _JOB -_JOB.oneofs_by_name["target"].fields.append(_JOB.fields_by_name["pubsub_target"]) -_JOB.fields_by_name["pubsub_target"].containing_oneof = _JOB.oneofs_by_name["target"] -_JOB.oneofs_by_name["target"].fields.append( - _JOB.fields_by_name["app_engine_http_target"] -) -_JOB.fields_by_name["app_engine_http_target"].containing_oneof = _JOB.oneofs_by_name[ - "target" -] -_JOB.oneofs_by_name["target"].fields.append(_JOB.fields_by_name["http_target"]) -_JOB.fields_by_name["http_target"].containing_oneof = _JOB.oneofs_by_name["target"] -_RETRYCONFIG.fields_by_name[ - "max_retry_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RETRYCONFIG.fields_by_name[ - "min_backoff_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RETRYCONFIG.fields_by_name[ - "max_backoff_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -DESCRIPTOR.message_types_by_name["Job"] = _JOB -DESCRIPTOR.message_types_by_name["RetryConfig"] = _RETRYCONFIG -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Job = _reflection.GeneratedProtocolMessageType( - "Job", - (_message.Message,), - dict( - DESCRIPTOR=_JOB, - __module__="google.cloud.scheduler_v1.proto.job_pb2", - __doc__="""Configuration for a job. The maximum allowed size for a job is 100KB. - Attributes: - name: - Optionally caller-specified in [CreateJob][google.cloud.schedu - ler.v1.CloudScheduler.CreateJob], after which it becomes - output only. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - - ``PROJECT_ID`` can contain letters ([A-Za-z]), numbers - ([0-9]), hyphens (-), colons (:), or periods (.). For more - information, see `Identifying projects - `__ - ``LOCATION_ID`` - is the canonical ID for the job's location. The list of - available locations can be obtained by calling [ListLocatio - ns][google.cloud.location.Locations.ListLocations]. For - more information, see - https://cloud.google.com/about/locations/. - ``JOB_ID`` can - contain only letters ([A-Za-z]), numbers ([0-9]), hyphens - (-), or underscores (\_). The maximum length is 500 - characters. - description: - Optionally caller-specified in [CreateJob][google.cloud.schedu - ler.v1.CloudScheduler.CreateJob] or [UpdateJob][google.cloud.s - cheduler.v1.CloudScheduler.UpdateJob]. A human-readable - description for the job. This string must not contain more - than 500 characters. - target: - Required. Delivery settings containing destination and - parameters. - pubsub_target: - Pub/Sub target. - app_engine_http_target: - App Engine HTTP target. - http_target: - HTTP target. - schedule: - Required, except when used with [UpdateJob][google.cloud.sched - uler.v1.CloudScheduler.UpdateJob]. Describes the schedule on - which the job will be executed. The schedule can be either of - the following types: - `Crontab - `__ - English- - like `schedule - `__ As a general rule, execution ``n + 1`` of a job - will not begin until execution ``n`` has finished. Cloud - Scheduler will never allow two simultaneously outstanding - executions. For example, this implies that if the ``n+1``\ th - execution is scheduled to run at 16:00 but the ``n``\ th - execution takes until 16:15, the ``n+1``\ th execution will - not start until ``16:15``. A scheduled start time will be - delayed if the previous execution has not ended when its - scheduled time occurs. If [retry\_count][google.cloud.schedul - er.v1.RetryConfig.retry\_count] > 0 and a job attempt fails, - the job will be tried a total of [retry\_count][google.cloud.s - cheduler.v1.RetryConfig.retry\_count] times, with exponential - backoff, until the next scheduled start time. - time_zone: - Specifies the time zone to be used in interpreting - [schedule][google.cloud.scheduler.v1.Job.schedule]. The value - of this field must be a time zone name from the `tz database - `__. Note that some - time zones include a provision for daylight savings time. The - rules for daylight saving time are determined by the chosen - tz. For UTC use the string "utc". If a time zone is not - specified, the default will be in UTC (also known as GMT). - user_update_time: - Output only. The creation time of the job. - state: - Output only. State of the job. - status: - Output only. The response from the target for the last - attempted execution. - schedule_time: - Output only. The next time the job is scheduled. Note that - this may be a retry of a previously failed attempt or the next - execution time according to the schedule. - last_attempt_time: - Output only. The time the last job attempt started. - retry_config: - Settings that determine the retry behavior. - attempt_deadline: - The deadline for job attempts. If the request handler does not - respond by this deadline then the request is cancelled and the - attempt is marked as a ``DEADLINE_EXCEEDED`` failure. The - failed attempt can be viewed in execution logs. Cloud - Scheduler will retry the job according to the - [RetryConfig][google.cloud.scheduler.v1.RetryConfig]. The - allowed duration for this deadline is: \* For [HTTP - targets][google.cloud.scheduler.v1.Job.http\_target], between - 15 seconds and 30 minutes. \* For [App Engine HTTP targets][go - ogle.cloud.scheduler.v1.Job.app\_engine\_http\_target], - between 15 seconds and 24 hours. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.Job) - ), -) -_sym_db.RegisterMessage(Job) - -RetryConfig = _reflection.GeneratedProtocolMessageType( - "RetryConfig", - (_message.Message,), - dict( - DESCRIPTOR=_RETRYCONFIG, - __module__="google.cloud.scheduler_v1.proto.job_pb2", - __doc__="""Settings that determine the retry behavior. By default, if a job does - not complete successfully (meaning that an acknowledgement is not - received from the handler, then it will be retried with exponential - backoff according to the settings in - [RetryConfig][google.cloud.scheduler.v1.RetryConfig]. - Attributes: - retry_count: - The number of attempts that the system will make to run a job - using the exponential backoff procedure described by [max\_dou - blings][google.cloud.scheduler.v1.RetryConfig.max\_doublings]. - The default value of retry\_count is zero. If retry\_count is - zero, a job attempt will *not* be retried if it fails. Instead - the Cloud Scheduler system will wait for the next scheduled - execution time. If retry\_count is set to a non-zero number - then Cloud Scheduler will retry failed attempts, using - exponential backoff, retry\_count times, or until the next - scheduled execution time, whichever comes first. Values - greater than 5 and negative values are not allowed. - max_retry_duration: - The time limit for retrying a failed job, measured from time - when an execution was first attempted. If specified with [retr - y\_count][google.cloud.scheduler.v1.RetryConfig.retry\_count], - the job will be retried until both limits are reached. The - default value for max\_retry\_duration is zero, which means - retry duration is unlimited. - min_backoff_duration: - The minimum amount of time to wait before retrying a job after - it fails. The default value of this field is 5 seconds. - max_backoff_duration: - The maximum amount of time to wait before retrying a job after - it fails. The default value of this field is 1 hour. - max_doublings: - The time between retries will double ``max_doublings`` times. - A job's retry interval starts at [min\_backoff\_duration][goog - le.cloud.scheduler.v1.RetryConfig.min\_backoff\_duration], - then doubles ``max_doublings`` times, then increases linearly, - and finally retries retries at intervals of [max\_backoff\_dur - ation][google.cloud.scheduler.v1.RetryConfig.max\_backoff\_dur - ation] up to [retry\_count][google.cloud.scheduler.v1.RetryCon - fig.retry\_count] times. For example, if [min\_backoff\_durat - ion][google.cloud.scheduler.v1.RetryConfig.min\_backoff\_durat - ion] is 10s, [max\_backoff\_duration][google.cloud.scheduler.v - 1.RetryConfig.max\_backoff\_duration] is 300s, and - ``max_doublings`` is 3, then the a job will first be retried - in 10s. The retry interval will double three times, and then - increase linearly by 2^3 \* 10s. Finally, the job will retry - at intervals of [max\_backoff\_duration][google.cloud.schedule - r.v1.RetryConfig.max\_backoff\_duration] until the job has - been attempted [retry\_count][google.cloud.scheduler.v1.RetryC - onfig.retry\_count] times. Thus, the requests will retry at - 10s, 20s, 40s, 80s, 160s, 240s, 300s, 300s, .... The default - value of this field is 5. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.RetryConfig) - ), -) -_sym_db.RegisterMessage(RetryConfig) - - -DESCRIPTOR._options = None -_JOB._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/scheduler_v1/proto/job_pb2_grpc.py b/google/cloud/scheduler_v1/proto/job_pb2_grpc.py deleted file mode 100644 index 07cb78fe..00000000 --- a/google/cloud/scheduler_v1/proto/job_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/scheduler_v1/proto/target_pb2.py b/google/cloud/scheduler_v1/proto/target_pb2.py deleted file mode 100644 index 3baad34c..00000000 --- a/google/cloud/scheduler_v1/proto/target_pb2.py +++ /dev/null @@ -1,1171 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/scheduler_v1/proto/target.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/scheduler_v1/proto/target.proto", - package="google.cloud.scheduler.v1", - syntax="proto3", - serialized_options=_b( - "\n\035com.google.cloud.scheduler.v1B\013TargetProtoP\001ZBgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1;scheduler\352A@\n\033pubsub.googleapis.com/Topic\022!projects/{project}/topics/{topic}" - ), - serialized_pb=_b( - '\n,google/cloud/scheduler_v1/proto/target.proto\x12\x19google.cloud.scheduler.v1\x1a\x19google/api/resource.proto\x1a\x1cgoogle/api/annotations.proto"\xea\x02\n\nHttpTarget\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12:\n\x0bhttp_method\x18\x02 \x01(\x0e\x32%.google.cloud.scheduler.v1.HttpMethod\x12\x43\n\x07headers\x18\x03 \x03(\x0b\x32\x32.google.cloud.scheduler.v1.HttpTarget.HeadersEntry\x12\x0c\n\x04\x62ody\x18\x04 \x01(\x0c\x12<\n\x0boauth_token\x18\x05 \x01(\x0b\x32%.google.cloud.scheduler.v1.OAuthTokenH\x00\x12:\n\noidc_token\x18\x06 \x01(\x0b\x32$.google.cloud.scheduler.v1.OidcTokenH\x00\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x16\n\x14\x61uthorization_header"\xbc\x02\n\x13\x41ppEngineHttpTarget\x12:\n\x0bhttp_method\x18\x01 \x01(\x0e\x32%.google.cloud.scheduler.v1.HttpMethod\x12G\n\x12\x61pp_engine_routing\x18\x02 \x01(\x0b\x32+.google.cloud.scheduler.v1.AppEngineRouting\x12\x14\n\x0crelative_uri\x18\x03 \x01(\t\x12L\n\x07headers\x18\x04 \x03(\x0b\x32;.google.cloud.scheduler.v1.AppEngineHttpTarget.HeadersEntry\x12\x0c\n\x04\x62ody\x18\x05 \x01(\x0c\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xd2\x01\n\x0cPubsubTarget\x12\x34\n\ntopic_name\x18\x01 \x01(\tB \xfa\x41\x1d\n\x1bpubsub.googleapis.com/Topic\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\x12K\n\nattributes\x18\x04 \x03(\x0b\x32\x37.google.cloud.scheduler.v1.PubsubTarget.AttributesEntry\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"T\n\x10\x41ppEngineRouting\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\x12\x10\n\x08instance\x18\x03 \x01(\t\x12\x0c\n\x04host\x18\x04 \x01(\t":\n\nOAuthToken\x12\x1d\n\x15service_account_email\x18\x01 \x01(\t\x12\r\n\x05scope\x18\x02 \x01(\t"<\n\tOidcToken\x12\x1d\n\x15service_account_email\x18\x01 \x01(\t\x12\x10\n\x08\x61udience\x18\x02 \x01(\t*s\n\nHttpMethod\x12\x1b\n\x17HTTP_METHOD_UNSPECIFIED\x10\x00\x12\x08\n\x04POST\x10\x01\x12\x07\n\x03GET\x10\x02\x12\x08\n\x04HEAD\x10\x03\x12\x07\n\x03PUT\x10\x04\x12\n\n\x06\x44\x45LETE\x10\x05\x12\t\n\x05PATCH\x10\x06\x12\x0b\n\x07OPTIONS\x10\x07\x42\xb5\x01\n\x1d\x63om.google.cloud.scheduler.v1B\x0bTargetProtoP\x01ZBgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1;scheduler\xea\x41@\n\x1bpubsub.googleapis.com/Topic\x12!projects/{project}/topics/{topic}b\x06proto3' - ), - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - -_HTTPMETHOD = _descriptor.EnumDescriptor( - name="HttpMethod", - full_name="google.cloud.scheduler.v1.HttpMethod", - filename=None, - file=DESCRIPTOR, - values=[ - _descriptor.EnumValueDescriptor( - name="HTTP_METHOD_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - ), - _descriptor.EnumValueDescriptor( - name="POST", index=1, number=1, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="GET", index=2, number=2, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="HEAD", index=3, number=3, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="PUT", index=4, number=4, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="DELETE", index=5, number=5, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="PATCH", index=6, number=6, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="OPTIONS", index=7, number=7, serialized_options=None, type=None - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1237, - serialized_end=1352, -) -_sym_db.RegisterEnumDescriptor(_HTTPMETHOD) - -HttpMethod = enum_type_wrapper.EnumTypeWrapper(_HTTPMETHOD) -HTTP_METHOD_UNSPECIFIED = 0 -POST = 1 -GET = 2 -HEAD = 3 -PUT = 4 -DELETE = 5 -PATCH = 6 -OPTIONS = 7 - - -_HTTPTARGET_HEADERSENTRY = _descriptor.Descriptor( - name="HeadersEntry", - full_name="google.cloud.scheduler.v1.HttpTarget.HeadersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.scheduler.v1.HttpTarget.HeadersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.scheduler.v1.HttpTarget.HeadersEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=_b("8\001"), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=425, - serialized_end=471, -) - -_HTTPTARGET = _descriptor.Descriptor( - name="HttpTarget", - full_name="google.cloud.scheduler.v1.HttpTarget", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.scheduler.v1.HttpTarget.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="http_method", - full_name="google.cloud.scheduler.v1.HttpTarget.http_method", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="headers", - full_name="google.cloud.scheduler.v1.HttpTarget.headers", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="body", - full_name="google.cloud.scheduler.v1.HttpTarget.body", - index=3, - number=4, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b(""), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="oauth_token", - full_name="google.cloud.scheduler.v1.HttpTarget.oauth_token", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="oidc_token", - full_name="google.cloud.scheduler.v1.HttpTarget.oidc_token", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[_HTTPTARGET_HEADERSENTRY], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="authorization_header", - full_name="google.cloud.scheduler.v1.HttpTarget.authorization_header", - index=0, - containing_type=None, - fields=[], - ) - ], - serialized_start=133, - serialized_end=495, -) - - -_APPENGINEHTTPTARGET_HEADERSENTRY = _descriptor.Descriptor( - name="HeadersEntry", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.HeadersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.HeadersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.HeadersEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=_b("8\001"), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=425, - serialized_end=471, -) - -_APPENGINEHTTPTARGET = _descriptor.Descriptor( - name="AppEngineHttpTarget", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="http_method", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.http_method", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="app_engine_routing", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.app_engine_routing", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="relative_uri", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.relative_uri", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="headers", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.headers", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="body", - full_name="google.cloud.scheduler.v1.AppEngineHttpTarget.body", - index=4, - number=5, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b(""), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[_APPENGINEHTTPTARGET_HEADERSENTRY], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=498, - serialized_end=814, -) - - -_PUBSUBTARGET_ATTRIBUTESENTRY = _descriptor.Descriptor( - name="AttributesEntry", - full_name="google.cloud.scheduler.v1.PubsubTarget.AttributesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.scheduler.v1.PubsubTarget.AttributesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.scheduler.v1.PubsubTarget.AttributesEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=_b("8\001"), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=978, - serialized_end=1027, -) - -_PUBSUBTARGET = _descriptor.Descriptor( - name="PubsubTarget", - full_name="google.cloud.scheduler.v1.PubsubTarget", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="topic_name", - full_name="google.cloud.scheduler.v1.PubsubTarget.topic_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\372A\035\n\033pubsub.googleapis.com/Topic"), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.scheduler.v1.PubsubTarget.data", - index=1, - number=3, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b(""), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="attributes", - full_name="google.cloud.scheduler.v1.PubsubTarget.attributes", - index=2, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[_PUBSUBTARGET_ATTRIBUTESENTRY], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=817, - serialized_end=1027, -) - - -_APPENGINEROUTING = _descriptor.Descriptor( - name="AppEngineRouting", - full_name="google.cloud.scheduler.v1.AppEngineRouting", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="service", - full_name="google.cloud.scheduler.v1.AppEngineRouting.service", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.scheduler.v1.AppEngineRouting.version", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="instance", - full_name="google.cloud.scheduler.v1.AppEngineRouting.instance", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="host", - full_name="google.cloud.scheduler.v1.AppEngineRouting.host", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1029, - serialized_end=1113, -) - - -_OAUTHTOKEN = _descriptor.Descriptor( - name="OAuthToken", - full_name="google.cloud.scheduler.v1.OAuthToken", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="service_account_email", - full_name="google.cloud.scheduler.v1.OAuthToken.service_account_email", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="scope", - full_name="google.cloud.scheduler.v1.OAuthToken.scope", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1115, - serialized_end=1173, -) - - -_OIDCTOKEN = _descriptor.Descriptor( - name="OidcToken", - full_name="google.cloud.scheduler.v1.OidcToken", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="service_account_email", - full_name="google.cloud.scheduler.v1.OidcToken.service_account_email", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="audience", - full_name="google.cloud.scheduler.v1.OidcToken.audience", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1175, - serialized_end=1235, -) - -_HTTPTARGET_HEADERSENTRY.containing_type = _HTTPTARGET -_HTTPTARGET.fields_by_name["http_method"].enum_type = _HTTPMETHOD -_HTTPTARGET.fields_by_name["headers"].message_type = _HTTPTARGET_HEADERSENTRY -_HTTPTARGET.fields_by_name["oauth_token"].message_type = _OAUTHTOKEN -_HTTPTARGET.fields_by_name["oidc_token"].message_type = _OIDCTOKEN -_HTTPTARGET.oneofs_by_name["authorization_header"].fields.append( - _HTTPTARGET.fields_by_name["oauth_token"] -) -_HTTPTARGET.fields_by_name["oauth_token"].containing_oneof = _HTTPTARGET.oneofs_by_name[ - "authorization_header" -] -_HTTPTARGET.oneofs_by_name["authorization_header"].fields.append( - _HTTPTARGET.fields_by_name["oidc_token"] -) -_HTTPTARGET.fields_by_name["oidc_token"].containing_oneof = _HTTPTARGET.oneofs_by_name[ - "authorization_header" -] -_APPENGINEHTTPTARGET_HEADERSENTRY.containing_type = _APPENGINEHTTPTARGET -_APPENGINEHTTPTARGET.fields_by_name["http_method"].enum_type = _HTTPMETHOD -_APPENGINEHTTPTARGET.fields_by_name[ - "app_engine_routing" -].message_type = _APPENGINEROUTING -_APPENGINEHTTPTARGET.fields_by_name[ - "headers" -].message_type = _APPENGINEHTTPTARGET_HEADERSENTRY -_PUBSUBTARGET_ATTRIBUTESENTRY.containing_type = _PUBSUBTARGET -_PUBSUBTARGET.fields_by_name["attributes"].message_type = _PUBSUBTARGET_ATTRIBUTESENTRY -DESCRIPTOR.message_types_by_name["HttpTarget"] = _HTTPTARGET -DESCRIPTOR.message_types_by_name["AppEngineHttpTarget"] = _APPENGINEHTTPTARGET -DESCRIPTOR.message_types_by_name["PubsubTarget"] = _PUBSUBTARGET -DESCRIPTOR.message_types_by_name["AppEngineRouting"] = _APPENGINEROUTING -DESCRIPTOR.message_types_by_name["OAuthToken"] = _OAUTHTOKEN -DESCRIPTOR.message_types_by_name["OidcToken"] = _OIDCTOKEN -DESCRIPTOR.enum_types_by_name["HttpMethod"] = _HTTPMETHOD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -HttpTarget = _reflection.GeneratedProtocolMessageType( - "HttpTarget", - (_message.Message,), - dict( - HeadersEntry=_reflection.GeneratedProtocolMessageType( - "HeadersEntry", - (_message.Message,), - dict( - DESCRIPTOR=_HTTPTARGET_HEADERSENTRY, - __module__="google.cloud.scheduler_v1.proto.target_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.HttpTarget.HeadersEntry) - ), - ), - DESCRIPTOR=_HTTPTARGET, - __module__="google.cloud.scheduler_v1.proto.target_pb2", - __doc__="""Http target. The job will be pushed to the job handler by means of an - HTTP request via an - [http\_method][google.cloud.scheduler.v1.HttpTarget.http\_method] such - as HTTP POST, HTTP GET, etc. The job is acknowledged by means of an - HTTP response code in the range [200 - 299]. A failure to receive a - response constitutes a failed execution. For a redirected request, the - response returned by the redirected request is considered. - Attributes: - uri: - Required. The full URI path that the request will be sent to. - This string must begin with either "https://" or "https://". - Some examples of valid values for - [uri][google.cloud.scheduler.v1.HttpTarget.uri] are: - ``http://acme.com`` and ``https://acme.com/sales:8080``. Cloud - Scheduler will encode some characters for safety and - compatibility. The maximum allowed URL length is 2083 - characters after encoding. - http_method: - Which HTTP method to use for the request. - headers: - The user can specify HTTP request headers to send with the - job's HTTP request. This map contains the header field names - and values. Repeated headers are not supported, but a header - value can contain commas. These headers represent a subset of - the headers that will accompany the job's HTTP request. Some - HTTP request headers will be ignored or replaced. A partial - list of headers that will be ignored or replaced is below: - - Host: This will be computed by Cloud Scheduler and derived - from [uri][google.cloud.scheduler.v1.HttpTarget.uri]. \* - ``Content-Length``: This will be computed by Cloud Scheduler. - \* ``User-Agent``: This will be set to ``"Google-Cloud- - Scheduler"``. \* ``X-Google-*``: Google internal use only. \* - ``X-AppEngine-*``: Google internal use only. The total size - of headers must be less than 80KB. - body: - HTTP request body. A request body is allowed only if the HTTP - method is POST, PUT, or PATCH. It is an error to set body on a - job with an incompatible - [HttpMethod][google.cloud.scheduler.v1.HttpMethod]. - authorization_header: - The mode for generating an ``Authorization`` header for HTTP - requests. If specified, all ``Authorization`` headers in the - [HttpTarget.headers][google.cloud.scheduler.v1.HttpTarget.head - ers] field will be overridden. - oauth_token: - If specified, an `OAuth token - `__ - will be generated and attached as an ``Authorization`` header - in the HTTP request. This type of authorization should - generally only be used when calling Google APIs hosted on - \*.googleapis.com. - oidc_token: - If specified, an `OIDC `__ token will be generated and - attached as an ``Authorization`` header in the HTTP request. - This type of authorization can be used for many scenarios, - including calling Cloud Run, or endpoints where you intend to - validate the token yourself. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.HttpTarget) - ), -) -_sym_db.RegisterMessage(HttpTarget) -_sym_db.RegisterMessage(HttpTarget.HeadersEntry) - -AppEngineHttpTarget = _reflection.GeneratedProtocolMessageType( - "AppEngineHttpTarget", - (_message.Message,), - dict( - HeadersEntry=_reflection.GeneratedProtocolMessageType( - "HeadersEntry", - (_message.Message,), - dict( - DESCRIPTOR=_APPENGINEHTTPTARGET_HEADERSENTRY, - __module__="google.cloud.scheduler_v1.proto.target_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.AppEngineHttpTarget.HeadersEntry) - ), - ), - DESCRIPTOR=_APPENGINEHTTPTARGET, - __module__="google.cloud.scheduler_v1.proto.target_pb2", - __doc__="""App Engine target. The job will be pushed to a job handler by means of - an HTTP request via an [http\_method][google.cloud.scheduler.v1.AppEng - ineHttpTarget.http\_method] such as HTTP POST, HTTP GET, etc. The job - is acknowledged by means of an HTTP response code in the range [200 - - 299]. Error 503 is considered an App Engine system error instead of an - application error. Requests returning error 503 will be retried - regardless of retry configuration and not counted against retry - counts. Any other response code, or a failure to receive a response - before the deadline, constitutes a failed attempt. - Attributes: - http_method: - The HTTP method to use for the request. PATCH and OPTIONS are - not permitted. - app_engine_routing: - App Engine Routing setting for the job. - relative_uri: - The relative URI. The relative URL must begin with "/" and - must be a valid HTTP relative URL. It can contain a path, - query string arguments, and ``#`` fragments. If the relative - URL is empty, then the root path "/" will be used. No spaces - are allowed, and the maximum length allowed is 2083 - characters. - headers: - HTTP request headers. This map contains the header field - names and values. Headers can be set when the job is created. - Cloud Scheduler sets some headers to default values: - - ``User-Agent``: By default, this header is ``"AppEngine- - Google; (+http://code.google.com/appengine)"``. This header - can be modified, but Cloud Scheduler will append - ``"AppEngine-Google; (+http://code.google.com/appengine)"`` to - the modified ``User-Agent``. - ``X-CloudScheduler``: This - header will be set to true. If the job has an - [body][google.cloud.scheduler.v1.AppEngineHttpTarget.body], - Cloud Scheduler sets the following headers: - ``Content- - Type``: By default, the ``Content-Type`` header is set to - ``"application/octet-stream"``. The default can be overridden - by explictly setting ``Content-Type`` to a particular media - type when the job is created. For example, ``Content-Type`` - can be set to ``"application/json"``. - ``Content- - Length``: This is computed by Cloud Scheduler. This value - is output only. It cannot be changed. The headers below are - output only. They cannot be set or overridden: - - ``X-Google-*``: For Google internal use only. - - ``X-AppEngine-*``: For Google internal use only. In addition, - some App Engine headers, which contain job-specific - information, are also be sent to the job handler. - body: - Body. HTTP request body. A request body is allowed only if - the HTTP method is POST or PUT. It will result in invalid - argument error to set a body on a job with an incompatible - [HttpMethod][google.cloud.scheduler.v1.HttpMethod]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.AppEngineHttpTarget) - ), -) -_sym_db.RegisterMessage(AppEngineHttpTarget) -_sym_db.RegisterMessage(AppEngineHttpTarget.HeadersEntry) - -PubsubTarget = _reflection.GeneratedProtocolMessageType( - "PubsubTarget", - (_message.Message,), - dict( - AttributesEntry=_reflection.GeneratedProtocolMessageType( - "AttributesEntry", - (_message.Message,), - dict( - DESCRIPTOR=_PUBSUBTARGET_ATTRIBUTESENTRY, - __module__="google.cloud.scheduler_v1.proto.target_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.PubsubTarget.AttributesEntry) - ), - ), - DESCRIPTOR=_PUBSUBTARGET, - __module__="google.cloud.scheduler_v1.proto.target_pb2", - __doc__="""Pub/Sub target. The job will be delivered by publishing a message to - the given Pub/Sub topic. - Attributes: - topic_name: - Required. The name of the Cloud Pub/Sub topic to which - messages will be published when a job is delivered. The topic - name must be in the same format as required by PubSub's - `PublishRequest.name `__, for example - ``projects/PROJECT_ID/topics/TOPIC_ID``. The topic must be in - the same project as the Cloud Scheduler job. - data: - The message payload for PubsubMessage. Pubsub message must - contain either non-empty data, or at least one attribute. - attributes: - Attributes for PubsubMessage. Pubsub message must contain - either non-empty data, or at least one attribute. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.PubsubTarget) - ), -) -_sym_db.RegisterMessage(PubsubTarget) -_sym_db.RegisterMessage(PubsubTarget.AttributesEntry) - -AppEngineRouting = _reflection.GeneratedProtocolMessageType( - "AppEngineRouting", - (_message.Message,), - dict( - DESCRIPTOR=_APPENGINEROUTING, - __module__="google.cloud.scheduler_v1.proto.target_pb2", - __doc__="""App Engine Routing. For more information about services, versions, - and instances see `An Overview of App Engine - `__, `Microservices Architecture on Google App Engine - `__, `App Engine Standard request routing - `__, and `App Engine Flex request routing - `__. - Attributes: - service: - App service. By default, the job is sent to the service which - is the default service when the job is attempted. - version: - App version. By default, the job is sent to the version which - is the default version when the job is attempted. - instance: - App instance. By default, the job is sent to an instance - which is available when the job is attempted. Requests can - only be sent to a specific instance if `manual scaling is used - in App Engine Standard - `__. - App Engine Flex does not support instances. For more - information, see `App Engine Standard request routing - `__ and `App Engine Flex request routing - `__. - host: - Output only. The host that the job is sent to. For more - information about how App Engine requests are routed, see - `here - `__. The host is constructed as: - - ``host = [application_domain_name]``\ ``| [service] + '.' - + [application_domain_name]``\ ``| [version] + '.' + - [application_domain_name]``\ ``| [version_dot_service]+ - '.' + [application_domain_name]``\ ``| [instance] + '.' + - [application_domain_name]``\ ``| [instance_dot_service] + - '.' + [application_domain_name]``\ ``| - [instance_dot_version] + '.' + [application_domain_name]``\ - ``| [instance_dot_version_dot_service] + '.' + - [application_domain_name]`` - ``application_domain_name`` = - The domain name of the app, for example .appspot.com, which - is associated with the job's project ID. - ``service =`` - [service][google.cloud.scheduler.v1.AppEngineRouting.service] - - ``version =`` - [version][google.cloud.scheduler.v1.AppEngineRouting.version] - - ``version_dot_service =`` - [version][google.cloud.scheduler.v1.AppEngineRouting.version] - ``+ '.' +`` - [service][google.cloud.scheduler.v1.AppEngineRouting.service] - - ``instance =`` [instance][google.cloud.scheduler.v1.AppE - ngineRouting.instance] - ``instance_dot_service =`` [inst - ance][google.cloud.scheduler.v1.AppEngineRouting.instance] - ``+ '.' +`` - [service][google.cloud.scheduler.v1.AppEngineRouting.service] - - ``instance_dot_version =`` [instance][google.cloud.sched - uler.v1.AppEngineRouting.instance] ``+ '.' +`` - [version][google.cloud.scheduler.v1.AppEngineRouting.version] - - ``instance_dot_version_dot_service =`` [instance][google - .cloud.scheduler.v1.AppEngineRouting.instance] ``+ '.' +`` - [version][google.cloud.scheduler.v1.AppEngineRouting.version] - ``+ '.' +`` - [service][google.cloud.scheduler.v1.AppEngineRouting.service] - If - [service][google.cloud.scheduler.v1.AppEngineRouting.service] - is empty, then the job will be sent to the service which is - the default service when the job is attempted. If - [version][google.cloud.scheduler.v1.AppEngineRouting.version] - is empty, then the job will be sent to the version which is - the default version when the job is attempted. If [instance][ - google.cloud.scheduler.v1.AppEngineRouting.instance] is empty, - then the job will be sent to an instance which is available - when the job is attempted. If - [service][google.cloud.scheduler.v1.AppEngineRouting.service], - [version][google.cloud.scheduler.v1.AppEngineRouting.version], - or [instance][google.cloud.scheduler.v1.AppEngineRouting.insta - nce] is invalid, then the job will be sent to the default - version of the default service when the job is attempted. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.AppEngineRouting) - ), -) -_sym_db.RegisterMessage(AppEngineRouting) - -OAuthToken = _reflection.GeneratedProtocolMessageType( - "OAuthToken", - (_message.Message,), - dict( - DESCRIPTOR=_OAUTHTOKEN, - __module__="google.cloud.scheduler_v1.proto.target_pb2", - __doc__="""Contains information needed for generating an `OAuth token - `__. This - type of authorization should generally only be used when calling - Google APIs hosted on \*.googleapis.com. - Attributes: - service_account_email: - \ `Service account email - `__ to be - used for generating OAuth token. The service account must be - within the same project as the job. The caller must have - iam.serviceAccounts.actAs permission for the service account. - scope: - OAuth scope to be used for generating OAuth access token. If - not specified, "https://www.googleapis.com/auth/cloud- - platform" will be used. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.OAuthToken) - ), -) -_sym_db.RegisterMessage(OAuthToken) - -OidcToken = _reflection.GeneratedProtocolMessageType( - "OidcToken", - (_message.Message,), - dict( - DESCRIPTOR=_OIDCTOKEN, - __module__="google.cloud.scheduler_v1.proto.target_pb2", - __doc__="""Contains information needed for generating an `OpenID Connect token - `__. - This type of authorization can be used for many scenarios, including - calling Cloud Run, or endpoints where you intend to validate the token - yourself. - Attributes: - service_account_email: - \ `Service account email - `__ to be - used for generating OIDC token. The service account must be - within the same project as the job. The caller must have - iam.serviceAccounts.actAs permission for the service account. - audience: - Audience to be used when generating OIDC token. If not - specified, the URI specified in target will be used. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.OidcToken) - ), -) -_sym_db.RegisterMessage(OidcToken) - - -DESCRIPTOR._options = None -_HTTPTARGET_HEADERSENTRY._options = None -_APPENGINEHTTPTARGET_HEADERSENTRY._options = None -_PUBSUBTARGET_ATTRIBUTESENTRY._options = None -_PUBSUBTARGET.fields_by_name["topic_name"]._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/scheduler_v1/proto/target_pb2_grpc.py b/google/cloud/scheduler_v1/proto/target_pb2_grpc.py deleted file mode 100644 index 07cb78fe..00000000 --- a/google/cloud/scheduler_v1/proto/target_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/scheduler_v1/py.typed b/google/cloud/scheduler_v1/py.typed new file mode 100644 index 00000000..ca4d524b --- /dev/null +++ b/google/cloud/scheduler_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-scheduler package uses inline types. diff --git a/google/cloud/scheduler.py b/google/cloud/scheduler_v1/services/__init__.py similarity index 65% rename from google/cloud/scheduler.py rename to google/cloud/scheduler_v1/services/__init__.py index bfa82a79..42ffdf2b 100644 --- a/google/cloud/scheduler.py +++ b/google/cloud/scheduler_v1/services/__init__.py @@ -1,25 +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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import - -from google.cloud.scheduler_v1 import CloudSchedulerClient -from google.cloud.scheduler_v1 import enums -from google.cloud.scheduler_v1 import types - - -__all__ = ("enums", "types", "CloudSchedulerClient") +# diff --git a/google/__init__.py b/google/cloud/scheduler_v1/services/cloud_scheduler/__init__.py similarity index 71% rename from google/__init__.py rename to google/cloud/scheduler_v1/services/cloud_scheduler/__init__.py index 9a1b64a6..7c90126a 100644 --- a/google/__init__.py +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import CloudSchedulerClient +from .async_client import CloudSchedulerAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "CloudSchedulerClient", + "CloudSchedulerAsyncClient", +) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/async_client.py b/google/cloud/scheduler_v1/services/cloud_scheduler/async_client.py new file mode 100644 index 00000000..a226291f --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/async_client.py @@ -0,0 +1,781 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.scheduler_v1.services.cloud_scheduler import pagers +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job +from google.cloud.scheduler_v1.types import job as gcs_job +from google.cloud.scheduler_v1.types import target +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import CloudSchedulerTransport +from .transports.grpc_asyncio import CloudSchedulerGrpcAsyncIOTransport +from .client import CloudSchedulerClient + + +class CloudSchedulerAsyncClient: + """The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + """ + + _client: CloudSchedulerClient + + DEFAULT_ENDPOINT = CloudSchedulerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudSchedulerClient.DEFAULT_MTLS_ENDPOINT + + job_path = staticmethod(CloudSchedulerClient.job_path) + + from_service_account_file = CloudSchedulerClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(CloudSchedulerClient).get_transport_class, type(CloudSchedulerClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, CloudSchedulerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the cloud scheduler 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, ~.CloudSchedulerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = CloudSchedulerClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def list_jobs( + self, + request: cloudscheduler.ListJobsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListJobsAsyncPager: + r"""Lists jobs. + + Args: + request (:class:`~.cloudscheduler.ListJobsRequest`): + The request object. Request message for listing jobs + using + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + 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: + ~.pagers.ListJobsAsyncPager: + Response message for listing jobs using + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.ListJobsRequest(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_jobs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_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.ListJobsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_job( + self, + request: cloudscheduler.GetJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Gets a job. + + Args: + request (:class:`~.cloudscheduler.GetJobRequest`): + The request object. Request message for + [GetJob][google.cloud.scheduler.v1.CloudScheduler.GetJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.GetJobRequest(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_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_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 create_job( + self, + request: cloudscheduler.CreateJobRequest = None, + *, + parent: str = None, + job: gcs_job.Job = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Creates a job. + + Args: + request (:class:`~.cloudscheduler.CreateJobRequest`): + The request object. Request message for + [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + job (:class:`~.gcs_job.Job`): + Required. The job to add. The user can optionally + specify a name for the job in + [name][google.cloud.scheduler.v1.Job.name]. + [name][google.cloud.scheduler.v1.Job.name] cannot be the + same as an existing job. If a name is not specified then + the system will generate a random unique name that will + be returned ([name][google.cloud.scheduler.v1.Job.name]) + in the response. + This corresponds to the ``job`` 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, job]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.CreateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if job is not None: + request.job = job + + # 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_job, + default_timeout=600.0, + client_info=_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 update_job( + self, + request: cloudscheduler.UpdateJobRequest = None, + *, + job: gcs_job.Job = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Updates a job. + + If successful, the updated [Job][google.cloud.scheduler.v1.Job] + is returned. If the job does not exist, ``NOT_FOUND`` is + returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Args: + request (:class:`~.cloudscheduler.UpdateJobRequest`): + The request object. Request message for + [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. + job (:class:`~.gcs_job.Job`): + Required. The new job properties. + [name][google.cloud.scheduler.v1.Job.name] must be + specified. + + Output only fields cannot be modified using UpdateJob. + Any value specified for an output only field will be + ignored. + This corresponds to the ``job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + A mask used to specify which fields + of the job are being 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([job, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.UpdateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if job is not None: + request.job = job + 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_job, + default_timeout=600.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("job.name", request.job.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_job( + self, + request: cloudscheduler.DeleteJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a job. + + Args: + request (:class:`~.cloudscheduler.DeleteJobRequest`): + The request object. Request message for deleting a job + using + [DeleteJob][google.cloud.scheduler.v1.CloudScheduler.DeleteJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.DeleteJobRequest(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_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def pause_job( + self, + request: cloudscheduler.PauseJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1.Job.state]; if paused it will + be set to + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED] + to be paused. + + Args: + request (:class:`~.cloudscheduler.PauseJobRequest`): + The request object. Request message for + [PauseJob][google.cloud.scheduler.v1.CloudScheduler.PauseJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.PauseJobRequest(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.pause_job, + default_timeout=600.0, + client_info=_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 resume_job( + self, + request: cloudscheduler.ResumeJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1.Job.state]; after calling + this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED] + to be resumed. + + Args: + request (:class:`~.cloudscheduler.ResumeJobRequest`): + The request object. Request message for + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.ResumeJobRequest(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.resume_job, + default_timeout=600.0, + client_info=_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 run_job( + self, + request: cloudscheduler.RunJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Args: + request (:class:`~.cloudscheduler.RunJobRequest`): + The request object. Request message for forcing a job to + run now using + [RunJob][google.cloud.scheduler.v1.CloudScheduler.RunJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.RunJobRequest(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.run_job, + default_timeout=600.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-scheduler",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("CloudSchedulerAsyncClient",) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/client.py b/google/cloud/scheduler_v1/services/cloud_scheduler/client.py new file mode 100644 index 00000000..87ff6565 --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/client.py @@ -0,0 +1,913 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.scheduler_v1.services.cloud_scheduler import pagers +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job +from google.cloud.scheduler_v1.types import job as gcs_job +from google.cloud.scheduler_v1.types import target +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import CloudSchedulerTransport +from .transports.grpc import CloudSchedulerGrpcTransport +from .transports.grpc_asyncio import CloudSchedulerGrpcAsyncIOTransport + + +class CloudSchedulerClientMeta(type): + """Metaclass for the CloudScheduler 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[CloudSchedulerTransport]] + _transport_registry["grpc"] = CloudSchedulerGrpcTransport + _transport_registry["grpc_asyncio"] = CloudSchedulerGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[CloudSchedulerTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudSchedulerClient(metaclass=CloudSchedulerClientMeta): + """The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudscheduler.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def job_path(project: str, location: str, job: str,) -> str: + """Return a fully-qualified job string.""" + return "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, location=location, job=job, + ) + + @staticmethod + def parse_job_path(path: str) -> Dict[str, str]: + """Parse a job path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, CloudSchedulerTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the cloud scheduler 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, ~.CloudSchedulerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CloudSchedulerTransport): + # transport is a CloudSchedulerTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def list_jobs( + self, + request: cloudscheduler.ListJobsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListJobsPager: + r"""Lists jobs. + + Args: + request (:class:`~.cloudscheduler.ListJobsRequest`): + The request object. Request message for listing jobs + using + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + 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: + ~.pagers.ListJobsPager: + Response message for listing jobs using + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + + 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 cloudscheduler.ListJobsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.ListJobsRequest): + request = cloudscheduler.ListJobsRequest(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_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.ListJobsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_job( + self, + request: cloudscheduler.GetJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Gets a job. + + Args: + request (:class:`~.cloudscheduler.GetJobRequest`): + The request object. Request message for + [GetJob][google.cloud.scheduler.v1.CloudScheduler.GetJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.GetJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.GetJobRequest): + request = cloudscheduler.GetJobRequest(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_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 create_job( + self, + request: cloudscheduler.CreateJobRequest = None, + *, + parent: str = None, + job: gcs_job.Job = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Creates a job. + + Args: + request (:class:`~.cloudscheduler.CreateJobRequest`): + The request object. Request message for + [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + job (:class:`~.gcs_job.Job`): + Required. The job to add. The user can optionally + specify a name for the job in + [name][google.cloud.scheduler.v1.Job.name]. + [name][google.cloud.scheduler.v1.Job.name] cannot be the + same as an existing job. If a name is not specified then + the system will generate a random unique name that will + be returned ([name][google.cloud.scheduler.v1.Job.name]) + in the response. + This corresponds to the ``job`` 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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, job]) + 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 cloudscheduler.CreateJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.CreateJobRequest): + request = cloudscheduler.CreateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if job is not None: + request.job = job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 update_job( + self, + request: cloudscheduler.UpdateJobRequest = None, + *, + job: gcs_job.Job = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Updates a job. + + If successful, the updated [Job][google.cloud.scheduler.v1.Job] + is returned. If the job does not exist, ``NOT_FOUND`` is + returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Args: + request (:class:`~.cloudscheduler.UpdateJobRequest`): + The request object. Request message for + [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. + job (:class:`~.gcs_job.Job`): + Required. The new job properties. + [name][google.cloud.scheduler.v1.Job.name] must be + specified. + + Output only fields cannot be modified using UpdateJob. + Any value specified for an output only field will be + ignored. + This corresponds to the ``job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + A mask used to specify which fields + of the job are being 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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([job, 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 cloudscheduler.UpdateJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.UpdateJobRequest): + request = cloudscheduler.UpdateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if job is not None: + request.job = job + 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_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("job.name", request.job.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_job( + self, + request: cloudscheduler.DeleteJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a job. + + Args: + request (:class:`~.cloudscheduler.DeleteJobRequest`): + The request object. Request message for deleting a job + using + [DeleteJob][google.cloud.scheduler.v1.CloudScheduler.DeleteJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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 cloudscheduler.DeleteJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.DeleteJobRequest): + request = cloudscheduler.DeleteJobRequest(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_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. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def pause_job( + self, + request: cloudscheduler.PauseJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1.Job.state]; if paused it will + be set to + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED] + to be paused. + + Args: + request (:class:`~.cloudscheduler.PauseJobRequest`): + The request object. Request message for + [PauseJob][google.cloud.scheduler.v1.CloudScheduler.PauseJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.PauseJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.PauseJobRequest): + request = cloudscheduler.PauseJobRequest(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.pause_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 resume_job( + self, + request: cloudscheduler.ResumeJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1.Job.state]; after calling + this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED] + to be resumed. + + Args: + request (:class:`~.cloudscheduler.ResumeJobRequest`): + The request object. Request message for + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.ResumeJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.ResumeJobRequest): + request = cloudscheduler.ResumeJobRequest(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.resume_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 run_job( + self, + request: cloudscheduler.RunJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Args: + request (:class:`~.cloudscheduler.RunJobRequest`): + The request object. Request message for forcing a job to + run now using + [RunJob][google.cloud.scheduler.v1.CloudScheduler.RunJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.RunJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.RunJobRequest): + request = cloudscheduler.RunJobRequest(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.run_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 + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-scheduler",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("CloudSchedulerClient",) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/pagers.py b/google/cloud/scheduler_v1/services/cloud_scheduler/pagers.py new file mode 100644 index 00000000..2417dde3 --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/pagers.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job + + +class ListJobsPager: + """A pager for iterating through ``list_jobs`` requests. + + This class thinly wraps an initial + :class:`~.cloudscheduler.ListJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListJobs`` requests and continue to iterate + through the ``jobs`` field on the + corresponding responses. + + All the usual :class:`~.cloudscheduler.ListJobsResponse` + 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[..., cloudscheduler.ListJobsResponse], + request: cloudscheduler.ListJobsRequest, + response: cloudscheduler.ListJobsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.cloudscheduler.ListJobsRequest`): + The initial request object. + response (:class:`~.cloudscheduler.ListJobsResponse`): + 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 = cloudscheduler.ListJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[cloudscheduler.ListJobsResponse]: + 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[job.Job]: + for page in self.pages: + yield from page.jobs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListJobsAsyncPager: + """A pager for iterating through ``list_jobs`` requests. + + This class thinly wraps an initial + :class:`~.cloudscheduler.ListJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListJobs`` requests and continue to iterate + through the ``jobs`` field on the + corresponding responses. + + All the usual :class:`~.cloudscheduler.ListJobsResponse` + 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[cloudscheduler.ListJobsResponse]], + request: cloudscheduler.ListJobsRequest, + response: cloudscheduler.ListJobsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.cloudscheduler.ListJobsRequest`): + The initial request object. + response (:class:`~.cloudscheduler.ListJobsResponse`): + 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 = cloudscheduler.ListJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[cloudscheduler.ListJobsResponse]: + 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[job.Job]: + async def async_generator(): + async for page in self.pages: + for response in page.jobs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/transports/__init__.py b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/__init__.py new file mode 100644 index 00000000..e9b56e23 --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudSchedulerTransport +from .grpc import CloudSchedulerGrpcTransport +from .grpc_asyncio import CloudSchedulerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CloudSchedulerTransport]] +_transport_registry["grpc"] = CloudSchedulerGrpcTransport +_transport_registry["grpc_asyncio"] = CloudSchedulerGrpcAsyncIOTransport + + +__all__ = ( + "CloudSchedulerTransport", + "CloudSchedulerGrpcTransport", + "CloudSchedulerGrpcAsyncIOTransport", +) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/transports/base.py b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/base.py new file mode 100644 index 00000000..f5cf4222 --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/base.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job +from google.cloud.scheduler_v1.types import job as gcs_job +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-scheduler",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class CloudSchedulerTransport(abc.ABC): + """Abstract transport class for CloudScheduler.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_jobs: gapic_v1.method.wrap_method( + self.list_jobs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.get_job: gapic_v1.method.wrap_method( + self.get_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.create_job: gapic_v1.method.wrap_method( + self.create_job, default_timeout=600.0, client_info=_client_info, + ), + self.update_job: gapic_v1.method.wrap_method( + self.update_job, default_timeout=600.0, client_info=_client_info, + ), + self.delete_job: gapic_v1.method.wrap_method( + self.delete_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.pause_job: gapic_v1.method.wrap_method( + self.pause_job, default_timeout=600.0, client_info=_client_info, + ), + self.resume_job: gapic_v1.method.wrap_method( + self.resume_job, default_timeout=600.0, client_info=_client_info, + ), + self.run_job: gapic_v1.method.wrap_method( + self.run_job, default_timeout=600.0, client_info=_client_info, + ), + } + + @property + def list_jobs( + self, + ) -> typing.Callable[ + [cloudscheduler.ListJobsRequest], + typing.Union[ + cloudscheduler.ListJobsResponse, + typing.Awaitable[cloudscheduler.ListJobsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_job( + self, + ) -> typing.Callable[ + [cloudscheduler.GetJobRequest], typing.Union[job.Job, typing.Awaitable[job.Job]] + ]: + raise NotImplementedError() + + @property + def create_job( + self, + ) -> typing.Callable[ + [cloudscheduler.CreateJobRequest], + typing.Union[gcs_job.Job, typing.Awaitable[gcs_job.Job]], + ]: + raise NotImplementedError() + + @property + def update_job( + self, + ) -> typing.Callable[ + [cloudscheduler.UpdateJobRequest], + typing.Union[gcs_job.Job, typing.Awaitable[gcs_job.Job]], + ]: + raise NotImplementedError() + + @property + def delete_job( + self, + ) -> typing.Callable[ + [cloudscheduler.DeleteJobRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def pause_job( + self, + ) -> typing.Callable[ + [cloudscheduler.PauseJobRequest], + typing.Union[job.Job, typing.Awaitable[job.Job]], + ]: + raise NotImplementedError() + + @property + def resume_job( + self, + ) -> typing.Callable[ + [cloudscheduler.ResumeJobRequest], + typing.Union[job.Job, typing.Awaitable[job.Job]], + ]: + raise NotImplementedError() + + @property + def run_job( + self, + ) -> typing.Callable[ + [cloudscheduler.RunJobRequest], typing.Union[job.Job, typing.Awaitable[job.Job]] + ]: + raise NotImplementedError() + + +__all__ = ("CloudSchedulerTransport",) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/transports/grpc.py b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/grpc.py new file mode 100644 index 00000000..1e0503cb --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/grpc.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. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job +from google.cloud.scheduler_v1.types import job as gcs_job +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import CloudSchedulerTransport + + +class CloudSchedulerGrpcTransport(CloudSchedulerTransport): + """gRPC backend transport for CloudScheduler. + + The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + + 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 = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_jobs( + self, + ) -> Callable[[cloudscheduler.ListJobsRequest], cloudscheduler.ListJobsResponse]: + r"""Return a callable for the list jobs method over gRPC. + + Lists jobs. + + Returns: + Callable[[~.ListJobsRequest], + ~.ListJobsResponse]: + 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_jobs" not in self._stubs: + self._stubs["list_jobs"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/ListJobs", + request_serializer=cloudscheduler.ListJobsRequest.serialize, + response_deserializer=cloudscheduler.ListJobsResponse.deserialize, + ) + return self._stubs["list_jobs"] + + @property + def get_job(self) -> Callable[[cloudscheduler.GetJobRequest], job.Job]: + r"""Return a callable for the get job method over gRPC. + + Gets a job. + + Returns: + Callable[[~.GetJobRequest], + ~.Job]: + 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_job" not in self._stubs: + self._stubs["get_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/GetJob", + request_serializer=cloudscheduler.GetJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["get_job"] + + @property + def create_job(self) -> Callable[[cloudscheduler.CreateJobRequest], gcs_job.Job]: + r"""Return a callable for the create job method over gRPC. + + Creates a job. + + Returns: + Callable[[~.CreateJobRequest], + ~.Job]: + 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_job" not in self._stubs: + self._stubs["create_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/CreateJob", + request_serializer=cloudscheduler.CreateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["create_job"] + + @property + def update_job(self) -> Callable[[cloudscheduler.UpdateJobRequest], gcs_job.Job]: + r"""Return a callable for the update job method over gRPC. + + Updates a job. + + If successful, the updated [Job][google.cloud.scheduler.v1.Job] + is returned. If the job does not exist, ``NOT_FOUND`` is + returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Returns: + Callable[[~.UpdateJobRequest], + ~.Job]: + 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_job" not in self._stubs: + self._stubs["update_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/UpdateJob", + request_serializer=cloudscheduler.UpdateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["update_job"] + + @property + def delete_job(self) -> Callable[[cloudscheduler.DeleteJobRequest], empty.Empty]: + r"""Return a callable for the delete job method over gRPC. + + Deletes a job. + + Returns: + Callable[[~.DeleteJobRequest], + ~.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_job" not in self._stubs: + self._stubs["delete_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/DeleteJob", + request_serializer=cloudscheduler.DeleteJobRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_job"] + + @property + def pause_job(self) -> Callable[[cloudscheduler.PauseJobRequest], job.Job]: + r"""Return a callable for the pause job method over gRPC. + + Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1.Job.state]; if paused it will + be set to + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED] + to be paused. + + Returns: + Callable[[~.PauseJobRequest], + ~.Job]: + 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 "pause_job" not in self._stubs: + self._stubs["pause_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/PauseJob", + request_serializer=cloudscheduler.PauseJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["pause_job"] + + @property + def resume_job(self) -> Callable[[cloudscheduler.ResumeJobRequest], job.Job]: + r"""Return a callable for the resume job method over gRPC. + + Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1.Job.state]; after calling + this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED] + to be resumed. + + Returns: + Callable[[~.ResumeJobRequest], + ~.Job]: + 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 "resume_job" not in self._stubs: + self._stubs["resume_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/ResumeJob", + request_serializer=cloudscheduler.ResumeJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["resume_job"] + + @property + def run_job(self) -> Callable[[cloudscheduler.RunJobRequest], job.Job]: + r"""Return a callable for the run job method over gRPC. + + Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Returns: + Callable[[~.RunJobRequest], + ~.Job]: + 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 "run_job" not in self._stubs: + self._stubs["run_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/RunJob", + request_serializer=cloudscheduler.RunJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["run_job"] + + +__all__ = ("CloudSchedulerGrpcTransport",) diff --git a/google/cloud/scheduler_v1/services/cloud_scheduler/transports/grpc_asyncio.py b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/grpc_asyncio.py new file mode 100644 index 00000000..29c9931e --- /dev/null +++ b/google/cloud/scheduler_v1/services/cloud_scheduler/transports/grpc_asyncio.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job +from google.cloud.scheduler_v1.types import job as gcs_job +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import CloudSchedulerTransport +from .grpc import CloudSchedulerGrpcTransport + + +class CloudSchedulerGrpcAsyncIOTransport(CloudSchedulerTransport): + """gRPC AsyncIO backend transport for CloudScheduler. + + The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + + 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 = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_jobs( + self, + ) -> Callable[ + [cloudscheduler.ListJobsRequest], Awaitable[cloudscheduler.ListJobsResponse] + ]: + r"""Return a callable for the list jobs method over gRPC. + + Lists jobs. + + Returns: + Callable[[~.ListJobsRequest], + Awaitable[~.ListJobsResponse]]: + 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_jobs" not in self._stubs: + self._stubs["list_jobs"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/ListJobs", + request_serializer=cloudscheduler.ListJobsRequest.serialize, + response_deserializer=cloudscheduler.ListJobsResponse.deserialize, + ) + return self._stubs["list_jobs"] + + @property + def get_job(self) -> Callable[[cloudscheduler.GetJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the get job method over gRPC. + + Gets a job. + + Returns: + Callable[[~.GetJobRequest], + Awaitable[~.Job]]: + 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_job" not in self._stubs: + self._stubs["get_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/GetJob", + request_serializer=cloudscheduler.GetJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["get_job"] + + @property + def create_job( + self, + ) -> Callable[[cloudscheduler.CreateJobRequest], Awaitable[gcs_job.Job]]: + r"""Return a callable for the create job method over gRPC. + + Creates a job. + + Returns: + Callable[[~.CreateJobRequest], + Awaitable[~.Job]]: + 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_job" not in self._stubs: + self._stubs["create_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/CreateJob", + request_serializer=cloudscheduler.CreateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["create_job"] + + @property + def update_job( + self, + ) -> Callable[[cloudscheduler.UpdateJobRequest], Awaitable[gcs_job.Job]]: + r"""Return a callable for the update job method over gRPC. + + Updates a job. + + If successful, the updated [Job][google.cloud.scheduler.v1.Job] + is returned. If the job does not exist, ``NOT_FOUND`` is + returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Returns: + Callable[[~.UpdateJobRequest], + Awaitable[~.Job]]: + 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_job" not in self._stubs: + self._stubs["update_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/UpdateJob", + request_serializer=cloudscheduler.UpdateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["update_job"] + + @property + def delete_job( + self, + ) -> Callable[[cloudscheduler.DeleteJobRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete job method over gRPC. + + Deletes a job. + + Returns: + Callable[[~.DeleteJobRequest], + 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_job" not in self._stubs: + self._stubs["delete_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/DeleteJob", + request_serializer=cloudscheduler.DeleteJobRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_job"] + + @property + def pause_job( + self, + ) -> Callable[[cloudscheduler.PauseJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the pause job method over gRPC. + + Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1.Job.state]; if paused it will + be set to + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED] + to be paused. + + Returns: + Callable[[~.PauseJobRequest], + Awaitable[~.Job]]: + 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 "pause_job" not in self._stubs: + self._stubs["pause_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/PauseJob", + request_serializer=cloudscheduler.PauseJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["pause_job"] + + @property + def resume_job( + self, + ) -> Callable[[cloudscheduler.ResumeJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the resume job method over gRPC. + + Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1.Job.state]; after calling + this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1.Job.State.PAUSED] + to be resumed. + + Returns: + Callable[[~.ResumeJobRequest], + Awaitable[~.Job]]: + 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 "resume_job" not in self._stubs: + self._stubs["resume_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/ResumeJob", + request_serializer=cloudscheduler.ResumeJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["resume_job"] + + @property + def run_job(self) -> Callable[[cloudscheduler.RunJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the run job method over gRPC. + + Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Returns: + Callable[[~.RunJobRequest], + Awaitable[~.Job]]: + 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 "run_job" not in self._stubs: + self._stubs["run_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1.CloudScheduler/RunJob", + request_serializer=cloudscheduler.RunJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["run_job"] + + +__all__ = ("CloudSchedulerGrpcAsyncIOTransport",) diff --git a/google/cloud/scheduler_v1/types.py b/google/cloud/scheduler_v1/types.py deleted file mode 100644 index 8646c06b..00000000 --- a/google/cloud/scheduler_v1/types.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.scheduler_v1.proto import cloudscheduler_pb2 -from google.cloud.scheduler_v1.proto import job_pb2 -from google.cloud.scheduler_v1.proto import target_pb2 -from google.protobuf import any_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 - - -_shared_modules = [ - any_pb2, - duration_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - status_pb2, -] - -_local_modules = [cloudscheduler_pb2, job_pb2, target_pb2] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.scheduler_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/scheduler_v1/types/__init__.py b/google/cloud/scheduler_v1/types/__init__.py new file mode 100644 index 00000000..53e55ca7 --- /dev/null +++ b/google/cloud/scheduler_v1/types/__init__.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .target import ( + HttpTarget, + AppEngineHttpTarget, + PubsubTarget, + AppEngineRouting, + OAuthToken, + OidcToken, +) +from .job import ( + Job, + RetryConfig, +) +from .cloudscheduler import ( + ListJobsRequest, + ListJobsResponse, + GetJobRequest, + CreateJobRequest, + UpdateJobRequest, + DeleteJobRequest, + PauseJobRequest, + ResumeJobRequest, + RunJobRequest, +) + + +__all__ = ( + "HttpTarget", + "AppEngineHttpTarget", + "PubsubTarget", + "AppEngineRouting", + "OAuthToken", + "OidcToken", + "Job", + "RetryConfig", + "ListJobsRequest", + "ListJobsResponse", + "GetJobRequest", + "CreateJobRequest", + "UpdateJobRequest", + "DeleteJobRequest", + "PauseJobRequest", + "ResumeJobRequest", + "RunJobRequest", +) diff --git a/google/cloud/scheduler_v1/types/cloudscheduler.py b/google/cloud/scheduler_v1/types/cloudscheduler.py new file mode 100644 index 00000000..b000f5aa --- /dev/null +++ b/google/cloud/scheduler_v1/types/cloudscheduler.py @@ -0,0 +1,218 @@ +# -*- 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.scheduler_v1.types import job as gcs_job +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.scheduler.v1", + manifest={ + "ListJobsRequest", + "ListJobsResponse", + "GetJobRequest", + "CreateJobRequest", + "UpdateJobRequest", + "DeleteJobRequest", + "PauseJobRequest", + "ResumeJobRequest", + "RunJobRequest", + }, +) + + +class ListJobsRequest(proto.Message): + r"""Request message for listing jobs using + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + + Attributes: + parent (str): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + page_size (int): + Requested page size. + + The maximum page size is 500. If unspecified, the page size + will be the maximum. Fewer jobs than requested might be + returned, even if more jobs exist; use next_page_token to + determine if more jobs exist. + page_token (str): + A token identifying a page of results the server will + return. To request the first page results, page_token must + be empty. To request the next page of results, page_token + must be the value of + [next_page_token][google.cloud.scheduler.v1.ListJobsResponse.next_page_token] + returned from the previous call to + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + It is an error to switch the value of + [filter][google.cloud.scheduler.v1.ListJobsRequest.filter] + or + [order_by][google.cloud.scheduler.v1.ListJobsRequest.order_by] + while iterating through pages. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=5) + + page_token = proto.Field(proto.STRING, number=6) + + +class ListJobsResponse(proto.Message): + r"""Response message for listing jobs using + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs]. + + Attributes: + jobs (Sequence[~.gcs_job.Job]): + The list of jobs. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + the + [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] + field in the subsequent call to + [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] + to retrieve the next page of results. If this is empty it + indicates that there are no more results through which to + paginate. + + The page token is valid for only 2 hours. + """ + + @property + def raw_page(self): + return self + + jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_job.Job,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetJobRequest(proto.Message): + r"""Request message for + [GetJob][google.cloud.scheduler.v1.CloudScheduler.GetJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateJobRequest(proto.Message): + r"""Request message for + [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob]. + + Attributes: + parent (str): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + job (~.gcs_job.Job): + Required. The job to add. The user can optionally specify a + name for the job in + [name][google.cloud.scheduler.v1.Job.name]. + [name][google.cloud.scheduler.v1.Job.name] cannot be the + same as an existing job. If a name is not specified then the + system will generate a random unique name that will be + returned ([name][google.cloud.scheduler.v1.Job.name]) in the + response. + """ + + parent = proto.Field(proto.STRING, number=1) + + job = proto.Field(proto.MESSAGE, number=2, message=gcs_job.Job,) + + +class UpdateJobRequest(proto.Message): + r"""Request message for + [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. + + Attributes: + job (~.gcs_job.Job): + Required. The new job properties. + [name][google.cloud.scheduler.v1.Job.name] must be + specified. + + Output only fields cannot be modified using UpdateJob. Any + value specified for an output only field will be ignored. + update_mask (~.field_mask.FieldMask): + A mask used to specify which fields of the + job are being updated. + """ + + job = proto.Field(proto.MESSAGE, number=1, message=gcs_job.Job,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteJobRequest(proto.Message): + r"""Request message for deleting a job using + [DeleteJob][google.cloud.scheduler.v1.CloudScheduler.DeleteJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class PauseJobRequest(proto.Message): + r"""Request message for + [PauseJob][google.cloud.scheduler.v1.CloudScheduler.PauseJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ResumeJobRequest(proto.Message): + r"""Request message for + [ResumeJob][google.cloud.scheduler.v1.CloudScheduler.ResumeJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class RunJobRequest(proto.Message): + r"""Request message for forcing a job to run now using + [RunJob][google.cloud.scheduler.v1.CloudScheduler.RunJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/scheduler_v1/types/job.py b/google/cloud/scheduler_v1/types/job.py new file mode 100644 index 00000000..269363ea --- /dev/null +++ b/google/cloud/scheduler_v1/types/job.py @@ -0,0 +1,285 @@ +# -*- 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.scheduler_v1.types import target +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as gr_status # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.scheduler.v1", manifest={"Job", "RetryConfig",}, +) + + +class Job(proto.Message): + r"""Configuration for a job. + The maximum allowed size for a job is 100KB. + + Attributes: + name (str): + Optionally caller-specified in + [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob], + after which it becomes output only. + + The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + + - ``PROJECT_ID`` can contain letters ([A-Za-z]), numbers + ([0-9]), hyphens (-), colons (:), or periods (.). For + more information, see `Identifying + projects `__ + - ``LOCATION_ID`` is the canonical ID for the job's + location. The list of available locations can be obtained + by calling + [ListLocations][google.cloud.location.Locations.ListLocations]. + For more information, see + https://cloud.google.com/about/locations/. + - ``JOB_ID`` can contain only letters ([A-Za-z]), numbers + ([0-9]), hyphens (-), or underscores (_). The maximum + length is 500 characters. + description (str): + Optionally caller-specified in + [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob] + or + [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. + + A human-readable description for the job. This string must + not contain more than 500 characters. + pubsub_target (~.target.PubsubTarget): + Pub/Sub target. + app_engine_http_target (~.target.AppEngineHttpTarget): + App Engine HTTP target. + http_target (~.target.HttpTarget): + HTTP target. + schedule (str): + Required, except when used with + [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. + + Describes the schedule on which the job will be executed. + + The schedule can be either of the following types: + + - `Crontab `__ + - English-like + `schedule `__ + + As a general rule, execution ``n + 1`` of a job will not + begin until execution ``n`` has finished. Cloud Scheduler + will never allow two simultaneously outstanding executions. + For example, this implies that if the ``n+1``\ th execution + is scheduled to run at 16:00 but the ``n``\ th execution + takes until 16:15, the ``n+1``\ th execution will not start + until ``16:15``. A scheduled start time will be delayed if + the previous execution has not ended when its scheduled time + occurs. + + If + [retry_count][google.cloud.scheduler.v1.RetryConfig.retry_count] + > 0 and a job attempt fails, the job will be tried a total + of + [retry_count][google.cloud.scheduler.v1.RetryConfig.retry_count] + times, with exponential backoff, until the next scheduled + start time. + time_zone (str): + Specifies the time zone to be used in interpreting + [schedule][google.cloud.scheduler.v1.Job.schedule]. The + value of this field must be a time zone name from the `tz + database `__. + + Note that some time zones include a provision for daylight + savings time. The rules for daylight saving time are + determined by the chosen tz. For UTC use the string "utc". + If a time zone is not specified, the default will be in UTC + (also known as GMT). + user_update_time (~.timestamp.Timestamp): + Output only. The creation time of the job. + state (~.job.Job.State): + Output only. State of the job. + status (~.gr_status.Status): + Output only. The response from the target for + the last attempted execution. + schedule_time (~.timestamp.Timestamp): + Output only. The next time the job is + scheduled. Note that this may be a retry of a + previously failed attempt or the next execution + time according to the schedule. + last_attempt_time (~.timestamp.Timestamp): + Output only. The time the last job attempt + started. + retry_config (~.job.RetryConfig): + Settings that determine the retry behavior. + attempt_deadline (~.duration.Duration): + The deadline for job attempts. If the request handler does + not respond by this deadline then the request is cancelled + and the attempt is marked as a ``DEADLINE_EXCEEDED`` + failure. The failed attempt can be viewed in execution logs. + Cloud Scheduler will retry the job according to the + [RetryConfig][google.cloud.scheduler.v1.RetryConfig]. + + The allowed duration for this deadline is: + + - For [HTTP + targets][google.cloud.scheduler.v1.Job.http_target], + between 15 seconds and 30 minutes. + - For [App Engine HTTP + targets][google.cloud.scheduler.v1.Job.app_engine_http_target], + between 15 seconds and 24 hours. + """ + + class State(proto.Enum): + r"""State of the job.""" + STATE_UNSPECIFIED = 0 + ENABLED = 1 + PAUSED = 2 + DISABLED = 3 + UPDATE_FAILED = 4 + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + pubsub_target = proto.Field( + proto.MESSAGE, number=4, oneof="target", message=target.PubsubTarget, + ) + + app_engine_http_target = proto.Field( + proto.MESSAGE, number=5, oneof="target", message=target.AppEngineHttpTarget, + ) + + http_target = proto.Field( + proto.MESSAGE, number=6, oneof="target", message=target.HttpTarget, + ) + + schedule = proto.Field(proto.STRING, number=20) + + time_zone = proto.Field(proto.STRING, number=21) + + user_update_time = proto.Field( + proto.MESSAGE, number=9, message=timestamp.Timestamp, + ) + + state = proto.Field(proto.ENUM, number=10, enum=State,) + + status = proto.Field(proto.MESSAGE, number=11, message=gr_status.Status,) + + schedule_time = proto.Field(proto.MESSAGE, number=17, message=timestamp.Timestamp,) + + last_attempt_time = proto.Field( + proto.MESSAGE, number=18, message=timestamp.Timestamp, + ) + + retry_config = proto.Field(proto.MESSAGE, number=19, message="RetryConfig",) + + attempt_deadline = proto.Field(proto.MESSAGE, number=22, message=duration.Duration,) + + +class RetryConfig(proto.Message): + r"""Settings that determine the retry behavior. + + By default, if a job does not complete successfully (meaning that an + acknowledgement is not received from the handler, then it will be + retried with exponential backoff according to the settings in + [RetryConfig][google.cloud.scheduler.v1.RetryConfig]. + + Attributes: + retry_count (int): + The number of attempts that the system will make to run a + job using the exponential backoff procedure described by + [max_doublings][google.cloud.scheduler.v1.RetryConfig.max_doublings]. + + The default value of retry_count is zero. + + If retry_count is zero, a job attempt will *not* be retried + if it fails. Instead the Cloud Scheduler system will wait + for the next scheduled execution time. + + If retry_count is set to a non-zero number then Cloud + Scheduler will retry failed attempts, using exponential + backoff, retry_count times, or until the next scheduled + execution time, whichever comes first. + + Values greater than 5 and negative values are not allowed. + max_retry_duration (~.duration.Duration): + The time limit for retrying a failed job, measured from time + when an execution was first attempted. If specified with + [retry_count][google.cloud.scheduler.v1.RetryConfig.retry_count], + the job will be retried until both limits are reached. + + The default value for max_retry_duration is zero, which + means retry duration is unlimited. + min_backoff_duration (~.duration.Duration): + The minimum amount of time to wait before + retrying a job after it fails. + + The default value of this field is 5 seconds. + max_backoff_duration (~.duration.Duration): + The maximum amount of time to wait before + retrying a job after it fails. + + The default value of this field is 1 hour. + max_doublings (int): + The time between retries will double ``max_doublings`` + times. + + A job's retry interval starts at + [min_backoff_duration][google.cloud.scheduler.v1.RetryConfig.min_backoff_duration], + then doubles ``max_doublings`` times, then increases + linearly, and finally retries retries at intervals of + [max_backoff_duration][google.cloud.scheduler.v1.RetryConfig.max_backoff_duration] + up to + [retry_count][google.cloud.scheduler.v1.RetryConfig.retry_count] + times. + + For example, if + [min_backoff_duration][google.cloud.scheduler.v1.RetryConfig.min_backoff_duration] + is 10s, + [max_backoff_duration][google.cloud.scheduler.v1.RetryConfig.max_backoff_duration] + is 300s, and ``max_doublings`` is 3, then the a job will + first be retried in 10s. The retry interval will double + three times, and then increase linearly by 2^3 \* 10s. + Finally, the job will retry at intervals of + [max_backoff_duration][google.cloud.scheduler.v1.RetryConfig.max_backoff_duration] + until the job has been attempted + [retry_count][google.cloud.scheduler.v1.RetryConfig.retry_count] + times. Thus, the requests will retry at 10s, 20s, 40s, 80s, + 160s, 240s, 300s, 300s, .... + + The default value of this field is 5. + """ + + retry_count = proto.Field(proto.INT32, number=1) + + max_retry_duration = proto.Field( + proto.MESSAGE, number=2, message=duration.Duration, + ) + + min_backoff_duration = proto.Field( + proto.MESSAGE, number=3, message=duration.Duration, + ) + + max_backoff_duration = proto.Field( + proto.MESSAGE, number=4, message=duration.Duration, + ) + + max_doublings = proto.Field(proto.INT32, number=5) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/scheduler_v1/types/target.py b/google/cloud/scheduler_v1/types/target.py new file mode 100644 index 00000000..ada2aafb --- /dev/null +++ b/google/cloud/scheduler_v1/types/target.py @@ -0,0 +1,425 @@ +# -*- 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.scheduler.v1", + manifest={ + "HttpMethod", + "HttpTarget", + "AppEngineHttpTarget", + "PubsubTarget", + "AppEngineRouting", + "OAuthToken", + "OidcToken", + }, +) + + +class HttpMethod(proto.Enum): + r"""The HTTP method used to execute the job.""" + HTTP_METHOD_UNSPECIFIED = 0 + POST = 1 + GET = 2 + HEAD = 3 + PUT = 4 + DELETE = 5 + PATCH = 6 + OPTIONS = 7 + + +class HttpTarget(proto.Message): + r"""Http target. The job will be pushed to the job handler by means of + an HTTP request via an + [http_method][google.cloud.scheduler.v1.HttpTarget.http_method] such + as HTTP POST, HTTP GET, etc. The job is acknowledged by means of an + HTTP response code in the range [200 - 299]. A failure to receive a + response constitutes a failed execution. For a redirected request, + the response returned by the redirected request is considered. + + Attributes: + uri (str): + Required. The full URI path that the request will be sent + to. This string must begin with either "https://" or + "https://". Some examples of valid values for + [uri][google.cloud.scheduler.v1.HttpTarget.uri] are: + ``http://acme.com`` and ``https://acme.com/sales:8080``. + Cloud Scheduler will encode some characters for safety and + compatibility. The maximum allowed URL length is 2083 + characters after encoding. + http_method (~.target.HttpMethod): + Which HTTP method to use for the request. + headers (Sequence[~.target.HttpTarget.HeadersEntry]): + The user can specify HTTP request headers to send with the + job's HTTP request. This map contains the header field names + and values. Repeated headers are not supported, but a header + value can contain commas. These headers represent a subset + of the headers that will accompany the job's HTTP request. + Some HTTP request headers will be ignored or replaced. A + partial list of headers that will be ignored or replaced is + below: + + - Host: This will be computed by Cloud Scheduler and + derived from + [uri][google.cloud.scheduler.v1.HttpTarget.uri]. + + - ``Content-Length``: This will be computed by Cloud + Scheduler. + - ``User-Agent``: This will be set to + ``"Google-Cloud-Scheduler"``. + - ``X-Google-*``: Google internal use only. + - ``X-AppEngine-*``: Google internal use only. + + The total size of headers must be less than 80KB. + body (bytes): + HTTP request body. A request body is allowed only if the + HTTP method is POST, PUT, or PATCH. It is an error to set + body on a job with an incompatible + [HttpMethod][google.cloud.scheduler.v1.HttpMethod]. + oauth_token (~.target.OAuthToken): + If specified, an `OAuth + token `__ + will be generated and attached as an ``Authorization`` + header in the HTTP request. + + This type of authorization should generally only be used + when calling Google APIs hosted on \*.googleapis.com. + oidc_token (~.target.OidcToken): + If specified, an + `OIDC `__ + token will be generated and attached as an ``Authorization`` + header in the HTTP request. + + This type of authorization can be used for many scenarios, + including calling Cloud Run, or endpoints where you intend + to validate the token yourself. + """ + + uri = proto.Field(proto.STRING, number=1) + + http_method = proto.Field(proto.ENUM, number=2, enum="HttpMethod",) + + headers = proto.MapField(proto.STRING, proto.STRING, number=3) + + body = proto.Field(proto.BYTES, number=4) + + oauth_token = proto.Field( + proto.MESSAGE, number=5, oneof="authorization_header", message="OAuthToken", + ) + + oidc_token = proto.Field( + proto.MESSAGE, number=6, oneof="authorization_header", message="OidcToken", + ) + + +class AppEngineHttpTarget(proto.Message): + r"""App Engine target. The job will be pushed to a job handler by means + of an HTTP request via an + [http_method][google.cloud.scheduler.v1.AppEngineHttpTarget.http_method] + such as HTTP POST, HTTP GET, etc. The job is acknowledged by means + of an HTTP response code in the range [200 - 299]. Error 503 is + considered an App Engine system error instead of an application + error. Requests returning error 503 will be retried regardless of + retry configuration and not counted against retry counts. Any other + response code, or a failure to receive a response before the + deadline, constitutes a failed attempt. + + Attributes: + http_method (~.target.HttpMethod): + The HTTP method to use for the request. PATCH + and OPTIONS are not permitted. + app_engine_routing (~.target.AppEngineRouting): + App Engine Routing setting for the job. + relative_uri (str): + The relative URI. + + The relative URL must begin with "/" and must be a valid + HTTP relative URL. It can contain a path, query string + arguments, and ``#`` fragments. If the relative URL is + empty, then the root path "/" will be used. No spaces are + allowed, and the maximum length allowed is 2083 characters. + headers (Sequence[~.target.AppEngineHttpTarget.HeadersEntry]): + HTTP request headers. + + This map contains the header field names and values. Headers + can be set when the job is created. + + Cloud Scheduler sets some headers to default values: + + - ``User-Agent``: By default, this header is + ``"AppEngine-Google; (+http://code.google.com/appengine)"``. + This header can be modified, but Cloud Scheduler will + append + ``"AppEngine-Google; (+http://code.google.com/appengine)"`` + to the modified ``User-Agent``. + - ``X-CloudScheduler``: This header will be set to true. + + If the job has an + [body][google.cloud.scheduler.v1.AppEngineHttpTarget.body], + Cloud Scheduler sets the following headers: + + - ``Content-Type``: By default, the ``Content-Type`` header + is set to ``"application/octet-stream"``. The default can + be overridden by explictly setting ``Content-Type`` to a + particular media type when the job is created. For + example, ``Content-Type`` can be set to + ``"application/json"``. + - ``Content-Length``: This is computed by Cloud Scheduler. + This value is output only. It cannot be changed. + + The headers below are output only. They cannot be set or + overridden: + + - ``X-Google-*``: For Google internal use only. + - ``X-AppEngine-*``: For Google internal use only. + + In addition, some App Engine headers, which contain + job-specific information, are also be sent to the job + handler. + body (bytes): + Body. + + HTTP request body. A request body is allowed only if the + HTTP method is POST or PUT. It will result in invalid + argument error to set a body on a job with an incompatible + [HttpMethod][google.cloud.scheduler.v1.HttpMethod]. + """ + + http_method = proto.Field(proto.ENUM, number=1, enum="HttpMethod",) + + app_engine_routing = proto.Field( + proto.MESSAGE, number=2, message="AppEngineRouting", + ) + + relative_uri = proto.Field(proto.STRING, number=3) + + headers = proto.MapField(proto.STRING, proto.STRING, number=4) + + body = proto.Field(proto.BYTES, number=5) + + +class PubsubTarget(proto.Message): + r"""Pub/Sub target. The job will be delivered by publishing a + message to the given Pub/Sub topic. + + Attributes: + topic_name (str): + Required. The name of the Cloud Pub/Sub topic to which + messages will be published when a job is delivered. The + topic name must be in the same format as required by + PubSub's + `PublishRequest.name `__, + for example ``projects/PROJECT_ID/topics/TOPIC_ID``. + + The topic must be in the same project as the Cloud Scheduler + job. + data (bytes): + The message payload for PubsubMessage. + Pubsub message must contain either non-empty + data, or at least one attribute. + attributes (Sequence[~.target.PubsubTarget.AttributesEntry]): + Attributes for PubsubMessage. + Pubsub message must contain either non-empty + data, or at least one attribute. + """ + + topic_name = proto.Field(proto.STRING, number=1) + + data = proto.Field(proto.BYTES, number=3) + + attributes = proto.MapField(proto.STRING, proto.STRING, number=4) + + +class AppEngineRouting(proto.Message): + r"""App Engine Routing. + + For more information about services, versions, and instances see `An + Overview of App + Engine `__, + `Microservices Architecture on Google App + Engine `__, + `App Engine Standard request + routing `__, + and `App Engine Flex request + routing `__. + + Attributes: + service (str): + App service. + By default, the job is sent to the service which + is the default service when the job is + attempted. + version (str): + App version. + By default, the job is sent to the version which + is the default version when the job is + attempted. + instance (str): + App instance. + + By default, the job is sent to an instance which is + available when the job is attempted. + + Requests can only be sent to a specific instance if `manual + scaling is used in App Engine + Standard `__. + App Engine Flex does not support instances. For more + information, see `App Engine Standard request + routing `__ + and `App Engine Flex request + routing `__. + host (str): + Output only. The host that the job is sent to. + + For more information about how App Engine requests are + routed, see + `here `__. + + The host is constructed as: + + - ``host = [application_domain_name]``\ + ``| [service] + '.' + [application_domain_name]``\ + ``| [version] + '.' + [application_domain_name]``\ + ``| [version_dot_service]+ '.' + [application_domain_name]``\ + ``| [instance] + '.' + [application_domain_name]``\ + ``| [instance_dot_service] + '.' + [application_domain_name]``\ + ``| [instance_dot_version] + '.' + [application_domain_name]``\ + ``| [instance_dot_version_dot_service] + '.' + [application_domain_name]`` + + - ``application_domain_name`` = The domain name of the app, + for example .appspot.com, which is associated with the + job's project ID. + + - ``service =`` + [service][google.cloud.scheduler.v1.AppEngineRouting.service] + + - ``version =`` + [version][google.cloud.scheduler.v1.AppEngineRouting.version] + + - ``version_dot_service =`` + [version][google.cloud.scheduler.v1.AppEngineRouting.version] + ``+ '.' +`` + [service][google.cloud.scheduler.v1.AppEngineRouting.service] + + - ``instance =`` + [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] + + - ``instance_dot_service =`` + [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] + ``+ '.' +`` + [service][google.cloud.scheduler.v1.AppEngineRouting.service] + + - ``instance_dot_version =`` + [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] + ``+ '.' +`` + [version][google.cloud.scheduler.v1.AppEngineRouting.version] + + - ``instance_dot_version_dot_service =`` + [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] + ``+ '.' +`` + [version][google.cloud.scheduler.v1.AppEngineRouting.version] + ``+ '.' +`` + [service][google.cloud.scheduler.v1.AppEngineRouting.service] + + If + [service][google.cloud.scheduler.v1.AppEngineRouting.service] + is empty, then the job will be sent to the service which is + the default service when the job is attempted. + + If + [version][google.cloud.scheduler.v1.AppEngineRouting.version] + is empty, then the job will be sent to the version which is + the default version when the job is attempted. + + If + [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] + is empty, then the job will be sent to an instance which is + available when the job is attempted. + + If + [service][google.cloud.scheduler.v1.AppEngineRouting.service], + [version][google.cloud.scheduler.v1.AppEngineRouting.version], + or + [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] + is invalid, then the job will be sent to the default version + of the default service when the job is attempted. + """ + + service = proto.Field(proto.STRING, number=1) + + version = proto.Field(proto.STRING, number=2) + + instance = proto.Field(proto.STRING, number=3) + + host = proto.Field(proto.STRING, number=4) + + +class OAuthToken(proto.Message): + r"""Contains information needed for generating an `OAuth + token `__. + This type of authorization should generally only be used when + calling Google APIs hosted on \*.googleapis.com. + + Attributes: + service_account_email (str): + `Service account + email `__ + to be used for generating OAuth token. The service account + must be within the same project as the job. The caller must + have iam.serviceAccounts.actAs permission for the service + account. + scope (str): + OAuth scope to be used for generating OAuth + access token. If not specified, + "https://www.googleapis.com/auth/cloud-platform" + will be used. + """ + + service_account_email = proto.Field(proto.STRING, number=1) + + scope = proto.Field(proto.STRING, number=2) + + +class OidcToken(proto.Message): + r"""Contains information needed for generating an `OpenID Connect + token `__. + This type of authorization can be used for many scenarios, including + calling Cloud Run, or endpoints where you intend to validate the + token yourself. + + Attributes: + service_account_email (str): + `Service account + email `__ + to be used for generating OIDC token. The service account + must be within the same project as the job. The caller must + have iam.serviceAccounts.actAs permission for the service + account. + audience (str): + Audience to be used when generating OIDC + token. If not specified, the URI specified in + target will be used. + """ + + service_account_email = proto.Field(proto.STRING, number=1) + + audience = proto.Field(proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/scheduler_v1beta1/__init__.py b/google/cloud/scheduler_v1beta1/__init__.py index a23cbd79..f2d528ea 100644 --- a/google/cloud/scheduler_v1beta1/__init__.py +++ b/google/cloud/scheduler_v1beta1/__init__.py @@ -1,41 +1,59 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# - -from __future__ import absolute_import -import sys -import warnings - -from google.cloud.scheduler_v1beta1 import types -from google.cloud.scheduler_v1beta1.gapic import cloud_scheduler_client -from google.cloud.scheduler_v1beta1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7." - "More details about Python 2 support for Google Cloud Client Libraries" - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class CloudSchedulerClient(cloud_scheduler_client.CloudSchedulerClient): - __doc__ = cloud_scheduler_client.CloudSchedulerClient.__doc__ - enums = enums - - -__all__ = ("enums", "types", "CloudSchedulerClient") +from .services.cloud_scheduler import CloudSchedulerClient +from .types.cloudscheduler import CreateJobRequest +from .types.cloudscheduler import DeleteJobRequest +from .types.cloudscheduler import GetJobRequest +from .types.cloudscheduler import ListJobsRequest +from .types.cloudscheduler import ListJobsResponse +from .types.cloudscheduler import PauseJobRequest +from .types.cloudscheduler import ResumeJobRequest +from .types.cloudscheduler import RunJobRequest +from .types.cloudscheduler import UpdateJobRequest +from .types.job import Job +from .types.job import RetryConfig +from .types.target import AppEngineHttpTarget +from .types.target import AppEngineRouting +from .types.target import HttpMethod +from .types.target import HttpTarget +from .types.target import OAuthToken +from .types.target import OidcToken +from .types.target import PubsubTarget + + +__all__ = ( + "AppEngineHttpTarget", + "AppEngineRouting", + "CreateJobRequest", + "DeleteJobRequest", + "GetJobRequest", + "HttpMethod", + "HttpTarget", + "Job", + "ListJobsRequest", + "ListJobsResponse", + "OAuthToken", + "OidcToken", + "PauseJobRequest", + "PubsubTarget", + "ResumeJobRequest", + "RetryConfig", + "RunJobRequest", + "UpdateJobRequest", + "CloudSchedulerClient", +) diff --git a/google/cloud/scheduler_v1beta1/gapic/__init__.py b/google/cloud/scheduler_v1beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client.py b/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client.py deleted file mode 100644 index f0ae1140..00000000 --- a/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client.py +++ /dev/null @@ -1,846 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.scheduler.v1beta1 CloudScheduler API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.scheduler_v1beta1.gapic import cloud_scheduler_client_config -from google.cloud.scheduler_v1beta1.gapic import enums -from google.cloud.scheduler_v1beta1.gapic.transports import ( - cloud_scheduler_grpc_transport, -) -from google.cloud.scheduler_v1beta1.proto import cloudscheduler_pb2 -from google.cloud.scheduler_v1beta1.proto import cloudscheduler_pb2_grpc -from google.cloud.scheduler_v1beta1.proto import job_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-scheduler" -).version - - -class CloudSchedulerClient(object): - """ - The Cloud Scheduler API allows external entities to reliably - schedule asynchronous jobs. - """ - - SERVICE_ADDRESS = "cloudscheduler.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.scheduler.v1beta1.CloudScheduler" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CloudSchedulerClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def job_path(cls, project, location, job): - """Return a fully-qualified job string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/jobs/{job}", - project=project, - location=location, - job=job, - ) - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.CloudSchedulerGrpcTransport, - Callable[[~.Credentials, type], ~.CloudSchedulerGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = cloud_scheduler_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=cloud_scheduler_grpc_transport.CloudSchedulerGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = cloud_scheduler_grpc_transport.CloudSchedulerGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME] - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_jobs( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists jobs. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_jobs(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_jobs(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.scheduler_v1beta1.types.Job` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_jobs" not in self._inner_api_calls: - self._inner_api_calls[ - "list_jobs" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_jobs, - default_retry=self._method_configs["ListJobs"].retry, - default_timeout=self._method_configs["ListJobs"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.ListJobsRequest(parent=parent, page_size=page_size) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_jobs"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="jobs", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a job. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.get_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1beta1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_job" not in self._inner_api_calls: - self._inner_api_calls[ - "get_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_job, - default_retry=self._method_configs["GetJob"].retry, - default_timeout=self._method_configs["GetJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.GetJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_job( - self, - parent, - job, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a job. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `job`: - >>> job = {} - >>> - >>> response = client.create_job(parent, job) - - Args: - parent (str): Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - job (Union[dict, ~google.cloud.scheduler_v1beta1.types.Job]): Required. The job to add. The user can optionally specify a name for the - job in ``name``. ``name`` cannot be the same as an existing job. If a - name is not specified then the system will generate a random unique name - that will be returned (``name``) in the response. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.scheduler_v1beta1.types.Job` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1beta1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_job" not in self._inner_api_calls: - self._inner_api_calls[ - "create_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_job, - default_retry=self._method_configs["CreateJob"].retry, - default_timeout=self._method_configs["CreateJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.CreateJobRequest(parent=parent, job=job) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_job( - self, - job, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a job. - - If successful, the updated ``Job`` is returned. If the job does not - exist, ``NOT_FOUND`` is returned. - - If UpdateJob does not successfully return, it is possible for the job to - be in an ``Job.State.UPDATE_FAILED`` state. A job in this state may not - be executed. If this happens, retry the UpdateJob request until a - successful response is received. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> # TODO: Initialize `job`: - >>> job = {} - >>> - >>> response = client.update_job(job) - - Args: - job (Union[dict, ~google.cloud.scheduler_v1beta1.types.Job]): Required. The new job properties. ``name`` must be specified. - - Output only fields cannot be modified using UpdateJob. Any value - specified for an output only field will be ignored. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.scheduler_v1beta1.types.Job` - update_mask (Union[dict, ~google.cloud.scheduler_v1beta1.types.FieldMask]): A mask used to specify which fields of the job are being updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.scheduler_v1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1beta1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_job" not in self._inner_api_calls: - self._inner_api_calls[ - "update_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_job, - default_retry=self._method_configs["UpdateJob"].retry, - default_timeout=self._method_configs["UpdateJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.UpdateJobRequest(job=job, update_mask=update_mask) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("job.name", job.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a job. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> client.delete_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_job" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_job, - default_retry=self._method_configs["DeleteJob"].retry, - default_timeout=self._method_configs["DeleteJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.DeleteJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def pause_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Pauses a job. - - If a job is paused then the system will stop executing the job until it - is re-enabled via ``ResumeJob``. The state of the job is stored in - ``state``; if paused it will be set to ``Job.State.PAUSED``. A job must - be in ``Job.State.ENABLED`` to be paused. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.pause_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1beta1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "pause_job" not in self._inner_api_calls: - self._inner_api_calls[ - "pause_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.pause_job, - default_retry=self._method_configs["PauseJob"].retry, - default_timeout=self._method_configs["PauseJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.PauseJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["pause_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def resume_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Resume a job. - - This method reenables a job after it has been ``Job.State.PAUSED``. The - state of a job is stored in ``Job.state``; after calling this method it - will be set to ``Job.State.ENABLED``. A job must be in - ``Job.State.PAUSED`` to be resumed. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.resume_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1beta1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "resume_job" not in self._inner_api_calls: - self._inner_api_calls[ - "resume_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.resume_job, - default_retry=self._method_configs["ResumeJob"].retry, - default_timeout=self._method_configs["ResumeJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.ResumeJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["resume_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def run_job( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Forces a job to run now. - - When this method is called, Cloud Scheduler will dispatch the job, even - if the job is already running. - - Example: - >>> from google.cloud import scheduler_v1beta1 - >>> - >>> client = scheduler_v1beta1.CloudSchedulerClient() - >>> - >>> name = client.job_path('[PROJECT]', '[LOCATION]', '[JOB]') - >>> - >>> response = client.run_job(name) - - Args: - name (str): Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.scheduler_v1beta1.types.Job` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "run_job" not in self._inner_api_calls: - self._inner_api_calls[ - "run_job" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.run_job, - default_retry=self._method_configs["RunJob"].retry, - default_timeout=self._method_configs["RunJob"].timeout, - client_info=self._client_info, - ) - - request = cloudscheduler_pb2.RunJobRequest(name=name) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["run_job"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client_config.py b/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client_config.py deleted file mode 100644 index f2dce757..00000000 --- a/google/cloud/scheduler_v1beta1/gapic/cloud_scheduler_client_config.py +++ /dev/null @@ -1,63 +0,0 @@ -config = { - "interfaces": { - "google.cloud.scheduler.v1beta1.CloudScheduler": { - "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "ListJobs": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "GetJob": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "CreateJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "UpdateJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "DeleteJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "PauseJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "ResumeJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - "RunJob": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - }, - }, - } - } -} diff --git a/google/cloud/scheduler_v1beta1/gapic/enums.py b/google/cloud/scheduler_v1beta1/gapic/enums.py deleted file mode 100644 index 746acde6..00000000 --- a/google/cloud/scheduler_v1beta1/gapic/enums.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class HttpMethod(enum.IntEnum): - """ - The HTTP method used to execute the job. - - Attributes: - HTTP_METHOD_UNSPECIFIED (int): HTTP method unspecified. Defaults to POST. - POST (int): HTTP POST - GET (int): HTTP GET - HEAD (int): HTTP HEAD - PUT (int): HTTP PUT - DELETE (int): HTTP DELETE - PATCH (int): HTTP PATCH - OPTIONS (int): HTTP OPTIONS - """ - - HTTP_METHOD_UNSPECIFIED = 0 - POST = 1 - GET = 2 - HEAD = 3 - PUT = 4 - DELETE = 5 - PATCH = 6 - OPTIONS = 7 - - -class Job(object): - class State(enum.IntEnum): - """ - State of the job. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ENABLED (int): The job is executing normally. - PAUSED (int): The job is paused by the user. It will not execute. A user can - intentionally pause the job using ``PauseJobRequest``. - DISABLED (int): The job is disabled by the system due to error. The user - cannot directly set a job to be disabled. - UPDATE_FAILED (int): The job state resulting from a failed ``CloudScheduler.UpdateJob`` - operation. To recover a job from this state, retry - ``CloudScheduler.UpdateJob`` until a successful response is received. - """ - - STATE_UNSPECIFIED = 0 - ENABLED = 1 - PAUSED = 2 - DISABLED = 3 - UPDATE_FAILED = 4 diff --git a/google/cloud/scheduler_v1beta1/gapic/transports/__init__.py b/google/cloud/scheduler_v1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/scheduler_v1beta1/gapic/transports/cloud_scheduler_grpc_transport.py b/google/cloud/scheduler_v1beta1/gapic/transports/cloud_scheduler_grpc_transport.py deleted file mode 100644 index 5c7c75bc..00000000 --- a/google/cloud/scheduler_v1beta1/gapic/transports/cloud_scheduler_grpc_transport.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.scheduler_v1beta1.proto import cloudscheduler_pb2_grpc - - -class CloudSchedulerGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.scheduler.v1beta1 CloudScheduler API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - channel=None, - credentials=None, - address="cloudscheduler.googleapis.com:443", - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive." - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "cloud_scheduler_stub": cloudscheduler_pb2_grpc.CloudSchedulerStub(channel) - } - - @classmethod - def create_channel( - cls, address="cloudscheduler.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_jobs(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.list_jobs`. - - Lists jobs. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].ListJobs - - @property - def get_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.get_job`. - - Gets a job. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].GetJob - - @property - def create_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.create_job`. - - Creates a job. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].CreateJob - - @property - def update_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.update_job`. - - Updates a job. - - If successful, the updated ``Job`` is returned. If the job does not - exist, ``NOT_FOUND`` is returned. - - If UpdateJob does not successfully return, it is possible for the job to - be in an ``Job.State.UPDATE_FAILED`` state. A job in this state may not - be executed. If this happens, retry the UpdateJob request until a - successful response is received. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].UpdateJob - - @property - def delete_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.delete_job`. - - Deletes a job. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].DeleteJob - - @property - def pause_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.pause_job`. - - Pauses a job. - - If a job is paused then the system will stop executing the job until it - is re-enabled via ``ResumeJob``. The state of the job is stored in - ``state``; if paused it will be set to ``Job.State.PAUSED``. A job must - be in ``Job.State.ENABLED`` to be paused. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].PauseJob - - @property - def resume_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.resume_job`. - - Resume a job. - - This method reenables a job after it has been ``Job.State.PAUSED``. The - state of a job is stored in ``Job.state``; after calling this method it - will be set to ``Job.State.ENABLED``. A job must be in - ``Job.State.PAUSED`` to be resumed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].ResumeJob - - @property - def run_job(self): - """Return the gRPC stub for :meth:`CloudSchedulerClient.run_job`. - - Forces a job to run now. - - When this method is called, Cloud Scheduler will dispatch the job, even - if the job is already running. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["cloud_scheduler_stub"].RunJob diff --git a/google/cloud/scheduler_v1beta1/proto/__init__.py b/google/cloud/scheduler_v1beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/scheduler_v1beta1/proto/cloudscheduler_pb2.py b/google/cloud/scheduler_v1beta1/proto/cloudscheduler_pb2.py deleted file mode 100644 index 20bb4cd0..00000000 --- a/google/cloud/scheduler_v1beta1/proto/cloudscheduler_pb2.py +++ /dev/null @@ -1,845 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/scheduler_v1beta1/proto/cloudscheduler.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.scheduler_v1beta1.proto import ( - job_pb2 as google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/scheduler_v1beta1/proto/cloudscheduler.proto", - package="google.cloud.scheduler.v1beta1", - syntax="proto3", - serialized_options=_b( - '\n"com.google.cloud.scheduler.v1beta1B\016SchedulerProtoP\001ZGgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1beta1;scheduler\242\002\tSCHEDULER' - ), - serialized_pb=_b( - '\n9google/cloud/scheduler_v1beta1/proto/cloudscheduler.proto\x12\x1egoogle.cloud.scheduler.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a.google/cloud/scheduler_v1beta1/proto/job.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto"s\n\x0fListJobsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\x12!cloudscheduler.googleapis.com/Job\x12\x11\n\tpage_size\x18\x05 \x01(\x05\x12\x12\n\npage_token\x18\x06 \x01(\t"^\n\x10ListJobsResponse\x12\x31\n\x04jobs\x18\x01 \x03(\x0b\x32#.google.cloud.scheduler.v1beta1.Job\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"H\n\rGetJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"\x84\x01\n\x10\x43reateJobRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\x12!cloudscheduler.googleapis.com/Job\x12\x35\n\x03job\x18\x02 \x01(\x0b\x32#.google.cloud.scheduler.v1beta1.JobB\x03\xe0\x41\x02"z\n\x10UpdateJobRequest\x12\x35\n\x03job\x18\x01 \x01(\x0b\x32#.google.cloud.scheduler.v1beta1.JobB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"K\n\x10\x44\x65leteJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"J\n\x0fPauseJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"K\n\x10ResumeJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job"H\n\rRunJobRequest\x12\x37\n\x04name\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!cloudscheduler.googleapis.com/Job2\xa6\x0b\n\x0e\x43loudScheduler\x12\xad\x01\n\x08ListJobs\x12/.google.cloud.scheduler.v1beta1.ListJobsRequest\x1a\x30.google.cloud.scheduler.v1beta1.ListJobsResponse">\x82\xd3\xe4\x93\x02/\x12-/v1beta1/{parent=projects/*/locations/*}/jobs\xda\x41\x06parent\x12\x9a\x01\n\x06GetJob\x12-.google.cloud.scheduler.v1beta1.GetJobRequest\x1a#.google.cloud.scheduler.v1beta1.Job"<\x82\xd3\xe4\x93\x02/\x12-/v1beta1/{name=projects/*/locations/*/jobs/*}\xda\x41\x04name\x12\xab\x01\n\tCreateJob\x12\x30.google.cloud.scheduler.v1beta1.CreateJobRequest\x1a#.google.cloud.scheduler.v1beta1.Job"G\x82\xd3\xe4\x93\x02\x34"-/v1beta1/{parent=projects/*/locations/*}/jobs:\x03job\xda\x41\nparent,job\x12\xb4\x01\n\tUpdateJob\x12\x30.google.cloud.scheduler.v1beta1.UpdateJobRequest\x1a#.google.cloud.scheduler.v1beta1.Job"P\x82\xd3\xe4\x93\x02\x38\x32\x31/v1beta1/{job.name=projects/*/locations/*/jobs/*}:\x03job\xda\x41\x0fjob,update_mask\x12\x93\x01\n\tDeleteJob\x12\x30.google.cloud.scheduler.v1beta1.DeleteJobRequest\x1a\x16.google.protobuf.Empty"<\x82\xd3\xe4\x93\x02/*-/v1beta1/{name=projects/*/locations/*/jobs/*}\xda\x41\x04name\x12\xa7\x01\n\x08PauseJob\x12/.google.cloud.scheduler.v1beta1.PauseJobRequest\x1a#.google.cloud.scheduler.v1beta1.Job"E\x82\xd3\xe4\x93\x02\x38"3/v1beta1/{name=projects/*/locations/*/jobs/*}:pause:\x01*\xda\x41\x04name\x12\xaa\x01\n\tResumeJob\x12\x30.google.cloud.scheduler.v1beta1.ResumeJobRequest\x1a#.google.cloud.scheduler.v1beta1.Job"F\x82\xd3\xe4\x93\x02\x39"4/v1beta1/{name=projects/*/locations/*/jobs/*}:resume:\x01*\xda\x41\x04name\x12\xa1\x01\n\x06RunJob\x12-.google.cloud.scheduler.v1beta1.RunJobRequest\x1a#.google.cloud.scheduler.v1beta1.Job"C\x82\xd3\xe4\x93\x02\x36"1/v1beta1/{name=projects/*/locations/*/jobs/*}:run:\x01*\xda\x41\x04name\x1aQ\xca\x41\x1d\x63loudscheduler.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\x8b\x01\n"com.google.cloud.scheduler.v1beta1B\x0eSchedulerProtoP\x01ZGgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1beta1;scheduler\xa2\x02\tSCHEDULERb\x06proto3' - ), - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - ], -) - - -_LISTJOBSREQUEST = _descriptor.Descriptor( - name="ListJobsRequest", - full_name="google.cloud.scheduler.v1beta1.ListJobsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.scheduler.v1beta1.ListJobsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\022!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.scheduler.v1beta1.ListJobsRequest.page_size", - index=1, - number=5, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.scheduler.v1beta1.ListJobsRequest.page_token", - index=2, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=319, - serialized_end=434, -) - - -_LISTJOBSRESPONSE = _descriptor.Descriptor( - name="ListJobsResponse", - full_name="google.cloud.scheduler.v1beta1.ListJobsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="jobs", - full_name="google.cloud.scheduler.v1beta1.ListJobsResponse.jobs", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.scheduler.v1beta1.ListJobsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=436, - serialized_end=530, -) - - -_GETJOBREQUEST = _descriptor.Descriptor( - name="GetJobRequest", - full_name="google.cloud.scheduler.v1beta1.GetJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1beta1.GetJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=532, - serialized_end=604, -) - - -_CREATEJOBREQUEST = _descriptor.Descriptor( - name="CreateJobRequest", - full_name="google.cloud.scheduler.v1beta1.CreateJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.scheduler.v1beta1.CreateJobRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\022!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="job", - full_name="google.cloud.scheduler.v1beta1.CreateJobRequest.job", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\340A\002"), - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=607, - serialized_end=739, -) - - -_UPDATEJOBREQUEST = _descriptor.Descriptor( - name="UpdateJobRequest", - full_name="google.cloud.scheduler.v1beta1.UpdateJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="job", - full_name="google.cloud.scheduler.v1beta1.UpdateJobRequest.job", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\340A\002"), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.scheduler.v1beta1.UpdateJobRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=741, - serialized_end=863, -) - - -_DELETEJOBREQUEST = _descriptor.Descriptor( - name="DeleteJobRequest", - full_name="google.cloud.scheduler.v1beta1.DeleteJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1beta1.DeleteJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=865, - serialized_end=940, -) - - -_PAUSEJOBREQUEST = _descriptor.Descriptor( - name="PauseJobRequest", - full_name="google.cloud.scheduler.v1beta1.PauseJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1beta1.PauseJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=942, - serialized_end=1016, -) - - -_RESUMEJOBREQUEST = _descriptor.Descriptor( - name="ResumeJobRequest", - full_name="google.cloud.scheduler.v1beta1.ResumeJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1beta1.ResumeJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1018, - serialized_end=1093, -) - - -_RUNJOBREQUEST = _descriptor.Descriptor( - name="RunJobRequest", - full_name="google.cloud.scheduler.v1beta1.RunJobRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1beta1.RunJobRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b( - "\340A\002\372A#\n!cloudscheduler.googleapis.com/Job" - ), - file=DESCRIPTOR, - ) - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1095, - serialized_end=1167, -) - -_LISTJOBSRESPONSE.fields_by_name[ - "jobs" -].message_type = google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB -_CREATEJOBREQUEST.fields_by_name[ - "job" -].message_type = google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB -_UPDATEJOBREQUEST.fields_by_name[ - "job" -].message_type = google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB -_UPDATEJOBREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -DESCRIPTOR.message_types_by_name["ListJobsRequest"] = _LISTJOBSREQUEST -DESCRIPTOR.message_types_by_name["ListJobsResponse"] = _LISTJOBSRESPONSE -DESCRIPTOR.message_types_by_name["GetJobRequest"] = _GETJOBREQUEST -DESCRIPTOR.message_types_by_name["CreateJobRequest"] = _CREATEJOBREQUEST -DESCRIPTOR.message_types_by_name["UpdateJobRequest"] = _UPDATEJOBREQUEST -DESCRIPTOR.message_types_by_name["DeleteJobRequest"] = _DELETEJOBREQUEST -DESCRIPTOR.message_types_by_name["PauseJobRequest"] = _PAUSEJOBREQUEST -DESCRIPTOR.message_types_by_name["ResumeJobRequest"] = _RESUMEJOBREQUEST -DESCRIPTOR.message_types_by_name["RunJobRequest"] = _RUNJOBREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListJobsRequest = _reflection.GeneratedProtocolMessageType( - "ListJobsRequest", - (_message.Message,), - dict( - DESCRIPTOR=_LISTJOBSREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for listing jobs using - [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. - Attributes: - parent: - Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - page_size: - Requested page size. The maximum page size is 500. If - unspecified, the page size will be the maximum. Fewer jobs - than requested might be returned, even if more jobs exist; use - next\_page\_token to determine if more jobs exist. - page_token: - A token identifying a page of results the server will return. - To request the first page results, page\_token must be empty. - To request the next page of results, page\_token must be the - value of [next\_page\_token][google.cloud.scheduler.v1beta1.Li - stJobsResponse.next\_page\_token] returned from the previous - call to [ListJobs][google.cloud.scheduler.v1beta1.CloudSchedul - er.ListJobs]. It is an error to switch the value of [filter][g - oogle.cloud.scheduler.v1beta1.ListJobsRequest.filter] or [orde - r\_by][google.cloud.scheduler.v1beta1.ListJobsRequest.order\_b - y] while iterating through pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.ListJobsRequest) - ), -) -_sym_db.RegisterMessage(ListJobsRequest) - -ListJobsResponse = _reflection.GeneratedProtocolMessageType( - "ListJobsResponse", - (_message.Message,), - dict( - DESCRIPTOR=_LISTJOBSRESPONSE, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Response message for listing jobs using - [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. - Attributes: - jobs: - The list of jobs. - next_page_token: - A token to retrieve next page of results. Pass this value in - the [page\_token][google.cloud.scheduler.v1beta1.ListJobsReque - st.page\_token] field in the subsequent call to [ListJobs][goo - gle.cloud.scheduler.v1beta1.CloudScheduler.ListJobs] to - retrieve the next page of results. If this is empty it - indicates that there are no more results through which to - paginate. The page token is valid for only 2 hours. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.ListJobsResponse) - ), -) -_sym_db.RegisterMessage(ListJobsResponse) - -GetJobRequest = _reflection.GeneratedProtocolMessageType( - "GetJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_GETJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [GetJob][google.cloud.scheduler.v1beta1.CloudScheduler.GetJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.GetJobRequest) - ), -) -_sym_db.RegisterMessage(GetJobRequest) - -CreateJobRequest = _reflection.GeneratedProtocolMessageType( - "CreateJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_CREATEJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob]. - Attributes: - parent: - Required. The location name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID``. - job: - Required. The job to add. The user can optionally specify a - name for the job in - [name][google.cloud.scheduler.v1beta1.Job.name]. - [name][google.cloud.scheduler.v1beta1.Job.name] cannot be the - same as an existing job. If a name is not specified then the - system will generate a random unique name that will be - returned ([name][google.cloud.scheduler.v1beta1.Job.name]) in - the response. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.CreateJobRequest) - ), -) -_sym_db.RegisterMessage(CreateJobRequest) - -UpdateJobRequest = _reflection.GeneratedProtocolMessageType( - "UpdateJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_UPDATEJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. - Attributes: - job: - Required. The new job properties. - [name][google.cloud.scheduler.v1beta1.Job.name] must be - specified. Output only fields cannot be modified using - UpdateJob. Any value specified for an output only field will - be ignored. - update_mask: - A mask used to specify which fields of the job are being - updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.UpdateJobRequest) - ), -) -_sym_db.RegisterMessage(UpdateJobRequest) - -DeleteJobRequest = _reflection.GeneratedProtocolMessageType( - "DeleteJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_DELETEJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for deleting a job using - [DeleteJob][google.cloud.scheduler.v1beta1.CloudScheduler.DeleteJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.DeleteJobRequest) - ), -) -_sym_db.RegisterMessage(DeleteJobRequest) - -PauseJobRequest = _reflection.GeneratedProtocolMessageType( - "PauseJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_PAUSEJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [PauseJob][google.cloud.scheduler.v1beta1.CloudScheduler.PauseJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.PauseJobRequest) - ), -) -_sym_db.RegisterMessage(PauseJobRequest) - -ResumeJobRequest = _reflection.GeneratedProtocolMessageType( - "ResumeJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_RESUMEJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for - [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.ResumeJobRequest) - ), -) -_sym_db.RegisterMessage(ResumeJobRequest) - -RunJobRequest = _reflection.GeneratedProtocolMessageType( - "RunJobRequest", - (_message.Message,), - dict( - DESCRIPTOR=_RUNJOBREQUEST, - __module__="google.cloud.scheduler_v1beta1.proto.cloudscheduler_pb2", - __doc__="""Request message for forcing a job to run now using - [RunJob][google.cloud.scheduler.v1beta1.CloudScheduler.RunJob]. - Attributes: - name: - Required. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.RunJobRequest) - ), -) -_sym_db.RegisterMessage(RunJobRequest) - - -DESCRIPTOR._options = None -_LISTJOBSREQUEST.fields_by_name["parent"]._options = None -_GETJOBREQUEST.fields_by_name["name"]._options = None -_CREATEJOBREQUEST.fields_by_name["parent"]._options = None -_CREATEJOBREQUEST.fields_by_name["job"]._options = None -_UPDATEJOBREQUEST.fields_by_name["job"]._options = None -_DELETEJOBREQUEST.fields_by_name["name"]._options = None -_PAUSEJOBREQUEST.fields_by_name["name"]._options = None -_RESUMEJOBREQUEST.fields_by_name["name"]._options = None -_RUNJOBREQUEST.fields_by_name["name"]._options = None - -_CLOUDSCHEDULER = _descriptor.ServiceDescriptor( - name="CloudScheduler", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler", - file=DESCRIPTOR, - index=0, - serialized_options=_b( - "\312A\035cloudscheduler.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform" - ), - serialized_start=1170, - serialized_end=2616, - methods=[ - _descriptor.MethodDescriptor( - name="ListJobs", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs", - index=0, - containing_service=None, - input_type=_LISTJOBSREQUEST, - output_type=_LISTJOBSRESPONSE, - serialized_options=_b( - "\202\323\344\223\002/\022-/v1beta1/{parent=projects/*/locations/*}/jobs\332A\006parent" - ), - ), - _descriptor.MethodDescriptor( - name="GetJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.GetJob", - index=1, - containing_service=None, - input_type=_GETJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - "\202\323\344\223\002/\022-/v1beta1/{name=projects/*/locations/*/jobs/*}\332A\004name" - ), - ), - _descriptor.MethodDescriptor( - name="CreateJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob", - index=2, - containing_service=None, - input_type=_CREATEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0024"-/v1beta1/{parent=projects/*/locations/*}/jobs:\003job\332A\nparent,job' - ), - ), - _descriptor.MethodDescriptor( - name="UpdateJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob", - index=3, - containing_service=None, - input_type=_UPDATEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - "\202\323\344\223\002821/v1beta1/{job.name=projects/*/locations/*/jobs/*}:\003job\332A\017job,update_mask" - ), - ), - _descriptor.MethodDescriptor( - name="DeleteJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.DeleteJob", - index=4, - containing_service=None, - input_type=_DELETEJOBREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=_b( - "\202\323\344\223\002/*-/v1beta1/{name=projects/*/locations/*/jobs/*}\332A\004name" - ), - ), - _descriptor.MethodDescriptor( - name="PauseJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.PauseJob", - index=5, - containing_service=None, - input_type=_PAUSEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0028"3/v1beta1/{name=projects/*/locations/*/jobs/*}:pause:\001*\332A\004name' - ), - ), - _descriptor.MethodDescriptor( - name="ResumeJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob", - index=6, - containing_service=None, - input_type=_RESUMEJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0029"4/v1beta1/{name=projects/*/locations/*/jobs/*}:resume:\001*\332A\004name' - ), - ), - _descriptor.MethodDescriptor( - name="RunJob", - full_name="google.cloud.scheduler.v1beta1.CloudScheduler.RunJob", - index=7, - containing_service=None, - input_type=_RUNJOBREQUEST, - output_type=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2._JOB, - serialized_options=_b( - '\202\323\344\223\0026"1/v1beta1/{name=projects/*/locations/*/jobs/*}:run:\001*\332A\004name' - ), - ), - ], -) -_sym_db.RegisterServiceDescriptor(_CLOUDSCHEDULER) - -DESCRIPTOR.services_by_name["CloudScheduler"] = _CLOUDSCHEDULER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/scheduler_v1beta1/proto/cloudscheduler_pb2_grpc.py b/google/cloud/scheduler_v1beta1/proto/cloudscheduler_pb2_grpc.py deleted file mode 100644 index fca5a0d9..00000000 --- a/google/cloud/scheduler_v1beta1/proto/cloudscheduler_pb2_grpc.py +++ /dev/null @@ -1,196 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -from google.cloud.scheduler_v1beta1.proto import ( - cloudscheduler_pb2 as google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2, -) -from google.cloud.scheduler_v1beta1.proto import ( - job_pb2 as google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class CloudSchedulerStub(object): - """The Cloud Scheduler API allows external entities to reliably - schedule asynchronous jobs. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListJobs = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/ListJobs", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.ListJobsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.ListJobsResponse.FromString, - ) - self.GetJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/GetJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.GetJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.CreateJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/CreateJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.CreateJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.UpdateJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/UpdateJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.UpdateJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.DeleteJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/DeleteJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.DeleteJobRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.PauseJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/PauseJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.PauseJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.ResumeJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/ResumeJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.ResumeJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.FromString, - ) - self.RunJob = channel.unary_unary( - "/google.cloud.scheduler.v1beta1.CloudScheduler/RunJob", - request_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.RunJobRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.FromString, - ) - - -class CloudSchedulerServicer(object): - """The Cloud Scheduler API allows external entities to reliably - schedule asynchronous jobs. - """ - - def ListJobs(self, request, context): - """Lists jobs. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetJob(self, request, context): - """Gets a job. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateJob(self, request, context): - """Creates a job. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateJob(self, request, context): - """Updates a job. - - If successful, the updated [Job][google.cloud.scheduler.v1beta1.Job] is returned. If the job does - not exist, `NOT_FOUND` is returned. - - If UpdateJob does not successfully return, it is possible for the - job to be in an [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1beta1.Job.State.UPDATE_FAILED] state. A job in this state may - not be executed. If this happens, retry the UpdateJob request - until a successful response is received. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteJob(self, request, context): - """Deletes a job. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def PauseJob(self, request, context): - """Pauses a job. - - If a job is paused then the system will stop executing the job - until it is re-enabled via [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. The - state of the job is stored in [state][google.cloud.scheduler.v1beta1.Job.state]; if paused it - will be set to [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. A job must be in [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED] - to be paused. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ResumeJob(self, request, context): - """Resume a job. - - This method reenables a job after it has been [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. The - state of a job is stored in [Job.state][google.cloud.scheduler.v1beta1.Job.state]; after calling this method it - will be set to [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED]. A job must be in - [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED] to be resumed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RunJob(self, request, context): - """Forces a job to run now. - - When this method is called, Cloud Scheduler will dispatch the job, even - if the job is already running. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_CloudSchedulerServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListJobs": grpc.unary_unary_rpc_method_handler( - servicer.ListJobs, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.ListJobsRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.ListJobsResponse.SerializeToString, - ), - "GetJob": grpc.unary_unary_rpc_method_handler( - servicer.GetJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.GetJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "CreateJob": grpc.unary_unary_rpc_method_handler( - servicer.CreateJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.CreateJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "UpdateJob": grpc.unary_unary_rpc_method_handler( - servicer.UpdateJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.UpdateJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "DeleteJob": grpc.unary_unary_rpc_method_handler( - servicer.DeleteJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.DeleteJobRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "PauseJob": grpc.unary_unary_rpc_method_handler( - servicer.PauseJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.PauseJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "ResumeJob": grpc.unary_unary_rpc_method_handler( - servicer.ResumeJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.ResumeJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - "RunJob": grpc.unary_unary_rpc_method_handler( - servicer.RunJob, - request_deserializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_cloudscheduler__pb2.RunJobRequest.FromString, - response_serializer=google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_job__pb2.Job.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.scheduler.v1beta1.CloudScheduler", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/google/cloud/scheduler_v1beta1/proto/job_pb2.py b/google/cloud/scheduler_v1beta1/proto/job_pb2.py deleted file mode 100644 index 171aff15..00000000 --- a/google/cloud/scheduler_v1beta1/proto/job_pb2.py +++ /dev/null @@ -1,704 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/scheduler_v1beta1/proto/job.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.scheduler_v1beta1.proto import ( - target_pb2 as google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_target__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/scheduler_v1beta1/proto/job.proto", - package="google.cloud.scheduler.v1beta1", - syntax="proto3", - serialized_options=_b( - '\n"com.google.cloud.scheduler.v1beta1B\010JobProtoP\001ZGgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1beta1;scheduler' - ), - serialized_pb=_b( - '\n.google/cloud/scheduler_v1beta1/proto/job.proto\x12\x1egoogle.cloud.scheduler.v1beta1\x1a\x19google/api/resource.proto\x1a\x31google/cloud/scheduler_v1beta1/proto/target.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\x1a\x1cgoogle/api/annotations.proto"\xe4\x06\n\x03Job\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x45\n\rpubsub_target\x18\x04 \x01(\x0b\x32,.google.cloud.scheduler.v1beta1.PubsubTargetH\x00\x12U\n\x16\x61pp_engine_http_target\x18\x05 \x01(\x0b\x32\x33.google.cloud.scheduler.v1beta1.AppEngineHttpTargetH\x00\x12\x41\n\x0bhttp_target\x18\x06 \x01(\x0b\x32*.google.cloud.scheduler.v1beta1.HttpTargetH\x00\x12\x10\n\x08schedule\x18\x14 \x01(\t\x12\x11\n\ttime_zone\x18\x15 \x01(\t\x12\x34\n\x10user_update_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x38\n\x05state\x18\n \x01(\x0e\x32).google.cloud.scheduler.v1beta1.Job.State\x12"\n\x06status\x18\x0b \x01(\x0b\x32\x12.google.rpc.Status\x12\x31\n\rschedule_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x35\n\x11last_attempt_time\x18\x12 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x41\n\x0cretry_config\x18\x13 \x01(\x0b\x32+.google.cloud.scheduler.v1beta1.RetryConfig\x12\x33\n\x10\x61ttempt_deadline\x18\x16 \x01(\x0b\x32\x19.google.protobuf.Duration"X\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x45NABLED\x10\x01\x12\n\n\x06PAUSED\x10\x02\x12\x0c\n\x08\x44ISABLED\x10\x03\x12\x11\n\rUPDATE_FAILED\x10\x04:Z\xea\x41W\n!cloudscheduler.googleapis.com/Job\x12\x32projects/{project}/locations/{location}/jobs/{job}B\x08\n\x06target"\xe2\x01\n\x0bRetryConfig\x12\x13\n\x0bretry_count\x18\x01 \x01(\x05\x12\x35\n\x12max_retry_duration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14min_backoff_duration\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x37\n\x14max_backoff_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x15\n\rmax_doublings\x18\x05 \x01(\x05\x42y\n"com.google.cloud.scheduler.v1beta1B\x08JobProtoP\x01ZGgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1beta1;schedulerb\x06proto3' - ), - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_target__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_JOB_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.scheduler.v1beta1.Job.State", - filename=None, - file=DESCRIPTOR, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - ), - _descriptor.EnumValueDescriptor( - name="ENABLED", index=1, number=1, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="PAUSED", index=2, number=2, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="DISABLED", index=3, number=3, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="UPDATE_FAILED", index=4, number=4, serialized_options=None, type=None - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=959, - serialized_end=1047, -) -_sym_db.RegisterEnumDescriptor(_JOB_STATE) - - -_JOB = _descriptor.Descriptor( - name="Job", - full_name="google.cloud.scheduler.v1beta1.Job", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.scheduler.v1beta1.Job.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.scheduler.v1beta1.Job.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="pubsub_target", - full_name="google.cloud.scheduler.v1beta1.Job.pubsub_target", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="app_engine_http_target", - full_name="google.cloud.scheduler.v1beta1.Job.app_engine_http_target", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="http_target", - full_name="google.cloud.scheduler.v1beta1.Job.http_target", - index=4, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="schedule", - full_name="google.cloud.scheduler.v1beta1.Job.schedule", - index=5, - number=20, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="time_zone", - full_name="google.cloud.scheduler.v1beta1.Job.time_zone", - index=6, - number=21, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="user_update_time", - full_name="google.cloud.scheduler.v1beta1.Job.user_update_time", - index=7, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.scheduler.v1beta1.Job.state", - index=8, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="status", - full_name="google.cloud.scheduler.v1beta1.Job.status", - index=9, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="schedule_time", - full_name="google.cloud.scheduler.v1beta1.Job.schedule_time", - index=10, - number=17, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="last_attempt_time", - full_name="google.cloud.scheduler.v1beta1.Job.last_attempt_time", - index=11, - number=18, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="retry_config", - full_name="google.cloud.scheduler.v1beta1.Job.retry_config", - index=12, - number=19, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="attempt_deadline", - full_name="google.cloud.scheduler.v1beta1.Job.attempt_deadline", - index=13, - number=22, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_JOB_STATE], - serialized_options=_b( - "\352AW\n!cloudscheduler.googleapis.com/Job\0222projects/{project}/locations/{location}/jobs/{job}" - ), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="target", - full_name="google.cloud.scheduler.v1beta1.Job.target", - index=0, - containing_type=None, - fields=[], - ) - ], - serialized_start=281, - serialized_end=1149, -) - - -_RETRYCONFIG = _descriptor.Descriptor( - name="RetryConfig", - full_name="google.cloud.scheduler.v1beta1.RetryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="retry_count", - full_name="google.cloud.scheduler.v1beta1.RetryConfig.retry_count", - index=0, - number=1, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="max_retry_duration", - full_name="google.cloud.scheduler.v1beta1.RetryConfig.max_retry_duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="min_backoff_duration", - full_name="google.cloud.scheduler.v1beta1.RetryConfig.min_backoff_duration", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="max_backoff_duration", - full_name="google.cloud.scheduler.v1beta1.RetryConfig.max_backoff_duration", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="max_doublings", - full_name="google.cloud.scheduler.v1beta1.RetryConfig.max_doublings", - index=4, - number=5, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1152, - serialized_end=1378, -) - -_JOB.fields_by_name[ - "pubsub_target" -].message_type = ( - google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_target__pb2._PUBSUBTARGET -) -_JOB.fields_by_name[ - "app_engine_http_target" -].message_type = ( - google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_target__pb2._APPENGINEHTTPTARGET -) -_JOB.fields_by_name[ - "http_target" -].message_type = ( - google_dot_cloud_dot_scheduler__v1beta1_dot_proto_dot_target__pb2._HTTPTARGET -) -_JOB.fields_by_name[ - "user_update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_JOB.fields_by_name["state"].enum_type = _JOB_STATE -_JOB.fields_by_name["status"].message_type = google_dot_rpc_dot_status__pb2._STATUS -_JOB.fields_by_name[ - "schedule_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_JOB.fields_by_name[ - "last_attempt_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_JOB.fields_by_name["retry_config"].message_type = _RETRYCONFIG -_JOB.fields_by_name[ - "attempt_deadline" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_JOB_STATE.containing_type = _JOB -_JOB.oneofs_by_name["target"].fields.append(_JOB.fields_by_name["pubsub_target"]) -_JOB.fields_by_name["pubsub_target"].containing_oneof = _JOB.oneofs_by_name["target"] -_JOB.oneofs_by_name["target"].fields.append( - _JOB.fields_by_name["app_engine_http_target"] -) -_JOB.fields_by_name["app_engine_http_target"].containing_oneof = _JOB.oneofs_by_name[ - "target" -] -_JOB.oneofs_by_name["target"].fields.append(_JOB.fields_by_name["http_target"]) -_JOB.fields_by_name["http_target"].containing_oneof = _JOB.oneofs_by_name["target"] -_RETRYCONFIG.fields_by_name[ - "max_retry_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RETRYCONFIG.fields_by_name[ - "min_backoff_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RETRYCONFIG.fields_by_name[ - "max_backoff_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -DESCRIPTOR.message_types_by_name["Job"] = _JOB -DESCRIPTOR.message_types_by_name["RetryConfig"] = _RETRYCONFIG -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Job = _reflection.GeneratedProtocolMessageType( - "Job", - (_message.Message,), - dict( - DESCRIPTOR=_JOB, - __module__="google.cloud.scheduler_v1beta1.proto.job_pb2", - __doc__="""Configuration for a job. The maximum allowed size for a job is 100KB. - Attributes: - name: - Optionally caller-specified in [CreateJob][google.cloud.schedu - ler.v1beta1.CloudScheduler.CreateJob], after which it becomes - output only. The job name. For example: - ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. - - ``PROJECT_ID`` can contain letters ([A-Za-z]), numbers - ([0-9]), hyphens (-), colons (:), or periods (.). For more - information, see `Identifying projects - `__ - ``LOCATION_ID`` - is the canonical ID for the job's location. The list of - available locations can be obtained by calling [ListLocatio - ns][google.cloud.location.Locations.ListLocations]. For - more information, see - https://cloud.google.com/about/locations/. - ``JOB_ID`` can - contain only letters ([A-Za-z]), numbers ([0-9]), hyphens - (-), or underscores (\_). The maximum length is 500 - characters. - description: - Optionally caller-specified in [CreateJob][google.cloud.schedu - ler.v1beta1.CloudScheduler.CreateJob] or [UpdateJob][google.cl - oud.scheduler.v1beta1.CloudScheduler.UpdateJob]. A human- - readable description for the job. This string must not contain - more than 500 characters. - target: - Required. Delivery settings containing destination and - parameters. - pubsub_target: - Pub/Sub target. - app_engine_http_target: - App Engine HTTP target. - http_target: - HTTP target. - schedule: - Required, except when used with [UpdateJob][google.cloud.sched - uler.v1beta1.CloudScheduler.UpdateJob]. Describes the - schedule on which the job will be executed. The schedule can - be either of the following types: - `Crontab - `__ - English- - like `schedule - `__ As a general rule, execution ``n + 1`` of a job - will not begin until execution ``n`` has finished. Cloud - Scheduler will never allow two simultaneously outstanding - executions. For example, this implies that if the ``n+1``\ th - execution is scheduled to run at 16:00 but the ``n``\ th - execution takes until 16:15, the ``n+1``\ th execution will - not start until ``16:15``. A scheduled start time will be - delayed if the previous execution has not ended when its - scheduled time occurs. If [retry\_count][google.cloud.schedul - er.v1beta1.RetryConfig.retry\_count] > 0 and a job attempt - fails, the job will be tried a total of [retry\_count][google. - cloud.scheduler.v1beta1.RetryConfig.retry\_count] times, with - exponential backoff, until the next scheduled start time. - time_zone: - Specifies the time zone to be used in interpreting - [schedule][google.cloud.scheduler.v1beta1.Job.schedule]. The - value of this field must be a time zone name from the `tz - database `__. Note - that some time zones include a provision for daylight savings - time. The rules for daylight saving time are determined by the - chosen tz. For UTC use the string "utc". If a time zone is not - specified, the default will be in UTC (also known as GMT). - user_update_time: - Output only. The creation time of the job. - state: - Output only. State of the job. - status: - Output only. The response from the target for the last - attempted execution. - schedule_time: - Output only. The next time the job is scheduled. Note that - this may be a retry of a previously failed attempt or the next - execution time according to the schedule. - last_attempt_time: - Output only. The time the last job attempt started. - retry_config: - Settings that determine the retry behavior. - attempt_deadline: - The deadline for job attempts. If the request handler does not - respond by this deadline then the request is cancelled and the - attempt is marked as a ``DEADLINE_EXCEEDED`` failure. The - failed attempt can be viewed in execution logs. Cloud - Scheduler will retry the job according to the - [RetryConfig][google.cloud.scheduler.v1beta1.RetryConfig]. - The allowed duration for this deadline is: - For [HTTP - targets][google.cloud.scheduler.v1beta1.Job.http\_target], - between 15 seconds and 30 minutes. - For [App Engine HTTP - targets][google.cloud.scheduler.v1beta1.Job.app\_engine\_http\ - _target], between 15 seconds and 24 hours. - For [PubSub - targets][google.cloud.scheduler.v1beta1.Job.pubsub\_target], - this field is ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.Job) - ), -) -_sym_db.RegisterMessage(Job) - -RetryConfig = _reflection.GeneratedProtocolMessageType( - "RetryConfig", - (_message.Message,), - dict( - DESCRIPTOR=_RETRYCONFIG, - __module__="google.cloud.scheduler_v1beta1.proto.job_pb2", - __doc__="""Settings that determine the retry behavior. By default, if a job does - not complete successfully (meaning that an acknowledgement is not - received from the handler, then it will be retried with exponential - backoff according to the settings in - [RetryConfig][google.cloud.scheduler.v1beta1.RetryConfig]. - Attributes: - retry_count: - The number of attempts that the system will make to run a job - using the exponential backoff procedure described by [max\_dou - blings][google.cloud.scheduler.v1beta1.RetryConfig.max\_doubli - ngs]. The default value of retry\_count is zero. If - retry\_count is zero, a job attempt will *not* be retried if - it fails. Instead the Cloud Scheduler system will wait for the - next scheduled execution time. If retry\_count is set to a - non-zero number then Cloud Scheduler will retry failed - attempts, using exponential backoff, retry\_count times, or - until the next scheduled execution time, whichever comes - first. Values greater than 5 and negative values are not - allowed. - max_retry_duration: - The time limit for retrying a failed job, measured from time - when an execution was first attempted. If specified with [retr - y\_count][google.cloud.scheduler.v1beta1.RetryConfig.retry\_co - unt], the job will be retried until both limits are reached. - The default value for max\_retry\_duration is zero, which - means retry duration is unlimited. - min_backoff_duration: - The minimum amount of time to wait before retrying a job after - it fails. The default value of this field is 5 seconds. - max_backoff_duration: - The maximum amount of time to wait before retrying a job after - it fails. The default value of this field is 1 hour. - max_doublings: - The time between retries will double ``max_doublings`` times. - A job's retry interval starts at [min\_backoff\_duration][goog - le.cloud.scheduler.v1beta1.RetryConfig.min\_backoff\_duration] - , then doubles ``max_doublings`` times, then increases - linearly, and finally retries retries at intervals of [max\_ba - ckoff\_duration][google.cloud.scheduler.v1beta1.RetryConfig.ma - x\_backoff\_duration] up to [retry\_count][google.cloud.schedu - ler.v1beta1.RetryConfig.retry\_count] times. For example, if - [min\_backoff\_duration][google.cloud.scheduler.v1beta1.RetryC - onfig.min\_backoff\_duration] is 10s, [max\_backoff\_duration] - [google.cloud.scheduler.v1beta1.RetryConfig.max\_backoff\_dura - tion] is 300s, and ``max_doublings`` is 3, then the a job will - first be retried in 10s. The retry interval will double three - times, and then increase linearly by 2^3 \* 10s. Finally, the - job will retry at intervals of [max\_backoff\_duration][google - .cloud.scheduler.v1beta1.RetryConfig.max\_backoff\_duration] - until the job has been attempted [retry\_count][google.cloud.s - cheduler.v1beta1.RetryConfig.retry\_count] times. Thus, the - requests will retry at 10s, 20s, 40s, 80s, 160s, 240s, 300s, - 300s, .... The default value of this field is 5. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.RetryConfig) - ), -) -_sym_db.RegisterMessage(RetryConfig) - - -DESCRIPTOR._options = None -_JOB._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/scheduler_v1beta1/proto/job_pb2_grpc.py b/google/cloud/scheduler_v1beta1/proto/job_pb2_grpc.py deleted file mode 100644 index 07cb78fe..00000000 --- a/google/cloud/scheduler_v1beta1/proto/job_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/scheduler_v1beta1/proto/target_pb2.py b/google/cloud/scheduler_v1beta1/proto/target_pb2.py deleted file mode 100644 index 3a7d2507..00000000 --- a/google/cloud/scheduler_v1beta1/proto/target_pb2.py +++ /dev/null @@ -1,1168 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/scheduler_v1beta1/proto/target.proto - -import sys - -_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/scheduler_v1beta1/proto/target.proto", - package="google.cloud.scheduler.v1beta1", - syntax="proto3", - serialized_options=_b( - '\n"com.google.cloud.scheduler.v1beta1B\013TargetProtoP\001ZGgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1beta1;scheduler\352A@\n\033pubsub.googleapis.com/Topic\022!projects/{project}/topics/{topic}' - ), - serialized_pb=_b( - '\n1google/cloud/scheduler_v1beta1/proto/target.proto\x12\x1egoogle.cloud.scheduler.v1beta1\x1a\x19google/api/resource.proto\x1a\x1cgoogle/api/annotations.proto"\xfe\x02\n\nHttpTarget\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12?\n\x0bhttp_method\x18\x02 \x01(\x0e\x32*.google.cloud.scheduler.v1beta1.HttpMethod\x12H\n\x07headers\x18\x03 \x03(\x0b\x32\x37.google.cloud.scheduler.v1beta1.HttpTarget.HeadersEntry\x12\x0c\n\x04\x62ody\x18\x04 \x01(\x0c\x12\x41\n\x0boauth_token\x18\x05 \x01(\x0b\x32*.google.cloud.scheduler.v1beta1.OAuthTokenH\x00\x12?\n\noidc_token\x18\x06 \x01(\x0b\x32).google.cloud.scheduler.v1beta1.OidcTokenH\x00\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x16\n\x14\x61uthorization_header"\xcb\x02\n\x13\x41ppEngineHttpTarget\x12?\n\x0bhttp_method\x18\x01 \x01(\x0e\x32*.google.cloud.scheduler.v1beta1.HttpMethod\x12L\n\x12\x61pp_engine_routing\x18\x02 \x01(\x0b\x32\x30.google.cloud.scheduler.v1beta1.AppEngineRouting\x12\x14\n\x0crelative_uri\x18\x03 \x01(\t\x12Q\n\x07headers\x18\x04 \x03(\x0b\x32@.google.cloud.scheduler.v1beta1.AppEngineHttpTarget.HeadersEntry\x12\x0c\n\x04\x62ody\x18\x05 \x01(\x0c\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xd7\x01\n\x0cPubsubTarget\x12\x34\n\ntopic_name\x18\x01 \x01(\tB \xfa\x41\x1d\n\x1bpubsub.googleapis.com/Topic\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\x12P\n\nattributes\x18\x04 \x03(\x0b\x32<.google.cloud.scheduler.v1beta1.PubsubTarget.AttributesEntry\x1a\x31\n\x0f\x41ttributesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"T\n\x10\x41ppEngineRouting\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\x12\x10\n\x08instance\x18\x03 \x01(\t\x12\x0c\n\x04host\x18\x04 \x01(\t":\n\nOAuthToken\x12\x1d\n\x15service_account_email\x18\x01 \x01(\t\x12\r\n\x05scope\x18\x02 \x01(\t"<\n\tOidcToken\x12\x1d\n\x15service_account_email\x18\x01 \x01(\t\x12\x10\n\x08\x61udience\x18\x02 \x01(\t*s\n\nHttpMethod\x12\x1b\n\x17HTTP_METHOD_UNSPECIFIED\x10\x00\x12\x08\n\x04POST\x10\x01\x12\x07\n\x03GET\x10\x02\x12\x08\n\x04HEAD\x10\x03\x12\x07\n\x03PUT\x10\x04\x12\n\n\x06\x44\x45LETE\x10\x05\x12\t\n\x05PATCH\x10\x06\x12\x0b\n\x07OPTIONS\x10\x07\x42\xbf\x01\n"com.google.cloud.scheduler.v1beta1B\x0bTargetProtoP\x01ZGgoogle.golang.org/genproto/googleapis/cloud/scheduler/v1beta1;scheduler\xea\x41@\n\x1bpubsub.googleapis.com/Topic\x12!projects/{project}/topics/{topic}b\x06proto3' - ), - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - -_HTTPMETHOD = _descriptor.EnumDescriptor( - name="HttpMethod", - full_name="google.cloud.scheduler.v1beta1.HttpMethod", - filename=None, - file=DESCRIPTOR, - values=[ - _descriptor.EnumValueDescriptor( - name="HTTP_METHOD_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - ), - _descriptor.EnumValueDescriptor( - name="POST", index=1, number=1, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="GET", index=2, number=2, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="HEAD", index=3, number=3, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="PUT", index=4, number=4, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="DELETE", index=5, number=5, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="PATCH", index=6, number=6, serialized_options=None, type=None - ), - _descriptor.EnumValueDescriptor( - name="OPTIONS", index=7, number=7, serialized_options=None, type=None - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1287, - serialized_end=1402, -) -_sym_db.RegisterEnumDescriptor(_HTTPMETHOD) - -HttpMethod = enum_type_wrapper.EnumTypeWrapper(_HTTPMETHOD) -HTTP_METHOD_UNSPECIFIED = 0 -POST = 1 -GET = 2 -HEAD = 3 -PUT = 4 -DELETE = 5 -PATCH = 6 -OPTIONS = 7 - - -_HTTPTARGET_HEADERSENTRY = _descriptor.Descriptor( - name="HeadersEntry", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.HeadersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.HeadersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.HeadersEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=_b("8\001"), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=455, - serialized_end=501, -) - -_HTTPTARGET = _descriptor.Descriptor( - name="HttpTarget", - full_name="google.cloud.scheduler.v1beta1.HttpTarget", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="http_method", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.http_method", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="headers", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.headers", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="body", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.body", - index=3, - number=4, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b(""), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="oauth_token", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.oauth_token", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="oidc_token", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.oidc_token", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[_HTTPTARGET_HEADERSENTRY], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="authorization_header", - full_name="google.cloud.scheduler.v1beta1.HttpTarget.authorization_header", - index=0, - containing_type=None, - fields=[], - ) - ], - serialized_start=143, - serialized_end=525, -) - - -_APPENGINEHTTPTARGET_HEADERSENTRY = _descriptor.Descriptor( - name="HeadersEntry", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.HeadersEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.HeadersEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.HeadersEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=_b("8\001"), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=455, - serialized_end=501, -) - -_APPENGINEHTTPTARGET = _descriptor.Descriptor( - name="AppEngineHttpTarget", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="http_method", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.http_method", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="app_engine_routing", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.app_engine_routing", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="relative_uri", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.relative_uri", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="headers", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.headers", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="body", - full_name="google.cloud.scheduler.v1beta1.AppEngineHttpTarget.body", - index=4, - number=5, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b(""), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[_APPENGINEHTTPTARGET_HEADERSENTRY], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=528, - serialized_end=859, -) - - -_PUBSUBTARGET_ATTRIBUTESENTRY = _descriptor.Descriptor( - name="AttributesEntry", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget.AttributesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget.AttributesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget.AttributesEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=_b("8\001"), - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1028, - serialized_end=1077, -) - -_PUBSUBTARGET = _descriptor.Descriptor( - name="PubsubTarget", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="topic_name", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget.topic_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=_b("\372A\035\n\033pubsub.googleapis.com/Topic"), - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget.data", - index=1, - number=3, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b(""), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="attributes", - full_name="google.cloud.scheduler.v1beta1.PubsubTarget.attributes", - index=2, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[_PUBSUBTARGET_ATTRIBUTESENTRY], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=862, - serialized_end=1077, -) - - -_APPENGINEROUTING = _descriptor.Descriptor( - name="AppEngineRouting", - full_name="google.cloud.scheduler.v1beta1.AppEngineRouting", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="service", - full_name="google.cloud.scheduler.v1beta1.AppEngineRouting.service", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.scheduler.v1beta1.AppEngineRouting.version", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="instance", - full_name="google.cloud.scheduler.v1beta1.AppEngineRouting.instance", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="host", - full_name="google.cloud.scheduler.v1beta1.AppEngineRouting.host", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1079, - serialized_end=1163, -) - - -_OAUTHTOKEN = _descriptor.Descriptor( - name="OAuthToken", - full_name="google.cloud.scheduler.v1beta1.OAuthToken", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="service_account_email", - full_name="google.cloud.scheduler.v1beta1.OAuthToken.service_account_email", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="scope", - full_name="google.cloud.scheduler.v1beta1.OAuthToken.scope", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1165, - serialized_end=1223, -) - - -_OIDCTOKEN = _descriptor.Descriptor( - name="OidcToken", - full_name="google.cloud.scheduler.v1beta1.OidcToken", - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name="service_account_email", - full_name="google.cloud.scheduler.v1beta1.OidcToken.service_account_email", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - _descriptor.FieldDescriptor( - name="audience", - full_name="google.cloud.scheduler.v1beta1.OidcToken.audience", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=_b("").decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1225, - serialized_end=1285, -) - -_HTTPTARGET_HEADERSENTRY.containing_type = _HTTPTARGET -_HTTPTARGET.fields_by_name["http_method"].enum_type = _HTTPMETHOD -_HTTPTARGET.fields_by_name["headers"].message_type = _HTTPTARGET_HEADERSENTRY -_HTTPTARGET.fields_by_name["oauth_token"].message_type = _OAUTHTOKEN -_HTTPTARGET.fields_by_name["oidc_token"].message_type = _OIDCTOKEN -_HTTPTARGET.oneofs_by_name["authorization_header"].fields.append( - _HTTPTARGET.fields_by_name["oauth_token"] -) -_HTTPTARGET.fields_by_name["oauth_token"].containing_oneof = _HTTPTARGET.oneofs_by_name[ - "authorization_header" -] -_HTTPTARGET.oneofs_by_name["authorization_header"].fields.append( - _HTTPTARGET.fields_by_name["oidc_token"] -) -_HTTPTARGET.fields_by_name["oidc_token"].containing_oneof = _HTTPTARGET.oneofs_by_name[ - "authorization_header" -] -_APPENGINEHTTPTARGET_HEADERSENTRY.containing_type = _APPENGINEHTTPTARGET -_APPENGINEHTTPTARGET.fields_by_name["http_method"].enum_type = _HTTPMETHOD -_APPENGINEHTTPTARGET.fields_by_name[ - "app_engine_routing" -].message_type = _APPENGINEROUTING -_APPENGINEHTTPTARGET.fields_by_name[ - "headers" -].message_type = _APPENGINEHTTPTARGET_HEADERSENTRY -_PUBSUBTARGET_ATTRIBUTESENTRY.containing_type = _PUBSUBTARGET -_PUBSUBTARGET.fields_by_name["attributes"].message_type = _PUBSUBTARGET_ATTRIBUTESENTRY -DESCRIPTOR.message_types_by_name["HttpTarget"] = _HTTPTARGET -DESCRIPTOR.message_types_by_name["AppEngineHttpTarget"] = _APPENGINEHTTPTARGET -DESCRIPTOR.message_types_by_name["PubsubTarget"] = _PUBSUBTARGET -DESCRIPTOR.message_types_by_name["AppEngineRouting"] = _APPENGINEROUTING -DESCRIPTOR.message_types_by_name["OAuthToken"] = _OAUTHTOKEN -DESCRIPTOR.message_types_by_name["OidcToken"] = _OIDCTOKEN -DESCRIPTOR.enum_types_by_name["HttpMethod"] = _HTTPMETHOD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -HttpTarget = _reflection.GeneratedProtocolMessageType( - "HttpTarget", - (_message.Message,), - dict( - HeadersEntry=_reflection.GeneratedProtocolMessageType( - "HeadersEntry", - (_message.Message,), - dict( - DESCRIPTOR=_HTTPTARGET_HEADERSENTRY, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.HttpTarget.HeadersEntry) - ), - ), - DESCRIPTOR=_HTTPTARGET, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2", - __doc__="""Http target. The job will be pushed to the job handler by means of an - HTTP request via an - [http\_method][google.cloud.scheduler.v1beta1.HttpTarget.http\_method] - such as HTTP POST, HTTP GET, etc. The job is acknowledged by means of - an HTTP response code in the range [200 - 299]. A failure to receive a - response constitutes a failed execution. For a redirected request, the - response returned by the redirected request is considered. - Attributes: - uri: - Required. The full URI path that the request will be sent to. - This string must begin with either "https://" or "https://". - Some examples of valid values for - [uri][google.cloud.scheduler.v1beta1.HttpTarget.uri] are: - ``http://acme.com`` and ``https://acme.com/sales:8080``. Cloud - Scheduler will encode some characters for safety and - compatibility. The maximum allowed URL length is 2083 - characters after encoding. - http_method: - Which HTTP method to use for the request. - headers: - The user can specify HTTP request headers to send with the - job's HTTP request. This map contains the header field names - and values. Repeated headers are not supported, but a header - value can contain commas. These headers represent a subset of - the headers that will accompany the job's HTTP request. Some - HTTP request headers will be ignored or replaced. A partial - list of headers that will be ignored or replaced is below: - - Host: This will be computed by Cloud Scheduler and derived - from [uri][google.cloud.scheduler.v1beta1.HttpTarget.uri]. \* - ``Content-Length``: This will be computed by Cloud Scheduler. - \* ``User-Agent``: This will be set to ``"Google-Cloud- - Scheduler"``. \* ``X-Google-*``: Google internal use only. \* - ``X-AppEngine-*``: Google internal use only. The total size - of headers must be less than 80KB. - body: - HTTP request body. A request body is allowed only if the HTTP - method is POST, PUT, or PATCH. It is an error to set body on a - job with an incompatible - [HttpMethod][google.cloud.scheduler.v1beta1.HttpMethod]. - authorization_header: - The mode for generating an ``Authorization`` header for HTTP - requests. If specified, all ``Authorization`` headers in the - [HttpTarget.headers][google.cloud.scheduler.v1beta1.HttpTarget - .headers] field will be overridden. - oauth_token: - If specified, an `OAuth token - `__ - will be generated and attached as an ``Authorization`` header - in the HTTP request. This type of authorization should - generally only be used when calling Google APIs hosted on - \*.googleapis.com. - oidc_token: - If specified, an `OIDC `__ token will be generated and - attached as an ``Authorization`` header in the HTTP request. - This type of authorization can be used for many scenarios, - including calling Cloud Run, or endpoints where you intend to - validate the token yourself. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.HttpTarget) - ), -) -_sym_db.RegisterMessage(HttpTarget) -_sym_db.RegisterMessage(HttpTarget.HeadersEntry) - -AppEngineHttpTarget = _reflection.GeneratedProtocolMessageType( - "AppEngineHttpTarget", - (_message.Message,), - dict( - HeadersEntry=_reflection.GeneratedProtocolMessageType( - "HeadersEntry", - (_message.Message,), - dict( - DESCRIPTOR=_APPENGINEHTTPTARGET_HEADERSENTRY, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.AppEngineHttpTarget.HeadersEntry) - ), - ), - DESCRIPTOR=_APPENGINEHTTPTARGET, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2", - __doc__="""App Engine target. The job will be pushed to a job handler by means of - an HTTP request via an [http\_method][google.cloud.scheduler.v1beta1.A - ppEngineHttpTarget.http\_method] such as HTTP POST, HTTP GET, etc. The - job is acknowledged by means of an HTTP response code in the range - [200 - 299]. Error 503 is considered an App Engine system error - instead of an application error. Requests returning error 503 will be - retried regardless of retry configuration and not counted against - retry counts. Any other response code, or a failure to receive a - response before the deadline, constitutes a failed attempt. - Attributes: - http_method: - The HTTP method to use for the request. PATCH and OPTIONS are - not permitted. - app_engine_routing: - App Engine Routing setting for the job. - relative_uri: - The relative URI. The relative URL must begin with "/" and - must be a valid HTTP relative URL. It can contain a path, - query string arguments, and ``#`` fragments. If the relative - URL is empty, then the root path "/" will be used. No spaces - are allowed, and the maximum length allowed is 2083 - characters. - headers: - HTTP request headers. This map contains the header field - names and values. Headers can be set when the job is created. - Cloud Scheduler sets some headers to default values: - - ``User-Agent``: By default, this header is ``"AppEngine- - Google; (+http://code.google.com/appengine)"``. This header - can be modified, but Cloud Scheduler will append - ``"AppEngine-Google; (+http://code.google.com/appengine)"`` to - the modified ``User-Agent``. - ``X-CloudScheduler``: This - header will be set to true. If the job has an [body][google.c - loud.scheduler.v1beta1.AppEngineHttpTarget.body], Cloud - Scheduler sets the following headers: - ``Content-Type``: By - default, the ``Content-Type`` header is set to - ``"application/octet-stream"``. The default can be overridden - by explictly setting ``Content-Type`` to a particular media - type when the job is created. For example, ``Content-Type`` - can be set to ``"application/json"``. - ``Content- - Length``: This is computed by Cloud Scheduler. This value - is output only. It cannot be changed. The headers below are - output only. They cannot be set or overridden: - - ``X-Google-*``: For Google internal use only. - - ``X-AppEngine-*``: For Google internal use only. In addition, - some App Engine headers, which contain job-specific - information, are also be sent to the job handler. - body: - Body. HTTP request body. A request body is allowed only if - the HTTP method is POST or PUT. It will result in invalid - argument error to set a body on a job with an incompatible - [HttpMethod][google.cloud.scheduler.v1beta1.HttpMethod]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.AppEngineHttpTarget) - ), -) -_sym_db.RegisterMessage(AppEngineHttpTarget) -_sym_db.RegisterMessage(AppEngineHttpTarget.HeadersEntry) - -PubsubTarget = _reflection.GeneratedProtocolMessageType( - "PubsubTarget", - (_message.Message,), - dict( - AttributesEntry=_reflection.GeneratedProtocolMessageType( - "AttributesEntry", - (_message.Message,), - dict( - DESCRIPTOR=_PUBSUBTARGET_ATTRIBUTESENTRY, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.PubsubTarget.AttributesEntry) - ), - ), - DESCRIPTOR=_PUBSUBTARGET, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2", - __doc__="""Pub/Sub target. The job will be delivered by publishing a message to - the given Pub/Sub topic. - Attributes: - topic_name: - Required. The name of the Cloud Pub/Sub topic to which - messages will be published when a job is delivered. The topic - name must be in the same format as required by PubSub's - `PublishRequest.name `__, for example - ``projects/PROJECT_ID/topics/TOPIC_ID``. The topic must be in - the same project as the Cloud Scheduler job. - data: - The message payload for PubsubMessage. Pubsub message must - contain either non-empty data, or at least one attribute. - attributes: - Attributes for PubsubMessage. Pubsub message must contain - either non-empty data, or at least one attribute. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.PubsubTarget) - ), -) -_sym_db.RegisterMessage(PubsubTarget) -_sym_db.RegisterMessage(PubsubTarget.AttributesEntry) - -AppEngineRouting = _reflection.GeneratedProtocolMessageType( - "AppEngineRouting", - (_message.Message,), - dict( - DESCRIPTOR=_APPENGINEROUTING, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2", - __doc__="""App Engine Routing. For more information about services, versions, - and instances see `An Overview of App Engine - `__, `Microservices Architecture on Google App Engine - `__, `App Engine Standard request routing - `__, and `App Engine Flex request routing - `__. - Attributes: - service: - App service. By default, the job is sent to the service which - is the default service when the job is attempted. - version: - App version. By default, the job is sent to the version which - is the default version when the job is attempted. - instance: - App instance. By default, the job is sent to an instance - which is available when the job is attempted. Requests can - only be sent to a specific instance if `manual scaling is used - in App Engine Standard - `__. - App Engine Flex does not support instances. For more - information, see `App Engine Standard request routing - `__ and `App Engine Flex request routing - `__. - host: - Output only. The host that the job is sent to. For more - information about how App Engine requests are routed, see - `here - `__. The host is constructed as: - - ``host = [application_domain_name]``\ ``| [service] + '.' - + [application_domain_name]``\ ``| [version] + '.' + - [application_domain_name]``\ ``| [version_dot_service]+ - '.' + [application_domain_name]``\ ``| [instance] + '.' + - [application_domain_name]``\ ``| [instance_dot_service] + - '.' + [application_domain_name]``\ ``| - [instance_dot_version] + '.' + [application_domain_name]``\ - ``| [instance_dot_version_dot_service] + '.' + - [application_domain_name]`` - ``application_domain_name`` = - The domain name of the app, for example .appspot.com, which - is associated with the job's project ID. - ``service =`` - [service][google.cloud.scheduler.v1beta1.AppEngineRouting.serv - ice] - ``version =`` [version][google.cloud.scheduler.v1b - eta1.AppEngineRouting.version] - ``version_dot_service =`` - [version][google.cloud.scheduler.v1beta1.AppEngineRouting.vers - ion] ``+ '.' +`` [service][google.cloud.scheduler.v1beta - 1.AppEngineRouting.service] - ``instance =`` [instance][g - oogle.cloud.scheduler.v1beta1.AppEngineRouting.instance] - - ``instance_dot_service =`` [instance][google.cloud.schedule - r.v1beta1.AppEngineRouting.instance] ``+ '.' +`` [servic - e][google.cloud.scheduler.v1beta1.AppEngineRouting.service] - - ``instance_dot_version =`` [instance][google.cloud.schedule - r.v1beta1.AppEngineRouting.instance] ``+ '.' +`` [versio - n][google.cloud.scheduler.v1beta1.AppEngineRouting.version] - - ``instance_dot_version_dot_service =`` [instance][google.cl - oud.scheduler.v1beta1.AppEngineRouting.instance] ``+ '.' - +`` [version][google.cloud.scheduler.v1beta1.AppEngineRouti - ng.version] ``+ '.' +`` [service][google.cloud.scheduler - .v1beta1.AppEngineRouting.service] If [service][google.cloud. - scheduler.v1beta1.AppEngineRouting.service] is empty, then the - job will be sent to the service which is the default service - when the job is attempted. If [version][google.cloud.schedule - r.v1beta1.AppEngineRouting.version] is empty, then the job - will be sent to the version which is the default version when - the job is attempted. If [instance][google.cloud.scheduler.v1 - beta1.AppEngineRouting.instance] is empty, then the job will - be sent to an instance which is available when the job is - attempted. If [service][google.cloud.scheduler.v1beta1.AppEng - ineRouting.service], [version][google.cloud.scheduler.v1beta1. - AppEngineRouting.version], or [instance][google.cloud.schedule - r.v1beta1.AppEngineRouting.instance] is invalid, then the job - will be sent to the default version of the default service - when the job is attempted. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.AppEngineRouting) - ), -) -_sym_db.RegisterMessage(AppEngineRouting) - -OAuthToken = _reflection.GeneratedProtocolMessageType( - "OAuthToken", - (_message.Message,), - dict( - DESCRIPTOR=_OAUTHTOKEN, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2", - __doc__="""Contains information needed for generating an `OAuth token - `__. This - type of authorization should generally only be used when calling - Google APIs hosted on \*.googleapis.com. - Attributes: - service_account_email: - \ `Service account email - `__ to be - used for generating OAuth token. The service account must be - within the same project as the job. The caller must have - iam.serviceAccounts.actAs permission for the service account. - scope: - OAuth scope to be used for generating OAuth access token. If - not specified, "https://www.googleapis.com/auth/cloud- - platform" will be used. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.OAuthToken) - ), -) -_sym_db.RegisterMessage(OAuthToken) - -OidcToken = _reflection.GeneratedProtocolMessageType( - "OidcToken", - (_message.Message,), - dict( - DESCRIPTOR=_OIDCTOKEN, - __module__="google.cloud.scheduler_v1beta1.proto.target_pb2", - __doc__="""Contains information needed for generating an `OpenID Connect token - `__. - This type of authorization can be used for many scenarios, including - calling Cloud Run, or endpoints where you intend to validate the token - yourself. - Attributes: - service_account_email: - \ `Service account email - `__ to be - used for generating OIDC token. The service account must be - within the same project as the job. The caller must have - iam.serviceAccounts.actAs permission for the service account. - audience: - Audience to be used when generating OIDC token. If not - specified, the URI specified in target will be used. - """, - # @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1beta1.OidcToken) - ), -) -_sym_db.RegisterMessage(OidcToken) - - -DESCRIPTOR._options = None -_HTTPTARGET_HEADERSENTRY._options = None -_APPENGINEHTTPTARGET_HEADERSENTRY._options = None -_PUBSUBTARGET_ATTRIBUTESENTRY._options = None -_PUBSUBTARGET.fields_by_name["topic_name"]._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/scheduler_v1beta1/proto/target_pb2_grpc.py b/google/cloud/scheduler_v1beta1/proto/target_pb2_grpc.py deleted file mode 100644 index 07cb78fe..00000000 --- a/google/cloud/scheduler_v1beta1/proto/target_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/scheduler_v1beta1/py.typed b/google/cloud/scheduler_v1beta1/py.typed new file mode 100644 index 00000000..ca4d524b --- /dev/null +++ b/google/cloud/scheduler_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-scheduler package uses inline types. diff --git a/google/cloud/scheduler_v1beta1/services/__init__.py b/google/cloud/scheduler_v1beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/__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/google/cloud/__init__.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/__init__.py similarity index 71% rename from google/cloud/__init__.py rename to google/cloud/scheduler_v1beta1/services/cloud_scheduler/__init__.py index 9a1b64a6..7c90126a 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import CloudSchedulerClient +from .async_client import CloudSchedulerAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "CloudSchedulerClient", + "CloudSchedulerAsyncClient", +) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/async_client.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/async_client.py new file mode 100644 index 00000000..496eaa4c --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/async_client.py @@ -0,0 +1,798 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.scheduler_v1beta1.services.cloud_scheduler import pagers +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job +from google.cloud.scheduler_v1beta1.types import job as gcs_job +from google.cloud.scheduler_v1beta1.types import target +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import CloudSchedulerTransport +from .transports.grpc_asyncio import CloudSchedulerGrpcAsyncIOTransport +from .client import CloudSchedulerClient + + +class CloudSchedulerAsyncClient: + """The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + """ + + _client: CloudSchedulerClient + + DEFAULT_ENDPOINT = CloudSchedulerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudSchedulerClient.DEFAULT_MTLS_ENDPOINT + + job_path = staticmethod(CloudSchedulerClient.job_path) + + from_service_account_file = CloudSchedulerClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(CloudSchedulerClient).get_transport_class, type(CloudSchedulerClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, CloudSchedulerTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the cloud scheduler 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, ~.CloudSchedulerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = CloudSchedulerClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def list_jobs( + self, + request: cloudscheduler.ListJobsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListJobsAsyncPager: + r"""Lists jobs. + + Args: + request (:class:`~.cloudscheduler.ListJobsRequest`): + The request object. Request message for listing jobs + using + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + 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: + ~.pagers.ListJobsAsyncPager: + Response message for listing jobs using + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.ListJobsRequest(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_jobs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_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.ListJobsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_job( + self, + request: cloudscheduler.GetJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Gets a job. + + Args: + request (:class:`~.cloudscheduler.GetJobRequest`): + The request object. Request message for + [GetJob][google.cloud.scheduler.v1beta1.CloudScheduler.GetJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.GetJobRequest(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_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_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 create_job( + self, + request: cloudscheduler.CreateJobRequest = None, + *, + parent: str = None, + job: gcs_job.Job = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Creates a job. + + Args: + request (:class:`~.cloudscheduler.CreateJobRequest`): + The request object. Request message for + [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + job (:class:`~.gcs_job.Job`): + Required. The job to add. The user can optionally + specify a name for the job in + [name][google.cloud.scheduler.v1beta1.Job.name]. + [name][google.cloud.scheduler.v1beta1.Job.name] cannot + be the same as an existing job. If a name is not + specified then the system will generate a random unique + name that will be returned + ([name][google.cloud.scheduler.v1beta1.Job.name]) in the + response. + This corresponds to the ``job`` 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, job]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.CreateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if job is not None: + request.job = job + + # 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_job, + default_timeout=600.0, + client_info=_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 update_job( + self, + request: cloudscheduler.UpdateJobRequest = None, + *, + job: gcs_job.Job = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Updates a job. + + If successful, the updated + [Job][google.cloud.scheduler.v1beta1.Job] is returned. If the + job does not exist, ``NOT_FOUND`` is returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1beta1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Args: + request (:class:`~.cloudscheduler.UpdateJobRequest`): + The request object. Request message for + [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. + job (:class:`~.gcs_job.Job`): + Required. The new job properties. + [name][google.cloud.scheduler.v1beta1.Job.name] must be + specified. + + Output only fields cannot be modified using UpdateJob. + Any value specified for an output only field will be + ignored. + This corresponds to the ``job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + A mask used to specify which fields + of the job are being 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([job, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.UpdateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if job is not None: + request.job = job + 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_job, + default_timeout=600.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("job.name", request.job.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_job( + self, + request: cloudscheduler.DeleteJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a job. + + Args: + request (:class:`~.cloudscheduler.DeleteJobRequest`): + The request object. Request message for deleting a job + using + [DeleteJob][google.cloud.scheduler.v1beta1.CloudScheduler.DeleteJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.DeleteJobRequest(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_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def pause_job( + self, + request: cloudscheduler.PauseJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1beta1.Job.state]; if paused it + will be set to + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED] + to be paused. + + Args: + request (:class:`~.cloudscheduler.PauseJobRequest`): + The request object. Request message for + [PauseJob][google.cloud.scheduler.v1beta1.CloudScheduler.PauseJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.PauseJobRequest(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.pause_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_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 resume_job( + self, + request: cloudscheduler.ResumeJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1beta1.Job.state]; after + calling this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED] + to be resumed. + + Args: + request (:class:`~.cloudscheduler.ResumeJobRequest`): + The request object. Request message for + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.ResumeJobRequest(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.resume_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_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 run_job( + self, + request: cloudscheduler.RunJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Args: + request (:class:`~.cloudscheduler.RunJobRequest`): + The request object. Request message for forcing a job to + run now using + [RunJob][google.cloud.scheduler.v1beta1.CloudScheduler.RunJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = cloudscheduler.RunJobRequest(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.run_job, + default_timeout=600.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-scheduler",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("CloudSchedulerAsyncClient",) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/client.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/client.py new file mode 100644 index 00000000..1b4399d4 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/client.py @@ -0,0 +1,914 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.scheduler_v1beta1.services.cloud_scheduler import pagers +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job +from google.cloud.scheduler_v1beta1.types import job as gcs_job +from google.cloud.scheduler_v1beta1.types import target +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import CloudSchedulerTransport +from .transports.grpc import CloudSchedulerGrpcTransport +from .transports.grpc_asyncio import CloudSchedulerGrpcAsyncIOTransport + + +class CloudSchedulerClientMeta(type): + """Metaclass for the CloudScheduler 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[CloudSchedulerTransport]] + _transport_registry["grpc"] = CloudSchedulerGrpcTransport + _transport_registry["grpc_asyncio"] = CloudSchedulerGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[CloudSchedulerTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudSchedulerClient(metaclass=CloudSchedulerClientMeta): + """The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudscheduler.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def job_path(project: str, location: str, job: str,) -> str: + """Return a fully-qualified job string.""" + return "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, location=location, job=job, + ) + + @staticmethod + def parse_job_path(path: str) -> Dict[str, str]: + """Parse a job path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, CloudSchedulerTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the cloud scheduler 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, ~.CloudSchedulerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CloudSchedulerTransport): + # transport is a CloudSchedulerTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def list_jobs( + self, + request: cloudscheduler.ListJobsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListJobsPager: + r"""Lists jobs. + + Args: + request (:class:`~.cloudscheduler.ListJobsRequest`): + The request object. Request message for listing jobs + using + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + 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: + ~.pagers.ListJobsPager: + Response message for listing jobs using + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + + 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 cloudscheduler.ListJobsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.ListJobsRequest): + request = cloudscheduler.ListJobsRequest(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_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.ListJobsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_job( + self, + request: cloudscheduler.GetJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Gets a job. + + Args: + request (:class:`~.cloudscheduler.GetJobRequest`): + The request object. Request message for + [GetJob][google.cloud.scheduler.v1beta1.CloudScheduler.GetJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.GetJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.GetJobRequest): + request = cloudscheduler.GetJobRequest(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_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 create_job( + self, + request: cloudscheduler.CreateJobRequest = None, + *, + parent: str = None, + job: gcs_job.Job = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Creates a job. + + Args: + request (:class:`~.cloudscheduler.CreateJobRequest`): + The request object. Request message for + [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob]. + parent (:class:`str`): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + job (:class:`~.gcs_job.Job`): + Required. The job to add. The user can optionally + specify a name for the job in + [name][google.cloud.scheduler.v1beta1.Job.name]. + [name][google.cloud.scheduler.v1beta1.Job.name] cannot + be the same as an existing job. If a name is not + specified then the system will generate a random unique + name that will be returned + ([name][google.cloud.scheduler.v1beta1.Job.name]) in the + response. + This corresponds to the ``job`` 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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, job]) + 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 cloudscheduler.CreateJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.CreateJobRequest): + request = cloudscheduler.CreateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if job is not None: + request.job = job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 update_job( + self, + request: cloudscheduler.UpdateJobRequest = None, + *, + job: gcs_job.Job = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_job.Job: + r"""Updates a job. + + If successful, the updated + [Job][google.cloud.scheduler.v1beta1.Job] is returned. If the + job does not exist, ``NOT_FOUND`` is returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1beta1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Args: + request (:class:`~.cloudscheduler.UpdateJobRequest`): + The request object. Request message for + [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. + job (:class:`~.gcs_job.Job`): + Required. The new job properties. + [name][google.cloud.scheduler.v1beta1.Job.name] must be + specified. + + Output only fields cannot be modified using UpdateJob. + Any value specified for an output only field will be + ignored. + This corresponds to the ``job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + A mask used to specify which fields + of the job are being 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: + ~.gcs_job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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([job, 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 cloudscheduler.UpdateJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.UpdateJobRequest): + request = cloudscheduler.UpdateJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if job is not None: + request.job = job + 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_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("job.name", request.job.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_job( + self, + request: cloudscheduler.DeleteJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a job. + + Args: + request (:class:`~.cloudscheduler.DeleteJobRequest`): + The request object. Request message for deleting a job + using + [DeleteJob][google.cloud.scheduler.v1beta1.CloudScheduler.DeleteJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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 cloudscheduler.DeleteJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.DeleteJobRequest): + request = cloudscheduler.DeleteJobRequest(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_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. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def pause_job( + self, + request: cloudscheduler.PauseJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1beta1.Job.state]; if paused it + will be set to + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED] + to be paused. + + Args: + request (:class:`~.cloudscheduler.PauseJobRequest`): + The request object. Request message for + [PauseJob][google.cloud.scheduler.v1beta1.CloudScheduler.PauseJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.PauseJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.PauseJobRequest): + request = cloudscheduler.PauseJobRequest(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.pause_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 resume_job( + self, + request: cloudscheduler.ResumeJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1beta1.Job.state]; after + calling this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED] + to be resumed. + + Args: + request (:class:`~.cloudscheduler.ResumeJobRequest`): + The request object. Request message for + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.ResumeJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.ResumeJobRequest): + request = cloudscheduler.ResumeJobRequest(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.resume_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 run_job( + self, + request: cloudscheduler.RunJobRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Args: + request (:class:`~.cloudscheduler.RunJobRequest`): + The request object. Request message for forcing a job to + run now using + [RunJob][google.cloud.scheduler.v1beta1.CloudScheduler.RunJob]. + name (:class:`str`): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + 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: + ~.job.Job: + Configuration for a job. + The maximum allowed size for a job is + 100KB. + + """ + # 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 cloudscheduler.RunJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, cloudscheduler.RunJobRequest): + request = cloudscheduler.RunJobRequest(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.run_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 + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-scheduler",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("CloudSchedulerClient",) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/pagers.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/pagers.py new file mode 100644 index 00000000..b6a18422 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/pagers.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job + + +class ListJobsPager: + """A pager for iterating through ``list_jobs`` requests. + + This class thinly wraps an initial + :class:`~.cloudscheduler.ListJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListJobs`` requests and continue to iterate + through the ``jobs`` field on the + corresponding responses. + + All the usual :class:`~.cloudscheduler.ListJobsResponse` + 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[..., cloudscheduler.ListJobsResponse], + request: cloudscheduler.ListJobsRequest, + response: cloudscheduler.ListJobsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.cloudscheduler.ListJobsRequest`): + The initial request object. + response (:class:`~.cloudscheduler.ListJobsResponse`): + 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 = cloudscheduler.ListJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[cloudscheduler.ListJobsResponse]: + 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[job.Job]: + for page in self.pages: + yield from page.jobs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListJobsAsyncPager: + """A pager for iterating through ``list_jobs`` requests. + + This class thinly wraps an initial + :class:`~.cloudscheduler.ListJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListJobs`` requests and continue to iterate + through the ``jobs`` field on the + corresponding responses. + + All the usual :class:`~.cloudscheduler.ListJobsResponse` + 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[cloudscheduler.ListJobsResponse]], + request: cloudscheduler.ListJobsRequest, + response: cloudscheduler.ListJobsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.cloudscheduler.ListJobsRequest`): + The initial request object. + response (:class:`~.cloudscheduler.ListJobsResponse`): + 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 = cloudscheduler.ListJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[cloudscheduler.ListJobsResponse]: + 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[job.Job]: + async def async_generator(): + async for page in self.pages: + for response in page.jobs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/__init__.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/__init__.py new file mode 100644 index 00000000..e9b56e23 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudSchedulerTransport +from .grpc import CloudSchedulerGrpcTransport +from .grpc_asyncio import CloudSchedulerGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CloudSchedulerTransport]] +_transport_registry["grpc"] = CloudSchedulerGrpcTransport +_transport_registry["grpc_asyncio"] = CloudSchedulerGrpcAsyncIOTransport + + +__all__ = ( + "CloudSchedulerTransport", + "CloudSchedulerGrpcTransport", + "CloudSchedulerGrpcAsyncIOTransport", +) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/base.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/base.py new file mode 100644 index 00000000..f43e6f42 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/base.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job +from google.cloud.scheduler_v1beta1.types import job as gcs_job +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-scheduler",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class CloudSchedulerTransport(abc.ABC): + """Abstract transport class for CloudScheduler.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_jobs: gapic_v1.method.wrap_method( + self.list_jobs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.get_job: gapic_v1.method.wrap_method( + self.get_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.create_job: gapic_v1.method.wrap_method( + self.create_job, default_timeout=600.0, client_info=_client_info, + ), + self.update_job: gapic_v1.method.wrap_method( + self.update_job, default_timeout=600.0, client_info=_client_info, + ), + self.delete_job: gapic_v1.method.wrap_method( + self.delete_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.pause_job: gapic_v1.method.wrap_method( + self.pause_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.resume_job: gapic_v1.method.wrap_method( + self.resume_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=_client_info, + ), + self.run_job: gapic_v1.method.wrap_method( + self.run_job, default_timeout=600.0, client_info=_client_info, + ), + } + + @property + def list_jobs( + self, + ) -> typing.Callable[ + [cloudscheduler.ListJobsRequest], + typing.Union[ + cloudscheduler.ListJobsResponse, + typing.Awaitable[cloudscheduler.ListJobsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_job( + self, + ) -> typing.Callable[ + [cloudscheduler.GetJobRequest], typing.Union[job.Job, typing.Awaitable[job.Job]] + ]: + raise NotImplementedError() + + @property + def create_job( + self, + ) -> typing.Callable[ + [cloudscheduler.CreateJobRequest], + typing.Union[gcs_job.Job, typing.Awaitable[gcs_job.Job]], + ]: + raise NotImplementedError() + + @property + def update_job( + self, + ) -> typing.Callable[ + [cloudscheduler.UpdateJobRequest], + typing.Union[gcs_job.Job, typing.Awaitable[gcs_job.Job]], + ]: + raise NotImplementedError() + + @property + def delete_job( + self, + ) -> typing.Callable[ + [cloudscheduler.DeleteJobRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def pause_job( + self, + ) -> typing.Callable[ + [cloudscheduler.PauseJobRequest], + typing.Union[job.Job, typing.Awaitable[job.Job]], + ]: + raise NotImplementedError() + + @property + def resume_job( + self, + ) -> typing.Callable[ + [cloudscheduler.ResumeJobRequest], + typing.Union[job.Job, typing.Awaitable[job.Job]], + ]: + raise NotImplementedError() + + @property + def run_job( + self, + ) -> typing.Callable[ + [cloudscheduler.RunJobRequest], typing.Union[job.Job, typing.Awaitable[job.Job]] + ]: + raise NotImplementedError() + + +__all__ = ("CloudSchedulerTransport",) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/grpc.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/grpc.py new file mode 100644 index 00000000..e9a4fc13 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/grpc.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. +# + +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job +from google.cloud.scheduler_v1beta1.types import job as gcs_job +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import CloudSchedulerTransport + + +class CloudSchedulerGrpcTransport(CloudSchedulerTransport): + """gRPC backend transport for CloudScheduler. + + The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + + 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 = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_jobs( + self, + ) -> Callable[[cloudscheduler.ListJobsRequest], cloudscheduler.ListJobsResponse]: + r"""Return a callable for the list jobs method over gRPC. + + Lists jobs. + + Returns: + Callable[[~.ListJobsRequest], + ~.ListJobsResponse]: + 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_jobs" not in self._stubs: + self._stubs["list_jobs"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/ListJobs", + request_serializer=cloudscheduler.ListJobsRequest.serialize, + response_deserializer=cloudscheduler.ListJobsResponse.deserialize, + ) + return self._stubs["list_jobs"] + + @property + def get_job(self) -> Callable[[cloudscheduler.GetJobRequest], job.Job]: + r"""Return a callable for the get job method over gRPC. + + Gets a job. + + Returns: + Callable[[~.GetJobRequest], + ~.Job]: + 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_job" not in self._stubs: + self._stubs["get_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/GetJob", + request_serializer=cloudscheduler.GetJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["get_job"] + + @property + def create_job(self) -> Callable[[cloudscheduler.CreateJobRequest], gcs_job.Job]: + r"""Return a callable for the create job method over gRPC. + + Creates a job. + + Returns: + Callable[[~.CreateJobRequest], + ~.Job]: + 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_job" not in self._stubs: + self._stubs["create_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/CreateJob", + request_serializer=cloudscheduler.CreateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["create_job"] + + @property + def update_job(self) -> Callable[[cloudscheduler.UpdateJobRequest], gcs_job.Job]: + r"""Return a callable for the update job method over gRPC. + + Updates a job. + + If successful, the updated + [Job][google.cloud.scheduler.v1beta1.Job] is returned. If the + job does not exist, ``NOT_FOUND`` is returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1beta1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Returns: + Callable[[~.UpdateJobRequest], + ~.Job]: + 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_job" not in self._stubs: + self._stubs["update_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/UpdateJob", + request_serializer=cloudscheduler.UpdateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["update_job"] + + @property + def delete_job(self) -> Callable[[cloudscheduler.DeleteJobRequest], empty.Empty]: + r"""Return a callable for the delete job method over gRPC. + + Deletes a job. + + Returns: + Callable[[~.DeleteJobRequest], + ~.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_job" not in self._stubs: + self._stubs["delete_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/DeleteJob", + request_serializer=cloudscheduler.DeleteJobRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_job"] + + @property + def pause_job(self) -> Callable[[cloudscheduler.PauseJobRequest], job.Job]: + r"""Return a callable for the pause job method over gRPC. + + Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1beta1.Job.state]; if paused it + will be set to + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED] + to be paused. + + Returns: + Callable[[~.PauseJobRequest], + ~.Job]: + 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 "pause_job" not in self._stubs: + self._stubs["pause_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/PauseJob", + request_serializer=cloudscheduler.PauseJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["pause_job"] + + @property + def resume_job(self) -> Callable[[cloudscheduler.ResumeJobRequest], job.Job]: + r"""Return a callable for the resume job method over gRPC. + + Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1beta1.Job.state]; after + calling this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED] + to be resumed. + + Returns: + Callable[[~.ResumeJobRequest], + ~.Job]: + 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 "resume_job" not in self._stubs: + self._stubs["resume_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/ResumeJob", + request_serializer=cloudscheduler.ResumeJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["resume_job"] + + @property + def run_job(self) -> Callable[[cloudscheduler.RunJobRequest], job.Job]: + r"""Return a callable for the run job method over gRPC. + + Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Returns: + Callable[[~.RunJobRequest], + ~.Job]: + 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 "run_job" not in self._stubs: + self._stubs["run_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/RunJob", + request_serializer=cloudscheduler.RunJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["run_job"] + + +__all__ = ("CloudSchedulerGrpcTransport",) diff --git a/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/grpc_asyncio.py b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/grpc_asyncio.py new file mode 100644 index 00000000..25897a2d --- /dev/null +++ b/google/cloud/scheduler_v1beta1/services/cloud_scheduler/transports/grpc_asyncio.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job +from google.cloud.scheduler_v1beta1.types import job as gcs_job +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import CloudSchedulerTransport +from .grpc import CloudSchedulerGrpcTransport + + +class CloudSchedulerGrpcAsyncIOTransport(CloudSchedulerTransport): + """gRPC AsyncIO backend transport for CloudScheduler. + + The Cloud Scheduler API allows external entities to reliably + schedule asynchronous jobs. + + 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 = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudscheduler.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If + provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A + callback to provide client SSL certificate bytes and private key + bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` + is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_jobs( + self, + ) -> Callable[ + [cloudscheduler.ListJobsRequest], Awaitable[cloudscheduler.ListJobsResponse] + ]: + r"""Return a callable for the list jobs method over gRPC. + + Lists jobs. + + Returns: + Callable[[~.ListJobsRequest], + Awaitable[~.ListJobsResponse]]: + 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_jobs" not in self._stubs: + self._stubs["list_jobs"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/ListJobs", + request_serializer=cloudscheduler.ListJobsRequest.serialize, + response_deserializer=cloudscheduler.ListJobsResponse.deserialize, + ) + return self._stubs["list_jobs"] + + @property + def get_job(self) -> Callable[[cloudscheduler.GetJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the get job method over gRPC. + + Gets a job. + + Returns: + Callable[[~.GetJobRequest], + Awaitable[~.Job]]: + 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_job" not in self._stubs: + self._stubs["get_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/GetJob", + request_serializer=cloudscheduler.GetJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["get_job"] + + @property + def create_job( + self, + ) -> Callable[[cloudscheduler.CreateJobRequest], Awaitable[gcs_job.Job]]: + r"""Return a callable for the create job method over gRPC. + + Creates a job. + + Returns: + Callable[[~.CreateJobRequest], + Awaitable[~.Job]]: + 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_job" not in self._stubs: + self._stubs["create_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/CreateJob", + request_serializer=cloudscheduler.CreateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["create_job"] + + @property + def update_job( + self, + ) -> Callable[[cloudscheduler.UpdateJobRequest], Awaitable[gcs_job.Job]]: + r"""Return a callable for the update job method over gRPC. + + Updates a job. + + If successful, the updated + [Job][google.cloud.scheduler.v1beta1.Job] is returned. If the + job does not exist, ``NOT_FOUND`` is returned. + + If UpdateJob does not successfully return, it is possible for + the job to be in an + [Job.State.UPDATE_FAILED][google.cloud.scheduler.v1beta1.Job.State.UPDATE_FAILED] + state. A job in this state may not be executed. If this happens, + retry the UpdateJob request until a successful response is + received. + + Returns: + Callable[[~.UpdateJobRequest], + Awaitable[~.Job]]: + 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_job" not in self._stubs: + self._stubs["update_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/UpdateJob", + request_serializer=cloudscheduler.UpdateJobRequest.serialize, + response_deserializer=gcs_job.Job.deserialize, + ) + return self._stubs["update_job"] + + @property + def delete_job( + self, + ) -> Callable[[cloudscheduler.DeleteJobRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete job method over gRPC. + + Deletes a job. + + Returns: + Callable[[~.DeleteJobRequest], + 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_job" not in self._stubs: + self._stubs["delete_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/DeleteJob", + request_serializer=cloudscheduler.DeleteJobRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_job"] + + @property + def pause_job( + self, + ) -> Callable[[cloudscheduler.PauseJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the pause job method over gRPC. + + Pauses a job. + + If a job is paused then the system will stop executing the job + until it is re-enabled via + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + The state of the job is stored in + [state][google.cloud.scheduler.v1beta1.Job.state]; if paused it + will be set to + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + A job must be in + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED] + to be paused. + + Returns: + Callable[[~.PauseJobRequest], + Awaitable[~.Job]]: + 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 "pause_job" not in self._stubs: + self._stubs["pause_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/PauseJob", + request_serializer=cloudscheduler.PauseJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["pause_job"] + + @property + def resume_job( + self, + ) -> Callable[[cloudscheduler.ResumeJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the resume job method over gRPC. + + Resume a job. + + This method reenables a job after it has been + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED]. + The state of a job is stored in + [Job.state][google.cloud.scheduler.v1beta1.Job.state]; after + calling this method it will be set to + [Job.State.ENABLED][google.cloud.scheduler.v1beta1.Job.State.ENABLED]. + A job must be in + [Job.State.PAUSED][google.cloud.scheduler.v1beta1.Job.State.PAUSED] + to be resumed. + + Returns: + Callable[[~.ResumeJobRequest], + Awaitable[~.Job]]: + 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 "resume_job" not in self._stubs: + self._stubs["resume_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/ResumeJob", + request_serializer=cloudscheduler.ResumeJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["resume_job"] + + @property + def run_job(self) -> Callable[[cloudscheduler.RunJobRequest], Awaitable[job.Job]]: + r"""Return a callable for the run job method over gRPC. + + Forces a job to run now. + When this method is called, Cloud Scheduler will + dispatch the job, even if the job is already running. + + Returns: + Callable[[~.RunJobRequest], + Awaitable[~.Job]]: + 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 "run_job" not in self._stubs: + self._stubs["run_job"] = self.grpc_channel.unary_unary( + "/google.cloud.scheduler.v1beta1.CloudScheduler/RunJob", + request_serializer=cloudscheduler.RunJobRequest.serialize, + response_deserializer=job.Job.deserialize, + ) + return self._stubs["run_job"] + + +__all__ = ("CloudSchedulerGrpcAsyncIOTransport",) diff --git a/google/cloud/scheduler_v1beta1/types.py b/google/cloud/scheduler_v1beta1/types.py deleted file mode 100644 index a4e9f480..00000000 --- a/google/cloud/scheduler_v1beta1/types.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.scheduler_v1beta1.proto import cloudscheduler_pb2 -from google.cloud.scheduler_v1beta1.proto import job_pb2 -from google.cloud.scheduler_v1beta1.proto import target_pb2 -from google.protobuf import any_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 - - -_shared_modules = [ - any_pb2, - duration_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - status_pb2, -] - -_local_modules = [cloudscheduler_pb2, job_pb2, target_pb2] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.scheduler_v1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/scheduler_v1beta1/types/__init__.py b/google/cloud/scheduler_v1beta1/types/__init__.py new file mode 100644 index 00000000..53e55ca7 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/types/__init__.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .target import ( + HttpTarget, + AppEngineHttpTarget, + PubsubTarget, + AppEngineRouting, + OAuthToken, + OidcToken, +) +from .job import ( + Job, + RetryConfig, +) +from .cloudscheduler import ( + ListJobsRequest, + ListJobsResponse, + GetJobRequest, + CreateJobRequest, + UpdateJobRequest, + DeleteJobRequest, + PauseJobRequest, + ResumeJobRequest, + RunJobRequest, +) + + +__all__ = ( + "HttpTarget", + "AppEngineHttpTarget", + "PubsubTarget", + "AppEngineRouting", + "OAuthToken", + "OidcToken", + "Job", + "RetryConfig", + "ListJobsRequest", + "ListJobsResponse", + "GetJobRequest", + "CreateJobRequest", + "UpdateJobRequest", + "DeleteJobRequest", + "PauseJobRequest", + "ResumeJobRequest", + "RunJobRequest", +) diff --git a/google/cloud/scheduler_v1beta1/types/cloudscheduler.py b/google/cloud/scheduler_v1beta1/types/cloudscheduler.py new file mode 100644 index 00000000..4334c7c2 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/types/cloudscheduler.py @@ -0,0 +1,218 @@ +# -*- 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.scheduler_v1beta1.types import job as gcs_job +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.scheduler.v1beta1", + manifest={ + "ListJobsRequest", + "ListJobsResponse", + "GetJobRequest", + "CreateJobRequest", + "UpdateJobRequest", + "DeleteJobRequest", + "PauseJobRequest", + "ResumeJobRequest", + "RunJobRequest", + }, +) + + +class ListJobsRequest(proto.Message): + r"""Request message for listing jobs using + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + + Attributes: + parent (str): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + page_size (int): + Requested page size. + + The maximum page size is 500. If unspecified, the page size + will be the maximum. Fewer jobs than requested might be + returned, even if more jobs exist; use next_page_token to + determine if more jobs exist. + page_token (str): + A token identifying a page of results the server will + return. To request the first page results, page_token must + be empty. To request the next page of results, page_token + must be the value of + [next_page_token][google.cloud.scheduler.v1beta1.ListJobsResponse.next_page_token] + returned from the previous call to + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + It is an error to switch the value of + [filter][google.cloud.scheduler.v1beta1.ListJobsRequest.filter] + or + [order_by][google.cloud.scheduler.v1beta1.ListJobsRequest.order_by] + while iterating through pages. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=5) + + page_token = proto.Field(proto.STRING, number=6) + + +class ListJobsResponse(proto.Message): + r"""Response message for listing jobs using + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs]. + + Attributes: + jobs (Sequence[~.gcs_job.Job]): + The list of jobs. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + the + [page_token][google.cloud.scheduler.v1beta1.ListJobsRequest.page_token] + field in the subsequent call to + [ListJobs][google.cloud.scheduler.v1beta1.CloudScheduler.ListJobs] + to retrieve the next page of results. If this is empty it + indicates that there are no more results through which to + paginate. + + The page token is valid for only 2 hours. + """ + + @property + def raw_page(self): + return self + + jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_job.Job,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetJobRequest(proto.Message): + r"""Request message for + [GetJob][google.cloud.scheduler.v1beta1.CloudScheduler.GetJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateJobRequest(proto.Message): + r"""Request message for + [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob]. + + Attributes: + parent (str): + Required. The location name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID``. + job (~.gcs_job.Job): + Required. The job to add. The user can optionally specify a + name for the job in + [name][google.cloud.scheduler.v1beta1.Job.name]. + [name][google.cloud.scheduler.v1beta1.Job.name] cannot be + the same as an existing job. If a name is not specified then + the system will generate a random unique name that will be + returned ([name][google.cloud.scheduler.v1beta1.Job.name]) + in the response. + """ + + parent = proto.Field(proto.STRING, number=1) + + job = proto.Field(proto.MESSAGE, number=2, message=gcs_job.Job,) + + +class UpdateJobRequest(proto.Message): + r"""Request message for + [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. + + Attributes: + job (~.gcs_job.Job): + Required. The new job properties. + [name][google.cloud.scheduler.v1beta1.Job.name] must be + specified. + + Output only fields cannot be modified using UpdateJob. Any + value specified for an output only field will be ignored. + update_mask (~.field_mask.FieldMask): + A mask used to specify which fields of the + job are being updated. + """ + + job = proto.Field(proto.MESSAGE, number=1, message=gcs_job.Job,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteJobRequest(proto.Message): + r"""Request message for deleting a job using + [DeleteJob][google.cloud.scheduler.v1beta1.CloudScheduler.DeleteJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class PauseJobRequest(proto.Message): + r"""Request message for + [PauseJob][google.cloud.scheduler.v1beta1.CloudScheduler.PauseJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ResumeJobRequest(proto.Message): + r"""Request message for + [ResumeJob][google.cloud.scheduler.v1beta1.CloudScheduler.ResumeJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class RunJobRequest(proto.Message): + r"""Request message for forcing a job to run now using + [RunJob][google.cloud.scheduler.v1beta1.CloudScheduler.RunJob]. + + Attributes: + name (str): + Required. The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/scheduler_v1beta1/types/job.py b/google/cloud/scheduler_v1beta1/types/job.py new file mode 100644 index 00000000..c11b2374 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/types/job.py @@ -0,0 +1,288 @@ +# -*- 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.scheduler_v1beta1.types import target +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as gr_status # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.scheduler.v1beta1", manifest={"Job", "RetryConfig",}, +) + + +class Job(proto.Message): + r"""Configuration for a job. + The maximum allowed size for a job is 100KB. + + Attributes: + name (str): + Optionally caller-specified in + [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob], + after which it becomes output only. + + The job name. For example: + ``projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID``. + + - ``PROJECT_ID`` can contain letters ([A-Za-z]), numbers + ([0-9]), hyphens (-), colons (:), or periods (.). For + more information, see `Identifying + projects `__ + - ``LOCATION_ID`` is the canonical ID for the job's + location. The list of available locations can be obtained + by calling + [ListLocations][google.cloud.location.Locations.ListLocations]. + For more information, see + https://cloud.google.com/about/locations/. + - ``JOB_ID`` can contain only letters ([A-Za-z]), numbers + ([0-9]), hyphens (-), or underscores (_). The maximum + length is 500 characters. + description (str): + Optionally caller-specified in + [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob] + or + [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. + + A human-readable description for the job. This string must + not contain more than 500 characters. + pubsub_target (~.target.PubsubTarget): + Pub/Sub target. + app_engine_http_target (~.target.AppEngineHttpTarget): + App Engine HTTP target. + http_target (~.target.HttpTarget): + HTTP target. + schedule (str): + Required, except when used with + [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. + + Describes the schedule on which the job will be executed. + + The schedule can be either of the following types: + + - `Crontab `__ + - English-like + `schedule `__ + + As a general rule, execution ``n + 1`` of a job will not + begin until execution ``n`` has finished. Cloud Scheduler + will never allow two simultaneously outstanding executions. + For example, this implies that if the ``n+1``\ th execution + is scheduled to run at 16:00 but the ``n``\ th execution + takes until 16:15, the ``n+1``\ th execution will not start + until ``16:15``. A scheduled start time will be delayed if + the previous execution has not ended when its scheduled time + occurs. + + If + [retry_count][google.cloud.scheduler.v1beta1.RetryConfig.retry_count] + > 0 and a job attempt fails, the job will be tried a total + of + [retry_count][google.cloud.scheduler.v1beta1.RetryConfig.retry_count] + times, with exponential backoff, until the next scheduled + start time. + time_zone (str): + Specifies the time zone to be used in interpreting + [schedule][google.cloud.scheduler.v1beta1.Job.schedule]. The + value of this field must be a time zone name from the `tz + database `__. + + Note that some time zones include a provision for daylight + savings time. The rules for daylight saving time are + determined by the chosen tz. For UTC use the string "utc". + If a time zone is not specified, the default will be in UTC + (also known as GMT). + user_update_time (~.timestamp.Timestamp): + Output only. The creation time of the job. + state (~.job.Job.State): + Output only. State of the job. + status (~.gr_status.Status): + Output only. The response from the target for + the last attempted execution. + schedule_time (~.timestamp.Timestamp): + Output only. The next time the job is + scheduled. Note that this may be a retry of a + previously failed attempt or the next execution + time according to the schedule. + last_attempt_time (~.timestamp.Timestamp): + Output only. The time the last job attempt + started. + retry_config (~.job.RetryConfig): + Settings that determine the retry behavior. + attempt_deadline (~.duration.Duration): + The deadline for job attempts. If the request handler does + not respond by this deadline then the request is cancelled + and the attempt is marked as a ``DEADLINE_EXCEEDED`` + failure. The failed attempt can be viewed in execution logs. + Cloud Scheduler will retry the job according to the + [RetryConfig][google.cloud.scheduler.v1beta1.RetryConfig]. + + The allowed duration for this deadline is: + + - For [HTTP + targets][google.cloud.scheduler.v1beta1.Job.http_target], + between 15 seconds and 30 minutes. + - For [App Engine HTTP + targets][google.cloud.scheduler.v1beta1.Job.app_engine_http_target], + between 15 seconds and 24 hours. + - For [PubSub + targets][google.cloud.scheduler.v1beta1.Job.pubsub_target], + this field is ignored. + """ + + class State(proto.Enum): + r"""State of the job.""" + STATE_UNSPECIFIED = 0 + ENABLED = 1 + PAUSED = 2 + DISABLED = 3 + UPDATE_FAILED = 4 + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + pubsub_target = proto.Field( + proto.MESSAGE, number=4, oneof="target", message=target.PubsubTarget, + ) + + app_engine_http_target = proto.Field( + proto.MESSAGE, number=5, oneof="target", message=target.AppEngineHttpTarget, + ) + + http_target = proto.Field( + proto.MESSAGE, number=6, oneof="target", message=target.HttpTarget, + ) + + schedule = proto.Field(proto.STRING, number=20) + + time_zone = proto.Field(proto.STRING, number=21) + + user_update_time = proto.Field( + proto.MESSAGE, number=9, message=timestamp.Timestamp, + ) + + state = proto.Field(proto.ENUM, number=10, enum=State,) + + status = proto.Field(proto.MESSAGE, number=11, message=gr_status.Status,) + + schedule_time = proto.Field(proto.MESSAGE, number=17, message=timestamp.Timestamp,) + + last_attempt_time = proto.Field( + proto.MESSAGE, number=18, message=timestamp.Timestamp, + ) + + retry_config = proto.Field(proto.MESSAGE, number=19, message="RetryConfig",) + + attempt_deadline = proto.Field(proto.MESSAGE, number=22, message=duration.Duration,) + + +class RetryConfig(proto.Message): + r"""Settings that determine the retry behavior. + + By default, if a job does not complete successfully (meaning that an + acknowledgement is not received from the handler, then it will be + retried with exponential backoff according to the settings in + [RetryConfig][google.cloud.scheduler.v1beta1.RetryConfig]. + + Attributes: + retry_count (int): + The number of attempts that the system will make to run a + job using the exponential backoff procedure described by + [max_doublings][google.cloud.scheduler.v1beta1.RetryConfig.max_doublings]. + + The default value of retry_count is zero. + + If retry_count is zero, a job attempt will *not* be retried + if it fails. Instead the Cloud Scheduler system will wait + for the next scheduled execution time. + + If retry_count is set to a non-zero number then Cloud + Scheduler will retry failed attempts, using exponential + backoff, retry_count times, or until the next scheduled + execution time, whichever comes first. + + Values greater than 5 and negative values are not allowed. + max_retry_duration (~.duration.Duration): + The time limit for retrying a failed job, measured from time + when an execution was first attempted. If specified with + [retry_count][google.cloud.scheduler.v1beta1.RetryConfig.retry_count], + the job will be retried until both limits are reached. + + The default value for max_retry_duration is zero, which + means retry duration is unlimited. + min_backoff_duration (~.duration.Duration): + The minimum amount of time to wait before + retrying a job after it fails. + + The default value of this field is 5 seconds. + max_backoff_duration (~.duration.Duration): + The maximum amount of time to wait before + retrying a job after it fails. + + The default value of this field is 1 hour. + max_doublings (int): + The time between retries will double ``max_doublings`` + times. + + A job's retry interval starts at + [min_backoff_duration][google.cloud.scheduler.v1beta1.RetryConfig.min_backoff_duration], + then doubles ``max_doublings`` times, then increases + linearly, and finally retries retries at intervals of + [max_backoff_duration][google.cloud.scheduler.v1beta1.RetryConfig.max_backoff_duration] + up to + [retry_count][google.cloud.scheduler.v1beta1.RetryConfig.retry_count] + times. + + For example, if + [min_backoff_duration][google.cloud.scheduler.v1beta1.RetryConfig.min_backoff_duration] + is 10s, + [max_backoff_duration][google.cloud.scheduler.v1beta1.RetryConfig.max_backoff_duration] + is 300s, and ``max_doublings`` is 3, then the a job will + first be retried in 10s. The retry interval will double + three times, and then increase linearly by 2^3 \* 10s. + Finally, the job will retry at intervals of + [max_backoff_duration][google.cloud.scheduler.v1beta1.RetryConfig.max_backoff_duration] + until the job has been attempted + [retry_count][google.cloud.scheduler.v1beta1.RetryConfig.retry_count] + times. Thus, the requests will retry at 10s, 20s, 40s, 80s, + 160s, 240s, 300s, 300s, .... + + The default value of this field is 5. + """ + + retry_count = proto.Field(proto.INT32, number=1) + + max_retry_duration = proto.Field( + proto.MESSAGE, number=2, message=duration.Duration, + ) + + min_backoff_duration = proto.Field( + proto.MESSAGE, number=3, message=duration.Duration, + ) + + max_backoff_duration = proto.Field( + proto.MESSAGE, number=4, message=duration.Duration, + ) + + max_doublings = proto.Field(proto.INT32, number=5) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/scheduler_v1beta1/types/target.py b/google/cloud/scheduler_v1beta1/types/target.py new file mode 100644 index 00000000..45ce8075 --- /dev/null +++ b/google/cloud/scheduler_v1beta1/types/target.py @@ -0,0 +1,426 @@ +# -*- 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.scheduler.v1beta1", + manifest={ + "HttpMethod", + "HttpTarget", + "AppEngineHttpTarget", + "PubsubTarget", + "AppEngineRouting", + "OAuthToken", + "OidcToken", + }, +) + + +class HttpMethod(proto.Enum): + r"""The HTTP method used to execute the job.""" + HTTP_METHOD_UNSPECIFIED = 0 + POST = 1 + GET = 2 + HEAD = 3 + PUT = 4 + DELETE = 5 + PATCH = 6 + OPTIONS = 7 + + +class HttpTarget(proto.Message): + r"""Http target. The job will be pushed to the job handler by means of + an HTTP request via an + [http_method][google.cloud.scheduler.v1beta1.HttpTarget.http_method] + such as HTTP POST, HTTP GET, etc. The job is acknowledged by means + of an HTTP response code in the range [200 - 299]. A failure to + receive a response constitutes a failed execution. For a redirected + request, the response returned by the redirected request is + considered. + + Attributes: + uri (str): + Required. The full URI path that the request will be sent + to. This string must begin with either "https://" or + "https://". Some examples of valid values for + [uri][google.cloud.scheduler.v1beta1.HttpTarget.uri] are: + ``http://acme.com`` and ``https://acme.com/sales:8080``. + Cloud Scheduler will encode some characters for safety and + compatibility. The maximum allowed URL length is 2083 + characters after encoding. + http_method (~.target.HttpMethod): + Which HTTP method to use for the request. + headers (Sequence[~.target.HttpTarget.HeadersEntry]): + The user can specify HTTP request headers to send with the + job's HTTP request. This map contains the header field names + and values. Repeated headers are not supported, but a header + value can contain commas. These headers represent a subset + of the headers that will accompany the job's HTTP request. + Some HTTP request headers will be ignored or replaced. A + partial list of headers that will be ignored or replaced is + below: + + - Host: This will be computed by Cloud Scheduler and + derived from + [uri][google.cloud.scheduler.v1beta1.HttpTarget.uri]. + + - ``Content-Length``: This will be computed by Cloud + Scheduler. + - ``User-Agent``: This will be set to + ``"Google-Cloud-Scheduler"``. + - ``X-Google-*``: Google internal use only. + - ``X-AppEngine-*``: Google internal use only. + + The total size of headers must be less than 80KB. + body (bytes): + HTTP request body. A request body is allowed only if the + HTTP method is POST, PUT, or PATCH. It is an error to set + body on a job with an incompatible + [HttpMethod][google.cloud.scheduler.v1beta1.HttpMethod]. + oauth_token (~.target.OAuthToken): + If specified, an `OAuth + token `__ + will be generated and attached as an ``Authorization`` + header in the HTTP request. + + This type of authorization should generally only be used + when calling Google APIs hosted on \*.googleapis.com. + oidc_token (~.target.OidcToken): + If specified, an + `OIDC `__ + token will be generated and attached as an ``Authorization`` + header in the HTTP request. + + This type of authorization can be used for many scenarios, + including calling Cloud Run, or endpoints where you intend + to validate the token yourself. + """ + + uri = proto.Field(proto.STRING, number=1) + + http_method = proto.Field(proto.ENUM, number=2, enum="HttpMethod",) + + headers = proto.MapField(proto.STRING, proto.STRING, number=3) + + body = proto.Field(proto.BYTES, number=4) + + oauth_token = proto.Field( + proto.MESSAGE, number=5, oneof="authorization_header", message="OAuthToken", + ) + + oidc_token = proto.Field( + proto.MESSAGE, number=6, oneof="authorization_header", message="OidcToken", + ) + + +class AppEngineHttpTarget(proto.Message): + r"""App Engine target. The job will be pushed to a job handler by means + of an HTTP request via an + [http_method][google.cloud.scheduler.v1beta1.AppEngineHttpTarget.http_method] + such as HTTP POST, HTTP GET, etc. The job is acknowledged by means + of an HTTP response code in the range [200 - 299]. Error 503 is + considered an App Engine system error instead of an application + error. Requests returning error 503 will be retried regardless of + retry configuration and not counted against retry counts. Any other + response code, or a failure to receive a response before the + deadline, constitutes a failed attempt. + + Attributes: + http_method (~.target.HttpMethod): + The HTTP method to use for the request. PATCH + and OPTIONS are not permitted. + app_engine_routing (~.target.AppEngineRouting): + App Engine Routing setting for the job. + relative_uri (str): + The relative URI. + + The relative URL must begin with "/" and must be a valid + HTTP relative URL. It can contain a path, query string + arguments, and ``#`` fragments. If the relative URL is + empty, then the root path "/" will be used. No spaces are + allowed, and the maximum length allowed is 2083 characters. + headers (Sequence[~.target.AppEngineHttpTarget.HeadersEntry]): + HTTP request headers. + + This map contains the header field names and values. Headers + can be set when the job is created. + + Cloud Scheduler sets some headers to default values: + + - ``User-Agent``: By default, this header is + ``"AppEngine-Google; (+http://code.google.com/appengine)"``. + This header can be modified, but Cloud Scheduler will + append + ``"AppEngine-Google; (+http://code.google.com/appengine)"`` + to the modified ``User-Agent``. + - ``X-CloudScheduler``: This header will be set to true. + + If the job has an + [body][google.cloud.scheduler.v1beta1.AppEngineHttpTarget.body], + Cloud Scheduler sets the following headers: + + - ``Content-Type``: By default, the ``Content-Type`` header + is set to ``"application/octet-stream"``. The default can + be overridden by explictly setting ``Content-Type`` to a + particular media type when the job is created. For + example, ``Content-Type`` can be set to + ``"application/json"``. + - ``Content-Length``: This is computed by Cloud Scheduler. + This value is output only. It cannot be changed. + + The headers below are output only. They cannot be set or + overridden: + + - ``X-Google-*``: For Google internal use only. + - ``X-AppEngine-*``: For Google internal use only. + + In addition, some App Engine headers, which contain + job-specific information, are also be sent to the job + handler. + body (bytes): + Body. + + HTTP request body. A request body is allowed only if the + HTTP method is POST or PUT. It will result in invalid + argument error to set a body on a job with an incompatible + [HttpMethod][google.cloud.scheduler.v1beta1.HttpMethod]. + """ + + http_method = proto.Field(proto.ENUM, number=1, enum="HttpMethod",) + + app_engine_routing = proto.Field( + proto.MESSAGE, number=2, message="AppEngineRouting", + ) + + relative_uri = proto.Field(proto.STRING, number=3) + + headers = proto.MapField(proto.STRING, proto.STRING, number=4) + + body = proto.Field(proto.BYTES, number=5) + + +class PubsubTarget(proto.Message): + r"""Pub/Sub target. The job will be delivered by publishing a + message to the given Pub/Sub topic. + + Attributes: + topic_name (str): + Required. The name of the Cloud Pub/Sub topic to which + messages will be published when a job is delivered. The + topic name must be in the same format as required by + PubSub's + `PublishRequest.name `__, + for example ``projects/PROJECT_ID/topics/TOPIC_ID``. + + The topic must be in the same project as the Cloud Scheduler + job. + data (bytes): + The message payload for PubsubMessage. + Pubsub message must contain either non-empty + data, or at least one attribute. + attributes (Sequence[~.target.PubsubTarget.AttributesEntry]): + Attributes for PubsubMessage. + Pubsub message must contain either non-empty + data, or at least one attribute. + """ + + topic_name = proto.Field(proto.STRING, number=1) + + data = proto.Field(proto.BYTES, number=3) + + attributes = proto.MapField(proto.STRING, proto.STRING, number=4) + + +class AppEngineRouting(proto.Message): + r"""App Engine Routing. + + For more information about services, versions, and instances see `An + Overview of App + Engine `__, + `Microservices Architecture on Google App + Engine `__, + `App Engine Standard request + routing `__, + and `App Engine Flex request + routing `__. + + Attributes: + service (str): + App service. + By default, the job is sent to the service which + is the default service when the job is + attempted. + version (str): + App version. + By default, the job is sent to the version which + is the default version when the job is + attempted. + instance (str): + App instance. + + By default, the job is sent to an instance which is + available when the job is attempted. + + Requests can only be sent to a specific instance if `manual + scaling is used in App Engine + Standard `__. + App Engine Flex does not support instances. For more + information, see `App Engine Standard request + routing `__ + and `App Engine Flex request + routing `__. + host (str): + Output only. The host that the job is sent to. + + For more information about how App Engine requests are + routed, see + `here `__. + + The host is constructed as: + + - ``host = [application_domain_name]``\ + ``| [service] + '.' + [application_domain_name]``\ + ``| [version] + '.' + [application_domain_name]``\ + ``| [version_dot_service]+ '.' + [application_domain_name]``\ + ``| [instance] + '.' + [application_domain_name]``\ + ``| [instance_dot_service] + '.' + [application_domain_name]``\ + ``| [instance_dot_version] + '.' + [application_domain_name]``\ + ``| [instance_dot_version_dot_service] + '.' + [application_domain_name]`` + + - ``application_domain_name`` = The domain name of the app, + for example .appspot.com, which is associated with the + job's project ID. + + - ``service =`` + [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + + - ``version =`` + [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] + + - ``version_dot_service =`` + [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] + ``+ '.' +`` + [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + + - ``instance =`` + [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] + + - ``instance_dot_service =`` + [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] + ``+ '.' +`` + [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + + - ``instance_dot_version =`` + [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] + ``+ '.' +`` + [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] + + - ``instance_dot_version_dot_service =`` + [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] + ``+ '.' +`` + [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] + ``+ '.' +`` + [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + + If + [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + is empty, then the job will be sent to the service which is + the default service when the job is attempted. + + If + [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] + is empty, then the job will be sent to the version which is + the default version when the job is attempted. + + If + [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] + is empty, then the job will be sent to an instance which is + available when the job is attempted. + + If + [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service], + [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version], + or + [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] + is invalid, then the job will be sent to the default version + of the default service when the job is attempted. + """ + + service = proto.Field(proto.STRING, number=1) + + version = proto.Field(proto.STRING, number=2) + + instance = proto.Field(proto.STRING, number=3) + + host = proto.Field(proto.STRING, number=4) + + +class OAuthToken(proto.Message): + r"""Contains information needed for generating an `OAuth + token `__. + This type of authorization should generally only be used when + calling Google APIs hosted on \*.googleapis.com. + + Attributes: + service_account_email (str): + `Service account + email `__ + to be used for generating OAuth token. The service account + must be within the same project as the job. The caller must + have iam.serviceAccounts.actAs permission for the service + account. + scope (str): + OAuth scope to be used for generating OAuth + access token. If not specified, + "https://www.googleapis.com/auth/cloud-platform" + will be used. + """ + + service_account_email = proto.Field(proto.STRING, number=1) + + scope = proto.Field(proto.STRING, number=2) + + +class OidcToken(proto.Message): + r"""Contains information needed for generating an `OpenID Connect + token `__. + This type of authorization can be used for many scenarios, including + calling Cloud Run, or endpoints where you intend to validate the + token yourself. + + Attributes: + service_account_email (str): + `Service account + email `__ + to be used for generating OIDC token. The service account + must be within the same project as the job. The caller must + have iam.serviceAccounts.actAs permission for the service + account. + audience (str): + Audience to be used when generating OIDC + token. If not specified, the URI specified in + target will be used. + """ + + service_account_email = proto.Field(proto.STRING, number=1) + + audience = proto.Field(proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index aa9f3c77..304ca21f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -23,14 +23,15 @@ import nox -BLACK_VERSION = "black==19.3b0" +BLACK_VERSION = "black==19.10b0" BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] -if os.path.exists("samples"): - BLACK_PATHS.append("samples") +DEFAULT_PYTHON_VERSION = "3.8" +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): """Run linters. @@ -38,7 +39,9 @@ def lint(session): serious code quality issues. """ session.install("flake8", BLACK_VERSION) - session.run("black", "--check", *BLACK_PATHS) + session.run( + "black", "--check", *BLACK_PATHS, + ) session.run("flake8", "google", "tests") @@ -53,10 +56,12 @@ def blacken(session): check the state of the `gcp_ubuntu_config` we use for that Kokoro run. """ session.install(BLACK_VERSION) - session.run("black", *BLACK_PATHS) + session.run( + "black", *BLACK_PATHS, + ) -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def lint_setup_py(session): """Verify that setup.py is valid (including RST check).""" session.install("docutils", "pygments") @@ -65,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -84,17 +91,21 @@ def default(session): ) -@nox.session(python=["2.7", "3.5", "3.6", "3.7", "3.8"]) +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) def unit(session): """Run the unit test suite.""" default(session) -@nox.session(python=["2.7", "3.7"]) +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -110,8 +121,9 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install("mock", "pytest") - session.install("git+https://github.com/googleapis/python-test-utils") + session.install( + "mock", "pytest", "google-cloud-testutils", + ) session.install("-e", ".") # Run py.test against the system tests. @@ -121,7 +133,7 @@ def system(session): session.run("py.test", "--quiet", system_test_folder_path, *session.posargs) -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def cover(session): """Run the final coverage report. @@ -129,17 +141,17 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=86") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -154,3 +166,36 @@ def docs(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install("sphinx", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md new file mode 100644 index 00000000..55c97b32 --- /dev/null +++ b/samples/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md new file mode 100644 index 00000000..34c882b6 --- /dev/null +++ b/samples/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/google/cloud/scheduler_v1/gapic/__init__.py b/samples/snippets/README.md similarity index 100% rename from google/cloud/scheduler_v1/gapic/__init__.py rename to samples/snippets/README.md diff --git a/samples/snippets/app.yaml b/samples/snippets/app.yaml new file mode 100644 index 00000000..8afa3473 --- /dev/null +++ b/samples/snippets/app.yaml @@ -0,0 +1,18 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START cloud_scheduler_python_yaml] +runtime: python37 +service: my-service +# [END cloud_scheduler_python_yaml] diff --git a/samples/snippets/create_job.py b/samples/snippets/create_job.py new file mode 100644 index 00000000..646a8978 --- /dev/null +++ b/samples/snippets/create_job.py @@ -0,0 +1,82 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def create_scheduler_job(project_id, location_id, service_id): + """Create a job with an App Engine target via the Cloud Scheduler API""" + # [START cloud_scheduler_create_job] + from google.cloud import scheduler + + # Create a client. + client = scheduler.CloudSchedulerClient() + + # TODO(developer): Uncomment and set the following variables + # project_id = 'PROJECT_ID' + # location_id = 'LOCATION_ID' + # service_id = 'my-service' + + # Construct the fully qualified location path. + parent = f"projects/{project_id}/locations/{location_id}" + + # Construct the request body. + job = { + 'app_engine_http_target': { + 'app_engine_routing': { + 'service': service_id + }, + 'relative_uri': '/log_payload', + 'http_method': 1, + 'body': 'Hello World'.encode() + }, + 'schedule': '* * * * *', + 'time_zone': 'America/Los_Angeles' + } + + # Use the client to send the job creation request. + response = client.create_job( + request={ + "parent": parent, + "job": job + } + ) + + print('Created job: {}'.format(response.name)) + # [END cloud_scheduler_create_job] + return response + + +def delete_scheduler_job(project_id, location_id, job_id): + """Delete a job via the Cloud Scheduler API""" + # [START cloud_scheduler_delete_job] + from google.cloud import scheduler + from google.api_core.exceptions import GoogleAPICallError + + # Create a client. + client = scheduler.CloudSchedulerClient() + + # TODO(developer): Uncomment and set the following variables + # project_id = 'PROJECT_ID' + # location_id = 'LOCATION_ID' + # job_id = 'JOB_ID' + + # Construct the fully qualified job path. + job = f"projects/{project_id}/locations/{location_id}/jobs/{job_id}" + + # Use the client to send the job deletion request. + try: + client.delete_job(name=job) + print("Job deleted.") + except GoogleAPICallError as e: + print("Error: %s" % e) + # [END cloud_scheduler_delete_job] diff --git a/samples/snippets/create_job_test.py b/samples/snippets/create_job_test.py new file mode 100644 index 00000000..e6b8a0eb --- /dev/null +++ b/samples/snippets/create_job_test.py @@ -0,0 +1,33 @@ +# Copyright 2019 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import create_job + +TEST_PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') +TEST_LOCATION = os.getenv('LOCATION_ID', 'us-central1') + + +def test_create_job(capsys): + create_result = create_job.create_scheduler_job( + TEST_PROJECT_ID, TEST_LOCATION, 'my-service') + out, _ = capsys.readouterr() + assert 'Created job:' in out + + job_name = create_result.name.split('/')[-1] + create_job.delete_scheduler_job(TEST_PROJECT_ID, TEST_LOCATION, job_name) + + out, _ = capsys.readouterr() + assert 'Job deleted.' in out diff --git a/samples/snippets/main.py b/samples/snippets/main.py new file mode 100644 index 00000000..9d4d9753 --- /dev/null +++ b/samples/snippets/main.py @@ -0,0 +1,42 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""App Engine app to serve as an endpoint for Cloud Scheduler samples.""" + +# [START cloud_scheduler_app] +from flask import Flask, request + +app = Flask(__name__) + + +# Define relative URI for job endpoint +@app.route('/log_payload', methods=['POST']) +def example_task_handler(): + """Log the job payload.""" + payload = request.get_data(as_text=True) or '(empty payload)' + print('Received job with payload: {}'.format(payload)) + return 'Printed job payload: {}'.format(payload) +# [END cloud_scheduler_app] + + +@app.route('/') +def hello(): + """Basic index to verify app is serving.""" + return 'Hello World!' + + +if __name__ == '__main__': + # This is used when running locally. Gunicorn is used to run the + # application on Google App Engine. See entrypoint in app.yaml. + app.run(host='127.0.0.1', port=8080, debug=True) diff --git a/samples/snippets/main_test.py b/samples/snippets/main_test.py new file mode 100644 index 00000000..3d6745a5 --- /dev/null +++ b/samples/snippets/main_test.py @@ -0,0 +1,45 @@ +# Copyright 2019 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + + +@pytest.fixture +def app(): + import main + main.app.testing = True + return main.app.test_client() + + +def test_index(app): + r = app.get('/') + assert r.status_code == 200 + + +def test_log_payload(capsys, app): + payload = 'test_payload' + + r = app.post('/log_payload', data=payload) + assert r.status_code == 200 + + out, _ = capsys.readouterr() + assert payload in out + + +def test_empty_payload(capsys, app): + r = app.post('/log_payload') + assert r.status_code == 200 + + out, _ = capsys.readouterr() + assert 'empty payload' in out diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py new file mode 100644 index 00000000..ba55d7ce --- /dev/null +++ b/samples/snippets/noxfile.py @@ -0,0 +1,224 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import print_function + +import os +from pathlib import Path +import sys + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +# Copy `noxfile_config.py` to your directory and modify it instead. + + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + 'ignored_versions': ["2.7"], + + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + 'envs': {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append('.') + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars(): + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG['gcloud_project_env'] + # This should error out if not set. + ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG['envs']) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to tested samples. +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +# +# Style Checks +# + + +def _determine_local_import_names(start_dir): + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session): + session.install("flake8", "flake8-import-order") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + "." + ] + session.run("flake8", *args) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests(session, post_install=None): + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars() + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session): + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip("SKIPPED: {} tests are disabled for this sample.".format( + session.python + )) + + +# +# Readmegen +# + + +def _get_repo_root(): + """ Returns the root folder of the project. """ + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session, path): + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt new file mode 100644 index 00000000..7e460c8c --- /dev/null +++ b/samples/snippets/requirements-test.txt @@ -0,0 +1 @@ +pytest==6.0.1 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt new file mode 100644 index 00000000..4179b5a1 --- /dev/null +++ b/samples/snippets/requirements.txt @@ -0,0 +1,3 @@ +Flask==1.1.2 +gunicorn==20.0.4 +google-cloud-scheduler==1.3.0 diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh new file mode 100755 index 00000000..ff599eb2 --- /dev/null +++ b/scripts/decrypt-secrets.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +# Copyright 2015 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + > testing/client-secrets.json \ No newline at end of file diff --git a/scripts/fixup_scheduler_v1_keywords.py b/scripts/fixup_scheduler_v1_keywords.py new file mode 100644 index 00000000..635b996e --- /dev/null +++ b/scripts/fixup_scheduler_v1_keywords.py @@ -0,0 +1,185 @@ +# -*- 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 schedulerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_job': ('parent', 'job', ), + 'delete_job': ('name', ), + 'get_job': ('name', ), + 'list_jobs': ('parent', 'page_size', 'page_token', ), + 'pause_job': ('name', ), + 'resume_job': ('name', ), + 'run_job': ('name', ), + 'update_job': ('job', '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=schedulerCallTransformer(), +): + """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 scheduler client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_scheduler_v1beta1_keywords.py b/scripts/fixup_scheduler_v1beta1_keywords.py new file mode 100644 index 00000000..635b996e --- /dev/null +++ b/scripts/fixup_scheduler_v1beta1_keywords.py @@ -0,0 +1,185 @@ +# -*- 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 schedulerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_job': ('parent', 'job', ), + 'delete_job': ('name', ), + 'get_job': ('name', ), + 'list_jobs': ('parent', 'page_size', 'page_token', ), + 'pause_job': ('name', ), + 'resume_job': ('name', ), + 'run_job': ('name', ), + 'update_job': ('job', '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=schedulerCallTransformer(), +): + """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 scheduler client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py new file mode 100644 index 00000000..d309d6e9 --- /dev/null +++ b/scripts/readme-gen/readme_gen.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generates READMEs using configuration defined in yaml.""" + +import argparse +import io +import os +import subprocess + +import jinja2 +import yaml + + +jinja_env = jinja2.Environment( + trim_blocks=True, + loader=jinja2.FileSystemLoader( + os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')))) + +README_TMPL = jinja_env.get_template('README.tmpl.rst') + + +def get_help(file): + return subprocess.check_output(['python', file, '--help']).decode() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('source') + parser.add_argument('--destination', default='README.rst') + + args = parser.parse_args() + + source = os.path.abspath(args.source) + root = os.path.dirname(source) + destination = os.path.join(root, args.destination) + + jinja_env.globals['get_help'] = get_help + + with io.open(source, 'r') as f: + config = yaml.load(f) + + # This allows get_help to execute in the right directory. + os.chdir(root) + + output = README_TMPL.render(config) + + with io.open(destination, 'w') as f: + f.write(output) + + +if __name__ == '__main__': + main() diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst new file mode 100644 index 00000000..4fd23976 --- /dev/null +++ b/scripts/readme-gen/templates/README.tmpl.rst @@ -0,0 +1,87 @@ +{# The following line is a lie. BUT! Once jinja2 is done with it, it will + become truth! #} +.. This file is automatically generated. Do not edit this file directly. + +{{product.name}} Python Samples +=============================================================================== + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst + + +This directory contains samples for {{product.name}}. {{product.description}} + +{{description}} + +.. _{{product.name}}: {{product.url}} + +{% if required_api_url %} +To run the sample, you need to enable the API at: {{required_api_url}} +{% endif %} + +{% if required_role %} +To run the sample, you need to have `{{required_role}}` role. +{% endif %} + +{{other_required_steps}} + +{% if setup %} +Setup +------------------------------------------------------------------------------- + +{% for section in setup %} + +{% include section + '.tmpl.rst' %} + +{% endfor %} +{% endif %} + +{% if samples %} +Samples +------------------------------------------------------------------------------- + +{% for sample in samples %} +{{sample.name}} ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +{% if not sample.hide_cloudshell_button %} +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst +{% endif %} + + +{{sample.description}} + +To run this sample: + +.. code-block:: bash + + $ python {{sample.file}} +{% if sample.show_help %} + + {{get_help(sample.file)|indent}} +{% endif %} + + +{% endfor %} +{% endif %} + +{% if cloud_client_library %} + +The client library +------------------------------------------------------------------------------- + +This sample uses the `Google Cloud Client Library for Python`_. +You can read the documentation for more details on API usage and use GitHub +to `browse the source`_ and `report issues`_. + +.. _Google Cloud Client Library for Python: + https://googlecloudplatform.github.io/google-cloud-python/ +.. _browse the source: + https://github.com/GoogleCloudPlatform/google-cloud-python +.. _report issues: + https://github.com/GoogleCloudPlatform/google-cloud-python/issues + +{% endif %} + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst new file mode 100644 index 00000000..1446b94a --- /dev/null +++ b/scripts/readme-gen/templates/auth.tmpl.rst @@ -0,0 +1,9 @@ +Authentication +++++++++++++++ + +This sample requires you to have authentication setup. Refer to the +`Authentication Getting Started Guide`_ for instructions on setting up +credentials for applications. + +.. _Authentication Getting Started Guide: + https://cloud.google.com/docs/authentication/getting-started diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst new file mode 100644 index 00000000..11957ce2 --- /dev/null +++ b/scripts/readme-gen/templates/auth_api_key.tmpl.rst @@ -0,0 +1,14 @@ +Authentication +++++++++++++++ + +Authentication for this service is done via an `API Key`_. To obtain an API +Key: + +1. Open the `Cloud Platform Console`_ +2. Make sure that billing is enabled for your project. +3. From the **Credentials** page, create a new **API Key** or use an existing + one for your project. + +.. _API Key: + https://developers.google.com/api-client-library/python/guide/aaa_apikeys +.. _Cloud Console: https://console.cloud.google.com/project?_ diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst new file mode 100644 index 00000000..a0406dba --- /dev/null +++ b/scripts/readme-gen/templates/install_deps.tmpl.rst @@ -0,0 +1,29 @@ +Install Dependencies +++++++++++++++++++++ + +#. Clone python-docs-samples and change directory to the sample directory you want to use. + + .. code-block:: bash + + $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + +#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. + + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup + +#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. + + .. code-block:: bash + + $ virtualenv env + $ source env/bin/activate + +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt + +.. _pip: https://pip.pypa.io/ +.. _virtualenv: https://virtualenv.pypa.io/ diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst new file mode 100644 index 00000000..5ea33d18 --- /dev/null +++ b/scripts/readme-gen/templates/install_portaudio.tmpl.rst @@ -0,0 +1,35 @@ +Install PortAudio ++++++++++++++++++ + +Install `PortAudio`_. This is required by the `PyAudio`_ library to stream +audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the +platform. + +* For Mac OS X, you can use `Homebrew`_:: + + brew install portaudio + + **Note**: if you encounter an error when running `pip install` that indicates + it can't find `portaudio.h`, try running `pip install` with the following + flags:: + + pip install --global-option='build_ext' \ + --global-option='-I/usr/local/include' \ + --global-option='-L/usr/local/lib' \ + pyaudio + +* For Debian / Ubuntu Linux:: + + apt-get install portaudio19-dev python-all-dev + +* Windows may work without having to install PortAudio explicitly (it will get + installed with PyAudio). + +For more details, see the `PyAudio installation`_ page. + + +.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/ +.. _PortAudio: http://www.portaudio.com/ +.. _PyAudio installation: + https://people.csail.mit.edu/hubert/pyaudio/#downloads +.. _Homebrew: http://brew.sh diff --git a/setup.py b/setup.py index 5ecd976b..41039479 100644 --- a/setup.py +++ b/setup.py @@ -21,14 +21,16 @@ name = "google-cloud-scheduler" description = "Cloud Scheduler API API client library" -version = "1.3.0" +version = "2.0.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", + "proto-plus >= 1.4.0", + "libcst >= 0.2.5", 'enum34; python_version < "3.4"', ] @@ -43,7 +45,9 @@ # Only include packages under the 'google' namespace. Do not include tests, # benchmarks, etc. packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] # Determine which namespaces are needed. @@ -65,12 +69,10 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -78,7 +80,11 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", include_package_data=True, zip_safe=False, + scripts=[ + "scripts/fixup_scheduler_v1_keywords.py", + "scripts/fixup_scheduler_v1beta1_keywords.py", + ], ) diff --git a/synth.metadata b/synth.metadata index b4a0f334..ee44b9a8 100644 --- a/synth.metadata +++ b/synth.metadata @@ -1,32 +1,24 @@ { "sources": [ - { - "generator": { - "name": "artman", - "version": "2.0.0", - "dockerImage": "googleapis/artman@sha256:b3b47805231a305d0f40c4bf069df20f6a2635574e6d4259fac651d3f9f6e098" - } - }, { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-scheduler.git", - "sha": "d17f5ffd8d6030190e3529d6eed5c9899145dd96" + "remote": "git@github.com:googleapis/python-scheduler.git", + "sha": "01d77f73c9c80b76376b7f1efa48a5eafeb47f2f" } }, { "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "42ee97c1b93a0e3759bbba3013da309f670a90ab", - "internalRef": "307114445" + "name": "synthtool", + "remote": "https://github.com/googleapis/synthtool.git", + "sha": "2e85c10b5153defd9d654c34b57e7e9263361959" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "f5e4c17dc78a966dbf29961dd01f9bbd63e20a04" + "sha": "2e85c10b5153defd9d654c34b57e7e9263361959" } } ], @@ -37,8 +29,7 @@ "apiName": "scheduler", "apiVersion": "v1beta1", "language": "python", - "generator": "gapic", - "config": "google/cloud/scheduler/artman_cloudscheduler_v1beta1.yaml" + "generator": "bazel" } }, { @@ -47,8 +38,7 @@ "apiName": "scheduler", "apiVersion": "v1", "language": "python", - "generator": "gapic", - "config": "google/cloud/scheduler/artman_cloudscheduler_v1.yaml" + "generator": "bazel" } } ] diff --git a/synth.py b/synth.py index 8bd9f163..74fbf3a4 100644 --- a/synth.py +++ b/synth.py @@ -16,6 +16,7 @@ import synthtool as s import synthtool.gcp as gcp +from synthtool.languages import python import logging logging.basicConfig(level=logging.DEBUG) @@ -49,7 +50,17 @@ # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=86) -s.move(templated_files) +templated_files = common.py_library( + samples=True, + microgenerator=True, +) +s.move(templated_files, excludes=[".coveragerc"]) + +# ---------------------------------------------------------------------------- +# Samples templates +# ---------------------------------------------------------------------------- + +python.py_samples(skip_readmes=True) + s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/testing/.gitignore b/testing/.gitignore new file mode 100644 index 00000000..b05fbd63 --- /dev/null +++ b/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file diff --git a/tests/system.py b/tests/system.py index 6e4daabb..317caf53 100644 --- a/tests/system.py +++ b/tests/system.py @@ -20,5 +20,7 @@ class TestSystemScheduler(object): def test_create_job(self): client = scheduler_v1.CloudSchedulerClient() - parent = client.location_path(os.environ.get("PROJECT_ID"), "us-central1") - client.list_jobs(parent) + project_id = os.environ.get("PROJECT_ID") + location_id = "us-central1" + parent = f"projects/{project_id}/locations/{location_id}" + client.list_jobs(parent=parent) diff --git a/tests/unit/gapic/scheduler_v1/__init__.py b/tests/unit/gapic/scheduler_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/scheduler_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/scheduler_v1/test_cloud_scheduler.py b/tests/unit/gapic/scheduler_v1/test_cloud_scheduler.py new file mode 100644 index 00000000..b0566dff --- /dev/null +++ b/tests/unit/gapic/scheduler_v1/test_cloud_scheduler.py @@ -0,0 +1,2494 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.scheduler_v1.services.cloud_scheduler import CloudSchedulerAsyncClient +from google.cloud.scheduler_v1.services.cloud_scheduler import CloudSchedulerClient +from google.cloud.scheduler_v1.services.cloud_scheduler import pagers +from google.cloud.scheduler_v1.services.cloud_scheduler import transports +from google.cloud.scheduler_v1.types import cloudscheduler +from google.cloud.scheduler_v1.types import job +from google.cloud.scheduler_v1.types import job as gcs_job +from google.cloud.scheduler_v1.types import target +from google.oauth2 import service_account +from google.protobuf import any_pb2 as any # type: ignore +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as gr_status # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudSchedulerClient._get_default_mtls_endpoint(None) is None + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [CloudSchedulerClient, CloudSchedulerAsyncClient] +) +def test_cloud_scheduler_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudscheduler.googleapis.com:443" + + +def test_cloud_scheduler_client_get_transport_class(): + transport = CloudSchedulerClient.get_transport_class() + assert transport == transports.CloudSchedulerGrpcTransport + + transport = CloudSchedulerClient.get_transport_class("grpc") + assert transport == transports.CloudSchedulerGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (CloudSchedulerClient, transports.CloudSchedulerGrpcTransport, "grpc"), + ( + CloudSchedulerAsyncClient, + transports.CloudSchedulerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + CloudSchedulerClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudSchedulerClient), +) +@mock.patch.object( + CloudSchedulerAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudSchedulerAsyncClient), +) +def test_cloud_scheduler_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(CloudSchedulerClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CloudSchedulerClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (CloudSchedulerClient, transports.CloudSchedulerGrpcTransport, "grpc"), + ( + CloudSchedulerAsyncClient, + transports.CloudSchedulerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_cloud_scheduler_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (CloudSchedulerClient, transports.CloudSchedulerGrpcTransport, "grpc"), + ( + CloudSchedulerAsyncClient, + transports.CloudSchedulerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_cloud_scheduler_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_cloud_scheduler_client_client_options_from_dict(): + with mock.patch( + "google.cloud.scheduler_v1.services.cloud_scheduler.transports.CloudSchedulerGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudSchedulerClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_list_jobs( + transport: str = "grpc", request_type=cloudscheduler.ListJobsRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = cloudscheduler.ListJobsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_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] == cloudscheduler.ListJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListJobsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_jobs_from_dict(): + test_list_jobs(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_jobs_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.ListJobsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloudscheduler.ListJobsResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_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 response is the type that we expect. + assert isinstance(response, pagers.ListJobsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_jobs_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ListJobsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + call.return_value = cloudscheduler.ListJobsResponse() + + client.list_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_jobs_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ListJobsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloudscheduler.ListJobsResponse() + ) + + await client.list_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_jobs_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = cloudscheduler.ListJobsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_jobs_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_jobs( + cloudscheduler.ListJobsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_jobs_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloudscheduler.ListJobsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloudscheduler.ListJobsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_jobs_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_jobs( + cloudscheduler.ListJobsRequest(), parent="parent_value", + ) + + +def test_list_jobs_pager(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_jobs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, job.Job) for i in results) + + +def test_list_jobs_pages(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + pages = list(client.list_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_jobs_async_pager(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + async_pager = await client.list_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, job.Job) for i in responses) + + +@pytest.mark.asyncio +async def test_list_jobs_async_pages(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + pages = [] + async for page in (await client.list_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_get_job(transport: str = "grpc", request_type=cloudscheduler.GetJobRequest): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.get_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] == cloudscheduler.GetJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_get_job_from_dict(): + test_get_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.GetJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.get_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_get_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.GetJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_job), "__call__") as call: + call.return_value = job.Job() + + client.get_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_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.GetJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.get_job), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.get_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_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_job( + cloudscheduler.GetJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_job( + cloudscheduler.GetJobRequest(), name="name_value", + ) + + +def test_create_job( + transport: str = "grpc", request_type=cloudscheduler.CreateJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.create_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] == cloudscheduler.CreateJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_create_job_from_dict(): + test_create_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.CreateJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + ) + ) + + response = await client.create_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 response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_create_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.CreateJobRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_job), "__call__") as call: + call.return_value = gcs_job.Job() + + client.create_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_create_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.CreateJobRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + + await client.create_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_create_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_job( + parent="parent_value", job=gcs_job.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].parent == "parent_value" + + assert args[0].job == gcs_job.Job(name="name_value") + + +def test_create_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_job( + cloudscheduler.CreateJobRequest(), + parent="parent_value", + job=gcs_job.Job(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_job( + parent="parent_value", job=gcs_job.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].parent == "parent_value" + + assert args[0].job == gcs_job.Job(name="name_value") + + +@pytest.mark.asyncio +async def test_create_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_job( + cloudscheduler.CreateJobRequest(), + parent="parent_value", + job=gcs_job.Job(name="name_value"), + ) + + +def test_update_job( + transport: str = "grpc", request_type=cloudscheduler.UpdateJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.update_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] == cloudscheduler.UpdateJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_update_job_from_dict(): + test_update_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.UpdateJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + ) + ) + + response = await client.update_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 response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_update_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.UpdateJobRequest() + request.job.name = "job.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_job), "__call__") as call: + call.return_value = gcs_job.Job() + + client.update_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", "job.name=job.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.UpdateJobRequest() + request.job.name = "job.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + + await client.update_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", "job.name=job.name/value",) in kw["metadata"] + + +def test_update_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_job( + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.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].job == gcs_job.Job(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_job( + cloudscheduler.UpdateJobRequest(), + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_job( + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.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].job == gcs_job.Job(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_job( + cloudscheduler.UpdateJobRequest(), + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_job( + transport: str = "grpc", request_type=cloudscheduler.DeleteJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_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] == cloudscheduler.DeleteJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_job_from_dict(): + test_delete_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.DeleteJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_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 response is the type that we expect. + assert response is None + + +def test_delete_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.DeleteJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_job), "__call__") as call: + call.return_value = None + + client.delete_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_delete_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.DeleteJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_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_delete_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_job), "__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_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_delete_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_job( + cloudscheduler.DeleteJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_job), "__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_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_delete_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_job( + cloudscheduler.DeleteJobRequest(), name="name_value", + ) + + +def test_pause_job( + transport: str = "grpc", request_type=cloudscheduler.PauseJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.pause_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.pause_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] == cloudscheduler.PauseJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_pause_job_from_dict(): + test_pause_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_pause_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.PauseJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.pause_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.pause_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_pause_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.PauseJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.pause_job), "__call__") as call: + call.return_value = job.Job() + + client.pause_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_pause_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.PauseJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.pause_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.pause_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_pause_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.pause_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.pause_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_pause_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.pause_job( + cloudscheduler.PauseJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_pause_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.pause_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.pause_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_pause_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.pause_job( + cloudscheduler.PauseJobRequest(), name="name_value", + ) + + +def test_resume_job( + transport: str = "grpc", request_type=cloudscheduler.ResumeJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.resume_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.resume_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] == cloudscheduler.ResumeJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_resume_job_from_dict(): + test_resume_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_resume_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.ResumeJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.resume_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.resume_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_resume_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ResumeJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.resume_job), "__call__") as call: + call.return_value = job.Job() + + client.resume_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_resume_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ResumeJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.resume_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.resume_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_resume_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.resume_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.resume_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_resume_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.resume_job( + cloudscheduler.ResumeJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_resume_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.resume_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.resume_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_resume_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.resume_job( + cloudscheduler.ResumeJobRequest(), name="name_value", + ) + + +def test_run_job(transport: str = "grpc", request_type=cloudscheduler.RunJobRequest): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.run_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] == cloudscheduler.RunJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_run_job_from_dict(): + test_run_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_run_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.RunJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.run_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_run_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.RunJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.run_job), "__call__") as call: + call.return_value = job.Job() + + client.run_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_run_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.RunJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.run_job), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.run_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_run_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.run_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_run_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_job( + cloudscheduler.RunJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_run_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.run_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_run_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_job( + cloudscheduler.RunJobRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudSchedulerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudSchedulerClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = CloudSchedulerClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.CloudSchedulerGrpcTransport,) + + +def test_cloud_scheduler_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.CloudSchedulerTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_scheduler_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.scheduler_v1.services.cloud_scheduler.transports.CloudSchedulerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudSchedulerTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_jobs", + "get_job", + "create_job", + "update_job", + "delete_job", + "pause_job", + "resume_job", + "run_job", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_cloud_scheduler_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.scheduler_v1.services.cloud_scheduler.transports.CloudSchedulerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.CloudSchedulerTransport( + 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_cloud_scheduler_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + CloudSchedulerClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_cloud_scheduler_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_scheduler_host_no_port(): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudscheduler.googleapis.com" + ), + ) + assert client._transport._host == "cloudscheduler.googleapis.com:443" + + +def test_cloud_scheduler_host_with_port(): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudscheduler.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudscheduler.googleapis.com:8000" + + +def test_cloud_scheduler_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_cloud_scheduler_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_cloud_scheduler_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_cloud_scheduler_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_cloud_scheduler_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_cloud_scheduler_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_job_path(): + project = "squid" + location = "clam" + job = "whelk" + + expected = "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, location=location, job=job, + ) + actual = CloudSchedulerClient.job_path(project, location, job) + assert expected == actual + + +def test_parse_job_path(): + expected = { + "project": "octopus", + "location": "oyster", + "job": "nudibranch", + } + path = CloudSchedulerClient.job_path(**expected) + + # Check that the path construction is reversible. + actual = CloudSchedulerClient.parse_job_path(path) + assert expected == actual diff --git a/tests/unit/gapic/scheduler_v1beta1/__init__.py b/tests/unit/gapic/scheduler_v1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/scheduler_v1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/scheduler_v1beta1/test_cloud_scheduler.py b/tests/unit/gapic/scheduler_v1beta1/test_cloud_scheduler.py new file mode 100644 index 00000000..fad4d6d1 --- /dev/null +++ b/tests/unit/gapic/scheduler_v1beta1/test_cloud_scheduler.py @@ -0,0 +1,2496 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.scheduler_v1beta1.services.cloud_scheduler import ( + CloudSchedulerAsyncClient, +) +from google.cloud.scheduler_v1beta1.services.cloud_scheduler import CloudSchedulerClient +from google.cloud.scheduler_v1beta1.services.cloud_scheduler import pagers +from google.cloud.scheduler_v1beta1.services.cloud_scheduler import transports +from google.cloud.scheduler_v1beta1.types import cloudscheduler +from google.cloud.scheduler_v1beta1.types import job +from google.cloud.scheduler_v1beta1.types import job as gcs_job +from google.cloud.scheduler_v1beta1.types import target +from google.oauth2 import service_account +from google.protobuf import any_pb2 as any # type: ignore +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as gr_status # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudSchedulerClient._get_default_mtls_endpoint(None) is None + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudSchedulerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [CloudSchedulerClient, CloudSchedulerAsyncClient] +) +def test_cloud_scheduler_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudscheduler.googleapis.com:443" + + +def test_cloud_scheduler_client_get_transport_class(): + transport = CloudSchedulerClient.get_transport_class() + assert transport == transports.CloudSchedulerGrpcTransport + + transport = CloudSchedulerClient.get_transport_class("grpc") + assert transport == transports.CloudSchedulerGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (CloudSchedulerClient, transports.CloudSchedulerGrpcTransport, "grpc"), + ( + CloudSchedulerAsyncClient, + transports.CloudSchedulerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + CloudSchedulerClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudSchedulerClient), +) +@mock.patch.object( + CloudSchedulerAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudSchedulerAsyncClient), +) +def test_cloud_scheduler_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(CloudSchedulerClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(CloudSchedulerClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (CloudSchedulerClient, transports.CloudSchedulerGrpcTransport, "grpc"), + ( + CloudSchedulerAsyncClient, + transports.CloudSchedulerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_cloud_scheduler_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (CloudSchedulerClient, transports.CloudSchedulerGrpcTransport, "grpc"), + ( + CloudSchedulerAsyncClient, + transports.CloudSchedulerGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_cloud_scheduler_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_cloud_scheduler_client_client_options_from_dict(): + with mock.patch( + "google.cloud.scheduler_v1beta1.services.cloud_scheduler.transports.CloudSchedulerGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudSchedulerClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_list_jobs( + transport: str = "grpc", request_type=cloudscheduler.ListJobsRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = cloudscheduler.ListJobsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_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] == cloudscheduler.ListJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListJobsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_jobs_from_dict(): + test_list_jobs(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_jobs_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.ListJobsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloudscheduler.ListJobsResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_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 response is the type that we expect. + assert isinstance(response, pagers.ListJobsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_jobs_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ListJobsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + call.return_value = cloudscheduler.ListJobsResponse() + + client.list_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_jobs_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ListJobsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloudscheduler.ListJobsResponse() + ) + + await client.list_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_jobs_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = cloudscheduler.ListJobsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_jobs_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_jobs( + cloudscheduler.ListJobsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_jobs_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cloudscheduler.ListJobsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloudscheduler.ListJobsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_jobs_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_jobs( + cloudscheduler.ListJobsRequest(), parent="parent_value", + ) + + +def test_list_jobs_pager(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_jobs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, job.Job) for i in results) + + +def test_list_jobs_pages(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_jobs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + pages = list(client.list_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_jobs_async_pager(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + async_pager = await client.list_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, job.Job) for i in responses) + + +@pytest.mark.asyncio +async def test_list_jobs_async_pages(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_jobs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + cloudscheduler.ListJobsResponse( + jobs=[job.Job(), job.Job(), job.Job(),], next_page_token="abc", + ), + cloudscheduler.ListJobsResponse(jobs=[], next_page_token="def",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(),], next_page_token="ghi",), + cloudscheduler.ListJobsResponse(jobs=[job.Job(), job.Job(),],), + RuntimeError, + ) + pages = [] + async for page in (await client.list_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_get_job(transport: str = "grpc", request_type=cloudscheduler.GetJobRequest): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.get_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] == cloudscheduler.GetJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_get_job_from_dict(): + test_get_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.GetJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.get_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_get_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.GetJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_job), "__call__") as call: + call.return_value = job.Job() + + client.get_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_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.GetJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.get_job), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.get_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_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_job( + cloudscheduler.GetJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_job( + cloudscheduler.GetJobRequest(), name="name_value", + ) + + +def test_create_job( + transport: str = "grpc", request_type=cloudscheduler.CreateJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.create_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] == cloudscheduler.CreateJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_create_job_from_dict(): + test_create_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.CreateJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + ) + ) + + response = await client.create_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 response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_create_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.CreateJobRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_job), "__call__") as call: + call.return_value = gcs_job.Job() + + client.create_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_create_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.CreateJobRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + + await client.create_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_create_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_job( + parent="parent_value", job=gcs_job.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].parent == "parent_value" + + assert args[0].job == gcs_job.Job(name="name_value") + + +def test_create_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_job( + cloudscheduler.CreateJobRequest(), + parent="parent_value", + job=gcs_job.Job(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_job( + parent="parent_value", job=gcs_job.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].parent == "parent_value" + + assert args[0].job == gcs_job.Job(name="name_value") + + +@pytest.mark.asyncio +async def test_create_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_job( + cloudscheduler.CreateJobRequest(), + parent="parent_value", + job=gcs_job.Job(name="name_value"), + ) + + +def test_update_job( + transport: str = "grpc", request_type=cloudscheduler.UpdateJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.update_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] == cloudscheduler.UpdateJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_update_job_from_dict(): + test_update_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.UpdateJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=gcs_job.Job.State.ENABLED, + ) + ) + + response = await client.update_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 response is the type that we expect. + assert isinstance(response, gcs_job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == gcs_job.Job.State.ENABLED + + +def test_update_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.UpdateJobRequest() + request.job.name = "job.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_job), "__call__") as call: + call.return_value = gcs_job.Job() + + client.update_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", "job.name=job.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.UpdateJobRequest() + request.job.name = "job.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + + await client.update_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", "job.name=job.name/value",) in kw["metadata"] + + +def test_update_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_job( + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.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].job == gcs_job.Job(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_job( + cloudscheduler.UpdateJobRequest(), + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_job( + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.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].job == gcs_job.Job(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_job( + cloudscheduler.UpdateJobRequest(), + job=gcs_job.Job(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_job( + transport: str = "grpc", request_type=cloudscheduler.DeleteJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_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] == cloudscheduler.DeleteJobRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_job_from_dict(): + test_delete_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.DeleteJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_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 response is the type that we expect. + assert response is None + + +def test_delete_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.DeleteJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_job), "__call__") as call: + call.return_value = None + + client.delete_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_delete_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.DeleteJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_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_delete_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_job), "__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_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_delete_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_job( + cloudscheduler.DeleteJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_job), "__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_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_delete_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_job( + cloudscheduler.DeleteJobRequest(), name="name_value", + ) + + +def test_pause_job( + transport: str = "grpc", request_type=cloudscheduler.PauseJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.pause_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.pause_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] == cloudscheduler.PauseJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_pause_job_from_dict(): + test_pause_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_pause_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.PauseJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.pause_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.pause_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_pause_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.PauseJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.pause_job), "__call__") as call: + call.return_value = job.Job() + + client.pause_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_pause_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.PauseJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.pause_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.pause_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_pause_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.pause_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.pause_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_pause_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.pause_job( + cloudscheduler.PauseJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_pause_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.pause_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.pause_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_pause_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.pause_job( + cloudscheduler.PauseJobRequest(), name="name_value", + ) + + +def test_resume_job( + transport: str = "grpc", request_type=cloudscheduler.ResumeJobRequest +): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.resume_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.resume_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] == cloudscheduler.ResumeJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_resume_job_from_dict(): + test_resume_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_resume_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.ResumeJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.resume_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.resume_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_resume_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ResumeJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.resume_job), "__call__") as call: + call.return_value = job.Job() + + client.resume_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_resume_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.ResumeJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.resume_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.resume_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_resume_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.resume_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.resume_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_resume_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.resume_job( + cloudscheduler.ResumeJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_resume_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.resume_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.resume_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_resume_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.resume_job( + cloudscheduler.ResumeJobRequest(), name="name_value", + ) + + +def test_run_job(transport: str = "grpc", request_type=cloudscheduler.RunJobRequest): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + pubsub_target=target.PubsubTarget(topic_name="topic_name_value"), + ) + + response = client.run_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] == cloudscheduler.RunJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_run_job_from_dict(): + test_run_job(request_type=dict) + + +@pytest.mark.asyncio +async def test_run_job_async(transport: str = "grpc_asyncio"): + client = CloudSchedulerAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = cloudscheduler.RunJobRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + description="description_value", + schedule="schedule_value", + time_zone="time_zone_value", + state=job.Job.State.ENABLED, + ) + ) + + response = await client.run_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 response is the type that we expect. + assert isinstance(response, job.Job) + + assert response.name == "name_value" + + assert response.description == "description_value" + + assert response.schedule == "schedule_value" + + assert response.time_zone == "time_zone_value" + + assert response.state == job.Job.State.ENABLED + + +def test_run_job_field_headers(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.RunJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.run_job), "__call__") as call: + call.return_value = job.Job() + + client.run_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_run_job_field_headers_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = cloudscheduler.RunJobRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.run_job), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + + await client.run_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_run_job_flattened(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.run_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_run_job_flattened_error(): + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_job( + cloudscheduler.RunJobRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_run_job_flattened_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._client._transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = job.Job() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.run_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_run_job_flattened_error_async(): + client = CloudSchedulerAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_job( + cloudscheduler.RunJobRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudSchedulerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudSchedulerClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = CloudSchedulerClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudSchedulerGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudSchedulerClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.CloudSchedulerGrpcTransport,) + + +def test_cloud_scheduler_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.CloudSchedulerTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_scheduler_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.scheduler_v1beta1.services.cloud_scheduler.transports.CloudSchedulerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudSchedulerTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_jobs", + "get_job", + "create_job", + "update_job", + "delete_job", + "pause_job", + "resume_job", + "run_job", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_cloud_scheduler_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.scheduler_v1beta1.services.cloud_scheduler.transports.CloudSchedulerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.CloudSchedulerTransport( + 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_cloud_scheduler_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + CloudSchedulerClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_cloud_scheduler_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_scheduler_host_no_port(): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudscheduler.googleapis.com" + ), + ) + assert client._transport._host == "cloudscheduler.googleapis.com:443" + + +def test_cloud_scheduler_host_with_port(): + client = CloudSchedulerClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudscheduler.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudscheduler.googleapis.com:8000" + + +def test_cloud_scheduler_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_cloud_scheduler_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_cloud_scheduler_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_cloud_scheduler_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_cloud_scheduler_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.CloudSchedulerGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_cloud_scheduler_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.CloudSchedulerGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_job_path(): + project = "squid" + location = "clam" + job = "whelk" + + expected = "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, location=location, job=job, + ) + actual = CloudSchedulerClient.job_path(project, location, job) + assert expected == actual + + +def test_parse_job_path(): + expected = { + "project": "octopus", + "location": "oyster", + "job": "nudibranch", + } + path = CloudSchedulerClient.job_path(**expected) + + # Check that the path construction is reversible. + actual = CloudSchedulerClient.parse_job_path(path) + assert expected == actual diff --git a/tests/unit/gapic/v1/test_cloud_scheduler_client_v1.py b/tests/unit/gapic/v1/test_cloud_scheduler_client_v1.py deleted file mode 100644 index 7b8a5412..00000000 --- a/tests/unit/gapic/v1/test_cloud_scheduler_client_v1.py +++ /dev/null @@ -1,420 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import scheduler_v1 -from google.cloud.scheduler_v1.proto import cloudscheduler_pb2 -from google.cloud.scheduler_v1.proto import job_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestCloudSchedulerClient(object): - def test_list_jobs(self): - # Setup Expected Response - next_page_token = "" - jobs_element = {} - jobs = [jobs_element] - expected_response = {"next_page_token": next_page_token, "jobs": jobs} - expected_response = cloudscheduler_pb2.ListJobsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_jobs(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.jobs[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.ListJobsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_jobs_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_jobs(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.get_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.GetJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.get_job(name) - - def test_create_job(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - job = {} - - response = client.create_job(parent, job) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.CreateJobRequest(parent=parent, job=job) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - job = {} - - with pytest.raises(CustomException): - client.create_job(parent, job) - - def test_update_job(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - job = {} - update_mask = {} - - response = client.update_job(job, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.UpdateJobRequest( - job=job, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - job = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_job(job, update_mask) - - def test_delete_job(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - client.delete_job(name) - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.DeleteJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.delete_job(name) - - def test_pause_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.pause_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.PauseJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_pause_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.pause_job(name) - - def test_resume_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.resume_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.ResumeJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_resume_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.resume_job(name) - - def test_run_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.run_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.RunJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_run_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.run_job(name) diff --git a/tests/unit/gapic/v1beta1/test_cloud_scheduler_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_cloud_scheduler_client_v1beta1.py deleted file mode 100644 index 84e0fd6d..00000000 --- a/tests/unit/gapic/v1beta1/test_cloud_scheduler_client_v1beta1.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import scheduler_v1beta1 -from google.cloud.scheduler_v1beta1.proto import cloudscheduler_pb2 -from google.cloud.scheduler_v1beta1.proto import job_pb2 -from google.protobuf import empty_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestCloudSchedulerClient(object): - def test_list_jobs(self): - # Setup Expected Response - next_page_token = "" - jobs_element = {} - jobs = [jobs_element] - expected_response = {"next_page_token": next_page_token, "jobs": jobs} - expected_response = cloudscheduler_pb2.ListJobsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_jobs(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.jobs[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.ListJobsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_jobs_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_jobs(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.get_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.GetJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.get_job(name) - - def test_create_job(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - job = {} - - response = client.create_job(parent, job) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.CreateJobRequest(parent=parent, job=job) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - job = {} - - with pytest.raises(CustomException): - client.create_job(parent, job) - - def test_update_job(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - job = {} - - response = client.update_job(job) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.UpdateJobRequest(job=job) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - job = {} - - with pytest.raises(CustomException): - client.update_job(job) - - def test_delete_job(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - client.delete_job(name) - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.DeleteJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.delete_job(name) - - def test_pause_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.pause_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.PauseJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_pause_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.pause_job(name) - - def test_resume_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.resume_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.ResumeJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_resume_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.resume_job(name) - - def test_run_job(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - schedule = "schedule-697920873" - time_zone = "timeZone36848094" - expected_response = { - "name": name_2, - "description": description, - "schedule": schedule, - "time_zone": time_zone, - } - expected_response = job_pb2.Job(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup Request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - response = client.run_job(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = cloudscheduler_pb2.RunJobRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_run_job_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = scheduler_v1beta1.CloudSchedulerClient() - - # Setup request - name = client.job_path("[PROJECT]", "[LOCATION]", "[JOB]") - - with pytest.raises(CustomException): - client.run_job(name)