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
206 changes: 193 additions & 13 deletions pyiceberg/catalog/glue.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@


import logging
from collections.abc import Iterator, Mapping
from contextlib import contextmanager, nullcontext
from contextvars import ContextVar
from typing import (
TYPE_CHECKING,
Any,
Expand All @@ -27,6 +30,7 @@

import boto3
from botocore.config import Config
from botocore.exceptions import ClientError, ParamValidationError
from typing_extensions import override

from pyiceberg.catalog import (
Expand All @@ -43,6 +47,7 @@
)
from pyiceberg.exceptions import (
CommitFailedException,
CommitStateUnknownException,
NamespaceAlreadyExistsError,
NamespaceNotEmptyError,
NoSuchIcebergTableError,
Expand All @@ -68,6 +73,7 @@
from pyiceberg.serializers import FromInputFile, ToOutputFile
from pyiceberg.table import (
CommitTableResponse,
StagedTable,
Table,
)
from pyiceberg.table.metadata import TableMetadata
Expand Down Expand Up @@ -343,6 +349,69 @@ def add_glue_catalog_id(params: dict[str, str], **kwargs: Any) -> None:
event_system.register("provide-client-params.glue", add_glue_catalog_id)


# Whether Glue rejected each attempt of the write whose commit status is being checked
_glue_write_attempts: ContextVar[list[bool] | None] = ContextVar("_glue_write_attempts", default=None)


# Errors with which Glue refuses a request without applying it. Others, such as timeouts, don't show whether it did.
_GLUE_REJECTION_CODES = frozenset(
{
"AccessDeniedException",
"AlreadyExistsException",
"ConcurrentModificationException",
"EntityNotFoundException",
"ExpiredTokenException",
"GlueEncryptionException",
"IncompleteSignature",
"InvalidClientTokenId",
"InvalidInputException",
"InvalidSignatureException",
"MalformedHttpRequestException",
"NotAuthorized",
"OptInRequired",
"RequestEntityTooLargeException",
"RequestExpired",
"ResourceNotReadyException",
"ResourceNumberLimitExceededException",
"ThrottlingException",
"UnknownOperationException",
"UnrecognizedClientException",
"ValidationError",
"ValidationException",
}
)


def _is_rejection(response: Mapping[str, Any]) -> bool:
"""Return whether a Glue response refuses the attempt that it answers."""
return response.get("Error", {}).get("Code") in _GLUE_REJECTION_CODES


def _record_attempt(response: tuple[Any, Mapping[str, Any]] | None = None, **kwargs: Any) -> None:
"""Record whether Glue rejected an attempt of the write whose commit status is being checked."""
if (attempts := _glue_write_attempts.get()) is not None:
attempts.append(response is not None and _is_rejection(response[1]))


def _register_attempt_recorder(glue: "GlueClient") -> None:
"""Register the handler that records whether Glue rejected each attempt of a write, once per client."""
for operation in ("CreateTable", "UpdateTable"):
glue.meta.events.register(
f"needs-retry.glue.{operation}", _record_attempt, unique_id=f"pyiceberg-record-{operation}-attempt"
)


def _proves_not_applied(error: Exception, attempts: list[bool]) -> bool:
"""Return whether the error and the recorded attempts show that Glue applied no attempt of the request."""
if isinstance(error, ParamValidationError):
# Raised before the request is sent
return True
# The handler runs after every attempt, including the last, so when a rejection ends the request, every attempt that
# was sent has been recorded. Glue may have applied any attempt that it didn't reject, and an empty record, such as
# for a request sent from another thread, shows nothing.
return isinstance(error, ClientError) and _is_rejection(error.response) and bool(attempts) and all(attempts)


class GlueCatalog(MetastoreCatalog):
glue: "GlueClient"

Expand Down Expand Up @@ -395,6 +464,9 @@ def __init__(self, name: str, client: Optional["GlueClient"] = None, **propertie
if glue_catalog_id := properties.get(GLUE_ID):
_register_glue_catalog_id_with_glue_client(self.glue, glue_catalog_id)

# Registered with the catalog, so that checked writes don't change the client's handlers while other threads use it
_register_attempt_recorder(self.glue)

def _convert_glue_to_iceberg(self, glue_table: "TableTypeDef") -> Table:
if (database_name := glue_table.get("DatabaseName")) is None:
raise ValueError("Glue table is missing DatabaseName property")
Expand Down Expand Up @@ -431,22 +503,112 @@ def _convert_glue_to_iceberg(self, glue_table: "TableTypeDef") -> Table:
catalog=self,
)

def _create_glue_table(self, database_name: str, table_name: str, table_input: "TableInputTypeDef") -> None:
@contextmanager
def _check_commit_status(self, database_name: str, table_name: str, staged_table: StagedTable) -> Iterator[None]:
"""Check whether a Glue write that fails was committed anyway.

Glue may have applied a write that failed without a response, with a server error, or with a timeout. The client
also retries failed requests, so a request that Glue applied but whose response was lost is sent again, and the
retry may be rejected, for example because the table is no longer at the expected version. So the error is raised
as is if the client rejected the request before sending it, if Glue rejected every attempt, or if a create that
the table doesn't confirm failed because the table exists. Otherwise, the write succeeds if the table confirms it.

Raises:
CommitStateUnknownException: If Glue may have applied the write, but the table doesn't confirm it.
"""
# The client may have been replaced since the catalog was created
_register_attempt_recorder(self.glue)
attempts: list[bool] = []
token = _glue_write_attempts.set(attempts)
try:
self.glue.create_table(DatabaseName=database_name, TableInput=table_input)
yield
except Exception as e:
if _proves_not_applied(e, attempts):
raise
logger.warning(
f"Commit to {database_name}.{table_name} failed, checking whether it succeeded: {e}",
exc_info=logger.isEnabledFor(logging.DEBUG),
)
try:
committed = self._is_committed(database_name, table_name, staged_table)
except Exception as check_error:
raise CommitStateUnknownException(
f"Cannot determine whether the commit to {database_name}.{table_name} succeeded: {e}. "
f"Checking the table failed: {check_error}"
) from check_error
if not committed:
if (
isinstance(e, ClientError)
and e.operation_name == "CreateTable"
and e.response.get("Error", {}).get("Code") == "AlreadyExistsException"
):
# Another table holds the name, and no create path deletes files on TableAlreadyExistsError
raise
# A landed write may have left the table's history since, for example when the metadata log was trimmed
raise CommitStateUnknownException(
f"Cannot determine whether the commit to {database_name}.{table_name} succeeded: {e}"
) from e
logger.info(f"Commit to {database_name}.{table_name} succeeded")
finally:
_glue_write_attempts.reset(token)

def _is_committed(self, database_name: str, table_name: str, staged_table: StagedTable) -> bool:
"""Return whether the table confirms the staged metadata by its location, or for a new table, by its table UUID."""
current_location = self._get_glue_table(database_name, table_name).get("Parameters", {}).get(METADATA_LOCATION)
if current_location == staged_table.metadata_location:
return True
if current_location is None:
return False
io = self._load_file_io(location=current_location)
metadata = FromInputFile.table_metadata(io.new_input(current_location))
# An update always logs the location that it replaces, so only a table's first metadata has an empty log. Its
# new table UUID stays after its location leaves the metadata log.
if not staged_table.metadata.metadata_log:
return metadata.table_uuid == staged_table.metadata.table_uuid
return any(entry.metadata_file == staged_table.metadata_location for entry in metadata.metadata_log)

def _create_glue_table(
self, database_name: str, table_name: str, table_input: "TableInputTypeDef", *, staged_table: StagedTable | None
) -> None:
"""Create a Glue table.

Args:
database_name: The Glue database to create the table in.
table_name: The name of the table.
table_input: The Glue table to create.
staged_table: The staged table whose new metadata location the table input points at, to check whether a failed
request created the table anyway. None skips the check, when the table input points at existing metadata,
as for a register or rename, or at none, as for a new S3 Tables table.
"""
status_check = (
self._check_commit_status(database_name, table_name, staged_table) if staged_table is not None else nullcontext()
)
try:
with status_check:
self.glue.create_table(DatabaseName=database_name, TableInput=table_input)
except self.glue.exceptions.AlreadyExistsException as e:
raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e
except self.glue.exceptions.EntityNotFoundException as e:
raise NoSuchNamespaceError(f"Database {database_name} does not exist") from e

def _update_glue_table(self, database_name: str, table_name: str, table_input: "TableInputTypeDef", version_id: str) -> None:
def _update_glue_table(
self,
database_name: str,
table_name: str,
table_input: "TableInputTypeDef",
version_id: str,
*,
staged_table: StagedTable,
) -> None:
skip_archive = property_as_bool(self.properties, GLUE_SKIP_ARCHIVE, GLUE_SKIP_ARCHIVE_DEFAULT)
try:
self.glue.update_table(
DatabaseName=database_name,
TableInput=table_input,
SkipArchive=property_as_bool(self.properties, GLUE_SKIP_ARCHIVE, GLUE_SKIP_ARCHIVE_DEFAULT),
VersionId=version_id,
)
with self._check_commit_status(database_name, table_name, staged_table):
self.glue.update_table(
DatabaseName=database_name,
TableInput=table_input,
SkipArchive=skip_archive,
VersionId=version_id,
)
except self.glue.exceptions.EntityNotFoundException as e:
raise NoSuchTableError(f"Table does not exist: {database_name}.{table_name} (Glue table version {version_id})") from e
except self.glue.exceptions.ConcurrentModificationException as e:
Expand Down Expand Up @@ -523,6 +685,7 @@ def _create_table_s3tables(
"Name": table_name,
"Parameters": {"format": "ICEBERG"},
},
staged_table=None,
)

try:
Expand Down Expand Up @@ -559,6 +722,7 @@ def _create_table_s3tables(
table_name=table_name,
table_input=table_input,
version_id=version_id,
staged_table=staged_table,
)
except Exception:
# Clean up the table created in step 1.
Expand Down Expand Up @@ -608,6 +772,8 @@ def create_table(
AlreadyExistsError: If a table with the name already exists.
ValueError: If the identifier is invalid, no path is given to store metadata,
or a location is specified for an S3 Tables table.
CommitStateUnknownException: If creating the table in Glue failed and whether it was created cannot be
determined.

"""
database_name, table_name = self.identifier_to_database_and_table(identifier)
Expand Down Expand Up @@ -635,7 +801,12 @@ def create_table(
table_input = _construct_table_input(
table_name, staged_table.metadata_location, staged_table.metadata.properties, staged_table.metadata
)
self._create_glue_table(database_name=database_name, table_name=table_name, table_input=table_input)
self._create_glue_table(
database_name=database_name,
table_name=table_name,
table_input=table_input,
staged_table=staged_table,
)

return Table(
identifier=self.identifier_to_tuple(identifier),
Expand Down Expand Up @@ -669,7 +840,7 @@ def register_table(self, identifier: str | Identifier, metadata_location: str, o
file = io.new_input(metadata_location)
metadata = FromInputFile.table_metadata(file)
table_input = _construct_table_input(table_name, metadata_location, properties, metadata)
self._create_glue_table(database_name=database_name, table_name=table_name, table_input=table_input)
self._create_glue_table(database_name=database_name, table_name=table_name, table_input=table_input, staged_table=None)
return self.load_table(identifier=identifier)

@override
Expand All @@ -689,6 +860,7 @@ def commit_table(
Raises:
NoSuchTableError: If a table with the given identifier does not exist.
CommitFailedException: Requirement not met, or a conflict with a concurrent commit.
CommitStateUnknownException: If the Glue write failed and whether it was applied cannot be determined.
"""
table_identifier = table.name()
database_name, table_name = self.identifier_to_database_and_table(table_identifier, NoSuchTableError)
Expand Down Expand Up @@ -742,6 +914,7 @@ def commit_table(
table_name=table_name,
table_input=update_table_input,
version_id=glue_table_version_id,
staged_table=updated_staged_table,
)
else:
# table does not exist, create the table
Expand All @@ -751,7 +924,12 @@ def commit_table(
properties=updated_staged_table.properties,
metadata=updated_staged_table.metadata,
)
self._create_glue_table(database_name=database_name, table_name=table_name, table_input=create_table_input)
self._create_glue_table(
database_name=database_name,
table_name=table_name,
table_input=create_table_input,
staged_table=updated_staged_table,
)

return CommitTableResponse(
metadata=updated_staged_table.metadata, metadata_location=updated_staged_table.metadata_location
Expand Down Expand Up @@ -835,7 +1013,9 @@ def rename_table(self, from_identifier: str | Identifier, to_identifier: str | I
) from e

rename_table_input = _construct_rename_table_input(to_table_name=to_table_name, glue_table=glue_table)
self._create_glue_table(database_name=to_database_name, table_name=to_table_name, table_input=rename_table_input)
self._create_glue_table(
database_name=to_database_name, table_name=to_table_name, table_input=rename_table_input, staged_table=None
)

try:
self.drop_table(from_identifier)
Expand Down
Loading
Loading