Skip to content
This repository has been archived by the owner on Mar 20, 2018. It is now read-only.

Add OperationFuture class #142

Merged
merged 20 commits into from
Jan 10, 2017
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
include README.rst LICENSE
global-include *.json
1 change: 1 addition & 0 deletions google/gapic/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__import__('pkg_resources').declare_namespace(__name__)
1 change: 1 addition & 0 deletions google/gapic/longrunning/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__import__('pkg_resources').declare_namespace(__name__)
279 changes: 279 additions & 0 deletions google/gapic/longrunning/operations_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
# Copyright 2016 Google Inc. All rights reserved.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to switch this to BSD to conform to the rest of GAX. This is supposed to be configured in the GAPIC config here, but I expect it's not working because Python isn't on MVVM and the license is hardcoded into the template files.

In a separate toolkit PR, could you update the Python templates to select the correct license based on that GAPIC config field?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you update this manually until we can regenerate the package in api-client-staging? (Or, preferably, update the package in api-client-staging and copy it back into here.)

#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# EDITING INSTRUCTIONS
# This file was generated from the file
# https://github.com/google/googleapis/blob/master/google/longrunning/operations.proto,
# and updates to that file get reflected here through a refresh process.
# For the short term, the refresh process will only be runnable by Google engineers.
#
# The only allowed edits are to method and file documentation. A 3-way
# merge preserves those additions if the generated source changes.
"""Accesses the google.longrunning Operations API."""

import json
import os
import pkg_resources
import platform

from google.gax import api_callable
from google.gax import config
from google.gax import path_template
import google.gax

from google.longrunning import operations_pb2

_PageDesc = google.gax.PageDescriptor


class OperationsClient(object):
"""
Manages long-running operations with an API service.

When an API method normally takes long time to complete, it can be designed
to return ``Operation`` to the client, and the client can use this
interface to receive the real response asynchronously by polling the
operation resource, or pass the operation resource to another API (such as
Google Cloud Pub/Sub API) to receive the response. Any API service that
returns long-running operations should implement the ``Operations`` interface
so developers can have a consistent client experience.
"""

SERVICE_ADDRESS = 'longrunning.googleapis.com'
"""The default address of the service."""

DEFAULT_SERVICE_PORT = 443
"""The default port of the service."""

_CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

_GAX_VERSION = pkg_resources.get_distribution('google-gax').version

_PAGE_DESCRIPTORS = {
'list_operations': _PageDesc('page_token', 'next_page_token',
'operations')
}

# The scopes needed to make gRPC calls to all of the methods defined in
# this service
_ALL_SCOPES = ()

def __init__(self,
service_path=SERVICE_ADDRESS,
port=DEFAULT_SERVICE_PORT,
channel=None,
credentials=None,
ssl_credentials=None,
scopes=None,
client_config=None,
app_name='gax',
app_version=_GAX_VERSION):
"""Constructor.

Args:
service_path (string): The domain name of the API remote host.
port (int): The port on which to connect to the remote host.
channel (:class:`grpc.Channel`): A ``Channel`` instance through
which to make calls.
credentials (object): The authorization credentials to attach to
requests. These credentials identify this application to the
service.
ssl_credentials (:class:`grpc.ChannelCredentials`): A
``ChannelCredentials`` instance for use with an SSL-enabled
channel.
scopes (list[string]): A list of OAuth2 scopes to attach to requests.
client_config (dict):
A dictionary for call options for each method. See
:func:`google.gax.construct_settings` for the structure of
this data. Falls back to the default config if not specified
or the specified config is missing data points.
app_name (string): The codename of the calling service.
app_version (string): The version of the calling service.

Returns:
A OperationsClient object.
"""
if scopes is None:
scopes = self._ALL_SCOPES
if client_config is None:
client_config = {}
goog_api_client = '{}/{} {} gax/{} python/{}'.format(
app_name, app_version, self._CODE_GEN_NAME_VERSION,
self._GAX_VERSION, platform.python_version())
metadata = [('x-goog-api-client', goog_api_client)]
default_client_config = json.loads(
pkg_resources.resource_string(
__name__, 'operations_client_config.json').decode())
defaults = api_callable.construct_settings(
'google.longrunning.Operations',
default_client_config,
client_config,
config.STATUS_CODE_NAMES,
kwargs={'metadata': metadata},
page_descriptors=self._PAGE_DESCRIPTORS)
self.operations_stub = config.create_stub(
operations_pb2.OperationsStub,
channel=channel,
service_path=service_path,
service_port=port,
credentials=credentials,
scopes=scopes,
ssl_credentials=ssl_credentials)

self._get_operation = api_callable.create_api_call(
self.operations_stub.GetOperation,
settings=defaults['get_operation'])
self._list_operations = api_callable.create_api_call(
self.operations_stub.ListOperations,
settings=defaults['list_operations'])
self._cancel_operation = api_callable.create_api_call(
self.operations_stub.CancelOperation,
settings=defaults['cancel_operation'])
self._delete_operation = api_callable.create_api_call(
self.operations_stub.DeleteOperation,
settings=defaults['delete_operation'])

# Service calls
def get_operation(self, name, options=None):
"""
Gets the latest state of a long-running operation. Clients can use this
method to poll the operation result at intervals as recommended by the API
service.

Example:
>>> from google.gapic.longrunning import operations_client
>>> api = operations_client.OperationsClient()
>>> name = ''
>>> response = api.get_operation(name)

Args:
name (string): The name of the operation resource.
options (:class:`google.gax.CallOptions`): Overrides the default
settings for this call, e.g, timeout, retries etc.

Returns:
A :class:`google.longrunning.operations_pb2.Operation` instance.

Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
request = operations_pb2.GetOperationRequest(name=name)
return self._get_operation(request, options)

def list_operations(self, name, filter_, page_size=0, options=None):
"""
Lists operations that match the specified filter in the request. If the
server doesn't support this method, it returns ``UNIMPLEMENTED``.
NOTE: the ``name`` binding below allows API services to override the binding
to use different resource name schemes, such as ``users/*/operations``.

Example:
>>> from google.gapic.longrunning import operations_client
>>> from google.gax import CallOptions, INITIAL_PAGE
>>> api = operations_client.OperationsClient()
>>> name = ''
>>> filter_ = ''
>>>
>>> # Iterate over all results
>>> for element in api.list_operations(name, filter_):
>>> # process element
>>> pass
>>>
>>> # Or iterate over results one page at a time
>>> for page in api.list_operations(name, filter_, options=CallOptions(page_token=INITIAL_PAGE)):
>>> for element in page:
>>> # process element
>>> pass

Args:
name (string): The name of the operation collection.
filter_ (string): The standard list filter.
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.
options (:class:`google.gax.CallOptions`): Overrides the default
settings for this call, e.g, timeout, retries etc.

Returns:
A :class:`google.gax.PageIterator` instance. By default, this
is an iterable of :class:`google.longrunning.operations_pb2.Operation` instances.
This object can also be configured to iterate over the pages
of the response through the `CallOptions` parameter.

Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
request = operations_pb2.ListOperationsRequest(
name=name, filter=filter_, page_size=page_size)
return self._list_operations(request, options)

def cancel_operation(self, name, options=None):
"""
Starts asynchronous cancellation on a long-running operation. The server
makes a best effort to cancel the operation, but success is not
guaranteed. If the server doesn't support this method, it returns
``google.rpc.Code.UNIMPLEMENTED``. Clients can use
``Operations.GetOperation`` or
other methods to check whether the cancellation succeeded or whether the
operation completed despite cancellation. On successful cancellation,
the operation is not deleted; instead, it becomes an operation with
an ``Operation.error`` value with a ``google.rpc.Status.code`` of 1,
corresponding to ``Code.CANCELLED``.

Example:
>>> from google.gapic.longrunning import operations_client
>>> api = operations_client.OperationsClient()
>>> name = ''
>>> api.cancel_operation(name)

Args:
name (string): The name of the operation resource to be cancelled.
options (:class:`google.gax.CallOptions`): Overrides the default
settings for this call, e.g, timeout, retries etc.

Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
request = operations_pb2.CancelOperationRequest(name=name)
self._cancel_operation(request, options)

def delete_operation(self, name, options=None):
"""
Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
``google.rpc.Code.UNIMPLEMENTED``.

Example:
>>> from google.gapic.longrunning import operations_client
>>> api = operations_client.OperationsClient()
>>> name = ''
>>> api.delete_operation(name)

Args:
name (string): The name of the operation resource to be deleted.
options (:class:`google.gax.CallOptions`): Overrides the default
settings for this call, e.g, timeout, retries etc.

Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
request = operations_pb2.DeleteOperationRequest(name=name)
self._delete_operation(request, options)
48 changes: 48 additions & 0 deletions google/gapic/longrunning/operations_client_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"interfaces": {
"google.longrunning.Operations": {
"retry_codes": {
"retry_codes_def": {
"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": {
"GetOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListOperations": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"CancelOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"DeleteOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}
Loading