Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import io.unitycatalog.server.exception.BaseExceptionHandler;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.persist.Repositories;
import io.unitycatalog.server.persist.utils.FileOperations;
import io.unitycatalog.server.persist.utils.HibernateConfigurator;
import io.unitycatalog.server.security.SecurityConfiguration;
import io.unitycatalog.server.security.SecurityContext;
Expand Down Expand Up @@ -39,7 +40,6 @@
import io.unitycatalog.server.service.credential.CloudCredentialVendor;
import io.unitycatalog.server.service.credential.StorageCredentialVendor;
import io.unitycatalog.server.service.delta.DeltaApiService;
import io.unitycatalog.server.service.iceberg.FileIOFactory;
import io.unitycatalog.server.service.iceberg.MetadataService;
import io.unitycatalog.server.service.iceberg.TableConfigService;
import io.unitycatalog.server.utils.OptionParser;
Expand Down Expand Up @@ -175,6 +175,7 @@ private void addApiServices(
: new CloudCredentialVendor(serverProperties);
StorageCredentialVendor storageCredentialVendor =
new StorageCredentialVendor(cloudCredentialVendor, repositories.getExternalLocationUtils());
FileOperations fileOperations = new FileOperations(storageCredentialVendor, serverProperties);

SchemaService schemaService = new SchemaService(authorizer, repositories, serverProperties);

Expand Down Expand Up @@ -216,29 +217,21 @@ private void addApiServices(
.annotateUc(
"external-locations",
new ExternalLocationService(authorizer, repositories, serverProperties));
addIcebergApiServices(
armeriaServerBuilder,
serverProperties,
storageCredentialVendor,
schemaService,
repositories);
addIcebergApiServices(armeriaServerBuilder, schemaService, repositories, fileOperations);
addDeltaApiServices(
armeriaServerBuilder, authorizer, repositories, serverProperties, storageCredentialVendor);
}

private void addIcebergApiServices(
ArmeriaServerBuilder armeriaServerBuilder,
ServerProperties serverProperties,
StorageCredentialVendor storageCredentialVendor,
SchemaService schemaService,
Repositories repositories) {
Repositories repositories,
FileOperations fileOperations) {
LOGGER.info("Adding Iceberg services...");

// Add support for Iceberg REST APIs
MetadataService metadataService =
new MetadataService(new FileIOFactory(storageCredentialVendor, serverProperties));
TableConfigService tableConfigService =
new TableConfigService(storageCredentialVendor, serverProperties);
MetadataService metadataService = new MetadataService(fileOperations);
TableConfigService tableConfigService = new TableConfigService(fileOperations);

armeriaServerBuilder.annotateIceberg(
"iceberg",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import io.unitycatalog.server.auth.decorator.KeyMapper;
import io.unitycatalog.server.persist.utils.ExternalLocationUtils;
import io.unitycatalog.server.persist.utils.FileOperations;
import io.unitycatalog.server.utils.ServerProperties;
import lombok.Getter;
import org.hibernate.SessionFactory;
Expand All @@ -14,7 +13,6 @@
@Getter
public class Repositories {
private final SessionFactory sessionFactory;
private final FileOperations fileOperations;
private final ExternalLocationUtils externalLocationUtils;

private final CatalogRepository catalogRepository;
Expand All @@ -35,7 +33,6 @@ public class Repositories {

public Repositories(SessionFactory sessionFactory, ServerProperties serverProperties) {
this.sessionFactory = sessionFactory;
this.fileOperations = new FileOperations(serverProperties);
this.externalLocationUtils = new ExternalLocationUtils(sessionFactory);

this.catalogRepository = new CatalogRepository(this, sessionFactory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ public class TableRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(TableRepository.class);
private final SessionFactory sessionFactory;
private final Repositories repositories;
private final FileOperations fileOperations;
private final ServerProperties serverProperties;
private static final PagedListingHelper<TableInfoDAO> LISTING_HELPER =
new PagedListingHelper<>(TableInfoDAO.class);
Expand All @@ -72,7 +71,6 @@ public TableRepository(
Repositories repositories, SessionFactory sessionFactory, ServerProperties serverProperties) {
this.repositories = repositories;
this.sessionFactory = sessionFactory;
this.fileOperations = repositories.getFileOperations();
this.serverProperties = serverProperties;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,12 @@ public class VolumeRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(VolumeRepository.class);
private final Repositories repositories;
private final SessionFactory sessionFactory;
private final FileOperations fileOperations;
private static final PagedListingHelper<VolumeInfoDAO> LISTING_HELPER =
new PagedListingHelper<>(VolumeInfoDAO.class);

public VolumeRepository(Repositories repositories, SessionFactory sessionFactory) {
this.repositories = repositories;
this.sessionFactory = sessionFactory;
this.fileOperations = repositories.getFileOperations();
}

public VolumeInfo createVolume(CreateVolumeRequestContent createVolumeRequest) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,54 @@

import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.model.AwsCredentials;
import io.unitycatalog.server.model.AzureUserDelegationSAS;
import io.unitycatalog.server.model.GcpOauthToken;
import io.unitycatalog.server.model.TemporaryCredentials;
import io.unitycatalog.server.service.credential.CredentialContext;
import io.unitycatalog.server.service.credential.StorageCredentialVendor;
import io.unitycatalog.server.service.credential.azure.ADLSLocationUtils;
import io.unitycatalog.server.utils.NormalizedURL;
import io.unitycatalog.server.utils.ServerProperties;
import io.unitycatalog.server.utils.UriScheme;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.stream.Stream;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.iceberg.aws.AwsClientProperties;
import org.apache.iceberg.aws.s3.S3FileIOProperties;
import org.apache.iceberg.azure.AzureProperties;
import org.apache.iceberg.gcp.GCPProperties;
import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.io.ResolvingFileIO;

/**
* Single entry point for all storage/file access in the server. Covers both directory lifecycle
* management for managed storage locations (create/delete) and credential-vended Iceberg {@link
* FileIO} construction used by the Iceberg REST catalog.
*/
public class FileOperations {

private final ServerProperties serverProperties;
private final StorageCredentialVendor storageCredentialVendor;
private final Map<NormalizedURL, String> s3BucketRegionMap;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I understand it's the correct direction to unify all cloud storage access in a abstracted FileOperations, but seems like we are implementing all the cloud storage operations inside this FileOperations class ? ultimately I assume we will need an abstraction to fully decouple those cloud storage access into several fully isolated classes, so that one cloud won't perceive and access any other cloud resource.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The core part of this file is the getFileIO, getFileIOConfig and get*Config functions which directly generates cloud specific FileIO objects. s3BucketRegionMap happens to be part of this process.

Other than that, all the other functions will be cloud agnostic. The abstraction is already handled by getFileIOConfig. Different cloud implementation of actual file IO is implemented by ResolvingFileIO (and its delegation).


public FileOperations(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
public FileOperations(
StorageCredentialVendor storageCredentialVendor, ServerProperties serverProperties) {
this.storageCredentialVendor = storageCredentialVendor;
this.s3BucketRegionMap =
serverProperties.getS3Configurations().entrySet().stream()
.filter(entry -> entry.getValue().getRegion() != null)
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getRegion()));
}

/** Delete entire directory recursively. Note that currently it does nothing for cloud FS */
public static void deleteDirectory(NormalizedURL url) throws IOException {
public static void deleteDirectory(NormalizedURL url) {
switch (UriScheme.fromURI(url.toUri())) {
case FILE, NULL -> deleteLocalDirectory(url);
// Directory deletion for local paths is handled by SimpleLocalFileIO.
case FILE, NULL -> SimpleLocalFileIO.deleteDirectory(url.toString());
// Currently we can NOT delete the path in cloud storage. We will update this in future
// when UC OSS begins using the hadoopfs libraries.
Comment thread
openinx marked this conversation as resolved.
Resolved
case S3 -> {}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Shouldn't we throw rather than silent return ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

If it throws, deleting a managed entity on cloud would simply fail. This is incomplete and pre-existing.

Expand All @@ -35,25 +58,6 @@ public static void deleteDirectory(NormalizedURL url) throws IOException {
}
}

private static void deleteLocalDirectory(NormalizedURL url) throws IOException {
Path dirPath = Paths.get(url.toUri());
if (Files.exists(dirPath)) {
try (Stream<Path> walk = Files.walk(dirPath, FileVisitOption.FOLLOW_LINKS)) {
walk.sorted(Comparator.reverseOrder())
.forEach(
path -> {
try {
Files.delete(path);
} catch (IOException e) {
throw new RuntimeException("Failed to delete " + path, e);
}
});
}
} else {
throw new FileNotFoundException("Directory does not exist: " + dirPath);
}
}

/** Create a directory for storage location. Note that currently it does nothing for cloud FS */
public static void createStorageLocationDir(NormalizedURL url) {
switch (UriScheme.fromURI(url.toUri())) {
Expand All @@ -79,4 +83,100 @@ private static void createLocalDirectory(NormalizedURL url) {
throw new BaseException(ErrorCode.INTERNAL, "Failed to create directory: " + dirPath, e);
}
}

/**
* Returns an Iceberg {@link FileIO} for reading the given location. Local paths use {@link
* SimpleLocalFileIO}; cloud paths use a credential-vended {@link ResolvingFileIO}.
*/
// TODO: Cache fileIOs

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

That's really important, otherwise, every access will exhaustively consume all the resources by creating massive fileIO instance.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes. But not in this PR yet.

public FileIO getFileIO(NormalizedURL path) {
return switch (UriScheme.fromURI(path.toUri())) {
// Local paths are served by SimpleLocalFileIO (backed by java.nio + iceberg-core). We
// deliberately do NOT route these through ResolvingFileIO: it resolves the file:// scheme to
// Iceberg's HadoopFileIO, which requires hadoop-client-runtime on the classpath. The server
// only depends on hadoop-client-api, and SimpleLocalFileIO covers the local read and
// directory operations we need without that heavy runtime dependency.
case FILE, NULL -> new SimpleLocalFileIO();
case S3, GS, ABFS, ABFSS -> {
ResolvingFileIO fileio = new ResolvingFileIO();
fileio.initialize(getFileIOConfig(path));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Actually, you can use HadoopFileIO directly to get a FileIO https://github.com/apache/iceberg/blob/main/core/src/main/java/org/apache/iceberg/hadoop/HadoopFileIO.java. that will automatically address your fileIO cache problem, since the FileSystem will have the cache by default.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The downsides of using Hadoop FS (hadoop-client-runtime) is heavy dependency. It's a shaded uber-jar of an entire ecosystem that weighs ~30 MB, ~18,000 classes adding to the server runtime.
For now I don't see a good reason to adopt that yet.

yield fileio;
}
Comment on lines +100 to +104

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think this needs tests

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

something that lets FileOperations.getFileIO("s3://…") build a real ResolvingFileIO and read through it against the S3Mock

};
}

/**
* Builds the Iceberg FileIO configuration (credentials, region, token expiry) for the given
* location by vending temporary storage credentials for it. Returns an empty map for local
* (file://) paths, which need no cloud credentials.
*
* @param path the normalized storage location to vend credentials and build config for
*/
public Map<String, String> getFileIOConfig(NormalizedURL path) {
UriScheme scheme = UriScheme.fromURI(path.toUri());
if (scheme == UriScheme.FILE || scheme == UriScheme.NULL) {
// Local (file://) paths need no cloud credentials, so short-circuit before vending: the
// scheme is known here and vending would do a needless external-location lookup for local
// tables.
return Map.of();
}

// FIXME!! privileges are defaulted to READ only here for now as Iceberg REST impl doesn't

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If iceberg rest impl does not support vending write cred, then the IRC cannot support write for now right ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

IRC write support is not implemented yet.

// support write
TemporaryCredentials cred =
storageCredentialVendor.vendCredential(path, Set.of(CredentialContext.Privilege.SELECT));
Comment on lines +126 to +127

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

recently I've discovered that there may be instances where deployments may actually just rely on ambient credentials for reading un-vended GCP tables. so I wonder, will that behaviour persist here?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes ambient credentials on server can also be used for vending a temp table cred. This is where it is picked up for S3:

        // Otherwise just defer to DefaultCredentialsProvider
        credentialsProvider = DefaultCredentialsProvider.create();

if (cred.getAzureUserDelegationSas() != null) {
return getADLSConfig(path, cred.getAzureUserDelegationSas());
} else if (cred.getGcpOauthToken() != null) {
return getGCSConfig(cred.getGcpOauthToken(), cred.getExpirationTime());
} else if (cred.getAwsTempCredentials() != null) {
return getS3Config(path, cred.getAwsTempCredentials());
} else {
// Cloud vend returned no recognized credential type. This should not happen for a cloud
// scheme, so fail loudly rather than silently returning an empty (credential-less) config
// that would later surface as an opaque access-denied error.
throw new BaseException(
ErrorCode.INTERNAL,
"No recognized storage credential was vended for location: " + path);
}
}

private Map<String, String> getADLSConfig(
NormalizedURL path, AzureUserDelegationSAS azureUserDelegationSAS) {
ADLSLocationUtils.ADLSLocationParts locationParts = ADLSLocationUtils.parseLocation(path);
// NOTE: when fileio caching is implemented, need to set/deal with expiry here
return Map.of(
AzureProperties.ADLS_SAS_TOKEN_PREFIX + locationParts.account(),
azureUserDelegationSAS.getSasToken());
}

private Map<String, String> getGCSConfig(GcpOauthToken gcpOauthToken, Long expirationTime) {
if (expirationTime != null) {
return Map.of(
GCPProperties.GCS_OAUTH2_TOKEN,
gcpOauthToken.getOauthToken(),
GCPProperties.GCS_OAUTH2_TOKEN_EXPIRES_AT,
Long.toString(expirationTime));
} else {
return Map.of(GCPProperties.GCS_OAUTH2_TOKEN, gcpOauthToken.getOauthToken());
}
}

private Map<String, String> getS3Config(NormalizedURL path, AwsCredentials awsCredentials) {
// TODO: if region isn't configured, use HEAD bucket to figure out
String s3Region = s3BucketRegionMap.get(path.getStorageBase());
if (s3Region == null) {
// s3BucketRegionMap has no entry for this bucket (Map.get returns null on a miss). Guard
// here with a clear message rather than letting Map.of throw an opaque NullPointerException
// below.
throw new BaseException(
ErrorCode.INVALID_ARGUMENT,
"No S3 region configured for bucket: " + path.getStorageBase());
}
return Map.of(
S3FileIOProperties.ACCESS_KEY_ID, awsCredentials.getAccessKeyId(),
S3FileIOProperties.SECRET_ACCESS_KEY, awsCredentials.getSecretAccessKey(),
S3FileIOProperties.SESSION_TOKEN, awsCredentials.getSessionToken(),
AwsClientProperties.CLIENT_REGION, s3Region);
}
}
Loading
Loading