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
25 changes: 25 additions & 0 deletions packages/google-cloud-bigtable/tests/system/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...]] = (
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# 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):
inst = mock.MagicMock()
inst.name = f"projects/p/instances/{instance_id}"
inst.display_name = "Test"
inst.create_time = datetime.now(timezone.utc) - timedelta(days=age_days)
return inst


def _run_cleanup(monkeypatch, instances, table_client, inst_client=None):
monkeypatch.delenv("BIGTABLE_EMULATOR_HOST", raising=False)
inst_client = inst_client or mock.MagicMock()
inst_client.common_project_path.return_value = "projects/p"
inst_client.list_instances.return_value = mock.MagicMock(
instances=instances, next_page_token=""
)
with (
mock.patch(
"tests.system.utils.admin_v2.BigtableInstanceAdminClient",
return_value=inst_client,
),
mock.patch(
"tests.system.utils.admin_v2.BigtableTableAdminClient",
return_value=table_client,
),
):
clear_stale_instances("p", older_than_days=1)
return inst_client


def test_deletes_backups_before_stale_instance(monkeypatch):
stale = _make_instance("g-c-p-stale-1", 2)
backups = []
for idx in (1, 2, 3):
b = mock.MagicMock()
b.name = f"{stale.name}/clusters/c1/backups/b{idx}"
backups.append(b)

order = []
inst_client = mock.MagicMock()
inst_client.delete_instance.side_effect = lambda name: order.append("instance")

def _del_backup(name):
order.append(name.rsplit("/", 1)[-1])
if name.endswith("b1"):
raise NotFound("gone")
if name.endswith("b2"):
raise RuntimeError("transient")

table_client = mock.MagicMock()
table_client.list_backups.return_value = backups
table_client.delete_backup.side_effect = _del_backup

_run_cleanup(monkeypatch, [stale], table_client, inst_client)

table_client.list_backups.assert_called_once_with(parent=f"{stale.name}/clusters/-")
assert order == ["b1", "b2", "b3", "instance"]


def test_continues_deleting_instance_when_list_backups_fails(monkeypatch):
stale = _make_instance("admin-overlay-instance-1", 3)
table_client = mock.MagicMock()
table_client.list_backups.side_effect = RuntimeError("list failed")

inst_client = _run_cleanup(monkeypatch, [stale], table_client)
inst_client.delete_instance.assert_called_once_with(name=stale.name)
Loading