Visitar URL original
fix(bigtable): fix authentication scopes for metrics exporter (#18609) · googleapis/google-cloud-python@722d34e · GitHub
Skip to content

Commit 722d34e

Browse files
fix(bigtable): fix authentication scopes for metrics exporter (#18609)
The Bigtable client holds an inner Metrics client, for exporting client-side metrics. This inner-client shares credentials with the Bigtable client. If the Bigtable client is created with scopes that don't allow interacting with the metrics service, the metrics client will fail on each write, printing logs each time This PR addresses the issue by: - attempting to add a new scope to the metrics client, before creation - disabling the exporter on the first auth failure, so it doesn't send excessive logs if it can't authenticate properly
1 parent 79579b8 commit 722d34e

3 files changed

Lines changed: 357 additions & 0 deletions

File tree

‎packages/google-cloud-bigtable/google/cloud/bigtable/data/_metrics/handlers/gcp_exporter.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@
1818
import time
1919
from collections import defaultdict
2020

21+
import google.auth.credentials
2122
from google.api.distribution_pb2 import Distribution
2223
from google.api.metric_pb2 import Metric as GMetric
2324
from google.api.metric_pb2 import MetricDescriptor
2425
from google.api.monitored_resource_pb2 import MonitoredResource
2526
from google.api_core import gapic_v1
27+
from google.api_core.exceptions import PermissionDenied, Unauthenticated
2628
from google.cloud.monitoring_v3 import (
2729
CreateTimeSeriesRequest,
2830
MetricServiceClient,
@@ -115,6 +117,53 @@ def _partition_attributes(
115117
return resource_labels, metric_labels
116118

117119

120+
# scope required to call CreateServiceTimeSeries
121+
_MONITORING_WRITE_SCOPE = "https://www.googleapis.com/auth/monitoring.write"
122+
# any one of these scopes is sufficient to write metrics to Cloud Monitoring
123+
_MONITORING_SCOPES = frozenset(
124+
{
125+
"https://www.googleapis.com/auth/cloud-platform",
126+
"https://www.googleapis.com/auth/monitoring",
127+
_MONITORING_WRITE_SCOPE,
128+
}
129+
)
130+
131+
132+
def _get_monitoring_credentials(
133+
credentials: google.auth.credentials.Credentials | None,
134+
) -> google.auth.credentials.Credentials | None:
135+
"""
136+
Return credentials that are able to authenticate against Cloud Monitoring.
137+
138+
The metrics exporter shares the credentials of the Bigtable client it belongs to.
139+
If those credentials are already pinned to a fixed set of scopes that doesn't
140+
cover Cloud Monitoring (for example, credentials created by the legacy
141+
``google.cloud.bigtable.Client``, which only requests Bigtable scopes),
142+
``MetricServiceClient`` can't add its own default scopes to them, and every
143+
export would be rejected as UNAUTHENTICATED. In that case, a copy of the
144+
credentials scoped to ``monitoring.write`` is returned instead. The original
145+
credentials object (and the scopes used for Bigtable traffic) are left untouched.
146+
147+
Credentials that don't support scoping (e.g. end-user credentials), or that still
148+
accept default scopes, are returned unchanged.
149+
150+
Args:
151+
credentials: the credentials used by the Bigtable client, or None to use
152+
application default credentials
153+
Returns:
154+
credentials suitable for the Cloud Monitoring client
155+
"""
156+
if credentials is None:
157+
return None
158+
if (
159+
isinstance(credentials, google.auth.credentials.Scoped)
160+
and not credentials.requires_scopes
161+
and not _MONITORING_SCOPES.intersection(credentials.scopes or ())
162+
):
163+
return credentials.with_scopes([_MONITORING_WRITE_SCOPE])
164+
return credentials
165+
166+
118167
class GoogleCloudMetricsHandler(OpenTelemetryMetricsHandler):
119168
"""
120169
Maintains an internal set of OpenTelemetry metrics for the Bigtable client library,
@@ -167,8 +216,18 @@ class BigtableMetricsExporter(MetricExporter):
167216

168217
def __init__(self, *client_args, **client_kwargs):
169218
super().__init__()
219+
if client_kwargs.get("credentials") is not None:
220+
# the exporter shares the Bigtable client's credentials. Make sure
221+
# they are able to authenticate against Cloud Monitoring
222+
client_kwargs["credentials"] = _get_monitoring_credentials(
223+
client_kwargs["credentials"]
224+
)
170225
self.client = MetricServiceClient(*client_args, **client_kwargs)
171226
self.prefix = "bigtable.googleapis.com/internal/client"
227+
# set after a non-retryable authentication/authorization failure.
228+
# Once disabled, exports are skipped instead of failing (and logging)
229+
# on every export interval
230+
self._disabled = False
172231

173232
def export(
174233
self, metrics_data: MetricsData, timeout_millis: float = 10_000, **kwargs
@@ -177,6 +236,8 @@ def export(
177236
Write a set of metrics to Cloud Monitoring.
178237
This method is called by the OpenTelemetry SDK
179238
"""
239+
if self._disabled:
240+
return MetricExportResult.FAILURE
180241
deadline = time.monotonic() + (timeout_millis / 1000)
181242
metric_kind = MetricDescriptor.MetricKind.CUMULATIVE
182243
series_by_project: dict[str, list[TimeSeries]] = defaultdict(list)
@@ -231,6 +292,23 @@ def export(
231292
)
232293
self._batch_write(project_id, series_list, deadline)
233294
return MetricExportResult.SUCCESS
295+
except (Unauthenticated, PermissionDenied) as e:
296+
# authentication/authorization failures won't resolve on their own.
297+
# Stop exporting instead of failing again on every export interval
298+
self._disabled = True
299+
_LOGGER.warning(
300+
"Bigtable client-side metrics could not be exported to Cloud "
301+
"Monitoring for project(s) %s: %s. Client-side metrics are now "
302+
"disabled for this client; Bigtable data operations are not "
303+
"affected. To publish client-side metrics, make sure the Cloud "
304+
"Monitoring API is enabled and the client's credentials are "
305+
"allowed to write metrics to the project "
306+
"(e.g. roles/monitoring.metricWriter).",
307+
", ".join(series_by_project),
308+
e,
309+
)
310+
_LOGGER.debug("Client-side metrics export failure details:", exc_info=True)
311+
return MetricExportResult.FAILURE
234312
except Exception as e:
235313
_LOGGER.warning(
236314
"Failed to export metrics to Cloud Monitoring: %s", e, exc_info=True

‎packages/google-cloud-bigtable/tests/unit/data/_metrics/test_gcp_exporter_handler.py‎

Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,12 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
import logging
15+
1416
import mock
1517
import pytest
1618
from google.api.distribution_pb2 import Distribution
19+
from google.api_core import exceptions as api_exceptions
1720
from google.cloud.monitoring_v3 import (
1821
Point,
1922
TimeSeries,
@@ -39,6 +42,8 @@
3942
_OpenTelemetryInstruments,
4043
)
4144

45+
EXPORTER_LOGGER = "google.cloud.bigtable.data._metrics.handlers.gcp_exporter"
46+
4247

4348
class TestGoogleCloudMetricsHandler:
4449
def _make_one(self, *args, **kwargs):
@@ -125,6 +130,105 @@ def test_close(self):
125130
assert mock_instance.meter_provider.shutdown.call_count == 1
126131

127132

133+
BIGTABLE_DATA_SCOPE = "https://www.googleapis.com/auth/bigtable.data"
134+
BIGTABLE_ADMIN_SCOPE = "https://www.googleapis.com/auth/bigtable.admin"
135+
MONITORING_WRITE_SCOPE = "https://www.googleapis.com/auth/monitoring.write"
136+
137+
138+
def _make_service_account_credentials(**kwargs):
139+
import google.auth.crypt
140+
from google.oauth2 import service_account
141+
142+
return service_account.Credentials(
143+
mock.Mock(spec=google.auth.crypt.Signer),
144+
"sa@example.iam.gserviceaccount.com",
145+
"https://oauth2.googleapis.com/token",
146+
**kwargs,
147+
)
148+
149+
150+
class Test_get_monitoring_credentials:
151+
@staticmethod
152+
def _call_fut(credentials):
153+
from google.cloud.bigtable.data._metrics.handlers.gcp_exporter import (
154+
_get_monitoring_credentials,
155+
)
156+
157+
return _get_monitoring_credentials(credentials)
158+
159+
def test_none(self):
160+
assert self._call_fut(None) is None
161+
162+
def test_non_scopable_credentials(self):
163+
"""credentials that can't be re-scoped (e.g. user credentials) pass through"""
164+
from google.auth.credentials import AnonymousCredentials
165+
from google.oauth2 import credentials as user_credentials
166+
167+
anonymous = AnonymousCredentials()
168+
assert self._call_fut(anonymous) is anonymous
169+
user = user_credentials.Credentials(token="token")
170+
assert self._call_fut(user) is user
171+
172+
def test_unscoped_credentials(self):
173+
"""
174+
credentials that still accept default scopes are left alone;
175+
MetricServiceClient will apply its own defaults to them
176+
"""
177+
credentials = _make_service_account_credentials()
178+
assert credentials.requires_scopes
179+
assert self._call_fut(credentials) is credentials
180+
181+
@pytest.mark.parametrize(
182+
"pinned_scopes",
183+
[
184+
(BIGTABLE_DATA_SCOPE,),
185+
(BIGTABLE_DATA_SCOPE, BIGTABLE_ADMIN_SCOPE),
186+
["https://www.googleapis.com/auth/bigtable.data.readonly"],
187+
],
188+
)
189+
def test_credentials_pinned_to_bigtable_scopes(self, pinned_scopes):
190+
"""
191+
credentials already pinned to non-monitoring scopes (e.g. by the legacy
192+
client) should be replaced by a copy that can write to Cloud Monitoring
193+
"""
194+
credentials = _make_service_account_credentials(
195+
scopes=pinned_scopes, quota_project_id="quota-project"
196+
)
197+
result = self._call_fut(credentials)
198+
assert result is not credentials
199+
assert list(result.scopes) == [MONITORING_WRITE_SCOPE]
200+
# identity and other settings are preserved
201+
assert result.service_account_email == credentials.service_account_email
202+
assert result.quota_project_id == "quota-project"
203+
# original credentials are left untouched for bigtable traffic
204+
assert tuple(credentials.scopes) == tuple(pinned_scopes)
205+
206+
def test_compute_engine_credentials_pinned_to_bigtable_scopes(self):
207+
from google.auth import compute_engine
208+
209+
credentials = compute_engine.Credentials(scopes=[BIGTABLE_DATA_SCOPE])
210+
assert not credentials.requires_scopes
211+
result = self._call_fut(credentials)
212+
assert result is not credentials
213+
assert list(result.scopes) == [MONITORING_WRITE_SCOPE]
214+
assert list(credentials.scopes) == [BIGTABLE_DATA_SCOPE]
215+
216+
@pytest.mark.parametrize(
217+
"scopes",
218+
[
219+
["https://www.googleapis.com/auth/cloud-platform"],
220+
["https://www.googleapis.com/auth/monitoring"],
221+
[MONITORING_WRITE_SCOPE],
222+
[BIGTABLE_DATA_SCOPE, MONITORING_WRITE_SCOPE],
223+
(BIGTABLE_DATA_SCOPE, "https://www.googleapis.com/auth/cloud-platform"),
224+
],
225+
)
226+
def test_credentials_already_cover_monitoring(self, scopes):
227+
credentials = _make_service_account_credentials(scopes=scopes)
228+
assert not credentials.requires_scopes
229+
assert self._call_fut(credentials) is credentials
230+
231+
128232
class TestBigtableMetricsExporter:
129233
def _make_one(self, *args, **kwargs):
130234
with mock.patch("google.auth.default", return_value=(mock.Mock(), "project")):
@@ -164,6 +268,7 @@ def test_ctor_defaults(self):
164268
instance = self._make_one()
165269
assert instance.prefix == "bigtable.googleapis.com/internal/client"
166270
assert isinstance(instance.client, MetricServiceClient)
271+
assert instance._disabled is False
167272

168273
def test_ctor_mocks(self):
169274
with mock.patch(
@@ -176,6 +281,46 @@ def test_ctor_mocks(self):
176281
assert instance.prefix == "bigtable.googleapis.com/internal/client"
177282
mock_client.assert_called_once_with(*args, **kwargs)
178283

284+
def test_ctor_rescopes_pinned_credentials(self):
285+
"""
286+
credentials pinned to bigtable-only scopes (e.g. from the legacy client)
287+
should be re-scoped for Cloud Monitoring before building the client
288+
"""
289+
credentials = _make_service_account_credentials(
290+
scopes=[BIGTABLE_DATA_SCOPE, BIGTABLE_ADMIN_SCOPE]
291+
)
292+
with mock.patch(
293+
"google.cloud.bigtable.data._metrics.handlers.gcp_exporter.MetricServiceClient"
294+
) as mock_client:
295+
instance = self._make_one(credentials=credentials, client_options=None)
296+
assert instance.client is mock_client.return_value
297+
mock_client.assert_called_once()
298+
_, kwargs = mock_client.call_args
299+
assert kwargs["client_options"] is None
300+
monitoring_credentials = kwargs["credentials"]
301+
assert monitoring_credentials is not credentials
302+
assert list(monitoring_credentials.scopes) == [MONITORING_WRITE_SCOPE]
303+
# original credentials are untouched
304+
assert list(credentials.scopes) == [BIGTABLE_DATA_SCOPE, BIGTABLE_ADMIN_SCOPE]
305+
306+
@pytest.mark.parametrize(
307+
"credentials",
308+
[
309+
None,
310+
_make_service_account_credentials(),
311+
_make_service_account_credentials(
312+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
313+
),
314+
],
315+
)
316+
def test_ctor_passes_through_usable_credentials(self, credentials):
317+
"""credentials that can already reach Cloud Monitoring are passed as-is"""
318+
with mock.patch(
319+
"google.cloud.bigtable.data._metrics.handlers.gcp_exporter.MetricServiceClient"
320+
) as mock_client:
321+
self._make_one(credentials=credentials)
322+
mock_client.assert_called_once_with(credentials=credentials)
323+
179324
@pytest.mark.parametrize(
180325
"value,expected_field",
181326
[
@@ -443,3 +588,91 @@ def test_exception_in_export(self):
443588
metrics_data = MetricsData(resource_metrics=[resource_metric])
444589
result = instance.export(metrics_data)
445590
assert result == MetricExportResult.FAILURE
591+
# generic errors may be transient; keep exporting on later intervals
592+
assert instance._disabled is False
593+
594+
@staticmethod
595+
def _make_metrics_data(project_id="project"):
596+
"""build a MetricsData object with one valid data point"""
597+
attributes = {
598+
"resource_project": project_id,
599+
"resource_instance": "instance1",
600+
"resource_cluster": "cluster1",
601+
"resource_table": "table1",
602+
"resource_zone": "zone1",
603+
}
604+
data_point = NumberDataPoint(
605+
attributes=attributes,
606+
start_time_unix_nano=100,
607+
time_unix_nano=200,
608+
value=123,
609+
)
610+
metric = Metric(
611+
name="operation_latencies",
612+
description="",
613+
unit="ms",
614+
data=Sum(
615+
data_points=[data_point],
616+
aggregation_temporality=AggregationTemporality.CUMULATIVE,
617+
is_monotonic=False,
618+
),
619+
)
620+
scope_metric = ScopeMetrics(
621+
scope=mock.Mock(), metrics=[metric], schema_url=None
622+
)
623+
resource_metric = ResourceMetrics(
624+
resource=mock.Mock(), scope_metrics=[scope_metric], schema_url=None
625+
)
626+
return MetricsData(resource_metrics=[resource_metric])
627+
628+
@pytest.mark.parametrize(
629+
"exc_type",
630+
[
631+
api_exceptions.Unauthenticated,
632+
api_exceptions.PermissionDenied,
633+
],
634+
)
635+
def test_export_auth_error_disables_exporter(self, exc_type, caplog):
636+
"""
637+
auth errors are not transient. The exporter should log a single, explanatory
638+
warning and stop exporting, without affecting the rest of the client
639+
"""
640+
project_id = "my-project"
641+
exc = exc_type("Request had invalid authentication credentials.")
642+
instance = self._make_one()
643+
instance.client = mock.Mock()
644+
instance.client.create_service_time_series.side_effect = exc
645+
metrics_data = self._make_metrics_data(project_id)
646+
with caplog.at_level(logging.WARNING, logger=EXPORTER_LOGGER):
647+
result = instance.export(metrics_data)
648+
assert result == MetricExportResult.FAILURE
649+
assert instance._disabled is True
650+
assert instance.client.create_service_time_series.call_count == 1
651+
# one warning that explains the consequences
652+
warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
653+
assert len(warnings) == 1
654+
message = warnings[0].getMessage()
655+
assert "Client-side metrics are now disabled" in message
656+
assert "Bigtable data operations are not affected" in message
657+
assert project_id in message
658+
assert "Request had invalid authentication credentials" in message
659+
# auth failures shouldn't dump a full traceback at warning level
660+
assert warnings[0].exc_info is None
661+
# later exports are skipped without touching the client or logging again
662+
caplog.clear()
663+
with caplog.at_level(logging.WARNING, logger=EXPORTER_LOGGER):
664+
result = instance.export(self._make_metrics_data(project_id))
665+
assert result == MetricExportResult.FAILURE
666+
assert instance.client.create_service_time_series.call_count == 1
667+
assert not caplog.records
668+
669+
def test_export_when_disabled(self):
670+
"""a disabled exporter should not attempt to convert or write metrics"""
671+
instance = self._make_one()
672+
instance._disabled = True
673+
instance._batch_write = mock.Mock()
674+
with mock.patch.object(instance, "_to_point") as to_point_mock:
675+
result = instance.export(self._make_metrics_data())
676+
assert result == MetricExportResult.FAILURE
677+
to_point_mock.assert_not_called()
678+
instance._batch_write.assert_not_called()

0 commit comments

Comments
 (0)