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
43 changes: 28 additions & 15 deletions packages/google-cloud-spanner/tests/system/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import os
import time
import uuid
import warnings

from google.api_core import datetime_helpers, exceptions
from test_utils import retry
Expand Down Expand Up @@ -111,7 +112,7 @@ def scrub_referencing_databases(to_scrub, db_list):
for db_name in db_list:
db = to_scrub.database(db_name.split("/")[-1])
try:
retry_429_503(db.delete)()
retry_429_503(db.drop)()
except exceptions.NotFound: # lost the race
pass

Expand All @@ -127,25 +128,34 @@ def scrub_instance_backups(to_scrub):
retry_429_503(bkp.delete)()
except exceptions.NotFound: # lost the race
pass
except exceptions.MethodNotImplemented:
# The CI emulator raises 501: local versions seem fine.
except (exceptions.MethodNotImplemented, exceptions.NotFound):
# The CI emulator raises 501, and NotFound means the instance is gone.
pass


def scrub_instance_ignore_not_found(to_scrub):
"""Helper for func:`cleanup_old_instances`"""
scrub_instance_backups(to_scrub)
try:
for database_pb in to_scrub.list_databases():
db = to_scrub.database(database_pb.name.split("/")[-1])
try:
db.reload()
if db.enable_drop_protection:
db.enable_drop_protection = False
operation = db.update(["enable_drop_protection"])
operation.result(DATABASE_OPERATION_TIMEOUT_IN_SECONDS)
except exceptions.NotFound:
pass
except Exception as exc:
warnings.warn(
f"Failed to disable drop protection for database {db.name}: {exc}"
)
except exceptions.NotFound:
return
Comment on lines +138 to +154

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In a teardown/cleanup helper, we want to be as robust as possible. Currently, if db.reload(), db.update(), or operation.result() raises any exception other than exceptions.NotFound (such as concurrent.futures.TimeoutError or transient gRPC errors like ServiceUnavailable), the exception will propagate and abort the entire cleanup process. This would prevent other databases, backups, and the instance itself from being deleted, leading to resource leaks.

When cleaning up multiple resources, wrap each cleanup call in a try-except block to handle exceptions individually, log any failures as warnings, and ensure that a failure in cleaning up one resource does not prevent other resources from being cleaned up.

Suggested change
try:
for database_pb in to_scrub.list_databases():
db = to_scrub.database(database_pb.name.split("/")[-1])
try:
db.reload()
if db.enable_drop_protection:
db.enable_drop_protection = False
operation = db.update(["enable_drop_protection"])
operation.result(DATABASE_OPERATION_TIMEOUT_IN_SECONDS)
except exceptions.NotFound:
pass
except exceptions.NotFound:
return
try:
for database_pb in to_scrub.list_databases():
db = to_scrub.database(database_pb.name.split('/')[-1])
try:
db.reload()
if db.enable_drop_protection:
db.enable_drop_protection = False
operation = db.update(['enable_drop_protection'])
operation.result(DATABASE_OPERATION_TIMEOUT_IN_SECONDS)
except Exception as e:
import warnings
warnings.warn(f"Failed to disable drop protection for database {db.name}: {e}")
except exceptions.NotFound:
return
except Exception as e:
import warnings
warnings.warn(f"Failed to list databases: {e}")
References
  1. When closing multiple resources during cleanup, wrap each close call in a try-except block to handle exceptions individually, log any failures as warnings, and use a finally block to clear the resource references.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated scrub_instance_ignore_not_found() to catch and warn on non-NotFound errors when listing databases or disabling drop protection so cleanup continues to the remaining databases, backups, and instance deletion. Kept the explicit NotFound handling so concurrent deletions still stay quiet, and moved the warnings import to module level. (commit 268496cd)

except Exception as exc:
warnings.warn(f"Failed to list databases for instance {to_scrub.name}: {exc}")

for database_pb in to_scrub.list_databases():
db = to_scrub.database(database_pb.name.split("/")[-1])
db.reload()
try:
if db.enable_drop_protection:
db.enable_drop_protection = False
operation = db.update(["enable_drop_protection"])
operation.result(DATABASE_OPERATION_TIMEOUT_IN_SECONDS)
except exceptions.NotFound:
pass
scrub_instance_backups(to_scrub)

try:
retry_429_503(to_scrub.delete)()
Expand All @@ -161,7 +171,10 @@ def cleanup_old_instances(spanner_client):
instance = instance_mod.Instance.from_pb(instance_pb, spanner_client)

if "created" in instance.labels:
create_time = int(instance.labels["created"])
try:
create_time = int(instance.labels["created"])
except ValueError:
continue

if create_time <= cutoff:
scrub_instance_ignore_not_found(instance)
Expand Down
24 changes: 11 additions & 13 deletions packages/google-cloud-spanner/tests/system/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,25 +223,23 @@ def shared_instance(
edition=spanner_instance_admin.Instance.Edition.ENTERPRISE,
),
)
created_op = _helpers.retry_429_503(
spanner_client.instance_admin_api.create_instance
)(request=request)
created_op.result(instance_operation_timeout) # block until completion

instance = spanner_client.instance(
shared_instance_id, instance_config.name, labels=labels
)

created_op = _helpers.retry_429_503(
spanner_client.instance_admin_api.create_instance
)(request=request)
try:
created_op.result(instance_operation_timeout) # block until completion
_helpers.cleanup_stale_databases(instance)
yield instance
finally:
_helpers.scrub_instance_ignore_not_found(instance)
else: # reuse existing instance
instance = spanner_client.instance(shared_instance_id)
instance.reload()

_helpers.cleanup_stale_databases(instance)

yield instance

if _helpers.CREATE_INSTANCE:
_helpers.retry_429_503(instance.delete)()
_helpers.cleanup_stale_databases(instance)
yield instance


@pytest.fixture(scope="session")
Expand Down
Loading