Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 96 additions & 8 deletions packages/google-cloud-bigtable/google/cloud/bigtable/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,15 @@
import warnings

import grpc # type: ignore
from google.api_core import universe
from google.api_core.gapic_v1 import client_info as client_info_lib
from google.auth.credentials import AnonymousCredentials # type: ignore
from google.cloud.client import ClientWithProject # type: ignore
from google.cloud.environment_vars import BIGTABLE_EMULATOR # type: ignore

from google.cloud import bigtable, bigtable_admin_v2
from google.cloud.bigtable.cluster import _CLUSTER_NAME_RE, Cluster
from google.cloud.bigtable.data._helpers import _validate_credentials_universe
from google.cloud.bigtable.instance import Instance
from google.cloud.bigtable_admin_v2.services.bigtable_instance_admin.transports import (
BigtableInstanceAdminGrpcTransport,
Expand Down Expand Up @@ -82,6 +84,57 @@ def inner(self):
return inner


def _get_client_option(options, name):
"""Read an attribute or dict key from ``options`` if present."""
if isinstance(options, dict):
return options.get(name)
return getattr(options, name, None)


def _inherit_admin_client_options(
client_options, admin_client_options, universe_domain_env
):
"""Return ``admin_client_options``, with the endpoint settings it does not
set filled in. Neither options argument is modified.

- ``universe_domain`` falls back to ``client_options``, then to
``universe_domain_env`` (the ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment
variable). If neither sets one, it is left unset.
- ``api_endpoint`` falls back to ``client_options`` only when
``admin_client_options`` sets neither ``api_endpoint`` nor
``universe_domain``, so a ``client_options`` endpoint never overrides a
universe chosen for admin operations.
"""
inherited = {}
# A universe set in admin_client_options stands on its own. Inheriting an
# api_endpoint from client_options would override it.
if _get_client_option(admin_client_options, "universe_domain") is None:
# Universe: client_options, then the environment variable. With
# neither, it stays unset and the admin clients apply their default.
universe_domain = _get_client_option(client_options, "universe_domain")
if universe_domain is None:
universe_domain = universe_domain_env
if universe_domain is not None:
inherited["universe_domain"] = universe_domain
# Endpoint: client_options, unless admin_client_options sets its own.
client_endpoint = _get_client_option(client_options, "api_endpoint")
if client_endpoint and not _get_client_option(
admin_client_options, "api_endpoint"
):
inherited["api_endpoint"] = client_endpoint
if not inherited:
# Nothing to add: use the options exactly as they were passed in.
return admin_client_options
# Add the inherited settings to a copy, so the caller's object is not
# modified. A dict stays a dict.
if admin_client_options is None or isinstance(admin_client_options, dict):
return {**(admin_client_options or {}), **inherited}
admin_client_options = copy.copy(admin_client_options)
for name, value in inherited.items():
setattr(admin_client_options, name, value)
return admin_client_options


class Client(ClientWithProject):
"""Client for interacting with Google Cloud Bigtable API.

Expand Down Expand Up @@ -120,13 +173,19 @@ class Client(ClientWithProject):
:type client_options: :class:`~google.api_core.client_options.ClientOptions`
or :class:`dict`
:param client_options: (Optional) Client options used to set user options
on the client. API Endpoint should be set through client_options.
on the client. The credential settings, ``api_endpoint`` and
``universe_domain`` set here are used for both data and admin
operations, unless ``admin_client_options`` overrides the last two
for admin operations.

:type admin_client_options:
:class:`~google.api_core.client_options.ClientOptions` or :class:`dict`
:param admin_client_options: (Optional) Client options used to set user
options on the client. API Endpoint for admin operations should be set
through admin_client_options.
:param admin_client_options: (Optional) Overrides the ``api_endpoint``
and ``universe_domain`` from ``client_options`` for admin operations
only. Data and admin operations are served by separate APIs, so use
this when admin operations need a different endpoint than data
operations. If neither is set here, the values from
``client_options`` are used.

:type channel: :instance: grpc.Channel
:param channel (grpc.Channel): (Optional) DEPRECATED:
Expand Down Expand Up @@ -183,7 +242,11 @@ def __init__(
)

self._client_options = client_options
self._admin_client_options = admin_client_options
self._admin_client_options = _inherit_admin_client_options(
client_options,
admin_client_options,
os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"),
)
self._channel = channel
self.SCOPE = self._get_scopes()
super(Client, self).__init__(
Expand Down Expand Up @@ -225,13 +288,38 @@ def _emulator_channel(self, transport, options):
channel_fn = grpc.insecure_channel
return channel_fn(self._emulator_host, options=options)

def _resolve_admin_endpoint(self, client_class):
"""Resolve the target host for GAPIC admin channels.

Uses ``admin_client_options`` as resolved when the client was
constructed (see ``_inherit_admin_client_options``), so the
``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment variable is not read
again here. If no ``universe_domain`` is set there, the default
``googleapis.com`` is used.

An explicit ``api_endpoint`` overrides ``universe_domain`` without
comparing hostnames, matching GAPIC behavior for regional, proxy, or
PSC endpoints. ``universe_domain`` is still validated first so an empty
string raises ``EmptyUniverseError`` even when ``api_endpoint`` is set.
"""
universe_domain = universe.determine_domain(
_get_client_option(self._admin_client_options, "universe_domain"), None
)
_validate_credentials_universe(universe_domain, self._credentials)
api_endpoint = _get_client_option(self._admin_client_options, "api_endpoint")
if api_endpoint:
return api_endpoint
if universe_domain == universe.DEFAULT_UNIVERSE:
return client_class.DEFAULT_ENDPOINT
return client_class._DEFAULT_ENDPOINT_TEMPLATE.format(
UNIVERSE_DOMAIN=universe_domain
)

def _create_gapic_client_channel(self, client_class, grpc_transport):
if self._emulator_host is not None:
api_endpoint = self._emulator_host
elif self._client_options and self._client_options.api_endpoint:
api_endpoint = self._client_options.api_endpoint
else:
api_endpoint = client_class.DEFAULT_ENDPOINT
api_endpoint = self._resolve_admin_endpoint(client_class)

if self._emulator_host is not None:
channel = self._emulator_channel(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import google.auth.credentials
from google.api_core import client_options as client_options_lib
from google.api_core import retry as retries
from google.api_core import universe
from google.api_core.exceptions import (
Aborted,
Cancelled,
Expand All @@ -61,6 +62,7 @@
_get_retryable_errors,
_get_timeouts,
_retry_exception_factory,
_validate_credentials_universe,
_validate_timeouts,
_WarmedInstanceKey,
)
Expand Down Expand Up @@ -253,6 +255,14 @@ def __init__(
project=project,
client_options=client_options,
)
if self._emulator_host is None:
client_universe = universe.determine_domain(
client_options.universe_domain if client_options else None,
os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"),
)
_validate_credentials_universe(
client_universe, getattr(self, "_credentials", None)
)
self._gapic_client = GapicClient(
credentials=credentials,
client_options=client_options,
Expand All @@ -261,33 +271,34 @@ def __init__(
*args, **kwargs, channel=self._build_grpc_channel
),
)
if (
credentials
and hasattr(credentials, "universe_domain")
and credentials.universe_domain != self.universe_domain
and self._emulator_host is None
):
# validate that the universe domain of the credentials matches the
# universe domain configured in client_options
raise ValueError(
f"The configured universe domain ({self.universe_domain}) does "
"not match the universe domain found in the credentials "
f"({self._credentials.universe_domain}). If you haven't "
"configured the universe domain explicitly, `googleapis.com` "
"is the default."
)
self._is_closed = CrossSync.Event()
# Private argument, for internal use only
self._disable_background_refresh = bool(
kwargs.get("_disable_background_refresh", False)
)
handlers: list[MetricsHandler] = []
if self._emulator_host is None:
has_custom_endpoint = bool(client_options and client_options.api_endpoint)
if (
self._emulator_host is None
and not isinstance(
self._credentials, google.auth.credentials.AnonymousCredentials
)
and not has_custom_endpoint
):
try:
# create a metrics exporter using the same client configuration
# Pass only universe_domain and client_cert_source so
# Bigtable-specific options (such as scopes or api_audience) are
# not sent to Cloud Monitoring.
exporter = BigtableMetricsExporter(
credentials=self._credentials,
client_options=client_options,
client_options=client_options_lib.ClientOptions(
universe_domain=self.universe_domain,
client_cert_source=(
client_options.client_cert_source
if client_options
else None
),
),
)
handlers.append(
GoogleCloudMetricsHandler(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@

from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.api_core import universe
from google.api_core.retry import RetryFailureReason, exponential_sleep_generator
from google.auth import compute_engine # type: ignore
from google.auth import credentials as auth_credentials # type: ignore
from google.protobuf import any_pb2, message
from google.rpc import code_pb2, status_pb2

Expand Down Expand Up @@ -476,3 +479,27 @@ def get_attempt_backoff(self, attempt_idx) -> float:
if attempt_idx < 0:
raise IndexError("received negative attempt number")
return self.history[attempt_idx]


# TODO(universe-domain): Replace with
# google.api_core.universe.validate_credentials_universe once minimum
# google-api-core version exceeds 2.44.0.
def _validate_credentials_universe(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SYNC WARNING:

I noticed two sync gaps between #19192 and the proposed shared helpers in catalog.py (cl/1029785586). I recommend the following actions:

  • Mirror _validate_credentials_universe on validate_credentials_universe in catalog.py (cl/1029785586) so google.auth.aio.credentials.AnonymousCredentials is also exempted (needed for BigtableDataClientAsync in custom universes).

  • Update _inherit_admin_client_options to match inherit_universe_in_client_options in catalog.py (cl/1029785586) so an explicit "googleapis.com" on the parent overrides GOOGLE_CLOUD_UNIVERSE_DOMAIN and prevents child admin clients from drifting.
    Keep the # TODO(universe-domain): markers until testing/constraints-3.10.txt exceeds google-api-core 2.44.0.

I know that you have better context on this than I do, so if any of these suggestions are wrong, please leave a comment here. Gemini will pick them up and learn from them during the next sync sweep.

client_universe: str,
credentials: auth_credentials.Credentials | None,
) -> None:
"""Validate that resolved client credentials match ``client_universe``."""
if credentials is None or isinstance(
credentials, auth_credentials.AnonymousCredentials
):
return
# Avoid synchronous GCE metadata server HTTP calls when
# compute_engine.Credentials hasn't resolved its universe yet.
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
cred_universe = getattr(credentials, "universe_domain", universe.DEFAULT_UNIVERSE)
if not isinstance(cred_universe, str):
return
universe.compare_domains(client_universe, credentials)
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import google.auth.credentials
from google.api_core import client_options as client_options_lib
from google.api_core import retry as retries
from google.api_core import universe
from google.api_core.exceptions import (
Aborted,
Cancelled,
Expand All @@ -55,6 +56,7 @@
_get_retryable_errors,
_get_timeouts,
_retry_exception_factory,
_validate_credentials_universe,
_validate_timeouts,
_WarmedInstanceKey,
)
Expand Down Expand Up @@ -186,6 +188,14 @@ def __init__(
project=project,
client_options=client_options,
)
if self._emulator_host is None:
client_universe = universe.determine_domain(
client_options.universe_domain if client_options else None,
os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"),
)
_validate_credentials_universe(
client_universe, getattr(self, "_credentials", None)
)
self._gapic_client = GapicClient(
credentials=credentials,
client_options=client_options,
Expand All @@ -194,24 +204,30 @@ def __init__(
*args, **kwargs, channel=self._build_grpc_channel
),
)
if (
credentials
and hasattr(credentials, "universe_domain")
and (credentials.universe_domain != self.universe_domain)
and (self._emulator_host is None)
):
raise ValueError(
f"The configured universe domain ({self.universe_domain}) does not match the universe domain found in the credentials ({self._credentials.universe_domain}). If you haven't configured the universe domain explicitly, `googleapis.com` is the default."
)
self._is_closed = CrossSync._Sync_Impl.Event()
self._disable_background_refresh = bool(
kwargs.get("_disable_background_refresh", False)
)
handlers: list[MetricsHandler] = []
if self._emulator_host is None:
has_custom_endpoint = bool(client_options and client_options.api_endpoint)
if (
self._emulator_host is None
and (
not isinstance(
self._credentials, google.auth.credentials.AnonymousCredentials
)
)
and (not has_custom_endpoint)
):
try:
exporter = BigtableMetricsExporter(
credentials=self._credentials, client_options=client_options
credentials=self._credentials,
client_options=client_options_lib.ClientOptions(
universe_domain=self.universe_domain,
client_cert_source=client_options.client_cert_source
if client_options
else None,
),
)
handlers.append(
GoogleCloudMetricsHandler(
Expand Down Expand Up @@ -1424,9 +1440,7 @@ def mutate_row(

def execute_rpc():
return self.client._gapic_client.mutate_row(
request=request,
timeout=next(attempt_timeout_gen),
retry=None,
request=request, timeout=next(attempt_timeout_gen), retry=None
)

return tracked_retry(
Expand Down
Loading
Loading