Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/logging_v2/services/metrics_service_v2/client.py: 33%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

339 statements  

1# -*- coding: utf-8 -*- 

2# Copyright 2025 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 

17from http import HTTPStatus 

18import json 

19import logging as std_logging 

20import os 

21import re 

22from typing import ( 

23 Dict, 

24 Callable, 

25 Mapping, 

26 MutableMapping, 

27 MutableSequence, 

28 Optional, 

29 Sequence, 

30 Tuple, 

31 Type, 

32 Union, 

33 cast, 

34) 

35import uuid 

36import warnings 

37 

38from google.cloud.logging_v2 import gapic_version as package_version 

39 

40from google.api_core import client_options as client_options_lib 

41from google.api_core import exceptions as core_exceptions 

42from google.api_core import gapic_v1 

43from google.api_core import retry as retries 

44from google.auth import credentials as ga_credentials # type: ignore 

45from google.auth.transport import mtls # type: ignore 

46from google.auth.transport.grpc import SslCredentials # type: ignore 

47from google.auth.exceptions import MutualTLSChannelError # type: ignore 

48from google.oauth2 import service_account # type: ignore 

49import google.protobuf 

50 

51try: 

52 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 

53except AttributeError: # pragma: NO COVER 

54 OptionalRetry = Union[retries.Retry, object, None] # type: ignore 

55 

56try: 

57 from google.api_core import client_logging # type: ignore 

58 

59 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

60except ImportError: # pragma: NO COVER 

61 CLIENT_LOGGING_SUPPORTED = False 

62 

63_LOGGER = std_logging.getLogger(__name__) 

64 

65from google.api import distribution_pb2 # type: ignore 

66from google.api import metric_pb2 # type: ignore 

67from google.cloud.logging_v2.services.metrics_service_v2 import pagers 

68from google.cloud.logging_v2.types import logging_metrics 

69from google.longrunning import operations_pb2 # type: ignore 

70from google.protobuf import timestamp_pb2 # type: ignore 

71from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO 

72from .transports.grpc import MetricsServiceV2GrpcTransport 

73from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport 

74 

75 

76class MetricsServiceV2ClientMeta(type): 

77 """Metaclass for the MetricsServiceV2 client. 

78 

79 This provides class-level methods for building and retrieving 

80 support objects (e.g. transport) without polluting the client instance 

81 objects. 

82 """ 

83 

84 _transport_registry = ( 

85 OrderedDict() 

86 ) # type: Dict[str, Type[MetricsServiceV2Transport]] 

87 _transport_registry["grpc"] = MetricsServiceV2GrpcTransport 

88 _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport 

89 

90 def get_transport_class( 

91 cls, 

92 label: Optional[str] = None, 

93 ) -> Type[MetricsServiceV2Transport]: 

94 """Returns an appropriate transport class. 

95 

96 Args: 

97 label: The name of the desired transport. If none is 

98 provided, then the first transport in the registry is used. 

99 

100 Returns: 

101 The transport class to use. 

102 """ 

103 # If a specific transport is requested, return that one. 

104 if label: 

105 return cls._transport_registry[label] 

106 

107 # No transport is requested; return the default (that is, the first one 

108 # in the dictionary). 

109 return next(iter(cls._transport_registry.values())) 

110 

111 

112class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta): 

113 """Service for configuring logs-based metrics.""" 

114 

115 @staticmethod 

116 def _get_default_mtls_endpoint(api_endpoint): 

117 """Converts api endpoint to mTLS endpoint. 

118 

119 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to 

120 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. 

121 Args: 

122 api_endpoint (Optional[str]): the api endpoint to convert. 

123 Returns: 

124 str: converted mTLS api endpoint. 

125 """ 

126 if not api_endpoint: 

127 return api_endpoint 

128 

129 mtls_endpoint_re = re.compile( 

130 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" 

131 ) 

132 

133 m = mtls_endpoint_re.match(api_endpoint) 

134 name, mtls, sandbox, googledomain = m.groups() 

135 if mtls or not googledomain: 

136 return api_endpoint 

137 

138 if sandbox: 

139 return api_endpoint.replace( 

140 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

141 ) 

142 

143 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") 

144 

145 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. 

146 DEFAULT_ENDPOINT = "logging.googleapis.com" 

147 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

148 DEFAULT_ENDPOINT 

149 ) 

150 

151 _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}" 

152 _DEFAULT_UNIVERSE = "googleapis.com" 

153 

154 @classmethod 

155 def from_service_account_info(cls, info: dict, *args, **kwargs): 

156 """Creates an instance of this client using the provided credentials 

157 info. 

158 

159 Args: 

160 info (dict): The service account private key info. 

161 args: Additional arguments to pass to the constructor. 

162 kwargs: Additional arguments to pass to the constructor. 

163 

164 Returns: 

165 MetricsServiceV2Client: The constructed client. 

166 """ 

167 credentials = service_account.Credentials.from_service_account_info(info) 

168 kwargs["credentials"] = credentials 

169 return cls(*args, **kwargs) 

170 

171 @classmethod 

172 def from_service_account_file(cls, filename: str, *args, **kwargs): 

173 """Creates an instance of this client using the provided credentials 

174 file. 

175 

176 Args: 

177 filename (str): The path to the service account private key json 

178 file. 

179 args: Additional arguments to pass to the constructor. 

180 kwargs: Additional arguments to pass to the constructor. 

181 

182 Returns: 

183 MetricsServiceV2Client: The constructed client. 

184 """ 

185 credentials = service_account.Credentials.from_service_account_file(filename) 

186 kwargs["credentials"] = credentials 

187 return cls(*args, **kwargs) 

188 

189 from_service_account_json = from_service_account_file 

190 

191 @property 

192 def transport(self) -> MetricsServiceV2Transport: 

193 """Returns the transport used by the client instance. 

194 

195 Returns: 

196 MetricsServiceV2Transport: The transport used by the client 

197 instance. 

198 """ 

199 return self._transport 

200 

201 @staticmethod 

202 def log_metric_path( 

203 project: str, 

204 metric: str, 

205 ) -> str: 

206 """Returns a fully-qualified log_metric string.""" 

207 return "projects/{project}/metrics/{metric}".format( 

208 project=project, 

209 metric=metric, 

210 ) 

211 

212 @staticmethod 

213 def parse_log_metric_path(path: str) -> Dict[str, str]: 

214 """Parses a log_metric path into its component segments.""" 

215 m = re.match(r"^projects/(?P<project>.+?)/metrics/(?P<metric>.+?)$", path) 

216 return m.groupdict() if m else {} 

217 

218 @staticmethod 

219 def common_billing_account_path( 

220 billing_account: str, 

221 ) -> str: 

222 """Returns a fully-qualified billing_account string.""" 

223 return "billingAccounts/{billing_account}".format( 

224 billing_account=billing_account, 

225 ) 

226 

227 @staticmethod 

228 def parse_common_billing_account_path(path: str) -> Dict[str, str]: 

229 """Parse a billing_account path into its component segments.""" 

230 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) 

231 return m.groupdict() if m else {} 

232 

233 @staticmethod 

234 def common_folder_path( 

235 folder: str, 

236 ) -> str: 

237 """Returns a fully-qualified folder string.""" 

238 return "folders/{folder}".format( 

239 folder=folder, 

240 ) 

241 

242 @staticmethod 

243 def parse_common_folder_path(path: str) -> Dict[str, str]: 

244 """Parse a folder path into its component segments.""" 

245 m = re.match(r"^folders/(?P<folder>.+?)$", path) 

246 return m.groupdict() if m else {} 

247 

248 @staticmethod 

249 def common_organization_path( 

250 organization: str, 

251 ) -> str: 

252 """Returns a fully-qualified organization string.""" 

253 return "organizations/{organization}".format( 

254 organization=organization, 

255 ) 

256 

257 @staticmethod 

258 def parse_common_organization_path(path: str) -> Dict[str, str]: 

259 """Parse a organization path into its component segments.""" 

260 m = re.match(r"^organizations/(?P<organization>.+?)$", path) 

261 return m.groupdict() if m else {} 

262 

263 @staticmethod 

264 def common_project_path( 

265 project: str, 

266 ) -> str: 

267 """Returns a fully-qualified project string.""" 

268 return "projects/{project}".format( 

269 project=project, 

270 ) 

271 

272 @staticmethod 

273 def parse_common_project_path(path: str) -> Dict[str, str]: 

274 """Parse a project path into its component segments.""" 

275 m = re.match(r"^projects/(?P<project>.+?)$", path) 

276 return m.groupdict() if m else {} 

277 

278 @staticmethod 

279 def common_location_path( 

280 project: str, 

281 location: str, 

282 ) -> str: 

283 """Returns a fully-qualified location string.""" 

284 return "projects/{project}/locations/{location}".format( 

285 project=project, 

286 location=location, 

287 ) 

288 

289 @staticmethod 

290 def parse_common_location_path(path: str) -> Dict[str, str]: 

291 """Parse a location path into its component segments.""" 

292 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) 

293 return m.groupdict() if m else {} 

294 

295 @classmethod 

296 def get_mtls_endpoint_and_cert_source( 

297 cls, client_options: Optional[client_options_lib.ClientOptions] = None 

298 ): 

299 """Deprecated. Return the API endpoint and client cert source for mutual TLS. 

300 

301 The client cert source is determined in the following order: 

302 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

303 client cert source is None. 

304 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

305 default client cert source exists, use the default one; otherwise the client cert 

306 source is None. 

307 

308 The API endpoint is determined in the following order: 

309 (1) if `client_options.api_endpoint` if provided, use the provided one. 

310 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

311 default mTLS endpoint; if the environment variable is "never", use the default API 

312 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

313 use the default API endpoint. 

314 

315 More details can be found at https://google.aip.dev/auth/4114. 

316 

317 Args: 

318 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

319 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

320 in this method. 

321 

322 Returns: 

323 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

324 client cert source to use. 

325 

326 Raises: 

327 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

328 """ 

329 

330 warnings.warn( 

331 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", 

332 DeprecationWarning, 

333 ) 

334 if client_options is None: 

335 client_options = client_options_lib.ClientOptions() 

336 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") 

337 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") 

338 if use_client_cert not in ("true", "false"): 

339 raise ValueError( 

340 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

341 ) 

342 if use_mtls_endpoint not in ("auto", "never", "always"): 

343 raise MutualTLSChannelError( 

344 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

345 ) 

346 

347 # Figure out the client cert source to use. 

348 client_cert_source = None 

349 if use_client_cert == "true": 

350 if client_options.client_cert_source: 

351 client_cert_source = client_options.client_cert_source 

352 elif mtls.has_default_client_cert_source(): 

353 client_cert_source = mtls.default_client_cert_source() 

354 

355 # Figure out which api endpoint to use. 

356 if client_options.api_endpoint is not None: 

357 api_endpoint = client_options.api_endpoint 

358 elif use_mtls_endpoint == "always" or ( 

359 use_mtls_endpoint == "auto" and client_cert_source 

360 ): 

361 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

362 else: 

363 api_endpoint = cls.DEFAULT_ENDPOINT 

364 

365 return api_endpoint, client_cert_source 

366 

367 @staticmethod 

368 def _read_environment_variables(): 

369 """Returns the environment variables used by the client. 

370 

371 Returns: 

372 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, 

373 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

374 

375 Raises: 

376 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

377 any of ["true", "false"]. 

378 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

379 is not any of ["auto", "never", "always"]. 

380 """ 

381 use_client_cert = os.getenv( 

382 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

383 ).lower() 

384 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() 

385 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

386 if use_client_cert not in ("true", "false"): 

387 raise ValueError( 

388 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

389 ) 

390 if use_mtls_endpoint not in ("auto", "never", "always"): 

391 raise MutualTLSChannelError( 

392 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

393 ) 

394 return use_client_cert == "true", use_mtls_endpoint, universe_domain_env 

395 

396 @staticmethod 

397 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

398 """Return the client cert source to be used by the client. 

399 

400 Args: 

401 provided_cert_source (bytes): The client certificate source provided. 

402 use_cert_flag (bool): A flag indicating whether to use the client certificate. 

403 

404 Returns: 

405 bytes or None: The client cert source to be used by the client. 

406 """ 

407 client_cert_source = None 

408 if use_cert_flag: 

409 if provided_cert_source: 

410 client_cert_source = provided_cert_source 

411 elif mtls.has_default_client_cert_source(): 

412 client_cert_source = mtls.default_client_cert_source() 

413 return client_cert_source 

414 

415 @staticmethod 

416 def _get_api_endpoint( 

417 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

418 ): 

419 """Return the API endpoint used by the client. 

420 

421 Args: 

422 api_override (str): The API endpoint override. If specified, this is always 

423 the return value of this function and the other arguments are not used. 

424 client_cert_source (bytes): The client certificate source used by the client. 

425 universe_domain (str): The universe domain used by the client. 

426 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. 

427 Possible values are "always", "auto", or "never". 

428 

429 Returns: 

430 str: The API endpoint to be used by the client. 

431 """ 

432 if api_override is not None: 

433 api_endpoint = api_override 

434 elif use_mtls_endpoint == "always" or ( 

435 use_mtls_endpoint == "auto" and client_cert_source 

436 ): 

437 _default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE 

438 if universe_domain != _default_universe: 

439 raise MutualTLSChannelError( 

440 f"mTLS is not supported in any universe other than {_default_universe}." 

441 ) 

442 api_endpoint = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT 

443 else: 

444 api_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( 

445 UNIVERSE_DOMAIN=universe_domain 

446 ) 

447 return api_endpoint 

448 

449 @staticmethod 

450 def _get_universe_domain( 

451 client_universe_domain: Optional[str], universe_domain_env: Optional[str] 

452 ) -> str: 

453 """Return the universe domain used by the client. 

454 

455 Args: 

456 client_universe_domain (Optional[str]): The universe domain configured via the client options. 

457 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. 

458 

459 Returns: 

460 str: The universe domain to be used by the client. 

461 

462 Raises: 

463 ValueError: If the universe domain is an empty string. 

464 """ 

465 universe_domain = MetricsServiceV2Client._DEFAULT_UNIVERSE 

466 if client_universe_domain is not None: 

467 universe_domain = client_universe_domain 

468 elif universe_domain_env is not None: 

469 universe_domain = universe_domain_env 

470 if len(universe_domain.strip()) == 0: 

471 raise ValueError("Universe Domain cannot be an empty string.") 

472 return universe_domain 

473 

474 def _validate_universe_domain(self): 

475 """Validates client's and credentials' universe domains are consistent. 

476 

477 Returns: 

478 bool: True iff the configured universe domain is valid. 

479 

480 Raises: 

481 ValueError: If the configured universe domain is not valid. 

482 """ 

483 

484 # NOTE (b/349488459): universe validation is disabled until further notice. 

485 return True 

486 

487 def _add_cred_info_for_auth_errors( 

488 self, error: core_exceptions.GoogleAPICallError 

489 ) -> None: 

490 """Adds credential info string to error details for 401/403/404 errors. 

491 

492 Args: 

493 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. 

494 """ 

495 if error.code not in [ 

496 HTTPStatus.UNAUTHORIZED, 

497 HTTPStatus.FORBIDDEN, 

498 HTTPStatus.NOT_FOUND, 

499 ]: 

500 return 

501 

502 cred = self._transport._credentials 

503 

504 # get_cred_info is only available in google-auth>=2.35.0 

505 if not hasattr(cred, "get_cred_info"): 

506 return 

507 

508 # ignore the type check since pypy test fails when get_cred_info 

509 # is not available 

510 cred_info = cred.get_cred_info() # type: ignore 

511 if cred_info and hasattr(error._details, "append"): 

512 error._details.append(json.dumps(cred_info)) 

513 

514 @property 

515 def api_endpoint(self): 

516 """Return the API endpoint used by the client instance. 

517 

518 Returns: 

519 str: The API endpoint used by the client instance. 

520 """ 

521 return self._api_endpoint 

522 

523 @property 

524 def universe_domain(self) -> str: 

525 """Return the universe domain used by the client instance. 

526 

527 Returns: 

528 str: The universe domain used by the client instance. 

529 """ 

530 return self._universe_domain 

531 

532 def __init__( 

533 self, 

534 *, 

535 credentials: Optional[ga_credentials.Credentials] = None, 

536 transport: Optional[ 

537 Union[ 

538 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] 

539 ] 

540 ] = None, 

541 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, 

542 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

543 ) -> None: 

544 """Instantiates the metrics service v2 client. 

545 

546 Args: 

547 credentials (Optional[google.auth.credentials.Credentials]): The 

548 authorization credentials to attach to requests. These 

549 credentials identify the application to the service; if none 

550 are specified, the client will attempt to ascertain the 

551 credentials from the environment. 

552 transport (Optional[Union[str,MetricsServiceV2Transport,Callable[..., MetricsServiceV2Transport]]]): 

553 The transport to use, or a Callable that constructs and returns a new transport. 

554 If a Callable is given, it will be called with the same set of initialization 

555 arguments as used in the MetricsServiceV2Transport constructor. 

556 If set to None, a transport is chosen automatically. 

557 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

558 Custom options for the client. 

559 

560 1. The ``api_endpoint`` property can be used to override the 

561 default endpoint provided by the client when ``transport`` is 

562 not explicitly provided. Only if this property is not set and 

563 ``transport`` was not explicitly provided, the endpoint is 

564 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

565 variable, which have one of the following values: 

566 "always" (always use the default mTLS endpoint), "never" (always 

567 use the default regular endpoint) and "auto" (auto-switch to the 

568 default mTLS endpoint if client certificate is present; this is 

569 the default value). 

570 

571 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

572 is "true", then the ``client_cert_source`` property can be used 

573 to provide a client certificate for mTLS transport. If 

574 not provided, the default SSL client certificate will be used if 

575 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

576 set, no client certificate will be used. 

577 

578 3. The ``universe_domain`` property can be used to override the 

579 default "googleapis.com" universe. Note that the ``api_endpoint`` 

580 property still takes precedence; and ``universe_domain`` is 

581 currently not supported for mTLS. 

582 

583 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

584 The client info used to send a user-agent string along with 

585 API requests. If ``None``, then default info will be used. 

586 Generally, you only need to set this if you're developing 

587 your own client library. 

588 

589 Raises: 

590 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport 

591 creation failed for any reason. 

592 """ 

593 self._client_options = client_options 

594 if isinstance(self._client_options, dict): 

595 self._client_options = client_options_lib.from_dict(self._client_options) 

596 if self._client_options is None: 

597 self._client_options = client_options_lib.ClientOptions() 

598 self._client_options = cast( 

599 client_options_lib.ClientOptions, self._client_options 

600 ) 

601 

602 universe_domain_opt = getattr(self._client_options, "universe_domain", None) 

603 

604 ( 

605 self._use_client_cert, 

606 self._use_mtls_endpoint, 

607 self._universe_domain_env, 

608 ) = MetricsServiceV2Client._read_environment_variables() 

609 self._client_cert_source = MetricsServiceV2Client._get_client_cert_source( 

610 self._client_options.client_cert_source, self._use_client_cert 

611 ) 

612 self._universe_domain = MetricsServiceV2Client._get_universe_domain( 

613 universe_domain_opt, self._universe_domain_env 

614 ) 

615 self._api_endpoint = None # updated below, depending on `transport` 

616 

617 # Initialize the universe domain validation. 

618 self._is_universe_domain_valid = False 

619 

620 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

621 # Setup logging. 

622 client_logging.initialize_logging() 

623 

624 api_key_value = getattr(self._client_options, "api_key", None) 

625 if api_key_value and credentials: 

626 raise ValueError( 

627 "client_options.api_key and credentials are mutually exclusive" 

628 ) 

629 

630 # Save or instantiate the transport. 

631 # Ordinarily, we provide the transport, but allowing a custom transport 

632 # instance provides an extensibility point for unusual situations. 

633 transport_provided = isinstance(transport, MetricsServiceV2Transport) 

634 if transport_provided: 

635 # transport is a MetricsServiceV2Transport instance. 

636 if credentials or self._client_options.credentials_file or api_key_value: 

637 raise ValueError( 

638 "When providing a transport instance, " 

639 "provide its credentials directly." 

640 ) 

641 if self._client_options.scopes: 

642 raise ValueError( 

643 "When providing a transport instance, provide its scopes " 

644 "directly." 

645 ) 

646 self._transport = cast(MetricsServiceV2Transport, transport) 

647 self._api_endpoint = self._transport.host 

648 

649 self._api_endpoint = ( 

650 self._api_endpoint 

651 or MetricsServiceV2Client._get_api_endpoint( 

652 self._client_options.api_endpoint, 

653 self._client_cert_source, 

654 self._universe_domain, 

655 self._use_mtls_endpoint, 

656 ) 

657 ) 

658 

659 if not transport_provided: 

660 import google.auth._default # type: ignore 

661 

662 if api_key_value and hasattr( 

663 google.auth._default, "get_api_key_credentials" 

664 ): 

665 credentials = google.auth._default.get_api_key_credentials( 

666 api_key_value 

667 ) 

668 

669 transport_init: Union[ 

670 Type[MetricsServiceV2Transport], 

671 Callable[..., MetricsServiceV2Transport], 

672 ] = ( 

673 MetricsServiceV2Client.get_transport_class(transport) 

674 if isinstance(transport, str) or transport is None 

675 else cast(Callable[..., MetricsServiceV2Transport], transport) 

676 ) 

677 # initialize with the provided callable or the passed in class 

678 self._transport = transport_init( 

679 credentials=credentials, 

680 credentials_file=self._client_options.credentials_file, 

681 host=self._api_endpoint, 

682 scopes=self._client_options.scopes, 

683 client_cert_source_for_mtls=self._client_cert_source, 

684 quota_project_id=self._client_options.quota_project_id, 

685 client_info=client_info, 

686 always_use_jwt_access=True, 

687 api_audience=self._client_options.api_audience, 

688 ) 

689 

690 if "async" not in str(self._transport): 

691 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

692 std_logging.DEBUG 

693 ): # pragma: NO COVER 

694 _LOGGER.debug( 

695 "Created client `google.logging_v2.MetricsServiceV2Client`.", 

696 extra={ 

697 "serviceName": "google.logging.v2.MetricsServiceV2", 

698 "universeDomain": getattr( 

699 self._transport._credentials, "universe_domain", "" 

700 ), 

701 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", 

702 "credentialsInfo": getattr( 

703 self.transport._credentials, "get_cred_info", lambda: None 

704 )(), 

705 } 

706 if hasattr(self._transport, "_credentials") 

707 else { 

708 "serviceName": "google.logging.v2.MetricsServiceV2", 

709 "credentialsType": None, 

710 }, 

711 ) 

712 

713 def list_log_metrics( 

714 self, 

715 request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, 

716 *, 

717 parent: Optional[str] = None, 

718 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

719 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

720 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

721 ) -> pagers.ListLogMetricsPager: 

722 r"""Lists logs-based metrics. 

723 

724 .. code-block:: python 

725 

726 # This snippet has been automatically generated and should be regarded as a 

727 # code template only. 

728 # It will require modifications to work: 

729 # - It may require correct/in-range values for request initialization. 

730 # - It may require specifying regional endpoints when creating the service 

731 # client as shown in: 

732 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

733 from google.cloud import logging_v2 

734 

735 def sample_list_log_metrics(): 

736 # Create a client 

737 client = logging_v2.MetricsServiceV2Client() 

738 

739 # Initialize request argument(s) 

740 request = logging_v2.ListLogMetricsRequest( 

741 parent="parent_value", 

742 ) 

743 

744 # Make the request 

745 page_result = client.list_log_metrics(request=request) 

746 

747 # Handle the response 

748 for response in page_result: 

749 print(response) 

750 

751 Args: 

752 request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]): 

753 The request object. The parameters to ListLogMetrics. 

754 parent (str): 

755 Required. The name of the project containing the 

756 metrics: 

757 

758 :: 

759 

760 "projects/[PROJECT_ID]" 

761 

762 This corresponds to the ``parent`` field 

763 on the ``request`` instance; if ``request`` is provided, this 

764 should not be set. 

765 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

766 should be retried. 

767 timeout (float): The timeout for this request. 

768 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

769 sent along with the request as metadata. Normally, each value must be of type `str`, 

770 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

771 be of type `bytes`. 

772 

773 Returns: 

774 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager: 

775 Result returned from ListLogMetrics. 

776 

777 Iterating over this object will yield 

778 results and resolve additional pages 

779 automatically. 

780 

781 """ 

782 # Create or coerce a protobuf request object. 

783 # - Quick check: If we got a request object, we should *not* have 

784 # gotten any keyword arguments that map to the request. 

785 flattened_params = [parent] 

786 has_flattened_params = ( 

787 len([param for param in flattened_params if param is not None]) > 0 

788 ) 

789 if request is not None and has_flattened_params: 

790 raise ValueError( 

791 "If the `request` argument is set, then none of " 

792 "the individual field arguments should be set." 

793 ) 

794 

795 # - Use the request object if provided (there's no risk of modifying the input as 

796 # there are no flattened fields), or create one. 

797 if not isinstance(request, logging_metrics.ListLogMetricsRequest): 

798 request = logging_metrics.ListLogMetricsRequest(request) 

799 # If we have keyword arguments corresponding to fields on the 

800 # request, apply these. 

801 if parent is not None: 

802 request.parent = parent 

803 

804 # Wrap the RPC method; this adds retry and timeout information, 

805 # and friendly error handling. 

806 rpc = self._transport._wrapped_methods[self._transport.list_log_metrics] 

807 

808 # Certain fields should be provided within the metadata header; 

809 # add these here. 

810 metadata = tuple(metadata) + ( 

811 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

812 ) 

813 

814 # Validate the universe domain. 

815 self._validate_universe_domain() 

816 

817 # Send the request. 

818 response = rpc( 

819 request, 

820 retry=retry, 

821 timeout=timeout, 

822 metadata=metadata, 

823 ) 

824 

825 # This method is paged; wrap the response in a pager, which provides 

826 # an `__iter__` convenience method. 

827 response = pagers.ListLogMetricsPager( 

828 method=rpc, 

829 request=request, 

830 response=response, 

831 retry=retry, 

832 timeout=timeout, 

833 metadata=metadata, 

834 ) 

835 

836 # Done; return the response. 

837 return response 

838 

839 def get_log_metric( 

840 self, 

841 request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, 

842 *, 

843 metric_name: Optional[str] = None, 

844 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

845 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

846 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

847 ) -> logging_metrics.LogMetric: 

848 r"""Gets a logs-based metric. 

849 

850 .. code-block:: python 

851 

852 # This snippet has been automatically generated and should be regarded as a 

853 # code template only. 

854 # It will require modifications to work: 

855 # - It may require correct/in-range values for request initialization. 

856 # - It may require specifying regional endpoints when creating the service 

857 # client as shown in: 

858 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

859 from google.cloud import logging_v2 

860 

861 def sample_get_log_metric(): 

862 # Create a client 

863 client = logging_v2.MetricsServiceV2Client() 

864 

865 # Initialize request argument(s) 

866 request = logging_v2.GetLogMetricRequest( 

867 metric_name="metric_name_value", 

868 ) 

869 

870 # Make the request 

871 response = client.get_log_metric(request=request) 

872 

873 # Handle the response 

874 print(response) 

875 

876 Args: 

877 request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]): 

878 The request object. The parameters to GetLogMetric. 

879 metric_name (str): 

880 Required. The resource name of the desired metric: 

881 

882 :: 

883 

884 "projects/[PROJECT_ID]/metrics/[METRIC_ID]" 

885 

886 This corresponds to the ``metric_name`` field 

887 on the ``request`` instance; if ``request`` is provided, this 

888 should not be set. 

889 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

890 should be retried. 

891 timeout (float): The timeout for this request. 

892 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

893 sent along with the request as metadata. Normally, each value must be of type `str`, 

894 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

895 be of type `bytes`. 

896 

897 Returns: 

898 google.cloud.logging_v2.types.LogMetric: 

899 Describes a logs-based metric. The 

900 value of the metric is the number of log 

901 entries that match a logs filter in a 

902 given time interval. 

903 

904 Logs-based metrics can also be used to 

905 extract values from logs and create a 

906 distribution of the values. The 

907 distribution records the statistics of 

908 the extracted values along with an 

909 optional histogram of the values as 

910 specified by the bucket options. 

911 

912 """ 

913 # Create or coerce a protobuf request object. 

914 # - Quick check: If we got a request object, we should *not* have 

915 # gotten any keyword arguments that map to the request. 

916 flattened_params = [metric_name] 

917 has_flattened_params = ( 

918 len([param for param in flattened_params if param is not None]) > 0 

919 ) 

920 if request is not None and has_flattened_params: 

921 raise ValueError( 

922 "If the `request` argument is set, then none of " 

923 "the individual field arguments should be set." 

924 ) 

925 

926 # - Use the request object if provided (there's no risk of modifying the input as 

927 # there are no flattened fields), or create one. 

928 if not isinstance(request, logging_metrics.GetLogMetricRequest): 

929 request = logging_metrics.GetLogMetricRequest(request) 

930 # If we have keyword arguments corresponding to fields on the 

931 # request, apply these. 

932 if metric_name is not None: 

933 request.metric_name = metric_name 

934 

935 # Wrap the RPC method; this adds retry and timeout information, 

936 # and friendly error handling. 

937 rpc = self._transport._wrapped_methods[self._transport.get_log_metric] 

938 

939 # Certain fields should be provided within the metadata header; 

940 # add these here. 

941 metadata = tuple(metadata) + ( 

942 gapic_v1.routing_header.to_grpc_metadata( 

943 (("metric_name", request.metric_name),) 

944 ), 

945 ) 

946 

947 # Validate the universe domain. 

948 self._validate_universe_domain() 

949 

950 # Send the request. 

951 response = rpc( 

952 request, 

953 retry=retry, 

954 timeout=timeout, 

955 metadata=metadata, 

956 ) 

957 

958 # Done; return the response. 

959 return response 

960 

961 def create_log_metric( 

962 self, 

963 request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, 

964 *, 

965 parent: Optional[str] = None, 

966 metric: Optional[logging_metrics.LogMetric] = None, 

967 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

968 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

969 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

970 ) -> logging_metrics.LogMetric: 

971 r"""Creates a logs-based metric. 

972 

973 .. code-block:: python 

974 

975 # This snippet has been automatically generated and should be regarded as a 

976 # code template only. 

977 # It will require modifications to work: 

978 # - It may require correct/in-range values for request initialization. 

979 # - It may require specifying regional endpoints when creating the service 

980 # client as shown in: 

981 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

982 from google.cloud import logging_v2 

983 

984 def sample_create_log_metric(): 

985 # Create a client 

986 client = logging_v2.MetricsServiceV2Client() 

987 

988 # Initialize request argument(s) 

989 metric = logging_v2.LogMetric() 

990 metric.name = "name_value" 

991 metric.filter = "filter_value" 

992 

993 request = logging_v2.CreateLogMetricRequest( 

994 parent="parent_value", 

995 metric=metric, 

996 ) 

997 

998 # Make the request 

999 response = client.create_log_metric(request=request) 

1000 

1001 # Handle the response 

1002 print(response) 

1003 

1004 Args: 

1005 request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]): 

1006 The request object. The parameters to CreateLogMetric. 

1007 parent (str): 

1008 Required. The resource name of the project in which to 

1009 create the metric: 

1010 

1011 :: 

1012 

1013 "projects/[PROJECT_ID]" 

1014 

1015 The new metric must be provided in the request. 

1016 

1017 This corresponds to the ``parent`` field 

1018 on the ``request`` instance; if ``request`` is provided, this 

1019 should not be set. 

1020 metric (google.cloud.logging_v2.types.LogMetric): 

1021 Required. The new logs-based metric, 

1022 which must not have an identifier that 

1023 already exists. 

1024 

1025 This corresponds to the ``metric`` field 

1026 on the ``request`` instance; if ``request`` is provided, this 

1027 should not be set. 

1028 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1029 should be retried. 

1030 timeout (float): The timeout for this request. 

1031 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1032 sent along with the request as metadata. Normally, each value must be of type `str`, 

1033 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1034 be of type `bytes`. 

1035 

1036 Returns: 

1037 google.cloud.logging_v2.types.LogMetric: 

1038 Describes a logs-based metric. The 

1039 value of the metric is the number of log 

1040 entries that match a logs filter in a 

1041 given time interval. 

1042 

1043 Logs-based metrics can also be used to 

1044 extract values from logs and create a 

1045 distribution of the values. The 

1046 distribution records the statistics of 

1047 the extracted values along with an 

1048 optional histogram of the values as 

1049 specified by the bucket options. 

1050 

1051 """ 

1052 # Create or coerce a protobuf request object. 

1053 # - Quick check: If we got a request object, we should *not* have 

1054 # gotten any keyword arguments that map to the request. 

1055 flattened_params = [parent, metric] 

1056 has_flattened_params = ( 

1057 len([param for param in flattened_params if param is not None]) > 0 

1058 ) 

1059 if request is not None and has_flattened_params: 

1060 raise ValueError( 

1061 "If the `request` argument is set, then none of " 

1062 "the individual field arguments should be set." 

1063 ) 

1064 

1065 # - Use the request object if provided (there's no risk of modifying the input as 

1066 # there are no flattened fields), or create one. 

1067 if not isinstance(request, logging_metrics.CreateLogMetricRequest): 

1068 request = logging_metrics.CreateLogMetricRequest(request) 

1069 # If we have keyword arguments corresponding to fields on the 

1070 # request, apply these. 

1071 if parent is not None: 

1072 request.parent = parent 

1073 if metric is not None: 

1074 request.metric = metric 

1075 

1076 # Wrap the RPC method; this adds retry and timeout information, 

1077 # and friendly error handling. 

1078 rpc = self._transport._wrapped_methods[self._transport.create_log_metric] 

1079 

1080 # Certain fields should be provided within the metadata header; 

1081 # add these here. 

1082 metadata = tuple(metadata) + ( 

1083 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

1084 ) 

1085 

1086 # Validate the universe domain. 

1087 self._validate_universe_domain() 

1088 

1089 # Send the request. 

1090 response = rpc( 

1091 request, 

1092 retry=retry, 

1093 timeout=timeout, 

1094 metadata=metadata, 

1095 ) 

1096 

1097 # Done; return the response. 

1098 return response 

1099 

1100 def update_log_metric( 

1101 self, 

1102 request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, 

1103 *, 

1104 metric_name: Optional[str] = None, 

1105 metric: Optional[logging_metrics.LogMetric] = None, 

1106 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1107 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1108 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1109 ) -> logging_metrics.LogMetric: 

1110 r"""Creates or updates a logs-based metric. 

1111 

1112 .. code-block:: python 

1113 

1114 # This snippet has been automatically generated and should be regarded as a 

1115 # code template only. 

1116 # It will require modifications to work: 

1117 # - It may require correct/in-range values for request initialization. 

1118 # - It may require specifying regional endpoints when creating the service 

1119 # client as shown in: 

1120 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1121 from google.cloud import logging_v2 

1122 

1123 def sample_update_log_metric(): 

1124 # Create a client 

1125 client = logging_v2.MetricsServiceV2Client() 

1126 

1127 # Initialize request argument(s) 

1128 metric = logging_v2.LogMetric() 

1129 metric.name = "name_value" 

1130 metric.filter = "filter_value" 

1131 

1132 request = logging_v2.UpdateLogMetricRequest( 

1133 metric_name="metric_name_value", 

1134 metric=metric, 

1135 ) 

1136 

1137 # Make the request 

1138 response = client.update_log_metric(request=request) 

1139 

1140 # Handle the response 

1141 print(response) 

1142 

1143 Args: 

1144 request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]): 

1145 The request object. The parameters to UpdateLogMetric. 

1146 metric_name (str): 

1147 Required. The resource name of the metric to update: 

1148 

1149 :: 

1150 

1151 "projects/[PROJECT_ID]/metrics/[METRIC_ID]" 

1152 

1153 The updated metric must be provided in the request and 

1154 it's ``name`` field must be the same as ``[METRIC_ID]`` 

1155 If the metric does not exist in ``[PROJECT_ID]``, then a 

1156 new metric is created. 

1157 

1158 This corresponds to the ``metric_name`` field 

1159 on the ``request`` instance; if ``request`` is provided, this 

1160 should not be set. 

1161 metric (google.cloud.logging_v2.types.LogMetric): 

1162 Required. The updated metric. 

1163 This corresponds to the ``metric`` field 

1164 on the ``request`` instance; if ``request`` is provided, this 

1165 should not be set. 

1166 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1167 should be retried. 

1168 timeout (float): The timeout for this request. 

1169 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1170 sent along with the request as metadata. Normally, each value must be of type `str`, 

1171 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1172 be of type `bytes`. 

1173 

1174 Returns: 

1175 google.cloud.logging_v2.types.LogMetric: 

1176 Describes a logs-based metric. The 

1177 value of the metric is the number of log 

1178 entries that match a logs filter in a 

1179 given time interval. 

1180 

1181 Logs-based metrics can also be used to 

1182 extract values from logs and create a 

1183 distribution of the values. The 

1184 distribution records the statistics of 

1185 the extracted values along with an 

1186 optional histogram of the values as 

1187 specified by the bucket options. 

1188 

1189 """ 

1190 # Create or coerce a protobuf request object. 

1191 # - Quick check: If we got a request object, we should *not* have 

1192 # gotten any keyword arguments that map to the request. 

1193 flattened_params = [metric_name, metric] 

1194 has_flattened_params = ( 

1195 len([param for param in flattened_params if param is not None]) > 0 

1196 ) 

1197 if request is not None and has_flattened_params: 

1198 raise ValueError( 

1199 "If the `request` argument is set, then none of " 

1200 "the individual field arguments should be set." 

1201 ) 

1202 

1203 # - Use the request object if provided (there's no risk of modifying the input as 

1204 # there are no flattened fields), or create one. 

1205 if not isinstance(request, logging_metrics.UpdateLogMetricRequest): 

1206 request = logging_metrics.UpdateLogMetricRequest(request) 

1207 # If we have keyword arguments corresponding to fields on the 

1208 # request, apply these. 

1209 if metric_name is not None: 

1210 request.metric_name = metric_name 

1211 if metric is not None: 

1212 request.metric = metric 

1213 

1214 # Wrap the RPC method; this adds retry and timeout information, 

1215 # and friendly error handling. 

1216 rpc = self._transport._wrapped_methods[self._transport.update_log_metric] 

1217 

1218 # Certain fields should be provided within the metadata header; 

1219 # add these here. 

1220 metadata = tuple(metadata) + ( 

1221 gapic_v1.routing_header.to_grpc_metadata( 

1222 (("metric_name", request.metric_name),) 

1223 ), 

1224 ) 

1225 

1226 # Validate the universe domain. 

1227 self._validate_universe_domain() 

1228 

1229 # Send the request. 

1230 response = rpc( 

1231 request, 

1232 retry=retry, 

1233 timeout=timeout, 

1234 metadata=metadata, 

1235 ) 

1236 

1237 # Done; return the response. 

1238 return response 

1239 

1240 def delete_log_metric( 

1241 self, 

1242 request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, 

1243 *, 

1244 metric_name: Optional[str] = None, 

1245 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1246 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1247 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1248 ) -> None: 

1249 r"""Deletes a logs-based metric. 

1250 

1251 .. code-block:: python 

1252 

1253 # This snippet has been automatically generated and should be regarded as a 

1254 # code template only. 

1255 # It will require modifications to work: 

1256 # - It may require correct/in-range values for request initialization. 

1257 # - It may require specifying regional endpoints when creating the service 

1258 # client as shown in: 

1259 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1260 from google.cloud import logging_v2 

1261 

1262 def sample_delete_log_metric(): 

1263 # Create a client 

1264 client = logging_v2.MetricsServiceV2Client() 

1265 

1266 # Initialize request argument(s) 

1267 request = logging_v2.DeleteLogMetricRequest( 

1268 metric_name="metric_name_value", 

1269 ) 

1270 

1271 # Make the request 

1272 client.delete_log_metric(request=request) 

1273 

1274 Args: 

1275 request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]): 

1276 The request object. The parameters to DeleteLogMetric. 

1277 metric_name (str): 

1278 Required. The resource name of the metric to delete: 

1279 

1280 :: 

1281 

1282 "projects/[PROJECT_ID]/metrics/[METRIC_ID]" 

1283 

1284 This corresponds to the ``metric_name`` field 

1285 on the ``request`` instance; if ``request`` is provided, this 

1286 should not be set. 

1287 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1288 should be retried. 

1289 timeout (float): The timeout for this request. 

1290 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1291 sent along with the request as metadata. Normally, each value must be of type `str`, 

1292 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1293 be of type `bytes`. 

1294 """ 

1295 # Create or coerce a protobuf request object. 

1296 # - Quick check: If we got a request object, we should *not* have 

1297 # gotten any keyword arguments that map to the request. 

1298 flattened_params = [metric_name] 

1299 has_flattened_params = ( 

1300 len([param for param in flattened_params if param is not None]) > 0 

1301 ) 

1302 if request is not None and has_flattened_params: 

1303 raise ValueError( 

1304 "If the `request` argument is set, then none of " 

1305 "the individual field arguments should be set." 

1306 ) 

1307 

1308 # - Use the request object if provided (there's no risk of modifying the input as 

1309 # there are no flattened fields), or create one. 

1310 if not isinstance(request, logging_metrics.DeleteLogMetricRequest): 

1311 request = logging_metrics.DeleteLogMetricRequest(request) 

1312 # If we have keyword arguments corresponding to fields on the 

1313 # request, apply these. 

1314 if metric_name is not None: 

1315 request.metric_name = metric_name 

1316 

1317 # Wrap the RPC method; this adds retry and timeout information, 

1318 # and friendly error handling. 

1319 rpc = self._transport._wrapped_methods[self._transport.delete_log_metric] 

1320 

1321 # Certain fields should be provided within the metadata header; 

1322 # add these here. 

1323 metadata = tuple(metadata) + ( 

1324 gapic_v1.routing_header.to_grpc_metadata( 

1325 (("metric_name", request.metric_name),) 

1326 ), 

1327 ) 

1328 

1329 # Validate the universe domain. 

1330 self._validate_universe_domain() 

1331 

1332 # Send the request. 

1333 rpc( 

1334 request, 

1335 retry=retry, 

1336 timeout=timeout, 

1337 metadata=metadata, 

1338 ) 

1339 

1340 def __enter__(self) -> "MetricsServiceV2Client": 

1341 return self 

1342 

1343 def __exit__(self, type, value, traceback): 

1344 """Releases underlying transport's resources. 

1345 

1346 .. warning:: 

1347 ONLY use as a context manager if the transport is NOT shared 

1348 with other clients! Exiting the with block will CLOSE the transport 

1349 and may cause errors in other clients! 

1350 """ 

1351 self.transport.close() 

1352 

1353 def list_operations( 

1354 self, 

1355 request: Optional[operations_pb2.ListOperationsRequest] = None, 

1356 *, 

1357 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1358 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1359 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1360 ) -> operations_pb2.ListOperationsResponse: 

1361 r"""Lists operations that match the specified filter in the request. 

1362 

1363 Args: 

1364 request (:class:`~.operations_pb2.ListOperationsRequest`): 

1365 The request object. Request message for 

1366 `ListOperations` method. 

1367 retry (google.api_core.retry.Retry): Designation of what errors, 

1368 if any, should be retried. 

1369 timeout (float): The timeout for this request. 

1370 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1371 sent along with the request as metadata. Normally, each value must be of type `str`, 

1372 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1373 be of type `bytes`. 

1374 Returns: 

1375 ~.operations_pb2.ListOperationsResponse: 

1376 Response message for ``ListOperations`` method. 

1377 """ 

1378 # Create or coerce a protobuf request object. 

1379 # The request isn't a proto-plus wrapped type, 

1380 # so it must be constructed via keyword expansion. 

1381 if isinstance(request, dict): 

1382 request = operations_pb2.ListOperationsRequest(**request) 

1383 

1384 # Wrap the RPC method; this adds retry and timeout information, 

1385 # and friendly error handling. 

1386 rpc = self._transport._wrapped_methods[self._transport.list_operations] 

1387 

1388 # Certain fields should be provided within the metadata header; 

1389 # add these here. 

1390 metadata = tuple(metadata) + ( 

1391 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1392 ) 

1393 

1394 # Validate the universe domain. 

1395 self._validate_universe_domain() 

1396 

1397 try: 

1398 # Send the request. 

1399 response = rpc( 

1400 request, 

1401 retry=retry, 

1402 timeout=timeout, 

1403 metadata=metadata, 

1404 ) 

1405 

1406 # Done; return the response. 

1407 return response 

1408 except core_exceptions.GoogleAPICallError as e: 

1409 self._add_cred_info_for_auth_errors(e) 

1410 raise e 

1411 

1412 def get_operation( 

1413 self, 

1414 request: Optional[operations_pb2.GetOperationRequest] = None, 

1415 *, 

1416 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1417 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1418 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1419 ) -> operations_pb2.Operation: 

1420 r"""Gets the latest state of a long-running operation. 

1421 

1422 Args: 

1423 request (:class:`~.operations_pb2.GetOperationRequest`): 

1424 The request object. Request message for 

1425 `GetOperation` method. 

1426 retry (google.api_core.retry.Retry): Designation of what errors, 

1427 if any, should be retried. 

1428 timeout (float): The timeout for this request. 

1429 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1430 sent along with the request as metadata. Normally, each value must be of type `str`, 

1431 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1432 be of type `bytes`. 

1433 Returns: 

1434 ~.operations_pb2.Operation: 

1435 An ``Operation`` object. 

1436 """ 

1437 # Create or coerce a protobuf request object. 

1438 # The request isn't a proto-plus wrapped type, 

1439 # so it must be constructed via keyword expansion. 

1440 if isinstance(request, dict): 

1441 request = operations_pb2.GetOperationRequest(**request) 

1442 

1443 # Wrap the RPC method; this adds retry and timeout information, 

1444 # and friendly error handling. 

1445 rpc = self._transport._wrapped_methods[self._transport.get_operation] 

1446 

1447 # Certain fields should be provided within the metadata header; 

1448 # add these here. 

1449 metadata = tuple(metadata) + ( 

1450 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1451 ) 

1452 

1453 # Validate the universe domain. 

1454 self._validate_universe_domain() 

1455 

1456 try: 

1457 # Send the request. 

1458 response = rpc( 

1459 request, 

1460 retry=retry, 

1461 timeout=timeout, 

1462 metadata=metadata, 

1463 ) 

1464 

1465 # Done; return the response. 

1466 return response 

1467 except core_exceptions.GoogleAPICallError as e: 

1468 self._add_cred_info_for_auth_errors(e) 

1469 raise e 

1470 

1471 def cancel_operation( 

1472 self, 

1473 request: Optional[operations_pb2.CancelOperationRequest] = None, 

1474 *, 

1475 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1476 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1477 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1478 ) -> None: 

1479 r"""Starts asynchronous cancellation on a long-running operation. 

1480 

1481 The server makes a best effort to cancel the operation, but success 

1482 is not guaranteed. If the server doesn't support this method, it returns 

1483 `google.rpc.Code.UNIMPLEMENTED`. 

1484 

1485 Args: 

1486 request (:class:`~.operations_pb2.CancelOperationRequest`): 

1487 The request object. Request message for 

1488 `CancelOperation` method. 

1489 retry (google.api_core.retry.Retry): Designation of what errors, 

1490 if any, should be retried. 

1491 timeout (float): The timeout for this request. 

1492 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1493 sent along with the request as metadata. Normally, each value must be of type `str`, 

1494 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1495 be of type `bytes`. 

1496 Returns: 

1497 None 

1498 """ 

1499 # Create or coerce a protobuf request object. 

1500 # The request isn't a proto-plus wrapped type, 

1501 # so it must be constructed via keyword expansion. 

1502 if isinstance(request, dict): 

1503 request = operations_pb2.CancelOperationRequest(**request) 

1504 

1505 # Wrap the RPC method; this adds retry and timeout information, 

1506 # and friendly error handling. 

1507 rpc = self._transport._wrapped_methods[self._transport.cancel_operation] 

1508 

1509 # Certain fields should be provided within the metadata header; 

1510 # add these here. 

1511 metadata = tuple(metadata) + ( 

1512 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1513 ) 

1514 

1515 # Validate the universe domain. 

1516 self._validate_universe_domain() 

1517 

1518 # Send the request. 

1519 rpc( 

1520 request, 

1521 retry=retry, 

1522 timeout=timeout, 

1523 metadata=metadata, 

1524 ) 

1525 

1526 

1527DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1528 gapic_version=package_version.__version__ 

1529) 

1530 

1531if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

1532 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1533 

1534__all__ = ("MetricsServiceV2Client",)