diff --git a/packages/google-cloud-bigtable/tests/system/data/__init__.py b/packages/google-cloud-bigtable/tests/system/data/__init__.py index b28ad6823b29..089d8c11e8ea 100644 --- a/packages/google-cloud-bigtable/tests/system/data/__init__.py +++ b/packages/google-cloud-bigtable/tests/system/data/__init__.py @@ -47,7 +47,7 @@ def cleanup_old_instances(self, project_id): if os.getenv(BIGTABLE_EMULATOR): return - clear_stale_instances(project_id, "python-bigtable-tests", older_than_days=1) + clear_stale_instances(project_id, older_than_days=1) @pytest.fixture(scope="session") def init_table_id(self, start_timestamp): diff --git a/packages/google-cloud-bigtable/tests/system/utils.py b/packages/google-cloud-bigtable/tests/system/utils.py index fe3f3a2b865f..b4314b4ea898 100644 --- a/packages/google-cloud-bigtable/tests/system/utils.py +++ b/packages/google-cloud-bigtable/tests/system/utils.py @@ -22,6 +22,25 @@ from google.cloud import bigtable_admin_v2 as admin_v2 +def _delete_instance_backups( + table_client: admin_v2.BigtableTableAdminClient, + instance_name: str, +): + """Deletes all backups under an instance before instance deletion.""" + try: + backups = table_client.list_backups(parent=f"{instance_name}/clusters/-") + for backup in backups: + try: + print(f"Deleting stale backup: {backup.name}") + table_client.delete_backup(name=backup.name) + except NotFound: + pass + except Exception as e: + print(f"Failed to delete stale backup {backup.name}: {e}") + except Exception as e: + print(f"Failed to list backups for stale instance {instance_name}: {e}") + + def clear_stale_instances( project_id: str, prefix: Union[str, Tuple[str, ...]] = ( @@ -43,6 +62,7 @@ def clear_stale_instances( client = admin_v2.BigtableInstanceAdminClient( client_options={"quota_project_id": project_id} ) + table_client = None parent = client.common_project_path(project_id) next_page_token = "" deleted_count = 0 @@ -72,6 +92,11 @@ def clear_stale_instances( now = datetime.now(timezone.utc) if now - create_time > timedelta(days=older_than_days): try: + if table_client is None: + table_client = admin_v2.BigtableTableAdminClient( + client_options={"quota_project_id": project_id} + ) + _delete_instance_backups(table_client, instance.name) print(f"Deleting stale instance: {instance.name}") client.delete_instance(name=instance.name) deleted_count += 1 diff --git a/packages/google-cloud-bigtable/tests/system/v2_client/conftest.py b/packages/google-cloud-bigtable/tests/system/v2_client/conftest.py index 59e016f52af8..c0daa69abba0 100644 --- a/packages/google-cloud-bigtable/tests/system/v2_client/conftest.py +++ b/packages/google-cloud-bigtable/tests/system/v2_client/conftest.py @@ -15,6 +15,7 @@ import os import pytest +from google.api_core import exceptions from google.cloud.environment_vars import BIGTABLE_EMULATOR from test_utils.system import unique_resource_id @@ -76,6 +77,16 @@ def admin_client(): return Client(admin=True) +@pytest.fixture(scope="session", autouse=True) +def cleanup_old_instances(admin_client, in_emulator): + """Automatically deletes stale test instances older than 1 day.""" + if in_emulator: + return + from tests.system.utils import clear_stale_instances + + clear_stale_instances(admin_client.project) + + @pytest.fixture(scope="session") def service_account(admin_client): from google.oauth2.service_account import Credentials @@ -131,14 +142,29 @@ def admin_cluster_with_autoscaling( def admin_instance_populated(admin_instance, admin_cluster, in_emulator): # Emulator does not support instance admin operations (create / delete). # See: https://cloud.google.com/bigtable/docs/emulator - if not in_emulator: - operation = admin_instance.create(clusters=[admin_cluster]) - operation.result(timeout=240) - - yield admin_instance + if in_emulator: + yield admin_instance + return - if not in_emulator: - _helpers.retry_429(admin_instance.delete)() + operation = admin_instance.create(clusters=[admin_cluster]) + created = False + try: + operation.result(timeout=240) + created = True + yield admin_instance + finally: + try: + _helpers.retry_429(admin_instance.delete)() + except exceptions.NotFound: + pass + except Exception as exc: + if not created: + print( + f"Failed to delete timed-out instance " + f"{admin_instance.instance_id}: {exc}" + ) + else: + raise @pytest.fixture(scope="session") @@ -169,19 +195,33 @@ def data_instance_populated( instance = admin_client.instance(data_instance_id, labels=instance_labels) # Emulator does not support instance admin operations (create / delete). # See: https://cloud.google.com/bigtable/docs/emulator - if not in_emulator: - cluster = instance.cluster( - data_cluster_id, - location_id=location_id, - serve_nodes=serve_nodes, - ) - operation = instance.create(clusters=[cluster]) - operation.result(timeout=240) - - yield instance + if in_emulator: + yield instance + return - if not in_emulator: - _helpers.retry_429(instance.delete)() + cluster = instance.cluster( + data_cluster_id, + location_id=location_id, + serve_nodes=serve_nodes, + ) + operation = instance.create(clusters=[cluster]) + created = False + try: + operation.result(timeout=240) + created = True + yield instance + finally: + try: + _helpers.retry_429(instance.delete)() + except exceptions.NotFound: + pass + except Exception as exc: + if not created: + print( + f"Failed to delete timed-out instance {instance.instance_id}: {exc}" + ) + else: + raise @pytest.fixture(scope="function") diff --git a/packages/google-cloud-bigtable/tests/unit/test_system_cleanup.py b/packages/google-cloud-bigtable/tests/unit/test_system_cleanup.py new file mode 100644 index 000000000000..c2dfdf6691c8 --- /dev/null +++ b/packages/google-cloud-bigtable/tests/unit/test_system_cleanup.py @@ -0,0 +1,144 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime, timedelta, timezone +from unittest import mock + +from google.api_core.exceptions import NotFound + +from tests.system.utils import clear_stale_instances + + +def _make_instance(instance_id, age_days, display_name="Test"): + inst = mock.MagicMock() + inst.name = f"projects/test-proj/instances/{instance_id}" + inst.display_name = display_name + inst.create_time = datetime.now(timezone.utc) - timedelta(days=age_days) + return inst + + +def test_clear_stale_instances_deletes_backups_before_instance(monkeypatch): + monkeypatch.delenv("BIGTABLE_EMULATOR_HOST", raising=False) + stale = _make_instance("g-c-p-stale-1", age_days=2) + fresh = _make_instance("g-c-p-fresh-1", age_days=0) + unrelated = _make_instance("keep-me", age_days=10, display_name="Production") + + backup = mock.MagicMock() + backup.name = f"{stale.name}/clusters/c1/backups/b1" + + call_order = [] + + instance_client = mock.MagicMock() + instance_client.common_project_path.return_value = "projects/test-proj" + instance_client.list_instances.return_value = mock.MagicMock( + instances=[stale, fresh, unrelated], + next_page_token="", + ) + instance_client.delete_instance.side_effect = lambda name: call_order.append( + ("delete_instance", name) + ) + + table_client = mock.MagicMock() + table_client.list_backups.return_value = [backup] + table_client.delete_backup.side_effect = lambda name: call_order.append( + ("delete_backup", name) + ) + + with ( + mock.patch( + "tests.system.utils.admin_v2.BigtableInstanceAdminClient", + return_value=instance_client, + ), + mock.patch( + "tests.system.utils.admin_v2.BigtableTableAdminClient", + return_value=table_client, + ), + ): + clear_stale_instances("test-proj", older_than_days=1) + + table_client.list_backups.assert_called_once_with(parent=f"{stale.name}/clusters/-") + assert call_order == [ + ("delete_backup", backup.name), + ("delete_instance", stale.name), + ] + + +def test_clear_stale_instances_continues_when_backup_cleanup_fails(monkeypatch): + monkeypatch.delenv("BIGTABLE_EMULATOR_HOST", raising=False) + stale = _make_instance("admin-overlay-instance-1", age_days=3) + + instance_client = mock.MagicMock() + instance_client.common_project_path.return_value = "projects/test-proj" + instance_client.list_instances.return_value = mock.MagicMock( + instances=[stale], + next_page_token="", + ) + + table_client = mock.MagicMock() + table_client.list_backups.side_effect = RuntimeError("transient list error") + + with ( + mock.patch( + "tests.system.utils.admin_v2.BigtableInstanceAdminClient", + return_value=instance_client, + ), + mock.patch( + "tests.system.utils.admin_v2.BigtableTableAdminClient", + return_value=table_client, + ), + ): + clear_stale_instances("test-proj", older_than_days=1) + + instance_client.delete_instance.assert_called_once_with(name=stale.name) + + +def test_clear_stale_instances_ignores_backup_delete_errors(monkeypatch): + monkeypatch.delenv("BIGTABLE_EMULATOR_HOST", raising=False) + stale = _make_instance("python-bigtable-tests-1", age_days=2) + b1 = mock.MagicMock(name="b1") + b1.name = f"{stale.name}/clusters/c1/backups/b1" + b2 = mock.MagicMock(name="b2") + b2.name = f"{stale.name}/clusters/c1/backups/b2" + b3 = mock.MagicMock(name="b3") + b3.name = f"{stale.name}/clusters/c1/backups/b3" + + instance_client = mock.MagicMock() + instance_client.common_project_path.return_value = "projects/test-proj" + instance_client.list_instances.return_value = mock.MagicMock( + instances=[stale], + next_page_token="", + ) + + table_client = mock.MagicMock() + table_client.list_backups.return_value = [b1, b2, b3] + table_client.delete_backup.side_effect = [ + NotFound("gone"), + RuntimeError("transient delete error"), + None, + ] + + with ( + mock.patch( + "tests.system.utils.admin_v2.BigtableInstanceAdminClient", + return_value=instance_client, + ), + mock.patch( + "tests.system.utils.admin_v2.BigtableTableAdminClient", + return_value=table_client, + ), + ): + clear_stale_instances("test-proj", older_than_days=1) + + assert table_client.delete_backup.call_count == 3 + instance_client.delete_instance.assert_called_once_with(name=stale.name)