1# -*- coding: utf-8 -*-
2# Copyright 2020 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16from typing import Optional, Sequence, Tuple, Union
17
18from google.api_core import client_options as client_options_lib # type: ignore
19from google.api_core import gapic_v1 # type: ignore
20from google.api_core import retry as retries # type: ignore
21from google.api_core.operations_v1 import pagers
22from google.api_core.operations_v1.transports.base import (
23 DEFAULT_CLIENT_INFO,
24 OperationsTransport,
25)
26from google.api_core.operations_v1.abstract_operations_base_client import (
27 AbstractOperationsBaseClient,
28)
29from google.auth import credentials as ga_credentials # type: ignore
30from google.longrunning import operations_pb2
31from google.oauth2 import service_account # type: ignore
32import grpc
33
34OptionalRetry = Union[retries.Retry, object]
35
36
37class AbstractOperationsClient(AbstractOperationsBaseClient):
38 """Manages long-running operations with an API service.
39
40 When an API method normally takes long time to complete, it can be
41 designed to return [Operation][google.api_core.operations_v1.Operation] to the
42 client, and the client can use this interface to receive the real
43 response asynchronously by polling the operation resource, or pass
44 the operation resource to another API (such as Google Cloud Pub/Sub
45 API) to receive the response. Any API service that returns
46 long-running operations should implement the ``Operations``
47 interface so developers can have a consistent client experience.
48 """
49
50 def __init__(
51 self,
52 *,
53 credentials: Optional[ga_credentials.Credentials] = None,
54 transport: Union[str, OperationsTransport, None] = None,
55 client_options: Optional[client_options_lib.ClientOptions] = None,
56 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
57 ) -> None:
58 """Instantiates the operations client.
59
60 Args:
61 credentials (Optional[google.auth.credentials.Credentials]): The
62 authorization credentials to attach to requests. These
63 credentials identify the application to the service; if none
64 are specified, the client will attempt to ascertain the
65 credentials from the environment.
66 transport (Union[str, OperationsTransport]): The
67 transport to use. If set to None, a transport is chosen
68 automatically.
69 client_options (google.api_core.client_options.ClientOptions): Custom options for the
70 client. It won't take effect if a ``transport`` instance is provided.
71 (1) The ``api_endpoint`` property can be used to override the
72 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
73 environment variable can also be used to override the endpoint:
74 "always" (always use the default mTLS endpoint), "never" (always
75 use the default regular endpoint) and "auto" (auto switch to the
76 default mTLS endpoint if client certificate is present, this is
77 the default value). However, the ``api_endpoint`` property takes
78 precedence if provided.
79 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
80 is "true", then the ``client_cert_source`` property can be used
81 to provide client certificate for mutual TLS transport. If
82 not provided, the default SSL client certificate will be used if
83 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
84 set, no client certificate will be used.
85 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
86 The client info used to send a user-agent string along with
87 API requests. If ``None``, then default info will be used.
88 Generally, you only need to set this if you're developing
89 your own client library.
90
91 Raises:
92 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
93 creation failed for any reason.
94 """
95 super().__init__(
96 credentials=credentials,
97 transport=transport,
98 client_options=client_options,
99 client_info=client_info,
100 )
101
102 @classmethod
103 def from_service_account_info(cls, info: dict, *args, **kwargs):
104 """Creates an instance of this client using the provided credentials
105 info.
106
107 Args:
108 info (dict): The service account private key info.
109 args: Additional arguments to pass to the constructor.
110 kwargs: Additional arguments to pass to the constructor.
111
112 Returns:
113 AbstractOperationsClient: The constructed client.
114 """
115 credentials = service_account.Credentials.from_service_account_info(info)
116 kwargs["credentials"] = credentials
117 return cls(*args, **kwargs)
118
119 @classmethod
120 def from_service_account_file(cls, filename: str, *args, **kwargs):
121 """Creates an instance of this client using the provided credentials
122 file.
123
124 Args:
125 filename (str): The path to the service account private key json
126 file.
127 args: Additional arguments to pass to the constructor.
128 kwargs: Additional arguments to pass to the constructor.
129
130 Returns:
131 AbstractOperationsClient: The constructed client.
132 """
133 credentials = service_account.Credentials.from_service_account_file(filename)
134 kwargs["credentials"] = credentials
135 return cls(*args, **kwargs)
136
137 from_service_account_json = from_service_account_file
138
139 def list_operations(
140 self,
141 name: str,
142 filter_: Optional[str] = None,
143 *,
144 page_size: Optional[int] = None,
145 page_token: Optional[str] = None,
146 retry: OptionalRetry = gapic_v1.method.DEFAULT,
147 timeout: Optional[float] = None,
148 compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
149 metadata: Sequence[Tuple[str, str]] = (),
150 ) -> pagers.ListOperationsPager:
151 r"""Lists operations that match the specified filter in the request.
152 If the server doesn't support this method, it returns
153 ``UNIMPLEMENTED``.
154
155 NOTE: the ``name`` binding allows API services to override the
156 binding to use different resource name schemes, such as
157 ``users/*/operations``. To override the binding, API services
158 can add a binding such as ``"/v1/{name=users/*}/operations"`` to
159 their service configuration. For backwards compatibility, the
160 default name includes the operations collection id, however
161 overriding users must ensure the name binding is the parent
162 resource, without the operations collection id.
163
164 Args:
165 name (str):
166 The name of the operation's parent
167 resource.
168 filter_ (str):
169 The standard list filter.
170 This corresponds to the ``filter`` field
171 on the ``request`` instance; if ``request`` is provided, this
172 should not be set.
173 retry (google.api_core.retry.Retry): Designation of what errors, if any,
174 should be retried.
175 timeout (float): The timeout for this request.
176 metadata (Sequence[Tuple[str, str]]): Strings which should be
177 sent along with the request as metadata.
178
179 Returns:
180 google.api_core.operations_v1.pagers.ListOperationsPager:
181 The response message for
182 [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
183
184 Iterating over this object will yield results and
185 resolve additional pages automatically.
186
187 """
188 # Create a protobuf request object.
189 request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
190 if page_size is not None:
191 request.page_size = page_size
192 if page_token is not None:
193 request.page_token = page_token
194
195 # Wrap the RPC method; this adds retry and timeout information,
196 # and friendly error handling.
197 rpc = self._transport._wrapped_methods[self._transport.list_operations]
198
199 # Certain fields should be provided within the metadata header;
200 # add these here.
201 metadata = tuple(metadata or ()) + (
202 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
203 )
204
205 # Send the request.
206 response = rpc(
207 request,
208 retry=retry,
209 timeout=timeout,
210 compression=compression,
211 metadata=metadata,
212 )
213
214 # This method is paged; wrap the response in a pager, which provides
215 # an `__iter__` convenience method.
216 response = pagers.ListOperationsPager(
217 method=rpc,
218 request=request,
219 response=response,
220 metadata=metadata,
221 )
222
223 # Done; return the response.
224 return response
225
226 def get_operation(
227 self,
228 name: str,
229 *,
230 retry: OptionalRetry = gapic_v1.method.DEFAULT,
231 timeout: Optional[float] = None,
232 compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
233 metadata: Sequence[Tuple[str, str]] = (),
234 ) -> operations_pb2.Operation:
235 r"""Gets the latest state of a long-running operation.
236 Clients can use this method to poll the operation result
237 at intervals as recommended by the API service.
238
239 Args:
240 name (str):
241 The name of the operation resource.
242 retry (google.api_core.retry.Retry): Designation of what errors, if any,
243 should be retried.
244 timeout (float): The timeout for this request.
245 metadata (Sequence[Tuple[str, str]]): Strings which should be
246 sent along with the request as metadata.
247
248 Returns:
249 google.longrunning.operations_pb2.Operation:
250 This resource represents a long-
251 running operation that is the result of a
252 network API call.
253
254 """
255
256 request = operations_pb2.GetOperationRequest(name=name)
257
258 # Wrap the RPC method; this adds retry and timeout information,
259 # and friendly error handling.
260 rpc = self._transport._wrapped_methods[self._transport.get_operation]
261
262 # Certain fields should be provided within the metadata header;
263 # add these here.
264 metadata = tuple(metadata or ()) + (
265 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
266 )
267
268 # Send the request.
269 response = rpc(
270 request,
271 retry=retry,
272 timeout=timeout,
273 compression=compression,
274 metadata=metadata,
275 )
276
277 # Done; return the response.
278 return response
279
280 def delete_operation(
281 self,
282 name: str,
283 *,
284 retry: OptionalRetry = gapic_v1.method.DEFAULT,
285 timeout: Optional[float] = None,
286 compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
287 metadata: Sequence[Tuple[str, str]] = (),
288 ) -> None:
289 r"""Deletes a long-running operation. This method indicates that the
290 client is no longer interested in the operation result. It does
291 not cancel the operation. If the server doesn't support this
292 method, it returns ``google.rpc.Code.UNIMPLEMENTED``.
293
294 Args:
295 name (str):
296 The name of the operation resource to
297 be deleted.
298
299 This corresponds to the ``name`` field
300 on the ``request`` instance; if ``request`` is provided, this
301 should not be set.
302 retry (google.api_core.retry.Retry): Designation of what errors, if any,
303 should be retried.
304 timeout (float): The timeout for this request.
305 metadata (Sequence[Tuple[str, str]]): Strings which should be
306 sent along with the request as metadata.
307 """
308 # Create the request object.
309 request = operations_pb2.DeleteOperationRequest(name=name)
310
311 # Wrap the RPC method; this adds retry and timeout information,
312 # and friendly error handling.
313 rpc = self._transport._wrapped_methods[self._transport.delete_operation]
314
315 # Certain fields should be provided within the metadata header;
316 # add these here.
317 metadata = tuple(metadata or ()) + (
318 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
319 )
320
321 # Send the request.
322 rpc(
323 request,
324 retry=retry,
325 timeout=timeout,
326 compression=compression,
327 metadata=metadata,
328 )
329
330 def cancel_operation(
331 self,
332 name: Optional[str] = None,
333 *,
334 retry: OptionalRetry = gapic_v1.method.DEFAULT,
335 timeout: Optional[float] = None,
336 compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
337 metadata: Sequence[Tuple[str, str]] = (),
338 ) -> None:
339 r"""Starts asynchronous cancellation on a long-running operation.
340 The server makes a best effort to cancel the operation, but
341 success is not guaranteed. If the server doesn't support this
342 method, it returns ``google.rpc.Code.UNIMPLEMENTED``. Clients
343 can use
344 [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation]
345 or other methods to check whether the cancellation succeeded or
346 whether the operation completed despite cancellation. On
347 successful cancellation, the operation is not deleted; instead,
348 it becomes an operation with an
349 [Operation.error][google.api_core.operations_v1.Operation.error] value with
350 a [google.rpc.Status.code][google.rpc.Status.code] of 1,
351 corresponding to ``Code.CANCELLED``.
352
353 Args:
354 name (str):
355 The name of the operation resource to
356 be cancelled.
357
358 This corresponds to the ``name`` field
359 on the ``request`` instance; if ``request`` is provided, this
360 should not be set.
361 retry (google.api_core.retry.Retry): Designation of what errors, if any,
362 should be retried.
363 timeout (float): The timeout for this request.
364 metadata (Sequence[Tuple[str, str]]): Strings which should be
365 sent along with the request as metadata.
366 """
367 # Create the request object.
368 request = operations_pb2.CancelOperationRequest(name=name)
369
370 # Wrap the RPC method; this adds retry and timeout information,
371 # and friendly error handling.
372 rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
373
374 # Certain fields should be provided within the metadata header;
375 # add these here.
376 metadata = tuple(metadata or ()) + (
377 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
378 )
379
380 # Send the request.
381 rpc(
382 request,
383 retry=retry,
384 timeout=timeout,
385 compression=compression,
386 metadata=metadata,
387 )