1# -*- coding: utf-8 -*-
2# Copyright 2022 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 collections import OrderedDict
17import functools
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29)
30
31from google.cloud.errorreporting_v1beta1 import gapic_version as package_version
32
33from google.api_core.client_options import ClientOptions
34from google.api_core import exceptions as core_exceptions
35from google.api_core import gapic_v1
36from google.api_core import retry as retries
37from google.auth import credentials as ga_credentials # type: ignore
38from google.oauth2 import service_account # type: ignore
39
40try:
41 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
42except AttributeError: # pragma: NO COVER
43 OptionalRetry = Union[retries.Retry, object] # type: ignore
44
45from google.cloud.errorreporting_v1beta1.services.error_stats_service import pagers
46from google.cloud.errorreporting_v1beta1.types import common
47from google.cloud.errorreporting_v1beta1.types import error_stats_service
48from .transports.base import ErrorStatsServiceTransport, DEFAULT_CLIENT_INFO
49from .transports.grpc_asyncio import ErrorStatsServiceGrpcAsyncIOTransport
50from .client import ErrorStatsServiceClient
51
52
53class ErrorStatsServiceAsyncClient:
54 """An API for retrieving and managing error statistics as well
55 as data for individual events.
56 """
57
58 _client: ErrorStatsServiceClient
59
60 DEFAULT_ENDPOINT = ErrorStatsServiceClient.DEFAULT_ENDPOINT
61 DEFAULT_MTLS_ENDPOINT = ErrorStatsServiceClient.DEFAULT_MTLS_ENDPOINT
62
63 error_group_path = staticmethod(ErrorStatsServiceClient.error_group_path)
64 parse_error_group_path = staticmethod(
65 ErrorStatsServiceClient.parse_error_group_path
66 )
67 common_billing_account_path = staticmethod(
68 ErrorStatsServiceClient.common_billing_account_path
69 )
70 parse_common_billing_account_path = staticmethod(
71 ErrorStatsServiceClient.parse_common_billing_account_path
72 )
73 common_folder_path = staticmethod(ErrorStatsServiceClient.common_folder_path)
74 parse_common_folder_path = staticmethod(
75 ErrorStatsServiceClient.parse_common_folder_path
76 )
77 common_organization_path = staticmethod(
78 ErrorStatsServiceClient.common_organization_path
79 )
80 parse_common_organization_path = staticmethod(
81 ErrorStatsServiceClient.parse_common_organization_path
82 )
83 common_project_path = staticmethod(ErrorStatsServiceClient.common_project_path)
84 parse_common_project_path = staticmethod(
85 ErrorStatsServiceClient.parse_common_project_path
86 )
87 common_location_path = staticmethod(ErrorStatsServiceClient.common_location_path)
88 parse_common_location_path = staticmethod(
89 ErrorStatsServiceClient.parse_common_location_path
90 )
91
92 @classmethod
93 def from_service_account_info(cls, info: dict, *args, **kwargs):
94 """Creates an instance of this client using the provided credentials
95 info.
96
97 Args:
98 info (dict): The service account private key info.
99 args: Additional arguments to pass to the constructor.
100 kwargs: Additional arguments to pass to the constructor.
101
102 Returns:
103 ErrorStatsServiceAsyncClient: The constructed client.
104 """
105 return ErrorStatsServiceClient.from_service_account_info.__func__(ErrorStatsServiceAsyncClient, info, *args, **kwargs) # type: ignore
106
107 @classmethod
108 def from_service_account_file(cls, filename: str, *args, **kwargs):
109 """Creates an instance of this client using the provided credentials
110 file.
111
112 Args:
113 filename (str): The path to the service account private key json
114 file.
115 args: Additional arguments to pass to the constructor.
116 kwargs: Additional arguments to pass to the constructor.
117
118 Returns:
119 ErrorStatsServiceAsyncClient: The constructed client.
120 """
121 return ErrorStatsServiceClient.from_service_account_file.__func__(ErrorStatsServiceAsyncClient, filename, *args, **kwargs) # type: ignore
122
123 from_service_account_json = from_service_account_file
124
125 @classmethod
126 def get_mtls_endpoint_and_cert_source(
127 cls, client_options: Optional[ClientOptions] = None
128 ):
129 """Return the API endpoint and client cert source for mutual TLS.
130
131 The client cert source is determined in the following order:
132 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
133 client cert source is None.
134 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
135 default client cert source exists, use the default one; otherwise the client cert
136 source is None.
137
138 The API endpoint is determined in the following order:
139 (1) if `client_options.api_endpoint` if provided, use the provided one.
140 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
141 default mTLS endpoint; if the environment variable is "never", use the default API
142 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
143 use the default API endpoint.
144
145 More details can be found at https://google.aip.dev/auth/4114.
146
147 Args:
148 client_options (google.api_core.client_options.ClientOptions): Custom options for the
149 client. Only the `api_endpoint` and `client_cert_source` properties may be used
150 in this method.
151
152 Returns:
153 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
154 client cert source to use.
155
156 Raises:
157 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
158 """
159 return ErrorStatsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
160
161 @property
162 def transport(self) -> ErrorStatsServiceTransport:
163 """Returns the transport used by the client instance.
164
165 Returns:
166 ErrorStatsServiceTransport: The transport used by the client instance.
167 """
168 return self._client.transport
169
170 get_transport_class = functools.partial(
171 type(ErrorStatsServiceClient).get_transport_class, type(ErrorStatsServiceClient)
172 )
173
174 def __init__(
175 self,
176 *,
177 credentials: Optional[ga_credentials.Credentials] = None,
178 transport: Union[str, ErrorStatsServiceTransport] = "grpc_asyncio",
179 client_options: Optional[ClientOptions] = None,
180 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
181 ) -> None:
182 """Instantiates the error stats service client.
183
184 Args:
185 credentials (Optional[google.auth.credentials.Credentials]): The
186 authorization credentials to attach to requests. These
187 credentials identify the application to the service; if none
188 are specified, the client will attempt to ascertain the
189 credentials from the environment.
190 transport (Union[str, ~.ErrorStatsServiceTransport]): The
191 transport to use. If set to None, a transport is chosen
192 automatically.
193 client_options (ClientOptions): Custom options for the client. It
194 won't take effect if a ``transport`` instance is provided.
195 (1) The ``api_endpoint`` property can be used to override the
196 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
197 environment variable can also be used to override the endpoint:
198 "always" (always use the default mTLS endpoint), "never" (always
199 use the default regular endpoint) and "auto" (auto switch to the
200 default mTLS endpoint if client certificate is present, this is
201 the default value). However, the ``api_endpoint`` property takes
202 precedence if provided.
203 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
204 is "true", then the ``client_cert_source`` property can be used
205 to provide client certificate for mutual TLS transport. If
206 not provided, the default SSL client certificate will be used if
207 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
208 set, no client certificate will be used.
209
210 Raises:
211 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
212 creation failed for any reason.
213 """
214 self._client = ErrorStatsServiceClient(
215 credentials=credentials,
216 transport=transport,
217 client_options=client_options,
218 client_info=client_info,
219 )
220
221 async def list_group_stats(
222 self,
223 request: Optional[
224 Union[error_stats_service.ListGroupStatsRequest, dict]
225 ] = None,
226 *,
227 project_name: Optional[str] = None,
228 time_range: Optional[error_stats_service.QueryTimeRange] = None,
229 retry: OptionalRetry = gapic_v1.method.DEFAULT,
230 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
231 metadata: Sequence[Tuple[str, str]] = (),
232 ) -> pagers.ListGroupStatsAsyncPager:
233 r"""Lists the specified groups.
234
235 .. code-block:: python
236
237 # This snippet has been automatically generated and should be regarded as a
238 # code template only.
239 # It will require modifications to work:
240 # - It may require correct/in-range values for request initialization.
241 # - It may require specifying regional endpoints when creating the service
242 # client as shown in:
243 # https://googleapis.dev/python/google-api-core/latest/client_options.html
244 from google.cloud import errorreporting_v1beta1
245
246 async def sample_list_group_stats():
247 # Create a client
248 client = errorreporting_v1beta1.ErrorStatsServiceAsyncClient()
249
250 # Initialize request argument(s)
251 request = errorreporting_v1beta1.ListGroupStatsRequest(
252 project_name="project_name_value",
253 )
254
255 # Make the request
256 page_result = client.list_group_stats(request=request)
257
258 # Handle the response
259 async for response in page_result:
260 print(response)
261
262 Args:
263 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.ListGroupStatsRequest, dict]]):
264 The request object. Specifies a set of ``ErrorGroupStats`` to return.
265 project_name (:class:`str`):
266 Required. The resource name of the Google Cloud Platform
267 project. Written as ``projects/{projectID}`` or
268 ``projects/{projectNumber}``, where ``{projectID}`` and
269 ``{projectNumber}`` can be found in the `Google Cloud
270 Console <https://support.google.com/cloud/answer/6158840>`__.
271
272 Examples: ``projects/my-project-123``,
273 ``projects/5551234``.
274
275 This corresponds to the ``project_name`` field
276 on the ``request`` instance; if ``request`` is provided, this
277 should not be set.
278 time_range (:class:`google.cloud.errorreporting_v1beta1.types.QueryTimeRange`):
279 Optional. List data for the given time range. If not
280 set, a default time range is used. The field
281 time_range_begin in the response will specify the
282 beginning of this time range. Only ErrorGroupStats with
283 a non-zero count in the given time range are returned,
284 unless the request contains an explicit group_id list.
285 If a group_id list is given, also ErrorGroupStats with
286 zero occurrences are returned.
287
288 This corresponds to the ``time_range`` field
289 on the ``request`` instance; if ``request`` is provided, this
290 should not be set.
291 retry (google.api_core.retry.Retry): Designation of what errors, if any,
292 should be retried.
293 timeout (float): The timeout for this request.
294 metadata (Sequence[Tuple[str, str]]): Strings which should be
295 sent along with the request as metadata.
296
297 Returns:
298 google.cloud.errorreporting_v1beta1.services.error_stats_service.pagers.ListGroupStatsAsyncPager:
299 Contains a set of requested error
300 group stats.
301 Iterating over this object will yield
302 results and resolve additional pages
303 automatically.
304
305 """
306 # Create or coerce a protobuf request object.
307 # Quick check: If we got a request object, we should *not* have
308 # gotten any keyword arguments that map to the request.
309 has_flattened_params = any([project_name, time_range])
310 if request is not None and has_flattened_params:
311 raise ValueError(
312 "If the `request` argument is set, then none of "
313 "the individual field arguments should be set."
314 )
315
316 request = error_stats_service.ListGroupStatsRequest(request)
317
318 # If we have keyword arguments corresponding to fields on the
319 # request, apply these.
320 if project_name is not None:
321 request.project_name = project_name
322 if time_range is not None:
323 request.time_range = time_range
324
325 # Wrap the RPC method; this adds retry and timeout information,
326 # and friendly error handling.
327 rpc = gapic_v1.method_async.wrap_method(
328 self._client._transport.list_group_stats,
329 default_timeout=None,
330 client_info=DEFAULT_CLIENT_INFO,
331 )
332
333 # Certain fields should be provided within the metadata header;
334 # add these here.
335 metadata = tuple(metadata) + (
336 gapic_v1.routing_header.to_grpc_metadata(
337 (("project_name", request.project_name),)
338 ),
339 )
340
341 # Send the request.
342 response = await rpc(
343 request,
344 retry=retry,
345 timeout=timeout,
346 metadata=metadata,
347 )
348
349 # This method is paged; wrap the response in a pager, which provides
350 # an `__aiter__` convenience method.
351 response = pagers.ListGroupStatsAsyncPager(
352 method=rpc,
353 request=request,
354 response=response,
355 metadata=metadata,
356 )
357
358 # Done; return the response.
359 return response
360
361 async def list_events(
362 self,
363 request: Optional[Union[error_stats_service.ListEventsRequest, dict]] = None,
364 *,
365 project_name: Optional[str] = None,
366 group_id: Optional[str] = None,
367 retry: OptionalRetry = gapic_v1.method.DEFAULT,
368 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
369 metadata: Sequence[Tuple[str, str]] = (),
370 ) -> pagers.ListEventsAsyncPager:
371 r"""Lists the specified events.
372
373 .. code-block:: python
374
375 # This snippet has been automatically generated and should be regarded as a
376 # code template only.
377 # It will require modifications to work:
378 # - It may require correct/in-range values for request initialization.
379 # - It may require specifying regional endpoints when creating the service
380 # client as shown in:
381 # https://googleapis.dev/python/google-api-core/latest/client_options.html
382 from google.cloud import errorreporting_v1beta1
383
384 async def sample_list_events():
385 # Create a client
386 client = errorreporting_v1beta1.ErrorStatsServiceAsyncClient()
387
388 # Initialize request argument(s)
389 request = errorreporting_v1beta1.ListEventsRequest(
390 project_name="project_name_value",
391 group_id="group_id_value",
392 )
393
394 # Make the request
395 page_result = client.list_events(request=request)
396
397 # Handle the response
398 async for response in page_result:
399 print(response)
400
401 Args:
402 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.ListEventsRequest, dict]]):
403 The request object. Specifies a set of error events to
404 return.
405 project_name (:class:`str`):
406 Required. The resource name of the Google Cloud Platform
407 project. Written as ``projects/{projectID}``, where
408 ``{projectID}`` is the `Google Cloud Platform project
409 ID <https://support.google.com/cloud/answer/6158840>`__.
410
411 Example: ``projects/my-project-123``.
412
413 This corresponds to the ``project_name`` field
414 on the ``request`` instance; if ``request`` is provided, this
415 should not be set.
416 group_id (:class:`str`):
417 Required. The group for which events
418 shall be returned.
419
420 This corresponds to the ``group_id`` field
421 on the ``request`` instance; if ``request`` is provided, this
422 should not be set.
423 retry (google.api_core.retry.Retry): Designation of what errors, if any,
424 should be retried.
425 timeout (float): The timeout for this request.
426 metadata (Sequence[Tuple[str, str]]): Strings which should be
427 sent along with the request as metadata.
428
429 Returns:
430 google.cloud.errorreporting_v1beta1.services.error_stats_service.pagers.ListEventsAsyncPager:
431 Contains a set of requested error
432 events.
433 Iterating over this object will yield
434 results and resolve additional pages
435 automatically.
436
437 """
438 # Create or coerce a protobuf request object.
439 # Quick check: If we got a request object, we should *not* have
440 # gotten any keyword arguments that map to the request.
441 has_flattened_params = any([project_name, group_id])
442 if request is not None and has_flattened_params:
443 raise ValueError(
444 "If the `request` argument is set, then none of "
445 "the individual field arguments should be set."
446 )
447
448 request = error_stats_service.ListEventsRequest(request)
449
450 # If we have keyword arguments corresponding to fields on the
451 # request, apply these.
452 if project_name is not None:
453 request.project_name = project_name
454 if group_id is not None:
455 request.group_id = group_id
456
457 # Wrap the RPC method; this adds retry and timeout information,
458 # and friendly error handling.
459 rpc = gapic_v1.method_async.wrap_method(
460 self._client._transport.list_events,
461 default_timeout=None,
462 client_info=DEFAULT_CLIENT_INFO,
463 )
464
465 # Certain fields should be provided within the metadata header;
466 # add these here.
467 metadata = tuple(metadata) + (
468 gapic_v1.routing_header.to_grpc_metadata(
469 (("project_name", request.project_name),)
470 ),
471 )
472
473 # Send the request.
474 response = await rpc(
475 request,
476 retry=retry,
477 timeout=timeout,
478 metadata=metadata,
479 )
480
481 # This method is paged; wrap the response in a pager, which provides
482 # an `__aiter__` convenience method.
483 response = pagers.ListEventsAsyncPager(
484 method=rpc,
485 request=request,
486 response=response,
487 metadata=metadata,
488 )
489
490 # Done; return the response.
491 return response
492
493 async def delete_events(
494 self,
495 request: Optional[Union[error_stats_service.DeleteEventsRequest, dict]] = None,
496 *,
497 project_name: Optional[str] = None,
498 retry: OptionalRetry = gapic_v1.method.DEFAULT,
499 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
500 metadata: Sequence[Tuple[str, str]] = (),
501 ) -> error_stats_service.DeleteEventsResponse:
502 r"""Deletes all error events of a given project.
503
504 .. code-block:: python
505
506 # This snippet has been automatically generated and should be regarded as a
507 # code template only.
508 # It will require modifications to work:
509 # - It may require correct/in-range values for request initialization.
510 # - It may require specifying regional endpoints when creating the service
511 # client as shown in:
512 # https://googleapis.dev/python/google-api-core/latest/client_options.html
513 from google.cloud import errorreporting_v1beta1
514
515 async def sample_delete_events():
516 # Create a client
517 client = errorreporting_v1beta1.ErrorStatsServiceAsyncClient()
518
519 # Initialize request argument(s)
520 request = errorreporting_v1beta1.DeleteEventsRequest(
521 project_name="project_name_value",
522 )
523
524 # Make the request
525 response = await client.delete_events(request=request)
526
527 # Handle the response
528 print(response)
529
530 Args:
531 request (Optional[Union[google.cloud.errorreporting_v1beta1.types.DeleteEventsRequest, dict]]):
532 The request object. Deletes all events in the project.
533 project_name (:class:`str`):
534 Required. The resource name of the Google Cloud Platform
535 project. Written as ``projects/{projectID}``, where
536 ``{projectID}`` is the `Google Cloud Platform project
537 ID <https://support.google.com/cloud/answer/6158840>`__.
538
539 Example: ``projects/my-project-123``.
540
541 This corresponds to the ``project_name`` field
542 on the ``request`` instance; if ``request`` is provided, this
543 should not be set.
544 retry (google.api_core.retry.Retry): Designation of what errors, if any,
545 should be retried.
546 timeout (float): The timeout for this request.
547 metadata (Sequence[Tuple[str, str]]): Strings which should be
548 sent along with the request as metadata.
549
550 Returns:
551 google.cloud.errorreporting_v1beta1.types.DeleteEventsResponse:
552 Response message for deleting error
553 events.
554
555 """
556 # Create or coerce a protobuf request object.
557 # Quick check: If we got a request object, we should *not* have
558 # gotten any keyword arguments that map to the request.
559 has_flattened_params = any([project_name])
560 if request is not None and has_flattened_params:
561 raise ValueError(
562 "If the `request` argument is set, then none of "
563 "the individual field arguments should be set."
564 )
565
566 request = error_stats_service.DeleteEventsRequest(request)
567
568 # If we have keyword arguments corresponding to fields on the
569 # request, apply these.
570 if project_name is not None:
571 request.project_name = project_name
572
573 # Wrap the RPC method; this adds retry and timeout information,
574 # and friendly error handling.
575 rpc = gapic_v1.method_async.wrap_method(
576 self._client._transport.delete_events,
577 default_timeout=None,
578 client_info=DEFAULT_CLIENT_INFO,
579 )
580
581 # Certain fields should be provided within the metadata header;
582 # add these here.
583 metadata = tuple(metadata) + (
584 gapic_v1.routing_header.to_grpc_metadata(
585 (("project_name", request.project_name),)
586 ),
587 )
588
589 # Send the request.
590 response = await rpc(
591 request,
592 retry=retry,
593 timeout=timeout,
594 metadata=metadata,
595 )
596
597 # Done; return the response.
598 return response
599
600 async def __aenter__(self):
601 return self
602
603 async def __aexit__(self, exc_type, exc, tb):
604 await self.transport.close()
605
606
607DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
608 gapic_version=package_version.__version__
609)
610
611
612__all__ = ("ErrorStatsServiceAsyncClient",)