Skip to content
Closed
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
88 changes: 74 additions & 14 deletions packages/google-cloud-spanner/tests/system/_async/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,77 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import time

import pytest
from google.api_core import exceptions

from google.cloud import spanner_v1
from google.cloud.spanner_admin_database_v1 import DatabaseDialect
from google.cloud.spanner_v1._async import instance as async_instance_mod

from .. import _helpers


async def _scrub_instance_ignore_not_found(to_scrub):
"""Delete backups, disable DB drop protection, and delete an async instance."""
try:
async for database_pb in await to_scrub.list_databases():
db = await to_scrub.database(database_pb.name.split("/")[-1])

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.

high

The to_scrub.database() method is a synchronous factory method that returns an AsyncDatabase instance without performing any network I/O. Awaiting it will raise a TypeError at runtime, which will propagate and cause the teardown/cleanup helper to fail.

Suggested change
db = await to_scrub.database(database_pb.name.split("/")[-1])
db = to_scrub.database(database_pb.name.split("/")[-1])

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.

The async Instance.database() method is an async def coroutine (it awaits db._pool.bind(db) in spanner_v1/_async/instance.py), so awaiting it here is required, same as shared_instance.database() below in this file.

try:
await db.reload()
if db.enable_drop_protection:
db.enable_drop_protection = False
operation = await db.update(["enable_drop_protection"])
await operation.result(
_helpers.DATABASE_OPERATION_TIMEOUT_IN_SECONDS
)
except exceptions.NotFound:
pass
except exceptions.NotFound:
return

try:
async for backup_pb in await to_scrub.list_backups():
for db_name in backup_pb.referencing_databases:
db = await to_scrub.database(db_name.split("/")[-1])

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.

high

The to_scrub.database() method is a synchronous factory method that returns an AsyncDatabase instance without performing any network I/O. Awaiting it will raise a TypeError at runtime, which will propagate and cause the teardown/cleanup helper to fail.

Suggested change
db = await to_scrub.database(db_name.split("/")[-1])
db = to_scrub.database(db_name.split("/")[-1])

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.

Same as above: the async Instance.database() method is an async def coroutine in spanner_v1/_async/instance.py (it awaits db._pool.bind(db)), so dropping await here would leave db as an unawaited coroutine.

try:
await db.drop()
except exceptions.NotFound:
pass
try:
await to_scrub._client.database_admin_api.delete_backup(
name=backup_pb.name
)
except exceptions.NotFound:
pass
except (exceptions.MethodNotImplemented, exceptions.NotFound):
pass

try:
await to_scrub.delete()
except exceptions.NotFound:
pass


async def _cleanup_old_instances(spanner_client):
"""Sweep stale labeled system-test instances older than 3 hours."""
cutoff = int(time.time()) - 3 * 60 * 60
instance_filter = "labels.python-spanner-systests:true"

async for instance_pb in await spanner_client.list_instances(
filter_=instance_filter
):
instance = async_instance_mod.Instance.from_pb(instance_pb, spanner_client)
if "created" in instance.labels:
try:
create_time = int(instance.labels["created"])
except ValueError:
continue
if create_time <= cutoff:
await _scrub_instance_ignore_not_found(instance)


@pytest.fixture(scope="session")
def spanner_client():
if _helpers.USE_EMULATOR:
Expand Down Expand Up @@ -140,14 +203,12 @@ async def shared_instance(
instance_config,
):
spanner_client._instance_admin_api = None
await _cleanup_old_instances(spanner_client)

if _helpers.CREATE_INSTANCE:
import time

from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

create_time = str(int(time.time()))
labels = {"python-spanner-systests": "true", "created": create_time}
labels = _helpers.systest_instance_labels()

request = spanner_instance_admin.CreateInstanceRequest(
parent=spanner_client.project_name,
Expand All @@ -160,22 +221,21 @@ async def shared_instance(
edition=spanner_instance_admin.Instance.Edition.ENTERPRISE,
),
)
created_op = await spanner_client.instance_admin_api.create_instance(
request=request
)
await created_op.result(instance_operation_timeout)

instance = spanner_client.instance(
shared_instance_id, instance_config.name, labels=labels
)
created_op = await spanner_client.instance_admin_api.create_instance(
request=request
)
try:
await created_op.result(instance_operation_timeout)
yield instance
finally:
await _scrub_instance_ignore_not_found(instance)
else:
instance = spanner_client.instance(shared_instance_id, instance_config.name)
await instance.reload()

yield instance

if _helpers.CREATE_INSTANCE:
await instance.delete()
yield instance


@pytest.fixture(scope="session")
Expand Down
44 changes: 29 additions & 15 deletions packages/google-cloud-spanner/tests/system/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,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 +127,28 @@ 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 exceptions.NotFound:
return

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 +164,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 Expand Up @@ -195,6 +201,14 @@ def cleanup_stale_databases(
pass


def systest_instance_labels():
"""Return standard labels so stale system-test instances are swept."""
return {
"python-spanner-systests": "true",
"created": str(int(time.time())),
}


def unique_id(prefix, separator="-"):
# Database name size: Spanner database names are limited to 30 characters.
# See: https://docs.cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#createdatabaserequest
Expand Down
28 changes: 12 additions & 16 deletions packages/google-cloud-spanner/tests/system/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import datetime
import os
import time

import pytest

Expand Down Expand Up @@ -209,8 +208,7 @@ def shared_instance(
if _helpers.CREATE_INSTANCE:
from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

create_time = str(int(time.time()))
labels = {"python-spanner-systests": "true", "created": create_time}
labels = _helpers.systest_instance_labels()

request = spanner_instance_admin.CreateInstanceRequest(
parent=spanner_client.project_name,
Expand All @@ -223,25 +221,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
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,11 @@ def test_create_instance(
instance_operation_timeout,
):
alt_instance_id = _helpers.unique_id("new")
instance = spanner_client.instance(alt_instance_id, instance_config.name)
instance = spanner_client.instance(
alt_instance_id,
instance_config.name,
labels=_helpers.systest_instance_labels(),
)
operation = instance.create()
# Make sure this instance gets deleted after the test case.
instances_to_delete.append(instance)
Expand Down Expand Up @@ -106,6 +110,7 @@ def test_create_instance_with_processing_units(
instance_id=alt_instance_id,
configuration_name=instance_config.name,
processing_units=processing_units,
labels=_helpers.systest_instance_labels(),
)
operation = instance.create()
# Make sure this instance gets deleted after the test case.
Expand Down
Loading