World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#1247] Improvement (trino-connector) Make Trino QueryIT test cases running in ci. (#1262)
Yuhuib8c81791bcf0
diff --git a/dev/docker/tools/docker-connector.conf b/dev/docker/tools/docker-connector.confindex d8e859b95c..04005cf71a 100644--- a/dev/docker/tools/docker-connector.conf+++ b/dev/docker/tools/docker-connector.conf@@ -6,3 +6,4 @@# Fixed docker container network subnet in Gravitino integration testing module# Generate command: `docker network ls --filter driver=bridge --format "{{.ID}}" | xargs docker network inspect --format "route {{range .IPAM.Config}}{{.Subnet}}{{end}}" > ${bin}/docker-connector.conf`route 10.20.30.0/28+route 10.20.31.16/28diff --git a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.javaindex e9a9e61718..bf43b21054 100644--- a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java+++ b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java@@ -65,16 +65,16 @@ public class MiniGravitino {// Generate random Gravitino Server port and backend storage path, avoiding conflictscustomizeConfigFile(- ITUtils.joinDirPath(gravitinoRootDir, "conf", "gravitino.conf.template"),- ITUtils.joinDirPath(mockConfDir.getAbsolutePath(), GravitinoServer.CONF_FILE));+ ITUtils.joinPath(gravitinoRootDir, "conf", "gravitino.conf.template"),+ ITUtils.joinPath(mockConfDir.getAbsolutePath(), GravitinoServer.CONF_FILE));Files.copy(- Paths.get(ITUtils.joinDirPath(gravitinoRootDir, "conf", "gravitino-env.sh.template")),- Paths.get(ITUtils.joinDirPath(mockConfDir.getAbsolutePath(), "gravitino-env.sh")));+ Paths.get(ITUtils.joinPath(gravitinoRootDir, "conf", "gravitino-env.sh.template")),+ Paths.get(ITUtils.joinPath(mockConfDir.getAbsolutePath(), "gravitino-env.sh")));Properties properties =serverConfig.loadPropertiesFromFile(- new File(ITUtils.joinDirPath(mockConfDir.getAbsolutePath(), "gravitino.conf")));+ new File(ITUtils.joinPath(mockConfDir.getAbsolutePath(), "gravitino.conf")));serverConfig.loadFromProperties(properties);// Prepare delete the rocksdb backend storage directory@@ -109,7 +109,7 @@ public class MiniGravitino {try {GravitinoServer.main(new String[] {- ITUtils.joinDirPath(mockConfDir.getAbsolutePath(), "gravitino.conf")+ ITUtils.joinPath(mockConfDir.getAbsolutePath(), "gravitino.conf")});} catch (Exception e) {LOG.error("Exception in startup MiniGravitino Server ", e);@@ -220,7 +220,7 @@ public class MiniGravitino {Collections.emptyMap(),ErrorHandlers.restErrorHandler());} catch (RESTException e) {- LOG.warn("checkIfServerIsRunning() fails, GravitinoServer is not running", e);+ LOG.warn("checkIfServerIsRunning() fails, GravitinoServer is not running {}", e.getMessage());return false;}if (response != null && response.getCode() == 0) {diff --git a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/ITUtils.java b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/ITUtils.javaindex a01d20e569..837d9e0bac 100644--- a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/ITUtils.java+++ b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/ITUtils.java@@ -17,7 +17,7 @@ public class ITUtils {public static final String TEST_MODE = "testMode";public static final String EMBEDDED_TEST_MODE = "embedded";- public static String joinDirPath(String... dirs) {+ public static String joinPath(String... dirs) {return String.join(File.separator, dirs);}diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/ContainerSuite.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/ContainerSuite.javaindex a42fa81520..591a80802d 100644--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/ContainerSuite.java+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/ContainerSuite.java@@ -35,6 +35,7 @@ public class ContainerSuite implements Closeable {private static Network network = null;private static HiveContainer hiveContainer;private static TrinoContainer trinoContainer;+ private static TrinoITContainers trinoITContainers;protected static final CloseableGroup closer = CloseableGroup.create();@@ -128,6 +129,14 @@ public class ContainerSuite implements Closeable {return trinoContainer;}+ public static TrinoITContainers getTrinoITContainers() {+ if (trinoITContainers == null) {+ trinoITContainers = new TrinoITContainers();+ closer.register(trinoITContainers);+ }+ return trinoITContainers;+ }+public HiveContainer getHiveContainer() {return hiveContainer;}diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/TrinoITContainers.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/TrinoITContainers.javanew file mode 100644index 0000000000..50b1647235--- /dev/null+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/container/TrinoITContainers.java@@ -0,0 +1,135 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.integration.test.container;++import com.datastrato.gravitino.integration.test.util.CommandExecutor;+import com.datastrato.gravitino.integration.test.util.ITUtils;+import com.datastrato.gravitino.integration.test.util.ProcessData;+import java.util.HashMap;+import java.util.Map;+import org.apache.logging.log4j.util.Strings;+import org.mortbay.log.Log;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;+import org.testcontainers.containers.ContainerLaunchException;+import org.testcontainers.shaded.com.google.common.collect.ImmutableSet;++public class TrinoITContainers implements AutoCloseable {+ private static final Logger LOG = LoggerFactory.getLogger(TrinoITContainers.class);++ public static String dockerComposeDir;++ private static ImmutableSet<String> servicesName =+ ImmutableSet.of("trino", "hive_metastore", "hdfs", "mysql", "postgresql");++ Map<String, String> servicesUri = new HashMap<>();++ TrinoITContainers() {+ String dir = System.getenv("GRAVITINO_ROOT_DIR");+ if (Strings.isEmpty(dir)) {+ throw new RuntimeException("GRAVITINO_ROOT_DIR is not set");+ }++ dockerComposeDir = ITUtils.joinPath(dir, "integration-test", "trino-it");+ }++ public void launch(int gravitinoServerPort) throws Exception {+ shutdown();++ Map<String, String> env = new HashMap<>();+ env.put("GRAVITINO_SERVER_PORT", String.valueOf(gravitinoServerPort));+ env.put("GRAVITINO_LOG_PATH", System.getProperty("gravitino.log.path"));++ String command = ITUtils.joinPath(dockerComposeDir, "launch.sh");+ Object output =+ CommandExecutor.executeCommandLocalHost(+ command, false, ProcessData.TypesOfData.STREAMS_MERGED, env);+ Log.info("Command {} output:\n{}", command, output);++ resolveServerAddress();+ }++ private void resolveServerAddress() throws Exception {+ String command = ITUtils.joinPath(dockerComposeDir, "inspect_ip.sh");+ Object output =+ CommandExecutor.executeCommandLocalHost(+ command, false, ProcessData.TypesOfData.STREAMS_MERGED);+ Log.info("Command {} output:\n{}", command, output);++ // expect the output to be like:+ // trino:10.20.30.21+ // hive:10.20.30.19+ // mysql:10.20.30.20+ // postgresql:10.20.30.18++ String containerIpMapping = output.toString();+ if (containerIpMapping.isEmpty()) {+ throw new ContainerLaunchException("Missing to get container status");+ }++ try {+ String[] containerInfos = containerIpMapping.split("\n");+ for (String container : containerInfos) {+ String[] info = container.split(":");++ String containerName = info[0];+ String address = info[1];++ if (containerName.equals("trino")) {+ servicesUri.put("trino", String.format("http://%s:8080", address));+ } else if (containerName.equals("hive")) {+ servicesUri.put("hive_metastore", String.format("thrift://%s:9083", address));+ servicesUri.put("hdfs", String.format("hdfs://%s:9000", address));+ } else if (containerName.equals("mysql")) {+ servicesUri.put("mysql", String.format("jdbc:mysql://%s:3306", address));+ } else if (containerName.equals("postgresql")) {+ servicesUri.put("postgresql", String.format("jdbc:postgresql://%s", address));+ }+ }+ } catch (Exception e) {+ throw new ContainerLaunchException("Unexpected container status :\n" + containerIpMapping, e);+ }++ for (String serviceName : servicesName) {+ if (!servicesUri.containsKey(serviceName)) {+ throw new ContainerLaunchException(+ "The container for the {} service is not started: " + serviceName);+ }+ }+ }++ public void shutdown() {+ String command = ITUtils.joinPath(dockerComposeDir, "shutdown.sh");+ Object output =+ CommandExecutor.executeCommandLocalHost(+ command, false, ProcessData.TypesOfData.STREAMS_MERGED);+ Log.info("Command {} output:\n{}", command, output);+ }++ public String getTrinoUri() {+ return servicesUri.get("trino");+ }++ public String getHiveMetastoreUri() {+ return servicesUri.get("hive_metastore");+ }++ public String getHdfsUri() {+ return servicesUri.get("hdfs");+ }++ public String getMysqlUri() {+ return servicesUri.get("mysql");+ }++ public String getPostgresqlUri() {+ return servicesUri.get("postgresql");+ }++ @Override+ public void close() throws Exception {+ shutdown();+ }+}diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoConnectorIT.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoConnectorIT.javaindex 95a09c85ac..6a8a90849e 100644--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoConnectorIT.java+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoConnectorIT.java@@ -99,7 +99,7 @@ public class TrinoConnectorIT extends AbstractIT {// Deploy mode, you should download jars to the Gravitino server iceberg lib directoryif (!ITUtils.EMBEDDED_TEST_MODE.equals(testMode)) {String gravitinoHome = System.getenv("GRAVITINO_HOME");- String destPath = ITUtils.joinDirPath(gravitinoHome, "catalogs", "lakehouse-iceberg", "libs");+ String destPath = ITUtils.joinPath(gravitinoHome, "catalogs", "lakehouse-iceberg", "libs");JdbcDriverDownloader.downloadJdbcDriver("https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.27/mysql-connector-java-8.0.27.jar",destPath);diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoQueryIT.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoQueryIT.javaindex 07b95828f8..57bfa92672 100644--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoQueryIT.java+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/trino/TrinoQueryIT.java@@ -12,6 +12,11 @@ import com.datastrato.gravitino.NameIdentifier;import com.datastrato.gravitino.Namespace;import com.datastrato.gravitino.client.GravitinoClient;import com.datastrato.gravitino.client.GravitinoMetaLake;+import com.datastrato.gravitino.exceptions.RESTException;+import com.datastrato.gravitino.integration.test.container.ContainerSuite;+import com.datastrato.gravitino.integration.test.container.TrinoITContainers;+import com.datastrato.gravitino.integration.test.util.AbstractIT;+import com.datastrato.gravitino.integration.test.util.ITUtils;import com.datastrato.gravitino.rel.SupportsSchemas;import com.datastrato.gravitino.rel.TableCatalog;import io.trino.cli.Query;@@ -47,6 +52,7 @@ import java.util.regex.Matcher;import java.util.regex.Pattern;import jodd.io.StringOutputStream;import okhttp3.logging.HttpLoggingInterceptor;+import org.apache.logging.log4j.util.Strings;import org.jline.terminal.Terminal;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;@@ -61,80 +67,96 @@ import org.slf4j.LoggerFactory;public class TrinoQueryIT {private static final Logger LOG = LoggerFactory.getLogger(TrinoQueryIT.class);- private static boolean isDockerRunning = false;+ private static boolean autoStartEnv = true;// TODO(yuhui) redo get the configs after we have the Docker image ready for testing.private static String gravitinoUri = "http://127.0.0.1:8090";private static String trinoUri = "http://127.0.0.1:8080";private static String hiveMetastoreUri = "thrift://127.0.0.1:9083";- private static String mysqlUri = "jdbc:mysql://127.0.0.1?useSSL=false";- private static String postgresqlUri = "jdbc:postgresql://127.0.0.1/mydb";+ private static String hdfsUri = "hdfs://127.0.0.1:9000";+ private static String mysqlUri = "jdbc:mysql://127.0.0.1";+ private static String postgresqlUri = "jdbc:postgresql://127.0.0.1";++ private static GravitinoClient gravitinoClient;+ private static TrinoITContainers trinoITContainers;+ private static TrinoQueryRunner trinoQueryRunner;private static final String metalakeName = "test";+ private static GravitinoMetaLake metalake;private static final Set<String> testCatalogs = new HashSet<>();- private static GravitinoClient client;- private static GravitinoMetaLake metalake;private static String testQueriesDir = "";private static AtomicInteger testCount = new AtomicInteger(0);private static AtomicInteger totalCount = new AtomicInteger(0);- static TrinoQueryRunner trinoQueryRunner;++ private static void setEnv() throws Exception {+ if (autoStartEnv) {+ AbstractIT.startIntegrationTest();+ trinoITContainers = ContainerSuite.getInstance().getTrinoITContainers();+ trinoITContainers.launch(AbstractIT.getGravitinoServerPort());+ gravitinoClient = AbstractIT.getGravitinoClient();++ gravitinoUri = String.format("http://127.0.0.1:%d", AbstractIT.getGravitinoServerPort());+ trinoUri = trinoITContainers.getTrinoUri();+ hiveMetastoreUri = trinoITContainers.getHiveMetastoreUri();+ hdfsUri = trinoITContainers.getHdfsUri();+ mysqlUri = trinoITContainers.getMysqlUri();+ postgresqlUri = trinoITContainers.getPostgresqlUri();++ } else {+ gravitinoClient = GravitinoClient.builder(gravitinoUri).build();+ }+ }@BeforeAllpublic static void setup() throws Exception {- try {- client = GravitinoClient.builder(gravitinoUri).build();- trinoQueryRunner = new TrinoQueryRunner();+ setEnv();- createMetalake();+ trinoQueryRunner = new TrinoQueryRunner();- Set<String> catalogs = new HashSet<>(testCatalogs);+ createMetalake();- if (catalogs.isEmpty() || catalogs.contains("hive")) {- dropCatalog("hive");- HashMap<String, String> properties = new HashMap<>();- properties.put("metastore.uris", hiveMetastoreUri);+ Set<String> catalogs = new HashSet<>(testCatalogs);- createCatalog("hive", "hive", properties);- }+ if (catalogs.isEmpty() || catalogs.contains("hive")) {+ dropCatalog("hive");+ HashMap<String, String> properties = new HashMap<>();+ properties.put("metastore.uris", hiveMetastoreUri);- if (catalogs.isEmpty() || catalogs.contains("lakehouse-iceberg")) {- dropCatalog("lakehouse-iceberg");- HashMap<String, String> properties = new HashMap<>();- properties.put("uri", hiveMetastoreUri);- properties.put("catalog-backend", "hive");- properties.put("warehouse", "hdfs://localhost:9000/user/iceberg/warehouse/TrinoQueryIT");+ createCatalog("hive", "hive", properties);+ }- createCatalog("lakehouse-iceberg", "lakehouse-iceberg", properties);- }+ if (catalogs.isEmpty() || catalogs.contains("lakehouse-iceberg")) {+ dropCatalog("lakehouse-iceberg");+ HashMap<String, String> properties = new HashMap<>();+ properties.put("uri", hiveMetastoreUri);+ properties.put("catalog-backend", "hive");+ properties.put("warehouse", hdfsUri + "/user/iceberg/warehouse/TrinoQueryIT");- if (catalogs.isEmpty() || catalogs.contains("jdbc-mysql")) {- dropCatalog("jdbc-mysql");- HashMap<String, String> properties = new HashMap<>();- properties.put("jdbc-url", mysqlUri);- properties.put("jdbc-user", "root");- properties.put("jdbc-password", "ds123");- properties.put("jdbc-driver", "com.mysql.cj.jdbc.Driver");+ createCatalog("lakehouse-iceberg", "lakehouse-iceberg", properties);+ }- createCatalog("jdbc-mysql", "jdbc-mysql", properties);- }+ if (catalogs.isEmpty() || catalogs.contains("jdbc-mysql")) {+ dropCatalog("jdbc-mysql");+ HashMap<String, String> properties = new HashMap<>();+ properties.put("jdbc-url", mysqlUri + "?useSSL=false");+ properties.put("jdbc-user", "trino");+ properties.put("jdbc-password", "ds123");+ properties.put("jdbc-driver", "com.mysql.cj.jdbc.Driver");- if (catalogs.isEmpty() || catalogs.contains("jdbc-postgresql")) {- dropCatalog("jdbc-postgresql");- HashMap<String, String> properties = new HashMap<>();- properties.put("jdbc-url", postgresqlUri);- properties.put("jdbc-user", "root");- properties.put("jdbc-password", "ds123");- properties.put("jdbc-database", "mydb");- properties.put("jdbc-driver", "org.postgresql.Driver");+ createCatalog("jdbc-mysql", "jdbc-mysql", properties);+ }- createCatalog("jdbc-postgresql", "jdbc-postgresql", properties);- }+ if (catalogs.isEmpty() || catalogs.contains("jdbc-postgresql")) {+ dropCatalog("jdbc-postgresql");+ HashMap<String, String> properties = new HashMap<>();+ properties.put("jdbc-url", postgresqlUri + "/gt_db");+ properties.put("jdbc-user", "trino");+ properties.put("jdbc-password", "ds123");+ properties.put("jdbc-database", "gt_db");+ properties.put("jdbc-driver", "org.postgresql.Driver");- isDockerRunning = true;- } catch (Exception e) {- LOG.error("Services are not connected", e);- return;+ createCatalog("jdbc-postgresql", "jdbc-postgresql", properties);}testQueriesDir =@@ -144,33 +166,59 @@ public class TrinoQueryIT {@AfterAllpublic static void cleanup() {- trinoQueryRunner.stop();+ if (trinoQueryRunner != null) {+ trinoQueryRunner.stop();+ }++ try {+ if (autoStartEnv) {+ trinoITContainers.shutdown();+ AbstractIT.stopIntegrationTest();+ }+ } catch (Exception e) {+ LOG.error("Error in cleanup", e);+ }}- private static void createMetalake() {- boolean exists = client.metalakeExists(NameIdentifier.of(metalakeName));- if (exists) {- metalake = client.loadMetalake(NameIdentifier.of(metalakeName));- return;+ private static void createMetalake() throws Exception {+ boolean created = false;+ int tries = 180;+ while (!created && tries-- >= 0) {+ try {+ boolean exists = gravitinoClient.metalakeExists(NameIdentifier.of(metalakeName));++ if (exists) {+ metalake = gravitinoClient.loadMetalake(NameIdentifier.of(metalakeName));+ return;+ }++ GravitinoMetaLake createdMetalake =+ gravitinoClient.createMetalake(+ NameIdentifier.of(metalakeName), "comment", Collections.emptyMap());+ Assertions.assertNotNull(createdMetalake);+ metalake = createdMetalake;+ created = true;+ } catch (RESTException exception) {+ LOG.info("Waiting for connecting to gravitino server");+ sleep(1000);+ }}- GravitinoMetaLake createdMetalake =- client.createMetalake(NameIdentifier.of(metalakeName), "comment", Collections.emptyMap());- Assertions.assertNotNull(createdMetalake);- metalake = createdMetalake;+ if (!created) {+ throw new Exception("Failed to create metalake " + metalakeName);+ }}private static void dropMetalake() {- boolean exists = client.metalakeExists(NameIdentifier.of(metalakeName));+ boolean exists = gravitinoClient.metalakeExists(NameIdentifier.of(metalakeName));if (!exists) {return;}- client.dropMetalake(NameIdentifier.of(metalakeName));+ gravitinoClient.dropMetalake(NameIdentifier.of(metalakeName));}private static void createCatalog(- String catalogName, String provider, Map<String, String> properties)- throws InterruptedException {+ String catalogName, String provider, Map<String, String> properties) throws Exception {boolean exists = metalake.catalogExists(NameIdentifier.of(metalakeName, catalogName));if (!exists) {Catalog createdCatalog =@@ -185,19 +233,24 @@ public class TrinoQueryIT {}boolean catalogCreated = false;- int tries = 30;+ int tries = 180;while (!catalogCreated && tries-- >= 0) {- String result = trinoQueryRunner.runQuery("show catalogs");- if (result.contains(metalakeName + "." + catalogName)) {- catalogCreated = true;- break;+ try {+ String result = trinoQueryRunner.runQuery("show catalogs");+ if (result.contains(metalakeName + "." + catalogName)) {+ catalogCreated = true;+ break;+ }+ LOG.info("Waiting for catalog {} to be created", catalogName);+ // connection exception need retry.+ } catch (Exception ConnectionException) {+ LOG.info("Waiting for connecting to Trino");}sleep(1000);- LOG.info("Waiting for catalog {} to be created", catalogName);}if (!catalogCreated) {- Assertions.fail("Catalog " + catalogName + " not created");+ throw new Exception("Catalog " + catalogName + " create timeout");}}@@ -263,10 +316,6 @@ public class TrinoQueryIT {@Testpublic void testSql() throws Exception {- if (!isDockerRunning) {- return;- }-String[] catalogNames = readCatalogNames();ExecutorService executor = Executors.newFixedThreadPool(catalogNames.length);@@ -304,7 +353,7 @@ public class TrinoQueryIT {}private String[] loadAllTestFiles(String dirName, String filterPrefix) {- String targetDir = testQueriesDir + "/" + dirName;+ String targetDir = ITUtils.joinPath(testQueriesDir, dirName);File targetDirFile = new File(targetDir);if (!targetDirFile.exists()) {return new String[0];@@ -331,7 +380,7 @@ public class TrinoQueryIT {Arrays.sort(testFileNames);for (int i = 0; i < testFileNames.length; i += 2) {String fileNamePrefix = testFileNames[i].substring(0, testFileNames[i].lastIndexOf('.'));- fileNamePrefix = testQueriesDir + "/" + testDirName + "/" + fileNamePrefix;+ fileNamePrefix = ITUtils.joinPath(testQueriesDir, testDirName, fileNamePrefix);String testFileName = fileNamePrefix + ".sql";String testResultFileName = fileNamePrefix + ".txt";@@ -352,15 +401,7 @@ public class TrinoQueryIT {}String result = queryRunner.runQuery(sql).trim();-- boolean match;-- if (!expectResult.isEmpty()- && Pattern.compile("^Query \\w+ failed:").matcher(result).find()) {- match = Pattern.compile("^Query \\w+ failed.*: " + expectResult).matcher(result).find();- } else {- match = expectResult.equals(result);- }+ boolean match = match(expectResult, result);if (match) {LOG.info(@@ -392,10 +433,60 @@ public class TrinoQueryIT {queryRunner.stop();}+ /**+ * * This method is used to match the result of the query. There are three cases: 1. The expected+ * result is equal to the actual result. 2. The expected result is a query failed result, and the+ * actual result matches the query failed result. 3. The expected result is a regular expression,+ * and the actual result matches the regular expression.+ *+ * @param expectResult+ * @param result+ * @return+ */+ boolean match(String expectResult, String result) {+ if (expectResult.isEmpty()) {+ return false;+ }++ boolean match = expectResult.equals(result);+ if (match) {+ return true;+ }++ // Match query failed result.+ // E.g., the expected result can be matched with the following actual result:+ // query result:+ // Query 20240103_132722_00006_pijfx failed: line 8:6: Schema must be specified when session+ // schema is not set+ // expectResult:+ // Schema must be specified when session schema is not set+ if (Pattern.compile("^Query \\w+ failed:").matcher(result).find()) {+ match = Pattern.compile("^Query \\w+ failed.*: " + expectResult).matcher(result).find();+ return match;+ }++ // Match Wildcard.+ // The valid wildcard is '%'. It can match any character.+ // E.g., the expected result can be matched with the following actual result:+ // query result:+ // ...+ // location = 'hdfs://10.1.30.1:9000/user/hive/warehouse/gt_db1.db/tb01',+ // ...+ // expectResult:+ //+ // location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',+ // ...+ expectResult = expectResult.replace("\n", "");+ expectResult = "\\Q" + expectResult.replace("%", "\\E.*?\\Q") + "\\E";+ result = result.replace("\n", "");+ match = Pattern.compile(expectResult).matcher(result).find();+ return match;+ }+static class TrinoQueryRunner {private QueryRunner queryRunner;private Terminal terminal;- private URI uri = new URI("http://192.168.215.2:8080");+ private URI uri;TrinoQueryRunner() throws Exception {this.uri = new URI(trinoUri);@@ -426,6 +517,16 @@ public class TrinoQueryIT {CSV,Optional.of(""),false);+ ClientSession session = queryRunner.getSession();++ // update catalog and schema if present+ if (queryResult.getSetCatalog().isPresent() || queryResult.getSetSchema().isPresent()) {+ ClientSession.Builder builder = ClientSession.builder(session);+ queryResult.getSetCatalog().ifPresent(builder::catalog);+ queryResult.getSetSchema().ifPresent(builder::schema);+ session = builder.build();+ queryRunner.setSession(session);+ }return outputStream.toString();}@@ -441,7 +542,22 @@ public class TrinoQueryIT {}}+ private static void checkEnv() {+ if (Strings.isEmpty(System.getenv("GRAVITINO_ROOT_DIR"))) {+ throw new RuntimeException("GRAVITINO_ROOT_DIR is not set");+ }++ if (Strings.isEmpty(System.getenv("GRAVITINO_HOME"))) {+ throw new RuntimeException("GRAVITINO_HOME is not set");+ }++ if (Strings.isEmpty(System.getenv("GRAVITINO_TEST"))) {+ throw new RuntimeException("GRAVITINO_TEST is not set");+ }+ }+public static void main(String[] args) {+ checkEnv();String targetTestId = null;try {if (args.length == 1) {diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.javaindex b9651be9ce..f2a6dcfe08 100644--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java@@ -177,6 +177,10 @@ public class AbstractIT {return hostIP;}+ public static GravitinoClient getGravitinoClient() {+ return client;+ }+protected String readGitCommitIdFromGitFile() {try {String gravitinoHome = System.getenv("GRAVITINO_HOME");diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/CommandExecutor.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/CommandExecutor.javaindex 7e8be95a95..35bb1ae479 100644--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/CommandExecutor.java+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/CommandExecutor.java@@ -19,7 +19,9 @@ package com.datastrato.gravitino.integration.test.util;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;+import java.util.HashMap;import java.util.List;+import java.util.Map;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -41,13 +43,15 @@ public class CommandExecutor {String[] command,boolean printToConsole,ProcessData.TypesOfData type,- IGNORE_ERRORS ignore_errors) {+ IGNORE_ERRORS ignore_errors,+ Map<String, String> env) {List<String> subCommandsAsList = new ArrayList<>(Arrays.asList(command));String mergedCommand = StringUtils.join(subCommandsAsList, " ");LOG.info("Sending command \"" + mergedCommand + "\" to localhost");ProcessBuilder processBuilder = new ProcessBuilder(command);+ processBuilder.environment().putAll(env);Process process = null;try {process = processBuilder.start();@@ -70,6 +74,23 @@ public class CommandExecutor {public static Object executeCommandLocalHost(String command, boolean printToConsole, ProcessData.TypesOfData type) {return executeCommandLocalHost(- new String[] {"bash", "-c", command}, printToConsole, type, DEFAULT_BEHAVIOUR_ON_ERRORS);+ new String[] {"bash", "-c", command},+ printToConsole,+ type,+ DEFAULT_BEHAVIOUR_ON_ERRORS,+ new HashMap<String, String>());+ }++ public static Object executeCommandLocalHost(+ String command,+ boolean printToConsole,+ ProcessData.TypesOfData type,+ Map<String, String> env) {+ return executeCommandLocalHost(+ new String[] {"bash", "-c", command},+ printToConsole,+ type,+ DEFAULT_BEHAVIOUR_ON_ERRORS,+ env);}}diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/ProcessData.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/ProcessData.javaindex 71c2044f79..6896d87d8f 100644--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/ProcessData.java+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/ProcessData.java@@ -86,7 +86,7 @@ public class ProcessData {switch (type) {case OUTPUT:{- return this.getOutPutStream();+ return this.getOutPutStream(false);}case ERROR:{@@ -98,7 +98,7 @@ public class ProcessData {}case STREAMS_MERGED:{- return this.getOutPutStream() + "\n" + this.getErrorStream();+ return this.getOutPutStream(true);}case PROCESS_DATA_OBJECT:{@@ -127,10 +127,10 @@ public class ProcessData {return this.returnCode;}- public String getOutPutStream() {+ public String getOutPutStream(boolean mergeStreams) {if (this.outPutStream == null) {try {- buildOutputAndErrorStreamData();+ buildOutputAndErrorStreamData(mergeStreams);} catch (Exception e) {throw new RuntimeException("Couldn't retrieve Output Stream data from process: " + this.checkedProcess.toString(),@@ -149,7 +149,7 @@ public class ProcessData {public String getErrorStream() {if (this.errorStream == null) {try {- buildOutputAndErrorStreamData();+ buildOutputAndErrorStreamData(false);} catch (Exception e) {throw new RuntimeException("Couldn't retrieve Error Stream data from process: " + this.checkedProcess.toString(),@@ -171,7 +171,7 @@ public class ProcessData {+ String.format("[EXIT CODE]\n%d", this.returnCode);}- private void buildOutputAndErrorStreamData() throws IOException {+ private void buildOutputAndErrorStreamData(boolean mergeStreams) throws IOException {StringBuilder sbInStream = new StringBuilder();StringBuilder sbErrorStream = new StringBuilder();@@ -233,7 +233,11 @@ public class ProcessData {break;}tempSB.append(charBuffer, 0, readCount);- sbErrorStream.append(tempSB);+ if (mergeStreams) {+ sbInStream.append(tempSB);+ } else {+ sbErrorStream.append(tempSB);+ }if (tempSB.length() > 0) {outputProduced = true;String temp = new String(tempSB);diff --git a/integration-test/src/test/resources/trino-queries/catalogs/hive/00002_alter_table.txt b/integration-test/src/test/resources/trino-queries/catalogs/hive/00002_alter_table.txtindex 2a9eb73ed3..5dff2d1b94 100644--- a/integration-test/src/test/resources/trino-queries/catalogs/hive/00002_alter_table.txt+++ b/integration-test/src/test/resources/trino-queries/catalogs/hive/00002_alter_table.txt@@ -19,7 +19,7 @@ DROP COLUMNCOMMENT ''WITH (input_format = 'org.apache.hadoop.mapred.TextInputFormat',- location = 'hdfs://localhost:9000/user/hive/warehouse/gt_db1.db/tb01',+ location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',num_files = '0',output_format = 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat',serde_lib = 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe',@@ -37,7 +37,7 @@ RENAME COLUMNCOMMENT ''WITH (input_format = 'org.apache.hadoop.mapred.TextInputFormat',- location = 'hdfs://localhost:9000/user/hive/warehouse/gt_db1.db/tb01',+ location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',num_files = '0',output_format = 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat',serde_lib = 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe',@@ -55,7 +55,7 @@ SET COLUMN TYPECOMMENT ''WITH (input_format = 'org.apache.hadoop.mapred.TextInputFormat',- location = 'hdfs://localhost:9000/user/hive/warehouse/gt_db1.db/tb01',+ location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',num_files = '0',output_format = 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat',serde_lib = 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe',@@ -73,7 +73,7 @@ COMMENTCOMMENT 'test table comments'WITH (input_format = 'org.apache.hadoop.mapred.TextInputFormat',- location = 'hdfs://localhost:9000/user/hive/warehouse/gt_db1.db/tb01',+ location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',num_files = '0',output_format = 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat',serde_lib = 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe',@@ -91,7 +91,7 @@ COMMENTCOMMENT 'test table comments'WITH (input_format = 'org.apache.hadoop.mapred.TextInputFormat',- location = 'hdfs://localhost:9000/user/hive/warehouse/gt_db1.db/tb01',+ location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',num_files = '0',output_format = 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat',serde_lib = 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe',@@ -110,7 +110,7 @@ ADD COLUMNCOMMENT 'test table comments'WITH (input_format = 'org.apache.hadoop.mapred.TextInputFormat',- location = 'hdfs://localhost:9000/user/hive/warehouse/gt_db1.db/tb01',+ location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',num_files = '0',output_format = 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat',serde_lib = 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe',diff --git a/integration-test/src/test/resources/trino-queries/catalogs/jdbc-mysql/00003_use.sql b/integration-test/src/test/resources/trino-queries/catalogs/jdbc-mysql/00003_use.sqlnew file mode 100644index 0000000000..bb7ad173d5--- /dev/null+++ b/integration-test/src/test/resources/trino-queries/catalogs/jdbc-mysql/00003_use.sql@@ -0,0 +1,17 @@+CREATE SCHEMA "test.jdbc-mysql".gt_db1;++USE "test.jdbc-mysql".gt_db1;++CREATE TABLE tb01 (+ name varchar,+ salary int+);++show create table tb01;++show tables from "test.jdbc-mysql".gt_db1;++drop table tb01;+++drop schema "test.jdbc-mysql".gt_db1;diff --git a/integration-test/src/test/resources/trino-queries/catalogs/jdbc-mysql/00003_use.txt b/integration-test/src/test/resources/trino-queries/catalogs/jdbc-mysql/00003_use.txtnew file mode 100644index 0000000000..9c25f7501e--- /dev/null+++ b/integration-test/src/test/resources/trino-queries/catalogs/jdbc-mysql/00003_use.txt@@ -0,0 +1,17 @@+CREATE SCHEMA++USE++CREATE TABLE++"CREATE TABLE ""test.jdbc-mysql"".gt_db1.tb01 (+ name varchar,+ salary integer+)+COMMENT ''"++"tb01"++DROP TABLE++DROP SCHEMA\ No newline at end of filediff --git a/integration-test/trino-it/docker-compose.yaml b/integration-test/trino-it/docker-compose.yamlnew file mode 100644index 0000000000..2963258f9c--- /dev/null+++ b/integration-test/trino-it/docker-compose.yaml@@ -0,0 +1,103 @@+#+# Copyright 2024 Datastrato Pvt Ltd.+# This software is licensed under the Apache License version 2.+#+version: '3.0'+services:++ hive:+ image: datastrato/gravitino-ci-hive:0.1.7+ networks:+ - trino-net+ container_name: trino-ci-hive+ environment:+ - HADOOP_USER_NAME=root+ entrypoint: /bin/bash /tmp/hive/init.sh+ volumes:+ - ./init/hive:/tmp/hive+ healthcheck:+ test: ["CMD", "/tmp/check-status.sh"]+ interval: 10s+ timeout: 60s+ retries: 5++ postgresql:+ image: postgres:13+ container_name: trino-ci-postgresql+ restart: always+ environment:+ POSTGRES_USER: trino+ POSTGRES_PASSWORD: ds123+ ALLOW_IP_RANGE: 0.0.0.0/0+ networks:+ - trino-net+ volumes:+ - ./init/postgres:/docker-entrypoint-initdb.d/+ healthcheck:+ test: ["CMD-SHELL", "pg_isready"]+ interval: 10s+ timeout: 60s+ retries: 5++ mysql:+ image: mysql:8.0+ container_name: trino-ci-mysql+ networks:+ - trino-net+ volumes:+ - ./init/mysql:/docker-entrypoint-initdb.d/+ environment:+ MYSQL_ROOT_PASSWORD: ds123+ MYSQL_USER: trino+ MYSQL_PASSWORD: ds123+ MYSQL_DATABASE: gt_db+ command:+ --default-authentication-plugin=mysql_native_password+ --character-set-server=utf8mb4+ --collation-server=utf8mb4_general_ci+ --explicit_defaults_for_timestamp=true+ --lower_case_table_names=1+ healthcheck:+ test: ["CMD-SHELL", "mysqladmin ping"]+ interval: 10s+ timeout: 60s+ retries: 5++ trino:+ image: datastrato/gravitino-ci-trino:0.1.3+ networks:+ - trino-net+ container_name: trino-ci-trino+ environment:+ - HADOOP_USER_NAME=root+ - GRAVITINO_HOST_IP=host.docker.internal+ - GRAVITINO_HOST_PORT=${GRAVITINO_SERVER_PORT:-8090}+ - GRAVITINO_METALAKE_NAME=test+ - HIVE_HOST_IP=hive+ entrypoint: /bin/bash /tmp/trino/init.sh+ volumes:+ - ./init/trino:/tmp/trino+ - ../../trino-connector/build/libs:/usr/lib/trino/plugin/gravitino+ extra_hosts:+ - "host.docker.internal:host-gateway"+ healthcheck:+ test: ["CMD", "trino", "--execute", "SELECT 1"]+ interval: 10s+ timeout: 60s+ retries: 5+ depends_on:+ hive:+ condition: service_healthy+ postgresql:+ condition: service_healthy+ mysql:+ condition: service_healthy+++networks:+ trino-net:+ driver: bridge+ name: trino-net+ ipam:+ config:+ - subnet: 10.20.31.16/28diff --git a/integration-test/trino-it/init/hive/init.sh b/integration-test/trino-it/init/hive/init.shnew file mode 100755index 0000000000..5da91155b8--- /dev/null+++ b/integration-test/trino-it/init/hive/init.sh@@ -0,0 +1,9 @@+#+# Copyright 2024 Datastrato Pvt Ltd.+# This software is licensed under the Apache License version 2.+#++IP=$(hostname -I | awk '{print $1}')+sed -i "s|<value>hdfs://localhost:9000|<value>hdfs://${IP}:9000|g" /usr/local/hive/conf/hive-site.xml++/bin/bash /usr/local/sbin/start.shdiff --git a/integration-test/trino-it/init/mysql/init.sql b/integration-test/trino-it/init/mysql/init.sqlnew file mode 100644index 0000000000..5fe4a984d2--- /dev/null+++ b/integration-test/trino-it/init/mysql/init.sql@@ -0,0 +1,6 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+GRANT ALL PRIVILEGES on *.* to 'trino'@'%';+FLUSH PRIVILEGES;diff --git a/integration-test/trino-it/init/postgres/init.sql b/integration-test/trino-it/init/postgres/init.sqlnew file mode 100644index 0000000000..7a94998ac5--- /dev/null+++ b/integration-test/trino-it/init/postgres/init.sql@@ -0,0 +1,5 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+CREATE DATABASE gt_db;diff --git a/integration-test/trino-it/init/trino/init.sh b/integration-test/trino-it/init/trino/init.shnew file mode 100644index 0000000000..f638102ebf--- /dev/null+++ b/integration-test/trino-it/init/trino/init.sh@@ -0,0 +1,22 @@+#+# Copyright 2024 Datastrato Pvt Ltd.+# This software is licensed under the Apache License version 2.+#++/etc/trino/update-trino-conf.sh+nohup /usr/lib/trino/bin/run-trino &++counter=0+while [ $counter -le 300 ]; do+ counter=$((counter + 1))+ trino_ready=$(trino --execute "SHOW CATALOGS LIKE 'gravitino'" | wc -l)+ if [ "$trino_ready" -eq 0 ];+ then+ echo "Wait for the initialization of services"+ sleep 1;+ else+ # persist the container+ tail -f /dev/null+ fi+done+exit 1diff --git a/integration-test/trino-it/init/trino/init.sql b/integration-test/trino-it/init/trino/init.sqlnew file mode 100644index 0000000000..3206c684fa--- /dev/null+++ b/integration-test/trino-it/init/trino/init.sql@@ -0,0 +1,6 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++select 1;diff --git a/integration-test/trino-it/inspect_ip.sh b/integration-test/trino-it/inspect_ip.shnew file mode 100755index 0000000000..b2d539a11c--- /dev/null+++ b/integration-test/trino-it/inspect_ip.sh@@ -0,0 +1,7 @@+#!/bin/bash+#+# Copyright 2024 Datastrato Pvt Ltd.+# This software is licensed under the Apache License version 2.+#++docker inspect --format='{{.Name}}:{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) |grep "/trino-ci-" | sed 's/\/trino-ci-//g'diff --git a/integration-test/trino-it/launch.sh b/integration-test/trino-it/launch.shnew file mode 100755index 0000000000..31574de5b9--- /dev/null+++ b/integration-test/trino-it/launch.sh@@ -0,0 +1,43 @@+#!/bin/bash+#+# Copyright 2024 Datastrato Pvt Ltd.+# This software is licensed under the Apache License version 2.+#+#set -ex+cd "$(dirname "$0")"++playground_dir="$(dirname "${BASH_SOURCE-$0}")"+playground_dir="$(cd "${playground_dir}">/dev/null; pwd)"+isExist=`which docker-compose`+if [ ! $isExist ]+then+ echo "ERROR: No docker service environment found, please install docker-compose first."+ exit+fi++cd ${playground_dir}++docker-compose up -d++if [ -n "$GRAVITINO_LOG_PATH" ]; then+ LOG_PATH=$GRAVITINO_LOG_PATH+else+ LOG_PATH=../build/integration-test.log+fi++echo "The docker-compose log is: $LOG_PATH"++nohup docker-compose logs -f -t >> $LOG_PATH &++max_attempts=180++for ((i = 0; i < max_attempts; i++)); do+ docker-compose exec -T trino trino --execute "SELECT 1" >/dev/null 2>&1 && {+ echo "All docker-compose service is now available."+ exit 0+ }+ sleep 1+done++echo "Trino service did not start within the specified time."+exit 1diff --git a/integration-test/trino-it/shutdown.sh b/integration-test/trino-it/shutdown.shnew file mode 100755index 0000000000..492eff685b--- /dev/null+++ b/integration-test/trino-it/shutdown.sh@@ -0,0 +1,8 @@+#!/bin/bash+#+# Copyright 2024 Datastrato Pvt Ltd.+# This software is licensed under the Apache License version 2.+#+cd "$(dirname "$0")"++docker-compose down