Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"""Database cursor for Google Cloud Spanner DB API."""

from collections import namedtuple
from dataclasses import replace

import sqlparse
from google.api_core.exceptions import (
Expand Down Expand Up @@ -61,22 +60,6 @@
ColumnDetails = namedtuple("column_details", ["null_ok", "spanner_type"])


def _ensure_where_clause(parsed_statement: ParsedStatement) -> ParsedStatement:
"""Ensure a dummy WHERE clause is present on UPDATE/DELETE statements.

TODO: Remove this once we no longer automatically add a dummy WHERE clause
to DML statements.
"""
if parsed_statement.statement_type == StatementType.UPDATE:
sql = parse_utils.ensure_where_clause(parsed_statement.statement.sql)
if sql != parsed_statement.statement.sql:
return replace(
parsed_statement,
statement=replace(parsed_statement.statement, sql=sql),
)
return parsed_statement


def check_not_closed(function):
"""`Cursor` class methods decorator.

Expand Down Expand Up @@ -354,7 +337,6 @@ def _execute(self, sql, args=None, call_from_execute_many=False):
else:
self._itr = PeekIterator(self._result_set)
elif self.connection._batch_mode == BatchMode.DML:
self._parsed_statement = _ensure_where_clause(self._parsed_statement)
self.connection.execute_batch_dml_statement(self._parsed_statement)
elif (
self._parsed_statement.statement_type == StatementType.QUERY
Expand All @@ -371,13 +353,12 @@ def _execute(self, sql, args=None, call_from_execute_many=False):
if not self.connection._client_transaction_started:
self.connection.run_prior_DDL_statements()
elif (
not self.connection._client_transaction_started
and self.connection.autocommit_dml_mode
self.connection.autocommit_dml_mode
is AutocommitDmlMode.PARTITIONED_NON_ATOMIC
):
self._row_count = self.connection.database.execute_partitioned_dml(
self._parsed_statement.statement.sql,
params=self._parsed_statement.statement.params,
sql,
params=args,
param_types=self._parsed_statement.statement.param_types,
request_options=self.request_options,
)
Expand Down Expand Up @@ -420,7 +401,6 @@ def _execute_in_rw_transaction(self):
# For every other operation, we've got to ensure that
# any prior DDL statements were run.
self.connection.run_prior_DDL_statements()
self._parsed_statement = _ensure_where_clause(self._parsed_statement)
statement = self._parsed_statement.statement
if self.connection._client_transaction_started:
while True:
Expand Down Expand Up @@ -481,9 +461,6 @@ def executemany(self, operation, seq_of_params):
+ ", with executemany() method is not allowed."
)

self._parsed_statement = _ensure_where_clause(self._parsed_statement)
sql = self._parsed_statement.statement.sql

# For every operation, we've got to ensure that any prior DDL
# statements were run.
self.connection.run_prior_DDL_statements()
Expand All @@ -496,12 +473,10 @@ def executemany(self, operation, seq_of_params):
):
statements = []
for params in seq_of_params:
statement_sql, params = parse_utils.sql_pyformat_args_to_spanner(
sql, params
)
statements.append(
Statement(statement_sql, params, get_param_types(params))
sql, params = parse_utils.sql_pyformat_args_to_spanner(
operation, params
)
statements.append(Statement(sql, params, get_param_types(params)))
many_result_set = batch_dml_executor.run_batch_dml(self, statements)
else:
many_result_set = StreamedManyResultSets()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,12 @@ def classify_statement(query, args=None):
args,
get_param_types(args or None),
)
statement_type = _get_statement_type(query)
statement_type = _get_statement_type(statement)
return ParsedStatement(statement_type, statement)


def _get_statement_type(query):
def _get_statement_type(statement):
query = statement.sql
if RE_DDL.match(query):
return StatementType.DDL
if RE_IS_INSERT.match(query):
Expand All @@ -270,6 +271,9 @@ def _get_statement_type(query):
return StatementType.QUERY

if RE_IS_UPDATE.match(query) or RE_IS_DELETE.match(query):
# TODO: Remove this? It makes more sense to have this in SQLAlchemy and
# Django than here.
statement.sql = ensure_where_clause(query)
return StatementType.UPDATE

return StatementType.UNKNOWN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@

EMULATOR_ENV_VAR = "SPANNER_EMULATOR_HOST"
SPANNER_DISABLE_BUILTIN_METRICS_ENV_VAR = "SPANNER_DISABLE_BUILTIN_METRICS"
SPANNER_MONITORING_HOST_ENV_VAR = "SPANNER_MONITORING_HOST"
LOG_CLIENT_OPTIONS_ENV_VAR = "GOOGLE_CLOUD_SPANNER_ENABLE_LOG_CLIENT_OPTIONS"
_EMULATOR_HOST_HTTP_SCHEME = (
"%s contains a http scheme. When used with a scheme it may cause gRPC's "
Expand Down Expand Up @@ -134,11 +135,15 @@ def _get_spanner_enable_builtin_metrics_env():
return os.getenv(SPANNER_DISABLE_BUILTIN_METRICS_ENV_VAR) != "true"


def _get_spanner_monitoring_host_env():
return os.getenv(SPANNER_MONITORING_HOST_ENV_VAR)


def _get_spanner_log_client_options_env():
return os.getenv(LOG_CLIENT_OPTIONS_ENV_VAR, "false").lower() == "true"


def _initialize_metrics(project, credentials, emulator_host=None):
def _initialize_metrics(project, credentials, emulator_host=None, client_options=None):
"""
Initializes the Spanner built-in metrics.

Expand All @@ -151,17 +156,41 @@ def _initialize_metrics(project, credentials, emulator_host=None):
if not _metrics_monitor_initialized:
meter_provider = metrics.NoOpMeterProvider()
try:
if isinstance(client_options, dict):
client_options = google.api_core.client_options.from_dict(
client_options
)
monitoring_host = _get_spanner_monitoring_host_env()
# Skip metrics export when a custom Spanner api_endpoint is
# set unless SPANNER_MONITORING_HOST is explicitly provided.
has_custom_endpoint = bool(
getattr(client_options, "api_endpoint", None)
)
if (
not _get_spanner_emulator_host()
and not emulator_host
and not isinstance(credentials, AnonymousCredentials)
and (not has_custom_endpoint or monitoring_host)
):
# Only forward universe_domain (and explicit monitoring host).
universe_domain = getattr(
client_options, "universe_domain", None
)
monitoring_options = (
google.api_core.client_options.ClientOptions(
api_endpoint=monitoring_host or None,
universe_domain=universe_domain,
)
if monitoring_host or universe_domain
else None
)
meter_provider = MeterProvider(
metric_readers=[
PeriodicExportingMetricReader(
CloudMonitoringMetricsExporter(
project_id=project,
credentials=credentials,
client_options=monitoring_options,
),
export_interval_millis=METRIC_EXPORT_INTERVAL_MS,
),
Expand Down Expand Up @@ -421,7 +450,12 @@ def __init__(
and not disable_builtin_metrics
and HAS_GOOGLE_CLOUD_MONITORING_INSTALLED
):
_initialize_metrics(project, credentials, self._emulator_host)
_initialize_metrics(
self.project,
self._credentials,
self._emulator_host,
client_options=self._client_options,
)
else:
SpannerMetricsTracerFactory(enabled=False)

Expand Down
38 changes: 35 additions & 3 deletions packages/google-cloud-spanner/google/cloud/spanner_v1/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
_CLIENT_INFO = client_info.ClientInfo(client_library_version=__version__)
EMULATOR_ENV_VAR = "SPANNER_EMULATOR_HOST"
SPANNER_DISABLE_BUILTIN_METRICS_ENV_VAR = "SPANNER_DISABLE_BUILTIN_METRICS"
SPANNER_MONITORING_HOST_ENV_VAR = "SPANNER_MONITORING_HOST"
LOG_CLIENT_OPTIONS_ENV_VAR = "GOOGLE_CLOUD_SPANNER_ENABLE_LOG_CLIENT_OPTIONS"
_EMULATOR_HOST_HTTP_SCHEME = (
"%s contains a http scheme. When used with a scheme it may cause gRPC's DNS resolver to endlessly attempt to resolve. %s is intended to be used without a scheme: ex %s=localhost:8080."
Expand Down Expand Up @@ -115,11 +116,15 @@ def _get_spanner_enable_builtin_metrics_env():
return os.getenv(SPANNER_DISABLE_BUILTIN_METRICS_ENV_VAR) != "true"


def _get_spanner_monitoring_host_env():
return os.getenv(SPANNER_MONITORING_HOST_ENV_VAR)


def _get_spanner_log_client_options_env():
return os.getenv(LOG_CLIENT_OPTIONS_ENV_VAR, "false").lower() == "true"


def _initialize_metrics(project, credentials, emulator_host=None):
def _initialize_metrics(project, credentials, emulator_host=None, client_options=None):
"""Initializes the Spanner built-in metrics.

This function sets up the OpenTelemetry MeterProvider and the SpannerMetricsTracerFactory.
Expand All @@ -130,16 +135,38 @@ def _initialize_metrics(project, credentials, emulator_host=None):
if not _metrics_monitor_initialized:
meter_provider = metrics.NoOpMeterProvider()
try:
if isinstance(client_options, dict):
client_options = google.api_core.client_options.from_dict(
client_options
)
monitoring_host = _get_spanner_monitoring_host_env()
has_custom_endpoint = bool(
getattr(client_options, "api_endpoint", None)
)
if (
not _get_spanner_emulator_host()
and (not emulator_host)
and (not isinstance(credentials, AnonymousCredentials))
and (not has_custom_endpoint or monitoring_host)
):
universe_domain = getattr(
client_options, "universe_domain", None
)
monitoring_options = (
google.api_core.client_options.ClientOptions(
api_endpoint=monitoring_host or None,
universe_domain=universe_domain,
)
if monitoring_host or universe_domain
else None
)
meter_provider = MeterProvider(
metric_readers=[
PeriodicExportingMetricReader(
CloudMonitoringMetricsExporter(
project_id=project, credentials=credentials
project_id=project,
credentials=credentials,
client_options=monitoring_options,
),
export_interval_millis=METRIC_EXPORT_INTERVAL_MS,
)
Expand Down Expand Up @@ -367,7 +394,12 @@ def __init__(
and (not disable_builtin_metrics)
and HAS_GOOGLE_CLOUD_MONITORING_INSTALLED
):
_initialize_metrics(project, credentials, self._emulator_host)
_initialize_metrics(
self.project,
self._credentials,
self._emulator_host,
client_options=self._client_options,
)
else:
SpannerMetricsTracerFactory(enabled=False)
self._route_to_leader_enabled = route_to_leader_enabled
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from google.api.monitored_resource_pb2 import (
MonitoredResource,
) # pylint: disable=no-name-in-module
from google.api_core import client_options as client_options_lib
from google.api_core.exceptions import (
DeadlineExceeded,
InvalidArgument,
Expand Down Expand Up @@ -95,6 +96,16 @@
("grpc.primary_user_agent", _USER_AGENT),
]

# Scopes that authorize writing time series to Cloud Monitoring.
_MONITORING_WRITE_SCOPE = "https://www.googleapis.com/auth/monitoring.write"
_MONITORING_SCOPES = frozenset(
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring",
_MONITORING_WRITE_SCOPE,
}
)


# pylint is unable to resolve members of protobuf objects
# pylint: disable=no-member
Expand All @@ -110,6 +121,11 @@ class CloudMonitoringMetricsExporter(MetricExporter):
Args:
project_id: project id of your Google Cloud project.
client: Client to upload metrics to Google Cloud Monitoring.
credentials: Optional credentials for authenticating with Cloud
Monitoring.
client_options: Optional client options (for example,
``universe_domain`` or ``api_endpoint``) passed to
``MetricServiceClient``.
"""

# Based on the cloud_monitoring exporter found here: https://github.com/GoogleCloudPlatform/opentelemetry-operations-python/blob/main/opentelemetry-exporter-gcp-monitoring/src/opentelemetry/exporter/cloud_monitoring/__init__.py
Expand All @@ -119,28 +135,47 @@ def __init__(
project_id: Optional[str] = None,
client: Optional["MetricServiceClient"] = None,
credentials: Optional[ga_credentials.Credentials] = None,
client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
):
"""Initialize a custom exporter to send metrics for the Spanner Service Metrics."""
# Default preferred_temporality is all CUMULATIVE so need to customize
super().__init__()

# Create a new GRPC Client for Google Cloud Monitoring if not provided
self.client = client or MetricServiceClient(
transport=MetricServiceGrpcTransport(
channel=MetricServiceGrpcTransport.create_channel(
options=_OPTIONS,
credentials=credentials,
if client is not None:
self.client = client
else:
# Re-scope credentials pinned to Spanner-only scopes for Cloud Monitoring.
monitoring_credentials = credentials
if (
isinstance(credentials, ga_credentials.Scoped)
and not credentials.requires_scopes
and not _MONITORING_SCOPES.intersection(credentials.scopes or ())
):
monitoring_credentials = credentials.with_scopes(
[_MONITORING_WRITE_SCOPE]
)

# Pass transport/channel callables so MetricServiceClient resolves
# universe_domain and validates credentials while keeping _OPTIONS.
self.client = MetricServiceClient(
credentials=monitoring_credentials,
client_options=client_options,
transport=lambda **kwargs: MetricServiceGrpcTransport(
**kwargs,
channel=lambda *a, **kw: MetricServiceGrpcTransport.create_channel(
*a, **{**kw, "options": _OPTIONS}
),
),
)
)

# Set project information
self.project_id: str
# Avoid ambient ADC project fallback when explicit credentials are provided.
if not project_id:
_, default_project_id = google.auth.default()
self.project_id = str(default_project_id)
else:
self.project_id = project_id
project_id = getattr(credentials, "project_id", None)
if not project_id and credentials is None:
_, project_id = google.auth.default()
if not project_id:
raise ValueError("project_id could not be determined.")
self.project_id = str(project_id)
self.project_name = self.client.common_project_path(self.project_id)

def _batch_write(self, series: List["TimeSeries"], timeout_millis: float) -> None:
Expand Down
Loading
Loading