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+
1416import mock
1517import pytest
1618from google .api .distribution_pb2 import Distribution
19+ from google .api_core import exceptions as api_exceptions
1720from google .cloud .monitoring_v3 import (
1821 Point ,
1922 TimeSeries ,
3942 _OpenTelemetryInstruments ,
4043)
4144
45+ EXPORTER_LOGGER = "google.cloud.bigtable.data._metrics.handlers.gcp_exporter"
46+
4247
4348class 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+
128232class 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