Skip to content
Draft
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
89 changes: 80 additions & 9 deletions packages/google-cloud-bigtable/google/cloud/bigtable/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
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
Expand Down Expand Up @@ -82,6 +83,13 @@ 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)


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

Expand Down Expand Up @@ -120,13 +128,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 @@ -225,13 +239,70 @@ 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.

Precedence order:
1. ``admin_client_options.api_endpoint``
2. ``admin_client_options.universe_domain``
3. ``client_options.api_endpoint``
4. ``client_options.universe_domain``
5. ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` environment variable
6. ``client_class.DEFAULT_ENDPOINT`` (``googleapis.com``)

Within the same options object (or against the environment variable),
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.
"""
admin_universe = _get_client_option(
self._admin_client_options, "universe_domain"
)
client_universe = _get_client_option(self._client_options, "universe_domain")
configured_universe = (
admin_universe if admin_universe is not None else client_universe
)
universe_domain = universe.determine_domain(
configured_universe, os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
)

admin_endpoint = _get_client_option(self._admin_client_options, "api_endpoint")
if admin_endpoint:
return admin_endpoint

if admin_universe is None:
client_endpoint = _get_client_option(self._client_options, "api_endpoint")
if client_endpoint:
return client_endpoint

if universe_domain == universe.DEFAULT_UNIVERSE:
return client_class.DEFAULT_ENDPOINT
return client_class._DEFAULT_ENDPOINT_TEMPLATE.format(
UNIVERSE_DOMAIN=universe_domain
)

def _resolve_admin_client_options(self):
"""Return ``admin_client_options``, inheriting ``universe_domain`` from
``client_options`` if unset so admin clients report the right universe."""
admin_options = self._admin_client_options
client_universe = _get_client_option(self._client_options, "universe_domain")
if (
not client_universe
or _get_client_option(admin_options, "universe_domain") is not None
):
return admin_options
if admin_options is None or isinstance(admin_options, dict):
return {**(admin_options or {}), "universe_domain": client_universe}
admin_options = copy.copy(admin_options)
admin_options.universe_domain = client_universe
return admin_options

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 Expand Up @@ -318,7 +389,7 @@ def table_admin_client(self):
)
klass = _create_gapic_client(
bigtable_admin_v2.BaseBigtableTableAdminClient,
client_options=self._admin_client_options,
client_options=self._resolve_admin_client_options(),
transport=transport,
)
self._table_admin_client = klass(self)
Expand Down Expand Up @@ -355,7 +426,7 @@ def instance_admin_client(self):
)
klass = _create_gapic_client(
bigtable_admin_v2.BigtableInstanceAdminClient,
client_options=self._admin_client_options,
client_options=self._resolve_admin_client_options(),
transport=transport,
)
self._instance_admin_client = klass(self)
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 Down Expand Up @@ -282,7 +283,12 @@ def __init__(
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 self.universe_domain == universe.DEFAULT_UNIVERSE
and not has_custom_endpoint
):
try:
# create a metrics exporter using the same client configuration
exporter = BigtableMetricsExporter(
Expand Down
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 Down Expand Up @@ -208,7 +209,12 @@ def __init__(
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 self.universe_domain == universe.DEFAULT_UNIVERSE
and (not has_custom_endpoint)
):
try:
exporter = BigtableMetricsExporter(
credentials=self._credentials, client_options=client_options
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,75 @@ async def test_configured_universe_domain_mismatched_credentials(self):
)
assert exc.value.args[0] == err_msg

@CrossSync.pytest
async def test_metrics_exporter_disabled_outside_gdu(self):
"""BigtableMetricsExporter should be disabled when universe_domain != googleapis.com."""
import os

universe_domain = "custom-universe.test"
creds = AnonymousCredentials()
creds._universe_domain = universe_domain
options = client_options.ClientOptions(universe_domain=universe_domain)
with (
mock.patch(
"google.cloud.bigtable.data._async.client.BigtableMetricsExporter"
) as exporter_mock_async,
mock.patch(
"google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter"
) as exporter_mock_sync,
):
async with self._make_client(
project="project_id",
credentials=creds,
client_options=options,
use_emulator=False,
use_mtls="never",
) as client:
assert client.universe_domain == universe_domain
assert client.api_endpoint == f"bigtable.{universe_domain}"
assert len(client._metrics.handlers) == 0
exporter_mock_async.assert_not_called()
exporter_mock_sync.assert_not_called()

with mock.patch.dict(
os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain}
):
async with self._make_client(
project="project_id",
credentials=creds,
use_emulator=False,
use_mtls="never",
) as client:
assert client.universe_domain == universe_domain
assert client.api_endpoint == f"bigtable.{universe_domain}"
assert len(client._metrics.handlers) == 0
exporter_mock_async.assert_not_called()
exporter_mock_sync.assert_not_called()

@CrossSync.pytest
async def test_metrics_exporter_disabled_with_custom_api_endpoint(self):
"""BigtableMetricsExporter should be disabled when a custom api_endpoint is set."""
options = client_options.ClientOptions(api_endpoint="bigtable.custom.local:443")
with (
mock.patch(
"google.cloud.bigtable.data._async.client.BigtableMetricsExporter"
) as exporter_mock_async,
mock.patch(
"google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter"
) as exporter_mock_sync,
):
async with self._make_client(
project="project_id",
credentials=AnonymousCredentials(),
client_options=options,
use_emulator=False,
use_mtls="never",
) as client:
assert client.api_endpoint == "bigtable.custom.local:443"
assert len(client._metrics.handlers) == 0
exporter_mock_async.assert_not_called()
exporter_mock_sync.assert_not_called()

@CrossSync.pytest
async def test_configured_universe_domain_matches_credentials(self):
"""Test that configured universe domain succeeds with matching universe
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1116,6 +1116,72 @@ def test_configured_universe_domain_mismatched_credentials(self):
err_msg = f"The configured universe domain ({universe_domain}) does not match the universe domain found in the credentials ({creds.universe_domain}). If you haven't configured the universe domain explicitly, `googleapis.com` is the default."
assert exc.value.args[0] == err_msg

def test_metrics_exporter_disabled_outside_gdu(self):
"""BigtableMetricsExporter should be disabled when universe_domain != googleapis.com."""
import os

universe_domain = "custom-universe.test"
creds = AnonymousCredentials()
creds._universe_domain = universe_domain
options = client_options.ClientOptions(universe_domain=universe_domain)
with (
mock.patch(
"google.cloud.bigtable.data._async.client.BigtableMetricsExporter"
) as exporter_mock_async,
mock.patch(
"google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter"
) as exporter_mock_sync,
):
with self._make_client(
project="project_id",
credentials=creds,
client_options=options,
use_emulator=False,
use_mtls="never",
) as client:
assert client.universe_domain == universe_domain
assert client.api_endpoint == f"bigtable.{universe_domain}"
assert len(client._metrics.handlers) == 0
exporter_mock_async.assert_not_called()
exporter_mock_sync.assert_not_called()
with mock.patch.dict(
os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain}
):
with self._make_client(
project="project_id",
credentials=creds,
use_emulator=False,
use_mtls="never",
) as client:
assert client.universe_domain == universe_domain
assert client.api_endpoint == f"bigtable.{universe_domain}"
assert len(client._metrics.handlers) == 0
exporter_mock_async.assert_not_called()
exporter_mock_sync.assert_not_called()

def test_metrics_exporter_disabled_with_custom_api_endpoint(self):
"""BigtableMetricsExporter should be disabled when a custom api_endpoint is set."""
options = client_options.ClientOptions(api_endpoint="bigtable.custom.local:443")
with (
mock.patch(
"google.cloud.bigtable.data._async.client.BigtableMetricsExporter"
) as exporter_mock_async,
mock.patch(
"google.cloud.bigtable.data._sync_autogen.client.BigtableMetricsExporter"
) as exporter_mock_sync,
):
with self._make_client(
project="project_id",
credentials=AnonymousCredentials(),
client_options=options,
use_emulator=False,
use_mtls="never",
) as client:
assert client.api_endpoint == "bigtable.custom.local:443"
assert len(client._metrics.handlers) == 0
exporter_mock_async.assert_not_called()
exporter_mock_sync.assert_not_called()

def test_configured_universe_domain_matches_credentials(self):
"""Test that configured universe domain succeeds with matching universe
domain credentials."""
Expand Down
Loading
Loading