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
136 changes: 82 additions & 54 deletions examples/cli/src/main/java/io/unitycatalog/cli/TableCli.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,21 @@
import io.unitycatalog.cli.utils.CliException;
import io.unitycatalog.cli.utils.CliParams;
import io.unitycatalog.cli.utils.CliUtils;
import io.unitycatalog.cli.utils.FileOperations;
import io.unitycatalog.client.ApiClient;
import io.unitycatalog.client.ApiException;
import io.unitycatalog.client.api.TablesApi;
import io.unitycatalog.client.api.TemporaryCredentialsApi;
import io.unitycatalog.client.model.AwsCredentials;
import io.unitycatalog.client.model.ColumnInfo;
import io.unitycatalog.client.model.CreateStagingTable;
import io.unitycatalog.client.model.CreateTable;
import io.unitycatalog.client.model.DataSourceFormat;
import io.unitycatalog.client.model.GenerateTemporaryTableCredential;
import io.unitycatalog.client.model.StagingTableInfo;
import io.unitycatalog.client.model.TableInfo;
import io.unitycatalog.client.model.TableOperation;
import io.unitycatalog.client.model.TableType;
import io.unitycatalog.client.model.TemporaryCredentials;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.json.JSONException;
Expand All @@ -47,7 +46,7 @@ public static void handle(CommandLine cmd, ApiClient apiClient)
String output = EMPTY;
switch (subCommand) {
case CliUtils.CREATE:
output = createTable(tablesApi, json);
output = createTable(tablesApi, temporaryCredentialsApi, json);
break;
case CliUtils.LIST:
output = listTables(tablesApi, json);
Expand All @@ -70,7 +69,8 @@ public static void handle(CommandLine cmd, ApiClient apiClient)
CliUtils.postProcessAndPrintOutput(cmd, output, subCommand);
}

private static String createTable(TablesApi apiClient, JSONObject json)
private static String createTable(
TablesApi tablesApi, TemporaryCredentialsApi temporaryCredentialsApi, JSONObject json)
throws JsonProcessingException, ApiException {
CliUtils.resolveFullNameToThreeLevelNamespace(json);
try {
Expand Down Expand Up @@ -98,44 +98,76 @@ private static String createTable(TablesApi apiClient, JSONObject json)
TableType.valueOf(
json.getString(CliParams.TABLE_TYPE.getServerParam()).toUpperCase()))
.dataSourceFormat(DataSourceFormat.valueOf(format.toUpperCase()));
TemporaryCredentials temporaryCredentials;
if (createTable.getTableType() == TableType.EXTERNAL) {
createTable.storageLocation(json.getString(CliParams.STORAGE_LOCATION.getServerParam()));
handleTableStorageLocation(createTable.getStorageLocation(), columnInfoList);
}
TableInfo tableInfo = apiClient.createTable(createTable);
return objectWriter.writeValueAsString(tableInfo);
}

private static Path getLocalPath(String path) {
if (path.startsWith("file:")) {
return Paths.get(URI.create(path));
if (!json.has(CliParams.STORAGE_LOCATION.getServerParam())) {
throw new CliException("Storage location is required for external tables");
}
String storageLocation =
FileOperations.toStandardizedURIString(
json.getString(CliParams.STORAGE_LOCATION.getServerParam()));
createTable.setStorageLocation(storageLocation);
// Currently generateTemporaryPathCredentials doesn't quite work yet due to lack of proper
// authorization in its implementation. So this step has to be skipped and only local dir can
// work. For details please check https://github.com/unitycatalog/unitycatalog/issues/1160
temporaryCredentials = null;
// temporaryCredentials =
// temporaryCredentialsApi.generateTemporaryPathCredentials(
// new GenerateTemporaryPathCredential()
// .url(storageLocation)
// .operation(PathOperation.PATH_CREATE_TABLE));
Comment on lines +114 to +118

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.

Why just remove this commented code ?

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.

This commented code here is to show the reader how it is supposed to work. Eventually it will be uncommented when it's actually working.

} else if (createTable.getTableType() == TableType.MANAGED) {
// handle delta managed tables

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.

This is the major change for creating a MANAGED table from CLI.

if (json.has(CliParams.STORAGE_LOCATION.getServerParam())) {
throw new CliException("Storage location is not allowed for managed tables");
}
// Create staging table if format is delta
if (!DataSourceFormat.DELTA.name().equals(format.toUpperCase())) {
throw new CliException("Only delta tables are supported for managed tables: " + format);
}
CreateStagingTable createStagingTable =
new CreateStagingTable()
.catalogName(json.getString(CliParams.CATALOG_NAME.getServerParam()))
.schemaName(json.getString(CliParams.SCHEMA_NAME.getServerParam()))
.name(json.getString(CliParams.NAME.getServerParam()));
StagingTableInfo stagingTableInfo = tablesApi.createStagingTable(createStagingTable);
String stagingTableId = stagingTableInfo.getId();
String stagingLocation = stagingTableInfo.getStagingLocation();
if (stagingTableId == null || stagingLocation == null) {
throw new CliException("Failed to create staging table");
}
createTable.setStorageLocation(stagingLocation);
temporaryCredentials =
temporaryCredentialsApi.generateTemporaryTableCredentials(
new GenerateTemporaryTableCredential()
.tableId(stagingTableId)
.operation(TableOperation.READ_WRITE));
} else {
return Paths.get(path);
throw new CliException("Unknown table type: " + createTable.getTableType());
}
}

private static void handleTableStorageLocation(
String storageLocation, List<ColumnInfo> columnInfos) {
if (!(storageLocation.startsWith("s3://")
|| storageLocation.startsWith("file:/")
|| storageLocation.startsWith("/"))) {
throw new CliException(
"Storage location must start with s3:// or file:/ or be an absolute local filesystem path.");
}
if (!storageLocation.startsWith("s3://")) {
// local filesystem path
Path path = getLocalPath(storageLocation);
// try and initialize the directory and initiate delta log at the location
try {
DeltaKernelUtils.createDeltaTable(path.toUri().toString(), columnInfos, null);
} catch (Exception e) {
if (e.getCause() instanceof TableAlreadyExistsException) {
// TODO confirm the schema of the existing table matches the schema of the new table
} else {
throw new CliException("Failed to create delta table at " + path, e);
}
// try and initialize the directory and initiate delta log at the location
try {
DeltaKernelUtils.createDeltaTable(
createTable.getStorageLocation(), columnInfoList, temporaryCredentials);
} catch (Exception e) {
if ((e instanceof TableAlreadyExistsException
|| e.getCause() instanceof TableAlreadyExistsException)
&& createTable.getTableType() == TableType.EXTERNAL) {
// A common pattern is that many tests would test the failure cases of table creation. But
// they often leave the delta table on disk after failing to register a table in UC. Then
// they retry the table creation on the same location. This would allow those tests to
// continue. This will only happen to external tables as managed tables would have a unique
// new location allocated by UC.
// TODO confirm the schema of the existing table matches the schema of the new table

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.

why do we need to do this? are we building create semantics or create or replace semantics?

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.

This behavior is unchanged by this PR.
A common pattern is that many tests would test the failure cases of table creation. But they often leave the delta table on disk after failing to register a table in UC. Then they retry the table creation on the same location. This would allow those tests to continue.

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.

got it. but that makes sense of external tables where it is valid to create an external table in the catalog by pointing it to an existing file system table. however, thats not the case of managed tables. for managed tables, every attempt to create a managed table will be in a new path provided by the catalog. so it should never happen that the

does that mean some logic here should change? i think we should allow this exception to be swallowed only when its an external table. if table-already-exists exception is ever hit for a managed table ... thats a cause for alarm.

} else {
throw new CliException(
"Failed to create delta table at " + createTable.getStorageLocation(), e);
}
}

TableInfo tableInfo = tablesApi.createTable(createTable);
return objectWriter.writeValueAsString(tableInfo);
}

private static String listTables(TablesApi tablesApi, JSONObject json)
Expand Down Expand Up @@ -178,10 +210,13 @@ private static String readTable(
maxResults = json.getInt(CliParams.MAX_RESULTS.getServerParam());
}
try {
TemporaryCredentials temporaryCredentials =
temporaryCredentialsApi.generateTemporaryTableCredentials(
new GenerateTemporaryTableCredential()
.tableId(tableId)
.operation(TableOperation.READ));
return DeltaKernelUtils.readDeltaTable(
info.getStorageLocation(),
getTemporaryTableCredentials(temporaryCredentialsApi, tableId, TableOperation.READ),
maxResults);
info.getStorageLocation(), temporaryCredentials, maxResults);
} catch (Exception e) {
throw new CliException("Failed to read delta table " + info.getStorageLocation(), e);
}
Expand All @@ -197,11 +232,13 @@ private static String writeTable(
}
String tableId = info.getTableId();
try {
TemporaryCredentials temporaryCredentials =

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.

This type of change is to get away from special treatment for S3. Previously these function calls only accepted AwsCredentials. Now it's TemporaryCredentials.

temporaryCredentialsApi.generateTemporaryTableCredentials(
new GenerateTemporaryTableCredential()
.tableId(tableId)
.operation(TableOperation.READ_WRITE));
DeltaKernelWriteUtils.writeSampleDataToDeltaTable(
info.getStorageLocation(),
info.getColumns(),
getTemporaryTableCredentials(
temporaryCredentialsApi, tableId, TableOperation.READ_WRITE));
info.getStorageLocation(), info.getColumns(), temporaryCredentials);
} catch (Exception e) {
throw new CliException(
"Failed to write sample data to delta table " + info.getStorageLocation(), e);
Expand All @@ -213,13 +250,4 @@ private static String deleteTable(TablesApi tablesApi, JSONObject json) throws A
tablesApi.deleteTable(json.getString(CliParams.FULL_NAME.getServerParam()));
return EMPTY;
}

public static AwsCredentials getTemporaryTableCredentials(
TemporaryCredentialsApi apiClient, String tableId, TableOperation operation)
throws ApiException {
TemporaryCredentials temporaryTableCredentials =
apiClient.generateTemporaryTableCredentials(
new GenerateTemporaryTableCredential().tableId(tableId).operation(operation));
return temporaryTableCredentials.getAwsTempCredentials();
}
}
20 changes: 8 additions & 12 deletions examples/cli/src/main/java/io/unitycatalog/cli/VolumeCli.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,10 @@ private static String writeRandomFileInVolume(
Configuration conf =
DeltaKernelUtils.getHDFSConfiguration(
baseURI,
tempCredApi
.generateTemporaryVolumeCredentials(
new GenerateTemporaryVolumeCredential()
.volumeId(volumeInfo.getVolumeId())
.operation(VolumeOperation.WRITE_VOLUME))
.getAwsTempCredentials());
tempCredApi.generateTemporaryVolumeCredentials(
new GenerateTemporaryVolumeCredential()
.volumeId(volumeInfo.getVolumeId())
.operation(VolumeOperation.WRITE_VOLUME)));
FileSystem fs =
DeltaKernelUtils.getFileSystem(
URI.create(DeltaKernelUtils.substituteSchemeForS3(volumeLocation)), conf);
Expand Down Expand Up @@ -178,12 +176,10 @@ private static String readVolume(
Configuration conf =
DeltaKernelUtils.getHDFSConfiguration(
relativeURI,
tempCredApi
.generateTemporaryVolumeCredentials(
new GenerateTemporaryVolumeCredential()
.volumeId(volumeInfo.getVolumeId())
.operation(VolumeOperation.READ_VOLUME))
.getAwsTempCredentials());
tempCredApi.generateTemporaryVolumeCredentials(
new GenerateTemporaryVolumeCredential()
.volumeId(volumeInfo.getVolumeId())
.operation(VolumeOperation.READ_VOLUME)));
URI relativeURIWithS3AScheme =
URI.create(DeltaKernelUtils.substituteSchemeForS3(relativeURI.toString()));
FileSystem fs =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package io.unitycatalog.cli.delta;

import static io.unitycatalog.cli.utils.CliUtils.EMPTY;

import de.vandermeer.asciitable.AsciiTable;
import io.delta.kernel.Operation;
import io.delta.kernel.ScanBuilder;
Expand All @@ -18,14 +16,18 @@
import io.delta.kernel.types.IntegerType;
import io.delta.kernel.types.StructType;
import io.delta.kernel.utils.CloseableIterable;
import io.unitycatalog.cli.utils.Constants;
import io.unitycatalog.client.model.AwsCredentials;
import io.unitycatalog.client.model.ColumnInfo;
import io.unitycatalog.client.model.TemporaryCredentials;
import java.net.URI;
import java.util.List;
import java.util.Locale;
import java.util.stream.IntStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Utility class to create and read Delta tables. The create method creates a Delta table with the
Expand All @@ -36,12 +38,13 @@
* examples</a>
*/
public class DeltaKernelUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(DeltaKernelUtils.class);

public static String createDeltaTable(
String tablePath, List<ColumnInfo> columns, AwsCredentials awsTempCredentials) {
public static void createDeltaTable(
String tablePath, List<ColumnInfo> columns, TemporaryCredentials temporaryCredentials) {
try {
URI tablePathUri = URI.create(tablePath);
Engine engine = getEngine(tablePathUri, awsTempCredentials);
Engine engine = getEngine(tablePathUri, temporaryCredentials);
Table table = Table.forPath(engine, substituteSchemeForS3(tablePath));

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.

So basically, this is creating a path-based delta table right ?

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.

Since we currenlty don't support the managed table creation.

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.

I don't know the managed vs path-based delta table in the Delta Kernel's context.
This code seems to do the work of constructing a Delta table.

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.

Yeah, we need to have updated Delta Kernel that can actually construct a Delta table where catalogManaged table feature is enabled.

// construct the schema
StructType tableSchema = getSchema(columns);
Expand All @@ -54,22 +57,22 @@ public static String createDeltaTable(
// create an empty table
TransactionCommitResult commitResult = txn.commit(engine, CloseableIterable.emptyIterable());
if (commitResult.getVersion() >= 0) {
System.out.println("Table created successfully at: " + tablePath);
LOGGER.info("Table created successfully at: {}", tablePathUri);

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.

Thanks for the change, I think we need to disable the System.out.println(), and enforce it in the checkstyle.

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.

Added this #1142

} else {
throw new RuntimeException("Table creation failed");
}
} catch (Exception e) {
throw new IllegalArgumentException("Failed to create delta table", e);
String errorMsg = String.format("Failed to create Delta table at '%s'", tablePath);
throw new IllegalArgumentException(errorMsg, e);
}
return EMPTY;
}

public static String substituteSchemeForS3(String tablePath) {
return tablePath.replace("s3://", "s3a://");
}

public static Engine getEngine(URI tablePathUri, AwsCredentials awsTempCredentials) {
return DefaultEngine.create(getHDFSConfiguration(tablePathUri, awsTempCredentials));
public static Engine getEngine(URI tablePathUri, TemporaryCredentials temporaryCredentials) {
return DefaultEngine.create(getHDFSConfiguration(tablePathUri, temporaryCredentials));
}

public static FileSystem getFileSystem(URI tablePathURI, Configuration conf) {
Expand All @@ -81,30 +84,33 @@ public static FileSystem getFileSystem(URI tablePathURI, Configuration conf) {
}

public static Configuration getHDFSConfiguration(
URI tablePathUri, AwsCredentials awsTempCredentials) {
URI tablePathUri, TemporaryCredentials temporaryCredentials) {
Configuration conf = new Configuration();
if (tablePathUri.getScheme() != null
&& tablePathUri.getScheme().equals("s3")
&& awsTempCredentials == null) {
throw new IllegalArgumentException("AWS temporary credentials are missing");
String scheme = tablePathUri.getScheme();
if (scheme == null) {
throw new IllegalArgumentException("URI scheme is missing");
}
if (tablePathUri.getScheme().equals("s3")) {
if (scheme.equals(Constants.URI_SCHEME_S3)) {
AwsCredentials awsTempCredentials = temporaryCredentials.getAwsTempCredentials();
if (awsTempCredentials == null) {
throw new IllegalArgumentException("AWS temporary credentials are missing");
}
conf.set("fs.s3a.access.key", awsTempCredentials.getAccessKeyId());
conf.set("fs.s3a.secret.key", awsTempCredentials.getSecretAccessKey());
conf.set("fs.s3a.session.token", awsTempCredentials.getSessionToken());
conf.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem");
conf.set("fs.s3a.path.style.access", "true");
Comment on lines +94 to 102

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.

Could you please also file a separate issue, so that we can reuse the credential properties setting with the

I think the credentials properties setting should be same.

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.

Not a blocking issue for this PR, but a nice to have issue.

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.

This is similar to #1136 (comment)
@tdas how do you think about this?

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.

Thanks for the links, added my comment there: #1136 (comment)

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.

Also one more general question is: Is it possible for us to provide an abstraction so that we don't need to use the if schema == s3 else if schema == gcp else everywhere, for supporting all the 3 cloud vendors. It make us some kind of hard to maintane and iterate new features.

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.

@openinx ideally yes. This also depend on the discussion of a common package to decide where it should live. For now I don't think it should block this PR though.

} else if (tablePathUri.getScheme().equals("file")) {
} else if (scheme.equals(Constants.URI_SCHEME_FILE)) {
conf.set("fs.file.impl", "org.apache.hadoop.fs.LocalFileSystem");
} else {
throw new IllegalArgumentException("Unsupported URI scheme: " + tablePathUri.getScheme());
throw new IllegalArgumentException("Unsupported URI scheme: " + scheme);

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.

Will we also need to consider the gcp and azure abfs ?

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 so please file separate task to address them, thanks.

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.

Filed #1182

}
return conf;
}

public static String readDeltaTable(
String tablePath, AwsCredentials awsCredentials, int maxResults) {
Engine engine = getEngine(URI.create(tablePath), awsCredentials);
String tablePath, TemporaryCredentials temporaryCredentials, int maxResults) {
Engine engine = getEngine(URI.create(tablePath), temporaryCredentials);
try {
Table table = Table.forPath(engine, substituteSchemeForS3(tablePath));
Snapshot snapshot = table.getLatestSnapshot(engine);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@
import io.delta.kernel.utils.CloseableIterator;
import io.delta.kernel.utils.DataFileStatus;
import io.unitycatalog.cli.UnityCatalogCli;
import io.unitycatalog.client.model.AwsCredentials;
import io.unitycatalog.cli.utils.Constants;
import io.unitycatalog.client.model.ColumnInfo;
import io.unitycatalog.client.model.TemporaryCredentials;
import java.io.File;
import java.io.IOException;
import java.net.URI;
Expand All @@ -55,13 +56,13 @@ public class DeltaKernelWriteUtils {
private static final Random random = new Random();

public static String writeSampleDataToDeltaTable(
String tablePath, List<ColumnInfo> columns, AwsCredentials tempCredentialResponse) {
String tablePath, List<ColumnInfo> columns, TemporaryCredentials temporaryCredentials) {
try {
StructType schema = DeltaKernelUtils.getSchema(columns);
URI tablePathUri = URI.create(tablePath);
Engine engine = DeltaKernelUtils.getEngine(tablePathUri, tempCredentialResponse);
Engine engine = DeltaKernelUtils.getEngine(tablePathUri, temporaryCredentials);
boolean createVsUpdate = true;
if (tablePathUri.getScheme().equals("file")) {
if (tablePathUri.getScheme().equals(Constants.URI_SCHEME_FILE)) {
createVsUpdate = !(new File(tablePathUri).isDirectory());
}
writeSampleDataToExistingDeltaTable(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,12 @@ public List<CliParams> getOptionalParams() {
put(
CREATE,
new CliOptions(
List.of(CliParams.FULL_NAME, CliParams.COLUMNS),
List.of(
CliParams.FULL_NAME, CliParams.COLUMNS, CliParams.STORAGE_LOCATION),

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.

STORAGE_LOCATION is now optional for MANAGED table.

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.

Sounds good to me, thanks for the comment.

List.of(CliParams.DATA_SOURCE_FORMAT, CliParams.PROPERTIES)));
CliParams.DATA_SOURCE_FORMAT,
CliParams.PROPERTIES,
CliParams.STORAGE_LOCATION,
CliParams.TABLE_TYPE)));
put(
LIST,
new CliOptions(
Expand Down
Loading