You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gobblin.apache.org by le...@apache.org on 2021/02/04 20:13:13 UTC
[incubator-gobblin] branch master updated: [GOBBLIN-1335] Publish
GMCE(GobblinMetadataChangeEvent) publisher and iceberg retention job to
Gobblin OSS
This is an automated email from the ASF dual-hosted git repository.
lesun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-gobblin.git
The following commit(s) were added to refs/heads/master by this push:
new 4e2dc94 [GOBBLIN-1335] Publish GMCE(GobblinMetadataChangeEvent) publisher and iceberg retention job to Gobblin OSS
4e2dc94 is described below
commit 4e2dc94eb570086c768c247f669255d62f84f3d6
Author: Zihan Li <zi...@linkedin.com>
AuthorDate: Thu Feb 4 12:13:05 2021 -0800
[GOBBLIN-1335] Publish GMCE(GobblinMetadataChangeEvent) publisher and iceberg retention job to Gobblin OSS
[GOBBLIN-1335] Publish
GMCE(GobblinMetadataChangeEvent) publisher and
iceberg retention job to Gobblin OSS
add OSS comments
add unit test
Add icebergWriter to be able to consume GMCE and
register into iceberg table
Make it re-writable for catalog inside
icebergWriter
address comments
trigger build
trigger build
address comments
Merge branch 'master' into GOBBLIN-1335
Merge branch 'master' into GOBBLIN-1335
define iceberg version
address comments
include recent changes
Merge remote-tracking branch 'origin' into
GOBBLIN-1335
Merge remote-tracking branch 'origin' into
GOBBLIN-1335
merge master and modify method privacy level to
make them be re-writable
Closes #3172 from ZihanLi58/GOBBLIN-1335
---
conf/aws/application.conf | 2 +-
gobblin-all/build.gradle | 1 +
.../gobblin/configuration/ConfigurationKeys.java | 6 +
gobblin-compaction/build.gradle | 1 +
.../action/CompactionGMCEPublishingAction.java | 121 +++
.../action/CompactionGMCEPublishingActionTest.java | 169 +++++
gobblin-data-management/build.gradle | 2 +
.../retention/dataset/CleanableIcebergDataset.java | 166 ++++
.../ManagedIcebergCleanableDatasetFinder.java | 62 ++
gobblin-iceberg/build.gradle | 58 ++
.../apache/gobblin/iceberg/GobblinMCEProducer.java | 256 +++++++
.../apache/gobblin/iceberg/Utils/IcebergUtils.java | 301 ++++++++
.../iceberg/Utils/TypeInfoToSchemaParser.java | 294 ++++++++
.../iceberg/publisher/GobblinMCEPublisher.java | 188 +++++
.../gobblin/iceberg/writer/GobblinMCEWriter.java | 311 ++++++++
.../iceberg/writer/GobblinMCEWriterBuilder.java | 33 +
.../iceberg/writer/IcebergMCEMetadataKeys.java | 37 +
.../iceberg/writer/IcebergMetadataWriter.java | 838 +++++++++++++++++++++
.../gobblin/iceberg/writer/MetadataWriter.java | 43 ++
.../iceberg/publisher/GobblinMCEPublisherTest.java | 268 +++++++
.../iceberg/writer/GobblinMCEWriterTest.java | 270 +++++++
.../src/test/resources/publisherTest/data.json | 8 +
.../src/test/resources/publisherTest/schema.avsc | 15 +
.../src/main/avro/DatasetIdentifier.avsc | 39 +
.../src/main/avro/GobblinMetadataChangeEvent.avsc | 281 +++++++
gobblin-modules/gobblin-kafka-common/build.gradle | 11 +
gradle/scripts/defaultBuildProperties.gradle | 2 +
gradle/scripts/dependencyDefinitions.gradle | 1 +
maven-nexus/upload-to-nexus.sh | 2 +-
maven-sonatype/upload-to-sonatype.sh | 2 +-
settings.gradle | 1 +
31 files changed, 3786 insertions(+), 3 deletions(-)
diff --git a/conf/aws/application.conf b/conf/aws/application.conf
index 33b5570..5b08507 100644
--- a/conf/aws/application.conf
+++ b/conf/aws/application.conf
@@ -159,7 +159,7 @@ gobblin.aws.master.s3.jars.uri="https://s3-us-west-2.amazonaws.com/gobblin-libs/
## All Gobblin Jars and Configuration on S3
gobblin.aws.master.s3.conf.files="application.conf,log4j.properties,quartz.properties"
gobblin.aws.master.s3.jars.uri="https://s3-us-west-2.amazonaws.com/gobblin-libs/latest-jars/"
-gobblin.aws.master.s3.jars.files="ST4-4.0.4.jar,activation-1.1.1.jar,annotations-2.0.1.jar,ant-1.9.1.jar,ant-launcher-1.9.1.jar,antlr-runtime-3.5.2.jar,aopalliance-1.0.jar,apache-log4j-extras-1.2.17.jar,asm-3.1.jar,asm-commons-3.1.jar,asm-tree-3.1.jar,avro-1.7.7.jar,avro-ipc-1.7.7-tests.jar,avro-ipc-1.7.7.jar,avro-mapred-1.7.7-hadoop2.jar,aws-java-sdk-applicationautoscaling-1.11.8.jar,aws-java-sdk-autoscaling-1.11.8.jar,aws-java-sdk-core-1.11.8.jar,aws-java-sdk-ec2-1.11.8.jar,aws-java-sd [...]
+gobblin.aws.master.s3.jars.files="ST4-4.0.4.jar,activation-1.1.1.jar,annotations-2.0.1.jar,ant-1.9.1.jar,ant-launcher-1.9.1.jar,antlr-runtime-3.5.2.jar,aopalliance-1.0.jar,apache-log4j-extras-1.2.17.jar,asm-3.1.jar,asm-commons-3.1.jar,asm-tree-3.1.jar,avro-1.7.7.jar,avro-ipc-1.7.7-tests.jar,avro-ipc-1.7.7.jar,avro-mapred-1.7.7-hadoop2.jar,aws-java-sdk-applicationautoscaling-1.11.8.jar,aws-java-sdk-autoscaling-1.11.8.jar,aws-java-sdk-core-1.11.8.jar,aws-java-sdk-ec2-1.11.8.jar,aws-java-sd [...]
gobblin.aws.worker.s3.conf.uri=${gobblin.aws.master.s3.conf.uri}
gobblin.aws.worker.s3.conf.files=${gobblin.aws.master.s3.conf.files}
diff --git a/gobblin-all/build.gradle b/gobblin-all/build.gradle
index 62cdc71..1eb480e 100644
--- a/gobblin-all/build.gradle
+++ b/gobblin-all/build.gradle
@@ -53,6 +53,7 @@ dependencies {
compile project(':gobblin-modules:gobblin-grok')
compile project(':gobblin-modules:gobblin-helix')
compile project(':gobblin-hive-registration')
+ compile project(':gobblin-iceberg')
compile project(':gobblin-modules:gobblin-http')
compile project(':gobblin-modules:gobblin-kafka-08')
//gobblin-kafka-09 is blacklisted for jacocoBuilds. check settings.xml
diff --git a/gobblin-api/src/main/java/org/apache/gobblin/configuration/ConfigurationKeys.java b/gobblin-api/src/main/java/org/apache/gobblin/configuration/ConfigurationKeys.java
index b86860d..abff79e 100644
--- a/gobblin-api/src/main/java/org/apache/gobblin/configuration/ConfigurationKeys.java
+++ b/gobblin-api/src/main/java/org/apache/gobblin/configuration/ConfigurationKeys.java
@@ -1052,6 +1052,12 @@ public class ConfigurationKeys {
"org.apache.gobblin.util.schema_check.AvroSchemaCheckDefaultStrategy";
/**
+ * Configuration and constant vale for GobblinMetadataChangeEvent
+ */
+ public static final String LIST_DELIMITER_KEY = ",";
+ public static final String RANGE_DELIMITER_KEY = "-";
+
+ /**
* Configuration for emitting task events
*/
public static final String TASK_EVENT_METADATA_GENERATOR_CLASS_KEY = "gobblin.task.event.metadata.generator.class";
diff --git a/gobblin-compaction/build.gradle b/gobblin-compaction/build.gradle
index d24019f..672bcbc 100644
--- a/gobblin-compaction/build.gradle
+++ b/gobblin-compaction/build.gradle
@@ -24,6 +24,7 @@ dependencies {
compile project(":gobblin-metrics-libs:gobblin-metrics")
compile project(":gobblin-core")
compile project(":gobblin-data-management")
+ compile project(":gobblin-iceberg")
compile project(":gobblin-runtime")
compile project(":gobblin-modules:gobblin-kafka-common")
compile externalDependency.orcMapreduce
diff --git a/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/action/CompactionGMCEPublishingAction.java b/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/action/CompactionGMCEPublishingAction.java
new file mode 100644
index 0000000..ad555c8
--- /dev/null
+++ b/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/action/CompactionGMCEPublishingAction.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.compaction.action;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.gobblin.compaction.mapreduce.CompactionJobConfigurator;
+import org.apache.gobblin.compaction.parser.CompactionPathParser;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.configuration.WorkUnitState;
+import org.apache.gobblin.dataset.FileSystemDataset;
+import org.apache.gobblin.iceberg.GobblinMCEProducer;
+import org.apache.gobblin.iceberg.Utils.IcebergUtils;
+import org.apache.gobblin.iceberg.publisher.GobblinMCEPublisher;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metadata.SchemaSource;
+import org.apache.gobblin.metrics.event.EventSubmitter;
+import org.apache.gobblin.util.HadoopUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.avro.AvroSchemaUtil;
+import org.apache.iceberg.mapping.MappingUtil;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.orc.ORCSchemaUtil;
+import org.apache.iceberg.shaded.org.apache.orc.TypeDescription;
+import org.apache.orc.OrcConf;
+
+
+/**
+ * Class responsible for emitting GMCE after compaction is complete
+ */
+@Slf4j
+public class CompactionGMCEPublishingAction implements CompactionCompleteAction<FileSystemDataset> {
+
+ public static final String ICEBERG_ID_ATTRIBUTE = "iceberg.id";
+ public static final String ICEBERG_REQUIRED_ATTRIBUTE = "iceberg.required";
+ private final State state;
+ private final CompactionJobConfigurator configurator;
+ private final Configuration conf;
+ private EventSubmitter eventSubmitter;
+
+ public CompactionGMCEPublishingAction(State state, CompactionJobConfigurator configurator) {
+ if (!(state instanceof WorkUnitState)) {
+ throw new UnsupportedOperationException(this.getClass().getName() + " only supports workunit state");
+ }
+ this.state = state;
+ this.configurator = configurator;
+ this.conf = HadoopUtils.getConfFromState(state);
+ }
+
+ public void onCompactionJobComplete(FileSystemDataset dataset) throws IOException {
+ if (dataset.isVirtual()) {
+ return;
+ }
+ try (GobblinMCEProducer producer = GobblinMCEProducer.getGobblinMCEProducer(state)) {
+
+ CompactionPathParser.CompactionParserResult result = new CompactionPathParser(state).parse(dataset);
+ String datasetDir = Joiner.on("/").join(result.getDstBaseDir(), result.getDatasetName());
+ state.setProp(ConfigurationKeys.DATA_PUBLISHER_DATASET_DIR, datasetDir);
+ producer.sendGMCE(getNewFileMetrics(result), null, Lists.newArrayList(this.configurator.getOldFiles()), null,
+ OperationType.rewrite_files, SchemaSource.NONE);
+ }
+ //clear old files to release memory
+ this.configurator.getOldFiles().clear();
+ }
+
+ private Map<Path, Metrics> getNewFileMetrics(CompactionPathParser.CompactionParserResult result) {
+ NameMapping mapping = null;
+ try {
+ if (IcebergUtils.getIcebergFormat(state) == FileFormat.ORC) {
+ String s =
+ this.configurator.getConfiguredJob().getConfiguration().get(OrcConf.MAPRED_OUTPUT_SCHEMA.getAttribute());
+ TypeDescription orcSchema = TypeDescription.fromString(s);
+ for (int i = 0; i <= orcSchema.getMaximumId(); i++) {
+ orcSchema.findSubtype(i).setAttribute(ICEBERG_ID_ATTRIBUTE, Integer.toString(i));
+ orcSchema.findSubtype(i).setAttribute(ICEBERG_REQUIRED_ATTRIBUTE, Boolean.toString(true));
+ }
+ Schema icebergSchema = ORCSchemaUtil.convert(orcSchema);
+ state.setProp(GobblinMCEPublisher.AVRO_SCHEMA_WITH_ICEBERG_ID,
+ AvroSchemaUtil.convert(icebergSchema.asStruct()).toString());
+ mapping = MappingUtil.create(icebergSchema);
+ }
+ } catch (Exception e) {
+ log.warn(
+ "Table {} contains complex union type which is not compatible with iceberg, will not calculate the metrics for it",
+ result.getDatasetName());
+ }
+ Map<Path, Metrics> newFiles = new HashMap<>();
+ for (Path filePath : this.configurator.getDstNewFiles()) {
+ newFiles.put(filePath, GobblinMCEPublisher.getMetrics(state, filePath, conf, mapping));
+ }
+ return newFiles;
+ }
+
+ public void addEventSubmitter(EventSubmitter submitter) {
+ this.eventSubmitter = submitter;
+ }
+}
diff --git a/gobblin-compaction/src/test/java/org/apache/gobblin/compaction/action/CompactionGMCEPublishingActionTest.java b/gobblin-compaction/src/test/java/org/apache/gobblin/compaction/action/CompactionGMCEPublishingActionTest.java
new file mode 100644
index 0000000..99b045c
--- /dev/null
+++ b/gobblin-compaction/src/test/java/org/apache/gobblin/compaction/action/CompactionGMCEPublishingActionTest.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.compaction.action;
+
+import com.google.common.base.Optional;
+import com.google.common.io.Files;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import org.apache.avro.Schema;
+import org.apache.avro.SchemaBuilder;
+import org.apache.avro.file.DataFileWriter;
+import org.apache.avro.generic.GenericDatumWriter;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.generic.GenericRecordBuilder;
+import org.apache.gobblin.compaction.dataset.TimeBasedSubDirDatasetsFinder;
+import org.apache.gobblin.compaction.mapreduce.MRCompactor;
+import org.apache.gobblin.compaction.source.CompactionSource;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.data.management.retention.profile.ConfigurableGlobDatasetFinder;
+import org.apache.gobblin.iceberg.GobblinMCEProducer;
+import org.apache.gobblin.metadata.GobblinMetadataChangeEvent;
+import org.apache.gobblin.runtime.api.JobExecutionResult;
+import org.apache.gobblin.runtime.embedded.EmbeddedGobblin;
+import org.apache.hadoop.fs.Path;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+
+public class CompactionGMCEPublishingActionTest {
+ @Test
+ public void testDedup() throws Exception {
+
+ File basePath = Files.createTempDir();
+ basePath.deleteOnExit();
+
+ File jobDir = new File(basePath, "Identity/MemberAccount/minutely/2017/04/03/10/20_30/run_2017-04-03-10-20");
+ Assert.assertTrue(jobDir.mkdirs());
+
+ GenericRecord r1 = createRandomRecord();
+ GenericRecord r2 = createRandomRecord();
+ GenericRecord r3 = createEvolvedSchemaRecord();
+ writeFileWithContent(jobDir, "file1", r1, 20);
+ writeFileWithContent(jobDir, "file2", r2, 18);
+ File newestFile = writeFileWithContent(jobDir, "file3", r3, 10, r3.getSchema());
+ newestFile.setLastModified(Long.MAX_VALUE);
+
+ EmbeddedGobblin embeddedGobblin = createEmbeddedGobblin("dedup", basePath.getAbsolutePath().toString());
+ JobExecutionResult result = embeddedGobblin.run();
+ Assert.assertTrue(result.isSuccessful());
+ }
+
+ public GenericRecord createEvolvedSchemaRecord() {
+ Schema evolvedSchema = SchemaBuilder.record("evolved")
+ .fields()
+ .requiredLong("partitionKey")
+ .requiredString("environment")
+ .requiredString("subKey")
+ .optionalString("oppo")
+ .endRecord();
+ GenericRecordBuilder keyRecordBuilder = new GenericRecordBuilder(evolvedSchema);
+ keyRecordBuilder.set("partitionKey", new Long(1));
+ keyRecordBuilder.set("environment", "test");
+ keyRecordBuilder.set("subKey", "2");
+ keyRecordBuilder.set("oppo", "poop");
+ return keyRecordBuilder.build();
+ }
+
+ // Returning file handler for setting modfication time.
+ private File writeFileWithContent(File dir, String fileName, GenericRecord r, int count) throws IOException {
+ File file = new File(dir, fileName + "." + count + ".avro");
+ Assert.assertTrue(file.createNewFile());
+ this.createAvroFileWithRepeatingRecords(file, r, count, Optional.absent());
+ return file;
+ }
+
+ private File writeFileWithContent(File dir, String fileName, GenericRecord r, int count, Schema schema)
+ throws IOException {
+ File file = new File(dir, fileName + "." + count + ".avro");
+ Assert.assertTrue(file.createNewFile());
+ this.createAvroFileWithRepeatingRecords(file, r, count, Optional.of(schema));
+ return file;
+ }
+
+ public void createAvroFileWithRepeatingRecords(File file, GenericRecord r, int count, Optional<Schema> schema)
+ throws IOException {
+ DataFileWriter<GenericRecord> writer = new DataFileWriter<>(new GenericDatumWriter<GenericRecord>());
+ writer.create(schema.isPresent() ? schema.get() : getSchema(), new FileOutputStream(file));
+ for (int i = 0; i < count; ++i) {
+ writer.append(r);
+ }
+ writer.close();
+ }
+
+ public GenericRecord createRandomRecord() {
+ GenericRecordBuilder keyRecordBuilder = new GenericRecordBuilder(getSchema());
+ keyRecordBuilder.set("partitionKey", new Long(1));
+ keyRecordBuilder.set("environment", "test");
+ keyRecordBuilder.set("subKey", "2");
+ GenericRecord record = keyRecordBuilder.build();
+ return record;
+ }
+
+ public Schema getSchema() {
+ final String KEY_SCHEMA =
+ "{ \"type\" : \"record\", \"name\" : \"etl\",\"namespace\" : \"reducerTest\", \"fields\" : [ { \"name\" : "
+ + "\"key\", \"type\" : {\"type\" : \"record\", \"name\" : \"key_name\", \"namespace\" : \"key_namespace\", "
+ + "\"fields\" : [ {\"name\" : \"partitionKey\", \"type\" : \"long\", \"doc\" : \"\"}, { \"name\" : \"environment"
+ + "\", \"type\" : \"string\",\"doc\" : \"\"}, {\"name\" : \"subKey\",\"type\" : \"string\", \"doc\" : \"\"} ]}, "
+ + "\"doc\" : \"\", \"attributes_json\" : \"{\\\"delta\\\":false,\\\"pk\\\":true}\" }]}";
+ Schema keySchema = new Schema.Parser().parse(KEY_SCHEMA);
+ return keySchema.getField("key").schema();
+ }
+
+ static EmbeddedGobblin createEmbeddedGobblin(String name, String basePath) {
+ String pattern = new Path(basePath, "*/*/minutely/*/*/*/*").toString();
+
+ return new EmbeddedGobblin(name).setConfiguration(ConfigurationKeys.SOURCE_CLASS_KEY,
+ CompactionSource.class.getName())
+ .setConfiguration(ConfigurableGlobDatasetFinder.DATASET_FINDER_PATTERN_KEY, pattern)
+ .setConfiguration(MRCompactor.COMPACTION_INPUT_DIR, basePath.toString())
+ .setConfiguration(MRCompactor.COMPACTION_INPUT_SUBDIR, "minutely")
+ .setConfiguration(MRCompactor.COMPACTION_DEST_DIR, basePath.toString())
+ .setConfiguration(MRCompactor.COMPACTION_DEST_SUBDIR, "hourly")
+ .setConfiguration(MRCompactor.COMPACTION_TMP_DEST_DIR, "/tmp/compaction/" + name)
+ .setConfiguration(TimeBasedSubDirDatasetsFinder.COMPACTION_TIMEBASED_MAX_TIME_AGO, "3000d")
+ .setConfiguration(TimeBasedSubDirDatasetsFinder.COMPACTION_TIMEBASED_MIN_TIME_AGO, "1d")
+ .setConfiguration(ConfigurationKeys.MAX_TASK_RETRIES_KEY, "0")
+ .setConfiguration("compaction.suite.factory",
+ "org.apache.gobblin.compaction.suite.CompactionSuiteBaseWithConfigurableCompleteActionFactory")
+ .setConfiguration("compaction.complete.actions",
+ "org.apache.gobblin.compaction.action.CompactionCompleteFileOperationAction, org.apache.gobblin.compaction.action.CompactionGMCEPublishingAction, org.apache.gobblin.compaction.action.CompactionMarkDirectoryAction")
+ .setConfiguration("old.files.hive.registration.policy",
+ "org.apache.gobblin.hive.policy.HiveRegistrationPolicyBase")
+ .setConfiguration("writer.output.format", "AVRO")
+ .setConfiguration(GobblinMCEProducer.GMCE_PRODUCER_CLASS, GobblinMCETestProducer.class.getName())
+ .setConfiguration("hive.registration.policy", "com.linkedin.gobblin.hive.policy.LiHiveDailyRegistrationPolicy");
+ }
+
+ public static class GobblinMCETestProducer extends GobblinMCEProducer {
+ public GobblinMCETestProducer(State state) {
+ super(state);
+ }
+
+ @Override
+ public void underlyingSendGMCE(GobblinMetadataChangeEvent gmce) {
+ System.out.println(gmce);
+ Assert.assertEquals(gmce.getNewFiles().size(), 1);
+ Assert.assertNotEquals(gmce.getOldFilePrefixes().size(), 0);
+ }
+ }
+
+}
diff --git a/gobblin-data-management/build.gradle b/gobblin-data-management/build.gradle
index d7eb3fc..0b57b0a 100644
--- a/gobblin-data-management/build.gradle
+++ b/gobblin-data-management/build.gradle
@@ -21,11 +21,13 @@ dependencies {
compile project(":gobblin-api")
compile project(":gobblin-core")
compile project(":gobblin-hive-registration")
+ compile project(":gobblin-iceberg")
compile project(":gobblin-metrics-libs:gobblin-metrics")
compile project(":gobblin-runtime")
compile project(":gobblin-utility")
compile project(":gobblin-config-management:gobblin-config-client")
compile project(":gobblin-config-management:gobblin-config-core")
+ compile externalDependency.avro
compile externalDependency.commonsLang
compile externalDependency.commonsLang3
compile externalDependency.guava
diff --git a/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/dataset/CleanableIcebergDataset.java b/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/dataset/CleanableIcebergDataset.java
new file mode 100644
index 0000000..c351ef1
--- /dev/null
+++ b/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/dataset/CleanableIcebergDataset.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.data.management.retention.dataset;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.typesafe.config.Config;
+import com.typesafe.config.ConfigFactory;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.data.management.policy.VersionSelectionPolicy;
+import org.apache.gobblin.data.management.version.FileSystemDatasetVersion;
+import org.apache.gobblin.data.management.version.finder.VersionFinder;
+import org.apache.gobblin.hive.policy.HiveRegistrationPolicyBase;
+import org.apache.gobblin.iceberg.GobblinMCEProducer;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metadata.SchemaSource;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A subclass of {@link ConfigurableCleanableDataset} that overwrite the {@link ConfigurableCleanableDataset#cleanImpl(Collection)}
+ * to firstly send gmce to delete dataset logically from iceberg and then
+ * call {@link org.apache.iceberg.Table#expireSnapshots()} to do physically data and metadata retention
+ */
+public class CleanableIcebergDataset<T extends FileSystemDatasetVersion> extends ConfigurableCleanableDataset<T> {
+ private final static String RETENTION_INTERVAL_TIME = "retention.interval.time";
+ private final static String DEFAULT_RETENTION_INTERVAL_TIME = "10000";
+ protected Config config;
+ protected Properties jobProps;
+ Set<TableIdentifier> expiredTable;
+
+ public CleanableIcebergDataset(FileSystem fs, Properties jobProps, Path datasetRoot, Config config, Logger log)
+ throws IOException {
+ super(fs, jobProps, datasetRoot, config, log);
+ this.config = config;
+ this.jobProps = jobProps;
+ this.expiredTable = new HashSet<>();
+ }
+
+ public CleanableIcebergDataset(FileSystem fs, Properties props, Path datasetRoot) throws IOException {
+ this(fs, props, datasetRoot, LoggerFactory.getLogger(CleanableIcebergDataset.class));
+ }
+
+ public CleanableIcebergDataset(FileSystem fs, Properties props, Path datasetRoot, Logger log) throws IOException {
+ this(fs, props, datasetRoot, ConfigFactory.parseProperties(props), log);
+ }
+
+ @Override
+ public void clean() throws IOException {
+
+ if (this.isDatasetBlacklisted) {
+ this.log.info("Dataset blacklisted. Cleanup skipped for " + datasetRoot());
+ return;
+ }
+
+ boolean atLeastOneFailureSeen = false;
+
+ for (VersionFinderAndPolicy<T> versionFinderAndPolicy : getVersionFindersAndPolicies()) {
+ Config retentionConfig = versionFinderAndPolicy.getConfig();
+ Preconditions.checkArgument(retentionConfig != null,
+ "Must specify retention config for iceberg dataset retention");
+ VersionSelectionPolicy<T> selectionPolicy = versionFinderAndPolicy.getVersionSelectionPolicy();
+ VersionFinder<? extends T> versionFinder = versionFinderAndPolicy.getVersionFinder();
+
+ if (!selectionPolicy.versionClass().isAssignableFrom(versionFinder.versionClass())) {
+ throw new IOException("Incompatible dataset version classes.");
+ }
+
+ this.log.info(String.format("Cleaning dataset %s. Using version finder %s and policy %s", this,
+ versionFinder.getClass().getName(), selectionPolicy));
+
+ List<T> versions = Lists.newArrayList(versionFinder.findDatasetVersions(this));
+
+ if (versions.isEmpty()) {
+ this.log.warn("No dataset version can be found. Ignoring.");
+ continue;
+ }
+
+ Collections.sort(versions, Collections.reverseOrder());
+
+ Collection<T> deletableVersions = selectionPolicy.listSelectedVersions(versions);
+
+ cleanImpl(deletableVersions, retentionConfig);
+ }
+
+ if (atLeastOneFailureSeen) {
+ throw new RuntimeException(
+ String.format("At least one failure happened while processing %s. Look for previous logs for failures",
+ datasetRoot()));
+ }
+ try {
+ // Sleep for a while to make sure metadata pipeline won't get bunch of retention events at the same time, which will
+ // affect the SLA of retention pipeline
+ Thread.sleep(Long.parseLong(jobProps.getProperty(RETENTION_INTERVAL_TIME, DEFAULT_RETENTION_INTERVAL_TIME)));
+ } catch (InterruptedException e) {
+ log.error("interrupted while sleep");
+ throw new IOException(e);
+ }
+ }
+
+ protected void cleanImpl(Collection<T> deletableVersions, Config retentionConfig) throws IOException {
+ List<String> deletablePrefix = new ArrayList<>();
+ for (T version : deletableVersions) {
+ version.getPaths().forEach(p -> deletablePrefix.add(fs.makeQualified(p).toString()));
+ }
+ if (deletablePrefix.isEmpty()) {
+ return;
+ }
+ Preconditions.checkArgument(retentionConfig.hasPath(ConfigurationKeys.HIVE_REGISTRATION_POLICY));
+ Preconditions.checkArgument(retentionConfig.hasPath(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME));
+
+ Properties prop = new Properties();
+ prop.putAll(jobProps);
+ State producerState = new State(prop);
+ producerState.setProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY,
+ retentionConfig.getString(ConfigurationKeys.HIVE_REGISTRATION_POLICY));
+ producerState.setProp(GobblinMCEProducer.OLD_FILES_HIVE_REGISTRATION_KEY,
+ retentionConfig.getString(ConfigurationKeys.HIVE_REGISTRATION_POLICY));
+ producerState.setProp(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME,
+ retentionConfig.getString(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME));
+ if (retentionConfig.hasPath(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_DATABASE_NAMES)) {
+ producerState.setProp(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_DATABASE_NAMES,
+ retentionConfig.getString(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_DATABASE_NAMES));
+ }
+ producerState.setProp(ConfigurationKeys.DATA_PUBLISHER_DATASET_DIR, this.datasetURN());
+ if (!this.simulate) {
+ try (GobblinMCEProducer producer = GobblinMCEProducer.getGobblinMCEProducer(producerState)) {
+ producer.sendGMCE(null, null, deletablePrefix, null, OperationType.drop_files, SchemaSource.NONE);
+ log.info("Sent gmce to delete path {} from icebergTable",
+ deletablePrefix.stream().map(Object::toString).collect(Collectors.joining(",")));
+ }
+ } else {
+ log.info("In simulate mode, going to send gmce to delete path {} from icebergTable",
+ deletablePrefix.stream().map(Object::toString).collect(Collectors.joining(",")));
+ }
+ }
+}
diff --git a/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/profile/ManagedIcebergCleanableDatasetFinder.java b/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/profile/ManagedIcebergCleanableDatasetFinder.java
new file mode 100644
index 0000000..a2684e4
--- /dev/null
+++ b/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/profile/ManagedIcebergCleanableDatasetFinder.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.data.management.retention.profile;
+
+import com.typesafe.config.Config;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.Properties;
+import org.apache.gobblin.config.client.ConfigClient;
+import org.apache.gobblin.config.client.ConfigClientCache;
+import org.apache.gobblin.config.client.api.ConfigStoreFactoryDoesNotExistsException;
+import org.apache.gobblin.config.client.api.VersionStabilityPolicy;
+import org.apache.gobblin.config.store.api.ConfigStoreCreationException;
+import org.apache.gobblin.config.store.api.VersionDoesNotExistException;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.data.management.retention.dataset.ConfigurableCleanableDataset;
+import org.apache.gobblin.data.management.version.FileSystemDatasetVersion;
+import org.apache.gobblin.data.management.retention.dataset.CleanableIcebergDataset;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.slf4j.LoggerFactory;
+
+
+public class ManagedIcebergCleanableDatasetFinder extends ManagedCleanableDatasetFinder {
+ private final static String ICEBERG_CONFIG_PREFIX = "/iceberg";
+ private final ConfigClient client;
+
+ public ManagedIcebergCleanableDatasetFinder(FileSystem fs, Properties jobProps, Config config) {
+ this(fs, jobProps, config, ConfigClientCache.getClient(VersionStabilityPolicy.STRONG_LOCAL_STABILITY));
+ }
+
+ public ManagedIcebergCleanableDatasetFinder(FileSystem fs, Properties jobProps, Config config, ConfigClient client) {
+ super(fs, jobProps, config, client);
+ this.client = client;
+ }
+
+ @Override
+ public ConfigurableCleanableDataset<FileSystemDatasetVersion> datasetAtPath(Path path) throws IOException {
+ try {
+ return new CleanableIcebergDataset<>(this.fs, this.props, path,
+ this.client.getConfig(this.props.getProperty(ConfigurationKeys.CONFIG_MANAGEMENT_STORE_URI) + ICEBERG_CONFIG_PREFIX + path.toString()),
+ LoggerFactory.getLogger(CleanableIcebergDataset.class));
+ } catch (ConfigStoreFactoryDoesNotExistsException | ConfigStoreCreationException | URISyntaxException | VersionDoesNotExistException var3) {
+ throw new IllegalArgumentException(var3);
+ }
+ }
+}
diff --git a/gobblin-iceberg/build.gradle b/gobblin-iceberg/build.gradle
new file mode 100644
index 0000000..81bb564
--- /dev/null
+++ b/gobblin-iceberg/build.gradle
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+apply plugin: 'java'
+
+dependencies {
+ compile project(":gobblin-api")
+ compile project(":gobblin-core")
+ compile project(":gobblin-hive-registration")
+ compile project(":gobblin-metrics-libs:gobblin-metrics")
+ compile project(":gobblin-modules:gobblin-kafka-common")
+ compile project(":gobblin-modules:gobblin-orc")
+ compile project(":gobblin-utility")
+
+ compile externalDependency.azkaban
+ compile externalDependency.datanucleusCore
+ compile externalDependency.datanucleusRdbms
+ compile externalDependency.guava
+ compile externalDependency.hiveCommon
+ compile externalDependency.hiveExec
+
+ compile externalDependency.hiveMetastore
+ compile externalDependency.hiveSerDe
+ compile (externalDependency.icebergHive) {
+ exclude group:'org.apache.avro', module:'avro'
+ }
+ compile externalDependency.avro
+ compile externalDependency.libthrift
+ compile externalDependency.slf4j
+ compile externalDependency.commonsIo
+ compile externalDependency.commonsLang3
+ compile externalDependency.commonsPool
+ compile externalDependency.findBugsAnnotations
+ compile externalDependency.avroMapredH2
+
+ testCompile(group: 'org.apache.iceberg', name: 'iceberg-hive-metastore', version: '0.10.0', classifier: 'tests') {
+ transitive = false
+ }
+ testCompile project(path: ':gobblin-modules:gobblin-kafka-common', configuration: 'tests')
+ testCompile externalDependency.testng
+ testCompile externalDependency.mockito
+}
+
+ext.classification="library"
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/GobblinMCEProducer.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/GobblinMCEProducer.java
new file mode 100644
index 0000000..76b276a
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/GobblinMCEProducer.java
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg;
+
+import azkaban.jobExecutor.AbstractJob;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.hive.policy.HiveRegistrationPolicyBase;
+import org.apache.gobblin.iceberg.Utils.IcebergUtils;
+import org.apache.gobblin.iceberg.publisher.GobblinMCEPublisher;
+import org.apache.gobblin.instrumented.Instrumented;
+import org.apache.gobblin.metadata.DataFile;
+import org.apache.gobblin.metadata.DataMetrics;
+import org.apache.gobblin.metadata.DataOrigin;
+import org.apache.gobblin.metadata.DatasetIdentifier;
+import org.apache.gobblin.metadata.GobblinMetadataChangeEvent;
+import org.apache.gobblin.metadata.IntegerBytesPair;
+import org.apache.gobblin.metadata.IntegerLongPair;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metadata.SchemaSource;
+import org.apache.gobblin.metrics.MetricContext;
+import org.apache.gobblin.util.ClustersNames;
+import org.apache.gobblin.util.reflection.GobblinConstructorUtils;
+import org.apache.gobblin.writer.PartitionedDataWriter;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.Metrics;
+
+
+/**
+ * A class running along with data ingestion pipeline for emitting GobblinMCE (Gobblin Metadata Change Event
+ * that includes the information of the file metadata change, i.e., add or delete file, and the column min/max value of the added file.
+ * GMCE will be consumed by another metadata ingestion pipeline to register/de-register hive/iceberg metadata)
+ *
+ * This is an abstract class, we need a sub system like Kakfa, which support at least once delivery, to emit the event
+ */
+@Slf4j
+public abstract class GobblinMCEProducer implements Closeable {
+
+ public static final String GMCE_PRODUCER_CLASS = "GobblinMCEProducer.class.name";
+ public static final String OLD_FILES_HIVE_REGISTRATION_KEY = "old.files.hive.registration.policy";
+ public static final String HIVE_PARTITION_NAME = "hive.partition.name";
+ private static final String HDFS_PLATFORM_URN = "urn:li:dataPlatform:hdfs";
+ private static final String DATASET_ORIGIN_KEY = "dataset.origin";
+ private static final String DEFAULT_DATASET_ORIGIN = "PROD";
+
+ @Setter
+ protected State state;
+ protected MetricContext metricContext;
+
+ public GobblinMCEProducer(State state) {
+ this.state = state;
+ this.metricContext = Instrumented.getMetricContext(state, this.getClass());
+ }
+
+
+ /**
+ * This method will use the files to compute the table name and dataset name, for each table it will generate one GMCE and send that to kafka so
+ * the metadata ingestion pipeline can use the information to register metadata
+ * @param newFiles The map of new files' path and metrics
+ * @param oldFiles the list of old file to be dropped
+ * @param offsetRange offset range of the new data, can be null
+ * @param operationType The opcode of gmce emitted by this method.
+ * @throws IOException
+ */
+ public void sendGMCE(Map<Path, Metrics> newFiles, List<String> oldFiles, List<String> oldFilePrefixes,
+ Map<String, String> offsetRange, OperationType operationType, SchemaSource schemaSource) throws IOException {
+ GobblinMetadataChangeEvent gmce =
+ getGobblinMetadataChangeEvent(newFiles, oldFiles, oldFilePrefixes, offsetRange, operationType, schemaSource);
+ underlyingSendGMCE(gmce);
+ }
+
+ /**
+ * Use the producer to send GMCE, the implementation need to make sure the emitting is at-least once in-order delivery
+ * (i.e. use kafka producer to send event and config it to be at-least once delivery)
+ * @param gmce GMCE that contains information of the metadata change
+ */
+ public abstract void underlyingSendGMCE(GobblinMetadataChangeEvent gmce);
+
+ private void setBasicInformationForGMCE(GobblinMetadataChangeEvent.Builder gmceBuilder,
+ Map<String, String> offsetRange, SchemaSource schemaSource) {
+ String origin = state.getProp(DATASET_ORIGIN_KEY, DEFAULT_DATASET_ORIGIN);
+ gmceBuilder.setDatasetIdentifier(DatasetIdentifier.newBuilder()
+ .setDataPlatformUrn(HDFS_PLATFORM_URN)
+ .setDataOrigin(DataOrigin.valueOf(origin))
+ .setNativeName(state.getProp(ConfigurationKeys.DATA_PUBLISHER_DATASET_DIR))
+ .build());
+ gmceBuilder.setCluster(ClustersNames.getInstance().getClusterName());
+ //retention job does not have job.id
+ gmceBuilder.setFlowId(
+ state.getProp(AbstractJob.JOB_ID, new Configuration().get(ConfigurationKeys.AZKABAN_FLOW_ID)));
+ gmceBuilder.setRegistrationPolicy(state.getProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY));
+ gmceBuilder.setSchemaSource(schemaSource);
+ gmceBuilder.setPartitionColumns(Lists.newArrayList(state.getProp(HIVE_PARTITION_NAME, "")));
+ if (offsetRange != null) {
+ gmceBuilder.setTopicPartitionOffsetsRange(offsetRange);
+ }
+ String schemaString = state.getProp(PartitionedDataWriter.WRITER_LATEST_SCHEMA);
+ if (schemaString != null) {
+ gmceBuilder.setTableSchema(schemaString);
+ }
+ if (state.contains(GobblinMCEPublisher.AVRO_SCHEMA_WITH_ICEBERG_ID)) {
+ gmceBuilder.setAvroSchemaWithIcebergSchemaID(state.getProp(GobblinMCEPublisher.AVRO_SCHEMA_WITH_ICEBERG_ID));
+ }
+ if (state.contains(OLD_FILES_HIVE_REGISTRATION_KEY)) {
+ gmceBuilder.setRegistrationPolicyForOldData(state.getProp(OLD_FILES_HIVE_REGISTRATION_KEY));
+ } else {
+ log.warn(
+ "properties {} does not set, if it's for rewrite/drop operation, there may be trouble to get partition value for old data",
+ OLD_FILES_HIVE_REGISTRATION_KEY);
+ }
+ Map<String, String> regProperties = new HashMap<>();
+ if (state.contains(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME)) {
+ regProperties.put(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME,
+ state.getProp(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME));
+ }
+ if (state.contains(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_DATABASE_NAMES)) {
+ regProperties.put(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_DATABASE_NAMES,
+ state.getProp(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_DATABASE_NAMES));
+ }
+ if (state.contains(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_TABLE_NAMES)) {
+ regProperties.put(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_TABLE_NAMES,
+ state.getProp(HiveRegistrationPolicyBase.ADDITIONAL_HIVE_TABLE_NAMES));
+ }
+ if (!regProperties.isEmpty()) {
+ gmceBuilder.setRegistrationProperties(regProperties);
+ }
+ }
+
+ public GobblinMetadataChangeEvent getGobblinMetadataChangeEvent(Map<Path, Metrics> newFiles, List<String> oldFiles,
+ List<String> oldFilePrefixes, Map<String, String> offsetRange, OperationType operationType,
+ SchemaSource schemaSource) {
+ if (!verifyInput(newFiles, oldFiles, oldFilePrefixes, operationType)) {
+ return null;
+ }
+ GobblinMetadataChangeEvent.Builder gmceBuilder = GobblinMetadataChangeEvent.newBuilder();
+ setBasicInformationForGMCE(gmceBuilder, offsetRange, schemaSource);
+ if (newFiles != null && !newFiles.isEmpty()) {
+ gmceBuilder.setNewFiles(toGobblinDataFileList(newFiles));
+ }
+ if (oldFiles != null && !oldFiles.isEmpty()) {
+ gmceBuilder.setOldFiles(oldFiles);
+ }
+ if (oldFilePrefixes != null && !oldFilePrefixes.isEmpty()) {
+ gmceBuilder.setOldFilePrefixes(oldFilePrefixes);
+ }
+ gmceBuilder.setOperationType(operationType);
+ return gmceBuilder.build();
+ }
+
+ private boolean verifyInput(Map<Path, Metrics> newFiles, List<String> oldFiles, List<String> oldFilePrefixes,
+ OperationType operationType) {
+ switch (operationType) {
+ case rewrite_files: {
+ if (newFiles == null || ((oldFiles == null || oldFiles.isEmpty()) && (oldFilePrefixes == null || oldFilePrefixes
+ .isEmpty())) || newFiles.isEmpty()) {
+ log.error("Rewrite files operation must contain newFiles to be added and oldFiles to be deleted");
+ return false;
+ }
+ break;
+ }
+ case add_files: {
+ if (newFiles == null || newFiles.isEmpty()) {
+ log.error("Add files operation must contain newFiles to be added");
+ return false;
+ }
+ break;
+ }
+ case drop_files: {
+ if ((oldFiles == null || oldFiles.isEmpty()) && (oldFilePrefixes == null || oldFilePrefixes.isEmpty())) {
+ log.error("Drop files operation must contain old files to be deleted");
+ return false;
+ }
+ break;
+ }
+ default: {
+ //unsupported operation
+ log.error("Unsupported operation type {}", operationType);
+ return false;
+ }
+ }
+ return true;
+ }
+
+
+ private List<DataFile> toGobblinDataFileList(Map<Path, Metrics> files) {
+ return Lists.newArrayList(Iterables.transform(files.entrySet(), file -> DataFile.newBuilder()
+ .setFilePath(file.getKey().toString())
+ .setFileFormat(IcebergUtils.getIcebergFormat(state).toString())
+ .setFileMetrics(DataMetrics.newBuilder()
+ .setRecordCount(file.getValue().recordCount())
+ .setColumnSizes(getIntegerLongPairsFromMap(file.getValue().columnSizes()))
+ .setValueCounts(getIntegerLongPairsFromMap(file.getValue().valueCounts()))
+ .setNullValueCounts(getIntegerLongPairsFromMap(file.getValue().nullValueCounts()))
+ .setLowerBounds(getIntegerBytesPairsFromMap(file.getValue().lowerBounds()))
+ .setUpperBounds(getIntegerBytesPairsFromMap(file.getValue().upperBounds()))
+ .build())
+ .build()));
+ }
+
+ private List<IntegerLongPair> getIntegerLongPairsFromMap(Map<Integer, Long> map) {
+ if (map == null || map.size() == 0) {
+ return null;
+ }
+ Iterable<Map.Entry<Integer, Long>> entries = map.entrySet();
+ Iterable<IntegerLongPair> pairs =
+ Iterables.transform(entries, entry -> new IntegerLongPair(entry.getKey(), entry.getValue()));
+ return Lists.newArrayList(pairs);
+ }
+
+ private List<IntegerBytesPair> getIntegerBytesPairsFromMap(Map<Integer, ByteBuffer> map) {
+ if (map == null || map.size() == 0) {
+ return null;
+ }
+ Iterable<Map.Entry<Integer, ByteBuffer>> entries = map.entrySet();
+ Iterable<IntegerBytesPair> pairs =
+ Iterables.transform(entries, entry -> new IntegerBytesPair(entry.getKey(), entry.getValue()));
+ return Lists.newArrayList(pairs);
+ }
+
+ public static GobblinMCEProducer getGobblinMCEProducer(State state) {
+ return GobblinConstructorUtils.invokeConstructor(GobblinMCEProducer.class,
+ state.getProp(GMCE_PRODUCER_CLASS), state);
+ }
+
+ @Override
+ public void close() throws IOException {
+ //producer close will handle by the cache
+ this.metricContext.close();
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/Utils/IcebergUtils.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/Utils/IcebergUtils.java
new file mode 100644
index 0000000..53cec5f
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/Utils/IcebergUtils.java
@@ -0,0 +1,301 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.Utils;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.metadata.IntegerBytesPair;
+import org.apache.gobblin.metadata.IntegerLongPair;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.avro.AvroSchemaUtil;
+import org.apache.iceberg.exceptions.RuntimeIOException;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+
+
+@Slf4j
+public class IcebergUtils {
+
+ private static final String AVRO_SCHEMA_URL = "avro.schema.url";
+ private static final String AVRO_SCHEMA_LITERAL = "avro.schema.literal";
+ private static final String[] RESTRICTED_PROPERTIES =
+ new String[]{AVRO_SCHEMA_URL, AVRO_SCHEMA_LITERAL};
+
+ private IcebergUtils() {
+ }
+ /**
+ * Calculate the {@Link PartitionSpec} used to create iceberg table
+ */
+ public static PartitionSpec getPartitionSpec(Schema tableSchema, Schema partitionSchema) {
+ //TODO: Add more information into partition spec e.g. day, year, month, kafka partition ids, offset ranges for better consuming
+ PartitionSpec.Builder builder = PartitionSpec.builderFor(tableSchema);
+ partitionSchema.asStruct().fields().forEach(f -> builder.identity(f.name()));
+ return builder.build();
+ }
+
+ /**
+ * Given a avro schema string and a hive table,
+ * calculate the iceberg table schema and partition schema.
+ * (Since we use 'datepartition' as partition column, which is not included inside the data schema,
+ * we'll need to add that column to data schema to construct table schema
+ */
+ public static IcebergDataAndPartitionSchema getIcebergSchema(String schema,
+ org.apache.hadoop.hive.metastore.api.Table table) {
+
+ org.apache.iceberg.shaded.org.apache.avro.Schema icebergDataSchema =
+ new org.apache.iceberg.shaded.org.apache.avro.Schema.Parser().parse(schema);
+ Types.StructType dataStructType = AvroSchemaUtil.convert(icebergDataSchema).asStructType();
+ List<Types.NestedField> dataFields = Lists.newArrayList(dataStructType.fields());
+ org.apache.iceberg.shaded.org.apache.avro.Schema icebergPartitionSchema =
+ parseSchemaFromCols(table.getPartitionKeys(), table.getDbName(), table.getTableName(), true);
+ Types.StructType partitionStructType = AvroSchemaUtil.convert(icebergPartitionSchema).asStructType();
+ List<Types.NestedField> partitionFields = partitionStructType.fields();
+ Preconditions.checkArgument(partitionFields.stream().allMatch(f -> f.type().isPrimitiveType()),
+ "Only primitive fields are supported for partition columns");
+ dataFields.addAll(partitionFields);
+ Types.StructType updatedStructType = Types.StructType.of(dataFields);
+ updatedStructType =
+ (Types.StructType) TypeUtil.assignFreshIds(updatedStructType, new AtomicInteger(0)::incrementAndGet);
+ return new IcebergDataAndPartitionSchema(new org.apache.iceberg.Schema(updatedStructType.fields()),
+ new org.apache.iceberg.Schema(partitionFields));
+ }
+
+ private static org.apache.iceberg.shaded.org.apache.avro.Schema parseSchemaFromCols(List<FieldSchema> cols,
+ String namespace, String recordName, boolean mkFieldsOptional) {
+ final List<String> colNames = new ArrayList<>(cols.size());
+ final List<TypeInfo> colsTypeInfo = new ArrayList<>(cols.size());
+ cols.forEach(fs -> {
+ colNames.add(fs.getName());
+ colsTypeInfo.add(TypeInfoUtils.getTypeInfoFromTypeString(fs.getType()));
+ });
+ final TypeInfoToSchemaParser parser =
+ new TypeInfoToSchemaParser(namespace, mkFieldsOptional, Collections.emptyMap());
+ return new org.apache.iceberg.shaded.org.apache.avro.Schema.Parser().parse(
+ parser.parseSchemaFromFieldsTypeInfo("", recordName, colNames, colsTypeInfo).toString());
+ }
+
+ /**
+ * Given a Hive table, get all the properties of the table, and drop unneeded ones and transfer to a map
+ */
+ public static Map<String, String> getTableProperties(org.apache.hadoop.hive.metastore.api.Table table) {
+ final Map<String, String> parameters = getRawTableProperties(table);
+ // drop unneeded parameters
+ for (String k : RESTRICTED_PROPERTIES) {
+ parameters.remove(k);
+ }
+ return parameters;
+ }
+
+ private static Map<String, String> getRawTableProperties(org.apache.hadoop.hive.metastore.api.Table table) {
+ final Map<String, String> parameters = new HashMap<>();
+ // lowest to highest priority of updating tableProperties
+ parameters.putAll(table.getSd().getSerdeInfo().getParameters());
+ parameters.putAll(table.getSd().getParameters());
+ parameters.putAll(table.getParameters());
+ return parameters;
+ }
+
+ /**
+ * Get the iceberg partition value for given partition strings
+ */
+ public static StructLike getPartition(Types.StructType partitionType, List<String> partitionValues) {
+ //TODO parse partitionValue as per partitionSchema
+ return new StructLike() {
+ @Override
+ public int size() {
+ return partitionValues.size();
+ }
+
+ @Override
+ public <T> T get(int pos, Class<T> javaClass) {
+ return partitionValue(partitionType.fields().get(pos), partitionValues.get(pos));
+ }
+
+ @Override
+ public <T> void set(int pos, T value) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ private static <T> T partitionValue(Types.NestedField partitionField, String colAsString) {
+ Preconditions.checkState(partitionField.type().isPrimitiveType(), "Partition column {} is not of primitive type",
+ partitionField);
+ return (T) Conversions.fromPartitionString(partitionField.type(), colAsString);
+ }
+
+ /**
+ * Transfer list of {@Link IntegerLongPair} from origin id to long, to Map<Integer, Long> from real column id to long
+ * This method is mainly used to get parse the file metrics from GMCE
+ * @param list list of {@Link IntegerLongPair}
+ * @param schemaIdMap A map from origin ID (defined by data pipeline) to the real iceberg table column id
+ * @return A map from real id to long as the file metrics
+ */
+ public static Map<Integer, Long> getMapFromIntegerLongPairs(
+ List<IntegerLongPair> list, Map<Integer, Integer> schemaIdMap) {
+ //If schemaIdMap is not set, we directly return null to avoid set wrong file metrics
+ if (list == null || list.size() == 0 || schemaIdMap == null) {
+ return null;
+ }
+ try {
+ return list.stream().filter(t -> schemaIdMap.containsKey(t.getKey()))
+ .collect(Collectors.toMap(t -> schemaIdMap.get(t.getKey()), IntegerLongPair::getValue));
+ } catch (Exception e) {
+ log.warn("get exception {} when calculate metrics", e);
+ return null;
+ }
+ }
+
+ /**
+ * Transfer list of {@Link IntegerBytesPair} from origin id to bytes, to Map<Integer, ByteBuffer> from real column id to ByteBuffer
+ * This method is mainly used to get parse the file metrics from GMCE
+ * @param list list of {@Link IntegerBytesPair} from origin id to bytes
+ * @param schemaIdMap A map from origin ID (defined by data pipeline) to the real iceberg table column id
+ * @return A map from real id to ByteBuffer as the file metrics
+ */
+ public static Map<Integer, ByteBuffer> getMapFromIntegerBytesPairs(
+ List<IntegerBytesPair> list, Map<Integer, Integer> schemaIdMap) {
+ //If schemaWithOriginId is not set, we directly return null to avoid set wrong file metrics
+ if (list == null || list.size() == 0 || schemaIdMap == null) {
+ return null;
+ }
+ try {
+ return list.stream().filter(t -> schemaIdMap.containsKey(t.getKey()))
+ .collect(Collectors.toMap(t -> schemaIdMap.get(t.getKey()), IntegerBytesPair::getValue));
+ } catch (Exception e) {
+ log.warn("get exception {} when calculate metrics", e);
+ return null;
+ }
+ }
+
+ /**
+ * Method to get DataFile without format and metrics information
+ * This method is mainly used to get the file to be deleted
+ */
+ public static DataFile getIcebergDataFileWithoutMetric(String file, PartitionSpec partitionSpec,
+ StructLike partition) {
+ //Use raw Path to support federation.
+ String rawPath = new Path(file).toUri().getRawPath();
+ //Just want to remove the old files, so set the record number and file size to a random value
+ DataFiles.Builder dataFileBuilder =
+ DataFiles.builder(partitionSpec).withPath(rawPath).withFileSizeInBytes(0).withRecordCount(0);
+
+ if (partition != null) {
+ dataFileBuilder.withPartition(partition);
+ }
+ return dataFileBuilder.build();
+ }
+
+ /**
+ * Method to get DataFile with format and metrics information
+ * This method is mainly used to get the file to be added
+ */
+ public static DataFile getIcebergDataFileWithMetric(org.apache.gobblin.metadata.DataFile file,
+ PartitionSpec partitionSpec, StructLike partition, Configuration conf, Map<Integer, Integer> schemaIdMap) {
+ Path filePath = new Path(file.getFilePath());
+ DataFiles.Builder dataFileBuilder = DataFiles.builder(partitionSpec);
+ try {
+ // Use absolute path to support federation
+ dataFileBuilder.withPath(filePath.toUri().getRawPath())
+ .withFileSizeInBytes(filePath.getFileSystem(conf).getFileStatus(filePath).getLen())
+ .withFormat(file.getFileFormat());
+ } catch (IOException exception) {
+ throw new RuntimeIOException(exception, "Failed to get dataFile for path: %s", filePath);
+ }
+ if (partition != null) {
+ dataFileBuilder.withPartition(partition);
+ }
+ Metrics metrics = new Metrics(file.getFileMetrics().getRecordCount(),
+ IcebergUtils.getMapFromIntegerLongPairs(file.getFileMetrics().getColumnSizes(), schemaIdMap),
+ IcebergUtils.getMapFromIntegerLongPairs(file.getFileMetrics().getValueCounts(), schemaIdMap),
+ IcebergUtils.getMapFromIntegerLongPairs(file.getFileMetrics().getNullValueCounts(), schemaIdMap),
+ IcebergUtils.getMapFromIntegerBytesPairs(file.getFileMetrics().getLowerBounds(), schemaIdMap),
+ IcebergUtils.getMapFromIntegerBytesPairs(file.getFileMetrics().getUpperBounds(), schemaIdMap));
+ return dataFileBuilder.withMetrics(metrics).build();
+ }
+
+ /**
+ * Calculate the schema id map from origin id (file metrics used) to the current table schema id
+ * @param schemaWithOriginId coming from GMCE, contains the original schema id which is used to calculate the file metrics
+ * @param tableSchema table schema, coming from iceberg
+ * @return Schema id map
+ */
+ public static Map<Integer, Integer> getSchemaIdMap(Schema schemaWithOriginId, Schema tableSchema) {
+ if (schemaWithOriginId == null || tableSchema == null) {
+ return null;
+ }
+ Map<Integer, Integer> map = new HashMap();
+ Map<String, Integer> originNameIdMap = TypeUtil.indexByName(schemaWithOriginId.asStruct());
+ for (Map.Entry<String, Integer> nameIdPair : originNameIdMap.entrySet()) {
+ if (tableSchema.findField(nameIdPair.getKey()) != null) {
+ map.put(nameIdPair.getValue(), tableSchema.findField(nameIdPair.getKey()).fieldId());
+ } else {
+ log.warn("Cannot find field {}, will skip the metrics for this column", nameIdPair.getKey());
+ }
+ }
+ return map;
+ }
+
+ /**
+ * Method to get Iceberg format from state, the format is determined by {@Link ConfigurationKeys.WRITER_OUTPUT_FORMAT_KEY}
+ */
+ public static FileFormat getIcebergFormat(State state) {
+ if (state.getProp(ConfigurationKeys.WRITER_OUTPUT_FORMAT_KEY).equalsIgnoreCase("AVRO")) {
+ return FileFormat.AVRO;
+ } else if (state.getProp(ConfigurationKeys.WRITER_OUTPUT_FORMAT_KEY).equalsIgnoreCase("ORC")) {
+ return FileFormat.ORC;
+ }
+
+ throw new IllegalArgumentException("Unsupported data format: " + state.getProp(ConfigurationKeys.WRITER_OUTPUT_FORMAT_KEY));
+ }
+
+
+ public static class IcebergDataAndPartitionSchema {
+ public Schema tableSchema;
+ public Schema partitionSchema;
+
+ IcebergDataAndPartitionSchema(Schema tableSchema, Schema partitionSchema) {
+ this.tableSchema = tableSchema;
+ this.partitionSchema = partitionSchema;
+ }
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/Utils/TypeInfoToSchemaParser.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/Utils/TypeInfoToSchemaParser.java
new file mode 100644
index 0000000..a14c237
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/Utils/TypeInfoToSchemaParser.java
@@ -0,0 +1,294 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.Utils;
+
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import org.apache.avro.Schema;
+import org.apache.avro.Schema.Field;
+import org.apache.avro.Schema.Type;
+import org.apache.commons.lang.StringUtils;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
+import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
+import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.UnionTypeInfo;
+import org.codehaus.jackson.node.JsonNodeFactory;
+import org.codehaus.jackson.node.NullNode;
+
+
+
+public final class TypeInfoToSchemaParser {
+ private static final String DECIMAL_TYPE_NAME = "decimal";
+ private static final String CHAR_TYPE_NAME = "char";
+ private static final String VARCHAR_TYPE_NAME = "varchar";
+ private static final String DATE_TYPE_NAME = "date";
+ private static final String TIMESTAMP_TYPE_NAME = "timestamp-millis";
+ private static final String AVRO_PROP_LOGICAL_TYPE = "logicalType";
+ private static final String AVRO_PROP_PRECISION = "precision";
+ private static final String AVRO_PROP_SCALE = "scale";
+ private static final String AVRO_PROP_MAX_LENGTH = "maxLength";
+ private static final String AVRO_STRING_TYPE_NAME = "string";
+ private static final String AVRO_INT_TYPE_NAME = "int";
+ private static final String AVRO_LONG_TYPE_NAME = "long";
+ private static final String AVRO_SHORT_TYPE_NAME = "short";
+ private static final String AVRO_BYTE_TYPE_NAME = "byte";
+ private int _recordCounter = 0;
+ private final String _namespace;
+ private final boolean _mkFieldsOptional;
+ private final Map<String, String> _downToUpCaseMap;
+
+ public TypeInfoToSchemaParser(String namespace, boolean mkFieldsOptional, Map<String, String> downToUpCaseMap) {
+ this._namespace = namespace;
+ this._mkFieldsOptional = mkFieldsOptional;
+ this._downToUpCaseMap = downToUpCaseMap;
+ }
+
+ public Schema parseSchemaFromFieldsTypeInfo(String recordNamespace, String recordName, List<String> fieldNames,
+ List<TypeInfo> fieldTypeInfos) {
+ List<Field> fields = new ArrayList();
+
+ for (int i = 0; i < fieldNames.size(); ++i) {
+ TypeInfo fieldTypeInfo = (TypeInfo) fieldTypeInfos.get(i);
+ String fieldName = (String) fieldNames.get(i);
+ fieldName = removePrefix(fieldName);
+ fieldName = (String) this._downToUpCaseMap.getOrDefault(fieldName, fieldName);
+ Schema schema = this.parseSchemaFromTypeInfo(fieldTypeInfo, recordNamespace + "." + recordName.toLowerCase(),
+ StringUtils.capitalize(fieldName));
+ Field f = new Field(fieldName, schema, (String) null, this._mkFieldsOptional ? NullNode.instance : null);
+ fields.add(f);
+ }
+
+ Schema recordSchema = Schema.createRecord(recordName, (String) null, this._namespace + recordNamespace, false);
+ recordSchema.setFields(fields);
+ return recordSchema;
+ }
+
+ Schema parseSchemaFromTypeInfo(TypeInfo typeInfo, String recordNamespace, String recordName) {
+ Category c = typeInfo.getCategory();
+ Schema schema;
+ switch (c) {
+ case STRUCT:
+ schema = this.parseSchemaFromStruct((StructTypeInfo) typeInfo, recordNamespace, recordName);
+ break;
+ case LIST:
+ schema = this.parseSchemaFromList((ListTypeInfo) typeInfo, recordNamespace, recordName);
+ break;
+ case MAP:
+ schema = this.parseSchemaFromMap((MapTypeInfo) typeInfo, recordNamespace, recordName);
+ break;
+ case PRIMITIVE:
+ schema = this.parseSchemaFromPrimitive((PrimitiveTypeInfo) typeInfo);
+ break;
+ case UNION:
+ schema = this.parseSchemaFromUnion((UnionTypeInfo) typeInfo, recordNamespace, recordName);
+ break;
+ default:
+ throw new UnsupportedOperationException("Conversion from " + c + " not supported");
+ }
+
+ return this._mkFieldsOptional ? wrapInNullableUnion(schema) : schema;
+ }
+
+ private Schema parseSchemaFromUnion(UnionTypeInfo typeInfo, String recordNamespace, String recordName) {
+ List<TypeInfo> typeInfos = typeInfo.getAllUnionObjectTypeInfos();
+ List<Schema> schemas = new ArrayList();
+
+ Schema candidate;
+ for (Iterator var6 = typeInfos.iterator(); var6.hasNext();
+ schemas.add(isNullableType(candidate) ? getOtherTypeFromNullableType(candidate) : candidate)) {
+ TypeInfo ti = (TypeInfo) var6.next();
+ if (ti instanceof StructTypeInfo) {
+ StructTypeInfo sti = (StructTypeInfo) ti;
+ String newRecordName = recordName + this._recordCounter;
+ ++this._recordCounter;
+ candidate = this.parseSchemaFromStruct(sti, recordNamespace, newRecordName);
+ } else {
+ candidate = this.parseSchemaFromTypeInfo(ti, recordNamespace, recordName);
+ }
+ }
+
+ return Schema.createUnion(schemas);
+ }
+
+ private Schema parseSchemaFromStruct(StructTypeInfo typeInfo, String recordNamespace, String recordName) {
+ Schema recordSchema =
+ this.parseSchemaFromFieldsTypeInfo(recordNamespace, recordName, typeInfo.getAllStructFieldNames(),
+ typeInfo.getAllStructFieldTypeInfos());
+ return recordSchema;
+ }
+
+ private Schema parseSchemaFromList(ListTypeInfo typeInfo, String recordNamespace, String recordName) {
+ Schema listSchema = this.parseSchemaFromTypeInfo(typeInfo.getListElementTypeInfo(), recordNamespace, recordName);
+ return Schema.createArray(listSchema);
+ }
+
+ private Schema parseSchemaFromMap(MapTypeInfo typeInfo, String recordNamespace, String recordName) {
+ TypeInfo keyTypeInfo = typeInfo.getMapKeyTypeInfo();
+ PrimitiveCategory pc = ((PrimitiveTypeInfo) keyTypeInfo).getPrimitiveCategory();
+ if (pc != PrimitiveCategory.STRING) {
+ throw new UnsupportedOperationException("Key of Map can only be a String");
+ } else {
+ TypeInfo valueTypeInfo = typeInfo.getMapValueTypeInfo();
+ Schema valueSchema = this.parseSchemaFromTypeInfo(valueTypeInfo, recordNamespace, recordName);
+ return Schema.createMap(valueSchema);
+ }
+ }
+
+ private Schema parseSchemaFromPrimitive(PrimitiveTypeInfo primitiveTypeInfo) {
+ Schema schema;
+ switch (primitiveTypeInfo.getPrimitiveCategory()) {
+ case LONG:
+ schema = Schema.create(Type.LONG);
+ break;
+ case DATE:
+ schema = Schema.create(Type.INT);
+ schema.addProp("logicalType", "date");
+ break;
+ case TIMESTAMP:
+ schema = Schema.create(Type.LONG);
+ schema.addProp("logicalType", "timestamp-millis");
+ break;
+ case BINARY:
+ schema = Schema.create(Type.BYTES);
+ break;
+ case BOOLEAN:
+ schema = Schema.create(Type.BOOLEAN);
+ break;
+ case DOUBLE:
+ schema = Schema.create(Type.DOUBLE);
+ break;
+ case DECIMAL:
+ DecimalTypeInfo dti = (DecimalTypeInfo) primitiveTypeInfo;
+ JsonNodeFactory factory = JsonNodeFactory.instance;
+ schema = Schema.create(Type.BYTES);
+ schema.addProp("logicalType", "decimal");
+ schema.addProp("precision", factory.numberNode(dti.getPrecision()));
+ schema.addProp("scale", factory.numberNode(dti.getScale()));
+ break;
+ case FLOAT:
+ schema = Schema.create(Type.FLOAT);
+ break;
+ case BYTE:
+ schema = Schema.create(Type.INT);
+ schema.addProp("logicalType", "byte");
+ break;
+ case SHORT:
+ schema = Schema.create(Type.INT);
+ schema.addProp("logicalType", "short");
+ break;
+ case INT:
+ schema = Schema.create(Type.INT);
+ break;
+ case CHAR:
+ case STRING:
+ case VARCHAR:
+ schema = Schema.create(Type.STRING);
+ break;
+ case VOID:
+ schema = Schema.create(Type.NULL);
+ break;
+ default:
+ throw new UnsupportedOperationException(primitiveTypeInfo + " is not supported.");
+ }
+
+ return schema;
+ }
+
+ @SuppressWarnings("checkstyle:FallThrough")
+ private static Schema wrapInNullableUnion(Schema schema) {
+ Schema wrappedSchema = schema;
+ switch (schema.getType()) {
+ case NULL:
+ break;
+ case UNION:
+ List<Schema> unionSchemas = Lists.newArrayList(new Schema[]{Schema.create(Type.NULL)});
+ unionSchemas.addAll(schema.getTypes());
+ wrappedSchema = Schema.createUnion(unionSchemas);
+ break;
+ default:
+ wrappedSchema = Schema.createUnion(Arrays.asList(Schema.create(Type.NULL), schema));
+ }
+
+ return wrappedSchema;
+ }
+
+ private static String removePrefix(String name) {
+ int idx = name.lastIndexOf(46);
+ return idx > 0 ? name.substring(idx + 1) : name;
+ }
+
+ private static boolean isNullableType(Schema schema) {
+ if (!schema.getType().equals(Type.UNION)) {
+ return false;
+ } else {
+ List<Schema> itemSchemas = schema.getTypes();
+ if (itemSchemas.size() < 2) {
+ return false;
+ } else {
+ Iterator var2 = itemSchemas.iterator();
+
+ Schema itemSchema;
+ do {
+ if (!var2.hasNext()) {
+ return false;
+ }
+
+ itemSchema = (Schema) var2.next();
+ } while (!Type.NULL.equals(itemSchema.getType()));
+
+ return true;
+ }
+ }
+ }
+
+ private static Schema getOtherTypeFromNullableType(Schema unionSchema) {
+ List<Schema> types = unionSchema.getTypes();
+ if (types.size() == 2) {
+ if (((Schema) types.get(0)).getType() == Type.NULL) {
+ return (Schema) types.get(1);
+ } else {
+ return ((Schema) types.get(1)).getType() == Type.NULL ? (Schema) types.get(0) : unionSchema;
+ }
+ } else {
+ List<Schema> itemSchemas = new ArrayList();
+ Iterator var3 = types.iterator();
+
+ while (var3.hasNext()) {
+ Schema itemSchema = (Schema) var3.next();
+ if (!Type.NULL.equals(itemSchema.getType())) {
+ itemSchemas.add(itemSchema);
+ }
+ }
+
+ if (itemSchemas.size() > 1) {
+ return Schema.createUnion(itemSchemas);
+ } else {
+ return (Schema) itemSchemas.get(0);
+ }
+ }
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/publisher/GobblinMCEPublisher.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/publisher/GobblinMCEPublisher.java
new file mode 100644
index 0000000..d3e6b7f
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/publisher/GobblinMCEPublisher.java
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.publisher;
+
+import com.google.common.io.Closer;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.iceberg.GobblinMCEProducer;
+import org.apache.gobblin.iceberg.Utils.IcebergUtils;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metadata.SchemaSource;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.stream.Collectors;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.configuration.WorkUnitState;
+import org.apache.gobblin.publisher.DataPublisher;
+import org.apache.gobblin.util.HadoopUtils;
+import org.apache.gobblin.util.filters.HiddenFilter;
+import org.apache.gobblin.writer.PartitionedDataWriter;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.PathFilter;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.avro.AvroSchemaUtil;
+import org.apache.iceberg.hadoop.HadoopInputFile;
+import org.apache.iceberg.mapping.MappingUtil;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.orc.OrcMetrics;
+
+
+/**
+ * A {@link DataPublisher} that compute and emit GobblinMetadataChangeEvent to kafka and rely on metadata ingestion pipeline
+ * to register metadata.
+ *
+ * <p>
+ * This publisher is not responsible for publishing data, and it relies on another publisher
+ * to document the published paths in property {@link NEW_FILES_LIST}.
+ * This publisher will use {@link GobblinMCEProducer} to emit GMCE events.
+ * </p>
+ */
+
+@Slf4j
+public class GobblinMCEPublisher extends DataPublisher {
+ public static final String OFFSET_RANGE_KEY = "offset.range";
+ public static final String MAP_DELIMITER_KEY = ":";
+ public static final String NEW_FILES_LIST = "new.files.list";
+ public static final String AVRO_SCHEMA_WITH_ICEBERG_ID = "avro.schema.with.iceberg.id";
+ private final GobblinMCEProducer producer;
+
+ private final Closer closer = Closer.create();
+ private final Configuration conf;
+ private static final PathFilter HIDDEN_FILES_FILTER = new HiddenFilter();
+
+ public GobblinMCEPublisher(State state) throws IOException {
+
+ this(state, GobblinMCEProducer.getGobblinMCEProducer(state));
+ }
+
+ public GobblinMCEPublisher(State state, GobblinMCEProducer producer) {
+ super(state);
+ this.producer = this.closer.register(producer);
+ conf = HadoopUtils.getConfFromState(state);
+ }
+
+ public void publishData(Collection<? extends WorkUnitState> states) throws IOException {
+ // First aggregate the new files by partition
+ for (State state : states) {
+ Map<Path, Metrics> newFiles = computeFileMetrics(state);
+ Map<String, String> offsetRange = getPartitionOffsetRange(OFFSET_RANGE_KEY);
+ if (newFiles.isEmpty()) {
+ return;
+ }
+ this.producer.sendGMCE(newFiles, null, null, offsetRange, OperationType.add_files, SchemaSource.SCHEMAREGISTRY);
+ }
+ }
+
+ private Map<String, String> getPartitionOffsetRange(String offsetKey) {
+ return state.getPropAsList(offsetKey)
+ .stream()
+ .collect(Collectors.toMap(s -> s.split(MAP_DELIMITER_KEY)[0], s -> s.split(MAP_DELIMITER_KEY)[1]));
+ }
+
+ /**
+ * For each publish path, get all the data files under path
+ * and calculate the hive spec for each datafile and submit the task to register that datafile
+ * @throws IOException
+ */
+ private Map<Path, Metrics> computeFileMetrics(State state) throws IOException {
+ Map<Path, Metrics> newFiles = new HashMap<>();
+ NameMapping mapping = getNameMapping();
+ FileSystem fs = FileSystem.get(conf);
+ for (final String pathString : state.getPropAsList(NEW_FILES_LIST, "")) {
+ Path path = new Path(pathString);
+ LinkedList<FileStatus> fileStatuses = new LinkedList<>();
+ fileStatuses.add(fs.getFileStatus(path));
+ // Only register files
+ while (!fileStatuses.isEmpty()) {
+ FileStatus fileStatus = fileStatuses.pollFirst();
+ if (fileStatus.isDirectory()) {
+ fileStatuses.addAll(Arrays.asList(fs.listStatus(fileStatus.getPath(), HIDDEN_FILES_FILTER)));
+ } else {
+ Path filePath = fileStatus.getPath();
+ Metrics metrics = getMetrics(state, filePath, conf, mapping);
+ newFiles.put(filePath, metrics);
+ }
+ }
+ }
+ return newFiles;
+ }
+
+ protected NameMapping getNameMapping() {
+ String writerSchema = state.getProp(PartitionedDataWriter.WRITER_LATEST_SCHEMA);
+ if (writerSchema == null) {
+ return null;
+ }
+ try {
+ org.apache.iceberg.shaded.org.apache.avro.Schema avroSchema = new org.apache.iceberg.shaded.org.apache.avro.Schema.Parser().parse(writerSchema);
+ Schema icebergSchema = AvroSchemaUtil.toIceberg(avroSchema);
+ //This conversion is to make sure the schema has the iceberg id setup
+ state.setProp(AVRO_SCHEMA_WITH_ICEBERG_ID, AvroSchemaUtil.convert(icebergSchema.asStruct()).toString());
+ return MappingUtil.create(icebergSchema);
+ } catch (Exception e) {
+ //This means table schema is not compatible with iceberg, so directly return null
+ log.warn("Dataset {} contains schema that does not compatible with iceberg, will not emit file metrics for it",
+ state.getProp(ConfigurationKeys.DATA_PUBLISHER_DATASET_DIR));
+ return null;
+ }
+ }
+
+ public static Metrics getMetrics(State state, Path path, Configuration conf, NameMapping mapping) {
+ switch (IcebergUtils.getIcebergFormat(state)) {
+ case ORC: {
+ if (mapping == null) {
+ //This means the table is not compatible with iceberg, so return a dummy metric
+ return new Metrics(100000000L, null, null, null);
+ }
+ return OrcMetrics.fromInputFile(HadoopInputFile.fromPath(path, conf), MetricsConfig.getDefault(), mapping);
+ }
+ case AVRO: {
+ try {
+ return new Metrics(100000000L, null, null, null);
+ } catch (Exception e) {
+ throw new RuntimeException("Cannot get file information for file " + path.toString(), e);
+ }
+ }
+ default: {
+ throw new IllegalArgumentException("Unsupported data format for file " + path);
+ }
+ }
+ }
+
+ public void publishMetadata(Collection<? extends WorkUnitState> states) {
+ }
+
+ @Deprecated
+ @Override
+ public void initialize() {
+ }
+
+ @Override
+ public void close() throws IOException {
+ this.closer.close();
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriter.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriter.java
new file mode 100644
index 0000000..44c0f23
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriter.java
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.writer;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.io.Closer;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.avro.Schema;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.specific.SpecificData;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.dataset.Descriptor;
+import org.apache.gobblin.hive.policy.HiveRegistrationPolicy;
+import org.apache.gobblin.hive.policy.HiveRegistrationPolicyBase;
+import org.apache.gobblin.hive.spec.HiveSpec;
+import org.apache.gobblin.metadata.GobblinMetadataChangeEvent;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.stream.RecordEnvelope;
+import org.apache.gobblin.util.ClustersNames;
+import org.apache.gobblin.util.HadoopUtils;
+import org.apache.gobblin.util.ParallelRunner;
+import org.apache.gobblin.util.reflection.GobblinConstructorUtils;
+import org.apache.gobblin.writer.DataWriter;
+import org.apache.gobblin.writer.DataWriterBuilder;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.serde2.avro.AvroSerdeUtils;
+
+
+/**
+ * This is a Wrapper of all the MetadataWriters. This writer will manage a list of {@Link MetadataWriter} which do the actual
+ * metadata registration for different metadata store.
+ * This writer is responsible for:
+ * 1. Managing a map of Iceberg tables that it is currently processing
+ * 2. Ensuring that the underlying metadata writers flush the metadata associated with each Iceberg table
+ * 3. Call flush method for a specific table on a change in operation type
+ * 4. Calculate {@Link HiveSpec}s and pass them to metadata writers to register metadata
+ */
+@Slf4j
+public class GobblinMCEWriter implements DataWriter<GenericRecord> {
+ public static final String DEFAULT_HIVE_REGISTRATION_POLICY_KEY = "default.hive.registration.policy";
+ public static final String FORCE_HIVE_DATABASE_NAME = "force.hive.database.name";
+ public static final String METADATA_REGISTRATION_THREADS = "metadata.registration.threads";
+ public static final String METADATA_PARALLEL_RUNNER_TIMEOUT_MILLS = "metadata.parallel.runner.timeout.mills";
+ public static final String HIVE_PARTITION_NAME = "hive.partition.name";
+ public static final String CACHE_EXPIRING_TIME = "GMCEWriter.cache.expiring.time.hours";
+ public static final String GMCE_METADATA_WRITER_CLASSES = "gmce.metadata.writer.classes";
+ public static final int DEFAULT_CACHE_EXPIRING_TIME = 1;
+ public static final int DEFAULT_ICEBERG_PARALLEL_TIMEOUT_MILLS = 60000;
+ public static final String TABLE_NAME_DELIMITER = ".";
+ @Getter
+ List<MetadataWriter> metadataWriters;
+ Map<String, OperationType> tableOperationTypeMap;
+ Map<String, OperationType> datasetOperationTypeMap;
+ protected State state;
+ private final ParallelRunner parallelRunner;
+ private int parallelRunnerTimeoutMills;
+ private Map<String, Cache<String, Collection<HiveSpec>>> oldSpecsMaps;
+ private Map<String, Cache<String, Collection<HiveSpec>>> newSpecsMaps;
+ private Closer closer = Closer.create();
+ protected final AtomicLong recordCount = new AtomicLong(0L);
+
+ public GobblinMCEWriter(DataWriterBuilder<Schema, GenericRecord> builder, State properties) throws IOException {
+ newSpecsMaps = new HashMap<>();
+ oldSpecsMaps = new HashMap<>();
+ metadataWriters = new ArrayList<>();
+ state = properties;
+ for (String className : state.getPropAsList(GMCE_METADATA_WRITER_CLASSES, IcebergMetadataWriter.class.getName())) {
+ metadataWriters.add(closer.register(GobblinConstructorUtils.invokeConstructor(MetadataWriter.class, className, state)));
+ }
+ tableOperationTypeMap = new HashMap<>();
+ datasetOperationTypeMap = new HashMap<>();
+ parallelRunner = closer.register(new ParallelRunner(state.getPropAsInt(METADATA_REGISTRATION_THREADS, 20),
+ FileSystem.get(HadoopUtils.getConfFromState(properties))));
+ parallelRunnerTimeoutMills =
+ state.getPropAsInt(METADATA_PARALLEL_RUNNER_TIMEOUT_MILLS, DEFAULT_ICEBERG_PARALLEL_TIMEOUT_MILLS);
+ }
+
+ @Override
+ public void write(GenericRecord record) throws IOException {
+ //Do nothing
+
+ }
+
+ /**
+ * This method is used to get the specs map for a list of files. It will firstly look up in cache
+ * to see if the specs has been calculated previously to recude the computing time
+ * We have an assumption here: "for the same path and the same operation type, the specs should be the same"
+ * @param files List of files' names
+ * @param specsMap The specs map for the files
+ * @param cache Cache that store the pre-calculated specs information
+ * @param registerState State used to compute the specs
+ * @param isPrefix if the name of file is prefix, if not we get the parent file name to calculate the hiveSpec
+ * @throws IOException
+ */
+ private void computeSpecMap(List<String> files, ConcurrentHashMap<String, Collection<HiveSpec>> specsMap,
+ Cache<String, Collection<HiveSpec>> cache, State registerState, boolean isPrefix) throws IOException {
+ HiveRegistrationPolicy policy = HiveRegistrationPolicyBase.getPolicy(registerState);
+ for (String file : files) {
+ parallelRunner.submitCallable(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ try {
+ Path regPath = new Path(file);
+ if (!isPrefix) {
+ regPath = regPath.getParent();
+ }
+ //Use raw path for federation purpose
+ Path rawPath = new Path(regPath.toUri().getRawPath());
+ cache.get(regPath.toString(), () -> policy.getHiveSpecs(rawPath));
+ specsMap.put(regPath.toString(), cache.getIfPresent(regPath.toString()));
+ } catch (Exception e) {
+ log.warn("Cannot get Hive Spec for {} using policy {}", file, policy.toString());
+ }
+ return null;
+ }
+ }, file);
+ }
+ parallelRunner.waitForTasks(parallelRunnerTimeoutMills);
+ }
+
+ @Override
+ public void commit() throws IOException {
+ this.flush();
+ }
+
+ @Override
+ public void cleanup() throws IOException {
+ //do nothing
+ }
+
+ @Override
+ public long recordsWritten() {
+ return recordCount.get();
+ }
+
+ @Override
+ public long bytesWritten() throws IOException {
+ return 0;
+ }
+
+ @Override
+ public Descriptor getDataDescriptor() {
+ return null;
+ }
+
+ @Override
+ public void writeEnvelope(RecordEnvelope<GenericRecord> recordEnvelope) throws IOException {
+ GenericRecord genericRecord = recordEnvelope.getRecord();
+ //filter out the events that not for this cluster
+ if (!genericRecord.get("cluster").equals(ClustersNames.getInstance().getClusterName())) {
+ return;
+ }
+ // Use schema from record to avoid issue when schema evolution
+ GobblinMetadataChangeEvent gmce =
+ (GobblinMetadataChangeEvent) SpecificData.get().deepCopy(genericRecord.getSchema(), genericRecord);
+ String datasetName = gmce.getDatasetIdentifier().toString();
+ //remove the old hive spec cache after flush
+ //Here we assume that new hive spec for one path always be the same(ingestion flow register to same tables)
+ if (!datasetOperationTypeMap.containsKey(datasetName)) {
+ oldSpecsMaps.remove(datasetName);
+ }
+ if (datasetOperationTypeMap.containsKey(datasetName)
+ && datasetOperationTypeMap.get(datasetName) != gmce.getOperationType()) {
+ datasetOperationTypeMap.put(datasetName, gmce.getOperationType());
+ }
+ //We assume in one same operation interval, for same dataset, the table property will not change to reduce the time to compute hiveSpec.
+ ConcurrentHashMap<String, Collection<HiveSpec>> newSpecsMap = new ConcurrentHashMap<>();
+ ConcurrentHashMap<String, Collection<HiveSpec>> oldSpecsMap = new ConcurrentHashMap<>();
+
+ if (gmce.getNewFiles() != null) {
+ State registerState = setHiveRegProperties(state, gmce, true);
+ computeSpecMap(Lists.newArrayList(Iterables.transform(gmce.getNewFiles(), dataFile -> dataFile.getFilePath())),
+ newSpecsMap, newSpecsMaps.computeIfAbsent(datasetName, t -> CacheBuilder.newBuilder()
+ .expireAfterAccess(state.getPropAsInt(CACHE_EXPIRING_TIME,
+ DEFAULT_CACHE_EXPIRING_TIME), TimeUnit.HOURS)
+ .build()), registerState, false);
+ }
+ if (gmce.getOldFilePrefixes() != null) {
+ State registerState = setHiveRegProperties(state, gmce, false);
+ computeSpecMap(gmce.getOldFilePrefixes(), oldSpecsMap, oldSpecsMaps.computeIfAbsent(datasetName, t -> CacheBuilder
+ .newBuilder()
+ .expireAfterAccess(state.getPropAsInt(CACHE_EXPIRING_TIME,
+ DEFAULT_CACHE_EXPIRING_TIME), TimeUnit.HOURS)
+ .build()), registerState, true);
+ } else if (gmce.getOldFiles() != null) {
+ State registerState = setHiveRegProperties(state, gmce, false);
+ computeSpecMap(gmce.getOldFiles(), oldSpecsMap, oldSpecsMaps.computeIfAbsent(datasetName,
+ t -> CacheBuilder.newBuilder()
+ .expireAfterAccess(state.getPropAsInt(CACHE_EXPIRING_TIME,
+ DEFAULT_CACHE_EXPIRING_TIME), TimeUnit.HOURS)
+ .build()), registerState, false);
+ }
+ if (newSpecsMap.isEmpty() && oldSpecsMap.isEmpty()) {
+ return;
+ }
+ Collection<HiveSpec> specs =
+ newSpecsMap.isEmpty() ? oldSpecsMap.values().iterator().next() : newSpecsMap.values().iterator().next();
+ for (HiveSpec spec : specs) {
+ String dbName = spec.getTable().getDbName();
+ String tableName = spec.getTable().getTableName();
+ String tableString = Joiner.on(TABLE_NAME_DELIMITER).join(dbName, tableName);
+ if (tableOperationTypeMap.containsKey(tableString)
+ && tableOperationTypeMap.get(tableString) != gmce.getOperationType()) {
+ for (MetadataWriter writer : metadataWriters) {
+ writer.flush(dbName, tableName);
+ }
+ }
+ tableOperationTypeMap.put(tableString, gmce.getOperationType());
+ for (MetadataWriter writer : metadataWriters) {
+ writer.writeEnvelope(recordEnvelope, newSpecsMap, oldSpecsMap, spec);
+ }
+ }
+ this.recordCount.incrementAndGet();
+ }
+
+ /**
+ * Call the metadata writers to do flush each table metadata.
+ * Flush of metadata writer is the place that do really metadata
+ * registration (For iceberg, this method will generate a snapshot)
+ * @throws IOException
+ */
+ @Override
+ public void flush() throws IOException {
+ log.info(String.format("start to flushing %s records", String.valueOf(recordCount.get())));
+ for (String tableString : tableOperationTypeMap.keySet()) {
+ List<String> tid = Splitter.on(TABLE_NAME_DELIMITER).splitToList(tableString);
+ for (MetadataWriter writer : metadataWriters) {
+ writer.flush(tid.get(0), tid.get(1));
+ }
+ }
+ tableOperationTypeMap.clear();
+ recordCount.lazySet(0L);
+ }
+
+ @Override
+ public void close() throws IOException {
+ this.flush();
+ this.closer.close();
+ }
+
+ /**
+ * Get a new state object with the properties used to calculate the {@Link HiveSpec} set
+ * First set the policy to compute HiveSpec, if the policy is not specified in record,
+ * then use the default policy defined in the pipeline
+ * Then set the {@Link ConfigurationKeys.HIVE_REGISTRATION_POLICY} and SCHEMA_LITERAL
+ */
+ public static State setHiveRegProperties(State state, GobblinMetadataChangeEvent gmce, boolean forNew) {
+ Preconditions.checkArgument(state.contains(DEFAULT_HIVE_REGISTRATION_POLICY_KEY),
+ String.format("Missing required configuration %s", DEFAULT_HIVE_REGISTRATION_POLICY_KEY));
+ String defaultPolicy = state.getProp(DEFAULT_HIVE_REGISTRATION_POLICY_KEY);
+ State tmpState = new State(state);
+ String policyClass = forNew ? (gmce.getRegistrationPolicy() != null ? gmce.getRegistrationPolicy() : defaultPolicy)
+ : (gmce.getRegistrationPolicyForOldData() != null ? gmce.getRegistrationPolicyForOldData() : defaultPolicy);
+
+ tmpState.setProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY, policyClass);
+ if (gmce.getPartitionColumns() != null && !gmce.getPartitionColumns().isEmpty()) {
+ //We only support on partition column for now
+ //TODO: Support multi partition columns
+ tmpState.setProp(HIVE_PARTITION_NAME, String.join(",", gmce.getPartitionColumns()));
+ }
+ if (gmce.getRegistrationProperties() != null) {
+ for (Map.Entry<String, String> entry : gmce.getRegistrationProperties().entrySet()) {
+ tmpState.setProp(entry.getKey(), entry.getValue());
+ }
+ }
+ //This config will force all the GMCE to register into the FORCE_HIVE_DATABASE_NAME
+ //This is mainly used during verification period that we register all iceberg data under iceberg_test
+ if (state.contains(FORCE_HIVE_DATABASE_NAME)) {
+ tmpState.setProp(HiveRegistrationPolicyBase.HIVE_DATABASE_NAME, state.getProp(FORCE_HIVE_DATABASE_NAME));
+ }
+ //Set schema
+ if (gmce.getTableSchema() != null) {
+ tmpState.setProp(AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName(), gmce.getTableSchema());
+ }
+ return tmpState;
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriterBuilder.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriterBuilder.java
new file mode 100644
index 0000000..2265b57
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriterBuilder.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.writer;
+
+import java.io.IOException;
+import org.apache.avro.Schema;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.gobblin.writer.DataWriter;
+import org.apache.gobblin.writer.DataWriterBuilder;
+
+
+public class GobblinMCEWriterBuilder extends DataWriterBuilder<Schema, GenericRecord> {
+
+ @Override
+ public DataWriter<GenericRecord> build() throws IOException {
+ return new GobblinMCEWriter(this, this.destination.getProperties());
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/IcebergMCEMetadataKeys.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/IcebergMCEMetadataKeys.java
new file mode 100644
index 0000000..310c01f
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/IcebergMCEMetadataKeys.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.writer;
+
+public class IcebergMCEMetadataKeys {
+ public static final String METRICS_NAMESPACE_ICEBERG_WRITER = "IcebergWriter";
+ public static final String ICEBERG_COMMIT_EVENT_NAME = "IcebergMetadataCommitEvent";
+ public static final String LAG_KEY_NAME = "endToEndLag";
+ public static final String SNAPSHOT_KEY_NAME = "currentSnapshotId";
+ public static final String MANIFEST_LOCATION = "currentManifestLocation";
+ public static final String SNAPSHOT_INFORMATION_KEY_NAME = "currentSnapshotDetailedInformation";
+ public static final String TABLE_KEY_NAME = "icebergTableName";
+ public static final String DATABASE_KEY_NAME = "icebergDatabaseName";
+ public static final String GMCE_TOPIC_NAME = "gmceTopicName";
+ public static final String GMCE_TOPIC_PARTITION = "gmceTopicPartition";
+ public static final String GMCE_HIGH_WATERMARK = "gmceHighWatermark";
+ public static final String GMCE_LOW_WATERMARK = "gmceLowWatermark";
+ public static final String DATASET_HDFS_PATH = "datasetHdfsPath";
+
+ private IcebergMCEMetadataKeys() {
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/IcebergMetadataWriter.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/IcebergMetadataWriter.java
new file mode 100644
index 0000000..ed89f1a
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/IcebergMetadataWriter.java
@@ -0,0 +1,838 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.writer;
+
+import com.codahale.metrics.Timer;
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+import com.google.common.collect.Sets;
+import com.google.common.io.Closer;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.specific.SpecificData;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.data.management.copy.hive.WhitelistBlacklist;
+import org.apache.gobblin.hive.AutoCloseableHiveLock;
+import org.apache.gobblin.hive.HiveLock;
+import org.apache.gobblin.hive.HivePartition;
+import org.apache.gobblin.hive.metastore.HiveMetaStoreUtils;
+import org.apache.gobblin.hive.spec.HiveSpec;
+import org.apache.gobblin.iceberg.Utils.IcebergUtils;
+import org.apache.gobblin.metadata.GobblinMetadataChangeEvent;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metrics.GobblinMetricsRegistry;
+import org.apache.gobblin.metrics.MetricContext;
+import org.apache.gobblin.metrics.Tag;
+import org.apache.gobblin.metrics.event.EventSubmitter;
+import org.apache.gobblin.metrics.event.GobblinEventBuilder;
+import org.apache.gobblin.metrics.kafka.KafkaSchemaRegistry;
+import org.apache.gobblin.metrics.kafka.SchemaRegistryException;
+import org.apache.gobblin.source.extractor.extract.kafka.KafkaStreamingExtractor;
+import org.apache.gobblin.stream.RecordEnvelope;
+import org.apache.gobblin.util.AvroUtils;
+import org.apache.gobblin.util.ClustersNames;
+import org.apache.gobblin.util.HadoopUtils;
+import org.apache.gobblin.util.ParallelRunner;
+import org.apache.gobblin.util.WriterUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.iceberg.AppendFiles;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFiles;
+import org.apache.iceberg.ExpireSnapshots;
+import org.apache.iceberg.FindFiles;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.Transaction;
+import org.apache.iceberg.UpdateProperties;
+import org.apache.iceberg.avro.AvroSchemaUtil;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.hive.HiveCatalog;
+import org.apache.iceberg.hive.HiveCatalogs;
+import org.apache.thrift.TException;
+import org.joda.time.DateTime;
+import org.joda.time.format.PeriodFormatter;
+import org.joda.time.format.PeriodFormatterBuilder;
+
+
+/**
+ * This writer is used to calculate iceberg metadata from GMCE and register to iceberg
+ * iceberg metadata here includes:
+ * 1. Data files that contained by the table and the metrics of the data files
+ * 2. Properties of the table (origin table properties, data offset range, high watermark of the GMCE and schema created time)
+ * 3. Latest schema of the table
+ */
+@Slf4j
+public class IcebergMetadataWriter implements MetadataWriter {
+
+ public static final String USE_DATA_PATH_AS_TABLE_LOCATION = "use.data.path.as.table.location";
+ public static final String TABLE_LOCATION_SUFFIX = "/_iceberg_metadata";
+ public static final String GMCE_HIGH_WATERMARK_KEY = "gmce.high.watermark.%s";
+ public static final String GMCE_LOW_WATERMARK_KEY = "gmce.low.watermark.%s";
+ private final static String EXPIRE_SNAPSHOTS_LOOKBACK_TIME = "gobblin.iceberg.dataset.expire.snapshots.lookBackTime";
+ private final static String DEFAULT_EXPIRE_SNAPSHOTS_LOOKBACK_TIME = "3d";
+ public static final String ICEBERG_REGISTRATION_BLACKLIST = "iceberg.registration.blacklist";
+ public static final String ICEBERG_REGISTRATION_WHITELIST = "iceberg.registration.whitelist";
+ public static final String ICEBERG_METADATA_FILE_PERMISSION = "iceberg.metadata.file.permission";
+ private static final String CLUSTER_IDENTIFIER_KEY_NAME = "clusterIdentifier";
+ private static final String CREATE_TABLE_TIME = "iceberg.create.table.time";
+ private static final String SCHEMA_CREATION_TIME_KEY = "schema.creation.time";
+ private static final String ADDED_FILES_CACHE_EXPIRING_TIME = "added.files.cache.expiring.time";
+ private static final int DEFAULT_ADDED_FILES_CACHE_EXPIRING_TIME = 1;
+ private static final String OFFSET_RANGE_KEY_PREFIX = "offset.range.";
+ private static final String OFFSET_RANGE_KEY_FORMAT = OFFSET_RANGE_KEY_PREFIX + "%s";
+ private static final String ICEBERG_FILE_PATH_COLUMN = "file_path";
+ private static final String DEFAULT_CREATION_TIME = "0";
+ private static final String SNAPSHOT_EXPIRE_THREADS = "snapshot.expire.threads";
+ private static final long DEFAULT_WATERMARK = -1L;
+ protected final MetricContext metricContext;
+ protected EventSubmitter eventSubmitter;
+ private final WhitelistBlacklist whiteistBlacklist;
+ private final Closer closer = Closer.create();
+ private final Map<TableIdentifier, Long> tableCurrentWaterMarkMap;
+ //Used to store the relationship between table and the gmce topicPartition
+ private final Map<TableIdentifier, String> tableTopicpartitionMap;
+ @Getter
+ private final KafkaSchemaRegistry schemaRegistry;
+ private final Map<TableIdentifier, TableMetadata> tableMetadataMap;
+ @Setter
+ protected HiveCatalog catalog;
+ protected final Configuration conf;
+ protected final ReadWriteLock readWriteLock;
+ private final HiveLock locks;
+ private final ParallelRunner parallelRunner;
+ private final boolean useDataLoacationAsTableLocation;
+ private FsPermission permission;
+
+ public IcebergMetadataWriter(State state) throws IOException {
+ this.schemaRegistry = KafkaSchemaRegistry.get(state.getProperties());
+ conf = HadoopUtils.getConfFromState(state);
+ initializeCatalog();
+ tableTopicpartitionMap = new HashMap<>();
+ tableMetadataMap = new HashMap<>();
+ tableCurrentWaterMarkMap = new HashMap<>();
+ List<Tag<?>> tags = Lists.newArrayList();
+ String clusterIdentifier = ClustersNames.getInstance().getClusterName();
+ tags.add(new Tag<>(CLUSTER_IDENTIFIER_KEY_NAME, clusterIdentifier));
+ metricContext = closer.register(
+ GobblinMetricsRegistry.getInstance().getMetricContext(state, IcebergMetadataWriter.class, tags));
+ this.eventSubmitter =
+ new EventSubmitter.Builder(this.metricContext, IcebergMCEMetadataKeys.METRICS_NAMESPACE_ICEBERG_WRITER).build();
+ this.whiteistBlacklist = new WhitelistBlacklist(state.getProp(ICEBERG_REGISTRATION_WHITELIST, ""),
+ state.getProp(ICEBERG_REGISTRATION_BLACKLIST, ""));
+ // Use lock to make it safe when flush and write are called async
+ readWriteLock = new ReentrantReadWriteLock();
+ this.locks = new HiveLock(state.getProperties());
+ parallelRunner = closer.register(new ParallelRunner(state.getPropAsInt(SNAPSHOT_EXPIRE_THREADS, 20),
+ FileSystem.get(HadoopUtils.getConfFromState(state))));
+ useDataLoacationAsTableLocation = state.getPropAsBoolean(USE_DATA_PATH_AS_TABLE_LOCATION, false);
+ if (useDataLoacationAsTableLocation) {
+ permission =
+ HadoopUtils.deserializeFsPermission(state, ICEBERG_METADATA_FILE_PERMISSION,
+ FsPermission.getDefault());
+ }
+ }
+
+ protected void initializeCatalog() {
+ catalog = HiveCatalogs.loadCatalog(conf);
+ }
+
+ private org.apache.iceberg.Table getIcebergTable(TableIdentifier tid) throws NoSuchTableException {
+ TableMetadata tableMetadata = tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata());
+ if (!tableMetadata.table.isPresent()) {
+ tableMetadata.table = Optional.of(catalog.loadTable(tid));
+ }
+ return tableMetadata.table.get();
+ }
+
+ /**
+ * The method is used to get current watermark of the gmce topic partition for a table
+ * Make the watermark config name contains topicPartition in case we change the gmce topic name for some reason
+ */
+ private Long getCurrentWaterMark(TableIdentifier tid, String topicPartition) {
+ if (tableCurrentWaterMarkMap.containsKey(tid)) {
+ return tableCurrentWaterMarkMap.get(tid);
+ }
+ org.apache.iceberg.Table icebergTable;
+ Long currentWatermark = DEFAULT_WATERMARK;
+ try {
+ icebergTable = getIcebergTable(tid);
+ } catch (NoSuchTableException e) {
+ return currentWatermark;
+ }
+ currentWatermark =
+ icebergTable.properties().containsKey(String.format(GMCE_HIGH_WATERMARK_KEY, topicPartition)) ? Long.parseLong(
+ icebergTable.properties().get(String.format(GMCE_HIGH_WATERMARK_KEY, topicPartition))) : DEFAULT_WATERMARK;
+ if (currentWatermark != DEFAULT_WATERMARK) {
+ // set the low watermark for current snapshot
+ tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata()).lowWatermark = Optional.of(currentWatermark);
+ }
+ return currentWatermark;
+ }
+
+ /**
+ *The write method will be responsible for process a given gmce and aggregate the metadata
+ * The logic of this function will be:
+ * 1. Check whether a table exists, if not then create the iceberg table
+ * 2. Compute schema from the gmce and update the cache for candidate schemas
+ * 3. Do the required operation of the gmce, i.e. addFile, rewriteFile or dropFile
+ * Note: this method only aggregate the metadata in cache without committing. The actual commit will be done in flush method
+ */
+ public void write(GobblinMetadataChangeEvent gmce, Map<String, Collection<HiveSpec>> newSpecsMap,
+ Map<String, Collection<HiveSpec>> oldSpecsMap, HiveSpec tableSpec) throws IOException {
+ TableIdentifier tid = TableIdentifier.of(tableSpec.getTable().getDbName(), tableSpec.getTable().getTableName());
+ TableMetadata tableMetadata = tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata());
+ Table table;
+ try {
+ table = getIcebergTable(tid);
+ } catch (NoSuchTableException e) {
+ try {
+ if (gmce.getOperationType() == OperationType.drop_files) {
+ log.warn("Table {} does not exist, skip processing this drop_file event", tid.toString());
+ return;
+ }
+ table = createTable(gmce, tableSpec);
+ tableMetadata.table = Optional.of(table);
+ } catch (Exception e1) {
+ log.error("skip processing {} for table {}.{} due to error when creating table", gmce.toString(),
+ tableSpec.getTable().getDbName(), tableSpec.getTable().getTableName());
+ log.debug(e1.toString());
+ return;
+ }
+ }
+ computeCandidateSchema(gmce, tid, tableSpec);
+ tableMetadata.transaction = Optional.of(tableMetadata.transaction.or(table::newTransaction));
+ tableMetadata.lowestGMCEEmittedTime = Long.min(tableMetadata.lowestGMCEEmittedTime, gmce.getGMCEmittedTime());
+ switch (gmce.getOperationType()) {
+ case add_files: {
+ updateTableProperty(tableSpec, tid);
+ addFiles(gmce, newSpecsMap, table, tableMetadata);
+ if (gmce.getTopicPartitionOffsetsRange() != null) {
+ mergeOffsets(gmce, tid);
+ }
+ break;
+ }
+ case rewrite_files: {
+ updateTableProperty(tableSpec, tid);
+ rewriteFiles(gmce, newSpecsMap, oldSpecsMap, table, tableMetadata);
+ break;
+ }
+ case drop_files: {
+ dropFiles(gmce, oldSpecsMap, table, tableMetadata, tid);
+ break;
+ }
+ default: {
+ log.error("unsupported operation {}", gmce.getOperationType().toString());
+ return;
+ }
+ }
+ }
+
+ private HashMap<String, List<Range>> getLastOffset(TableMetadata tableMetadata) {
+ HashMap<String, List<Range>> offsets = new HashMap<>();
+ if (tableMetadata.lastProperties.isPresent()) {
+ for (Map.Entry<String, String> entry : tableMetadata.lastProperties.get().entrySet()) {
+ if (entry.getKey().startsWith(OFFSET_RANGE_KEY_PREFIX)) {
+ List<Range> ranges = Arrays.asList(entry.getValue().split(ConfigurationKeys.LIST_DELIMITER_KEY))
+ .stream()
+ .map(s -> {
+ List<String> rangePair = Splitter.on(ConfigurationKeys.RANGE_DELIMITER_KEY).splitToList(s);
+ return Range.openClosed(Long.parseLong(rangePair.get(0)), Long.parseLong(rangePair.get(1)));})
+ .collect(Collectors.toList());
+ offsets.put(entry.getKey().substring(OFFSET_RANGE_KEY_PREFIX.length()), ranges);
+ }
+ }
+ }
+ return offsets;
+ }
+
+ private void mergeOffsets(GobblinMetadataChangeEvent gmce, TableIdentifier tid) throws IOException {
+ TableMetadata tableMetadata = tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata());
+ tableMetadata.dataOffsetRange = Optional.of(tableMetadata.dataOffsetRange.or(() -> getLastOffset(tableMetadata)));
+ Map<String, List<Range>> offsets = tableMetadata.dataOffsetRange.get();
+ for (Map.Entry<String, String> entry : gmce.getTopicPartitionOffsetsRange().entrySet()) {
+ List<String> rangePair = Splitter.on(ConfigurationKeys.RANGE_DELIMITER_KEY).splitToList(entry.getValue());
+ Range range = Range.openClosed(Long.parseLong(rangePair.get(0)), Long.parseLong(rangePair.get(1)));
+ List<Range> existRanges = offsets.getOrDefault(entry.getKey(), new ArrayList<>());
+ List<Range> newRanges = new ArrayList<>();
+ for (Range r : existRanges) {
+ if (range.isConnected(r)) {
+ range = range.span(r);
+ } else {
+ newRanges.add(r);
+ }
+ }
+ newRanges.add(range);
+ Collections.sort(newRanges, new Comparator<Range>() {
+ @Override
+ public int compare(Range o1, Range o2) {
+ return o1.lowerEndpoint().compareTo(o2.lowerEndpoint());
+ }
+ });
+ offsets.put(entry.getKey(), newRanges);
+ }
+ }
+
+ private void updateTableProperty(HiveSpec tableSpec, TableIdentifier tid) {
+ org.apache.hadoop.hive.metastore.api.Table table = HiveMetaStoreUtils.getTable(tableSpec.getTable());
+ tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata()).newProperties =
+ Optional.of(IcebergUtils.getTableProperties(table));
+ }
+
+ /**
+ * Compute the candidate schema from the gmce.
+ * If the schema source is schemaRegistry, we will use the schema creation time as the schema version to compute candidate schema and determine latest schema
+ * If the schema does not contain creation time, we will treat it the same as when schema source is event
+ * If the schema source is event, we will put it as default creation time, during flush, if we only have one candidate with default creation time,
+ * we'll use that to update schema.
+ * @param gmce
+ * @param tid
+ */
+ private void computeCandidateSchema(GobblinMetadataChangeEvent gmce, TableIdentifier tid, HiveSpec spec)
+ throws IOException {
+ Table table = getIcebergTable(tid);
+ TableMetadata tableMetadata = tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata());
+ org.apache.hadoop.hive.metastore.api.Table hiveTable = HiveMetaStoreUtils.getTable(spec.getTable());
+ tableMetadata.lastProperties = Optional.of(tableMetadata.lastProperties.or(() -> table.properties()));
+ Map<String, String> props = tableMetadata.lastProperties.get();
+ tableMetadata.lastSchemaVersion = Optional.of(
+ tableMetadata.lastSchemaVersion.or(() -> props.getOrDefault(SCHEMA_CREATION_TIME_KEY, DEFAULT_CREATION_TIME)));
+ String lastSchemaVersion = tableMetadata.lastSchemaVersion.get();
+ tableMetadata.candidateSchemas = Optional.of(tableMetadata.candidateSchemas.or(() -> CacheBuilder.newBuilder()
+ .expireAfterAccess(conf.getInt(GobblinMCEWriter.CACHE_EXPIRING_TIME,
+ GobblinMCEWriter.DEFAULT_CACHE_EXPIRING_TIME), TimeUnit.HOURS)
+ .build()));
+ Cache<String, Schema> candidate = tableMetadata.candidateSchemas.get();
+ try {
+ switch (gmce.getSchemaSource()) {
+ case SCHEMAREGISTRY: {
+ org.apache.avro.Schema schema = new org.apache.avro.Schema.Parser().parse(gmce.getTableSchema());
+ String createdOn = AvroUtils.getSchemaCreationTime(schema);
+ if (createdOn == null) {
+ candidate.put(DEFAULT_CREATION_TIME,
+ IcebergUtils.getIcebergSchema(gmce.getTableSchema(), hiveTable).tableSchema);
+ } else if (!createdOn.equals(lastSchemaVersion)) {
+ candidate.put(createdOn, IcebergUtils.getIcebergSchema(gmce.getTableSchema(), hiveTable).tableSchema);
+ }
+ break;
+ }
+ case EVENT: {
+ candidate.put(DEFAULT_CREATION_TIME,
+ IcebergUtils.getIcebergSchema(gmce.getTableSchema(), hiveTable).tableSchema);
+ break;
+ }
+ case NONE: {
+ log.debug("Schema source set to be none, will ignore the schema");
+ break;
+ }
+ default: {
+ throw new IOException(String.format("unsupported schema source %s", gmce.getSchemaSource()));
+ }
+ }
+ } catch (Exception e) {
+ log.error("Cannot get candidate schema from event due to", e);
+ }
+ }
+
+ protected Table createTable(GobblinMetadataChangeEvent gmce, HiveSpec spec) throws IOException {
+ String schema = gmce.getTableSchema();
+ org.apache.hadoop.hive.metastore.api.Table table = HiveMetaStoreUtils.getTable(spec.getTable());
+ IcebergUtils.IcebergDataAndPartitionSchema schemas = IcebergUtils.getIcebergSchema(schema, table);
+ TableIdentifier tid = TableIdentifier.of(table.getDbName(), table.getTableName());
+ Schema tableSchema = schemas.tableSchema;
+ Preconditions.checkState(tableSchema != null, "Table schema cannot be null when creating a table");
+ PartitionSpec partitionSpec = IcebergUtils.getPartitionSpec(tableSchema, schemas.partitionSchema);
+ Table icebergTable = null;
+ String tableLocation = null;
+ if (useDataLoacationAsTableLocation) {
+ tableLocation = gmce.getDatasetIdentifier().getNativeName() + TABLE_LOCATION_SUFFIX;
+ //Set the path permission
+ Path tablePath = new Path(tableLocation);
+ WriterUtils.mkdirsWithRecursivePermission(tablePath.getFileSystem(conf), tablePath, permission);
+ }
+ try (Timer.Context context = metricContext.timer(CREATE_TABLE_TIME).time()) {
+ icebergTable =
+ catalog.createTable(tid, tableSchema, partitionSpec, tableLocation, IcebergUtils.getTableProperties(table));
+ log.info("Created table {}, schema: {} partition spec: {}", tid, tableSchema, partitionSpec);
+ } catch (AlreadyExistsException e) {
+ log.warn("table {} already exist, there may be some other process try to create table concurrently", tid);
+ }
+ return icebergTable;
+ }
+
+ protected void rewriteFiles(GobblinMetadataChangeEvent gmce, Map<String, Collection<HiveSpec>> newSpecsMap,
+ Map<String, Collection<HiveSpec>> oldSpecsMap, Table table, TableMetadata tableMetadata) throws IOException {
+ PartitionSpec partitionSpec = table.spec();
+ tableMetadata.transaction = Optional.of(tableMetadata.transaction.or(table::newTransaction));
+ Transaction transaction = tableMetadata.transaction.get();
+ Set<DataFile> newDataFiles = new HashSet<>();
+ getIcebergDataFilesToBeAddedHelper(gmce, table, newSpecsMap, tableMetadata)
+ .forEach(dataFile -> {
+ newDataFiles.add(dataFile);
+ tableMetadata.addedFiles.put(dataFile.path(), "");
+ });
+ Set<DataFile> oldDataFiles = getIcebergDataFilesToBeDeleted(gmce, table, newSpecsMap, oldSpecsMap, partitionSpec);
+ if (oldDataFiles.isEmpty() && !newDataFiles.isEmpty()) {
+ //We randomly check whether one of the new data files already exists in the db to avoid duplication of re-write events
+ DataFile file = newDataFiles.iterator().next();
+ Expression exp = Expressions.startsWith(ICEBERG_FILE_PATH_COLUMN, (String) file.path());
+ if (FindFiles.in(table).withMetadataMatching(exp).collect().iterator().hasNext()) {
+ //This means this re-write event is duplicated with the one we already handled, so directly return
+ return;
+ }
+ //This is the case when the files to be deleted do not exist in table
+ //So we directly call addFiles interface to add new files into the table.
+ tableMetadata.appendFiles = Optional.of(tableMetadata.appendFiles.or(transaction::newAppend));
+ AppendFiles appendFiles = tableMetadata.appendFiles.get();
+ newDataFiles.forEach(appendFiles::appendFile);
+ return;
+ }
+ transaction.newRewrite().rewriteFiles(oldDataFiles, newDataFiles).commit();
+ }
+
+ /**
+ * Given the GMCE, get the iceberg schema with the origin ID specified by data pipeline which
+ * is corresponding to the file metrics index.
+ * @param gmce GMCE emitted by data pipeline
+ * @return iceberg schema with the origin ID
+ */
+ private Schema getSchemaWithOriginId(GobblinMetadataChangeEvent gmce) {
+ Schema schemaWithOriginId = null;
+ if (gmce.getAvroSchemaWithIcebergSchemaID() != null) {
+ org.apache.iceberg.shaded.org.apache.avro.Schema avroSchema =
+ new org.apache.iceberg.shaded.org.apache.avro.Schema.Parser().parse(gmce.getAvroSchemaWithIcebergSchemaID());
+ schemaWithOriginId = AvroSchemaUtil.toIceberg(avroSchema);
+ }
+ return schemaWithOriginId;
+ }
+
+ protected void dropFiles(GobblinMetadataChangeEvent gmce, Map<String, Collection<HiveSpec>> oldSpecsMap, Table table,
+ TableMetadata tableMetadata, TableIdentifier tid) throws IOException {
+ PartitionSpec partitionSpec = table.spec();
+ Transaction transaction = tableMetadata.transaction.get();
+ Set<DataFile> oldDataFiles =
+ getIcebergDataFilesToBeDeleted(gmce, table, new HashMap<>(), oldSpecsMap, partitionSpec);
+ tableMetadata.deleteFiles = Optional.of(tableMetadata.deleteFiles.or(transaction::newDelete));
+ DeleteFiles deleteFiles = tableMetadata.deleteFiles.get();
+ oldDataFiles.stream().forEach(deleteFiles::deleteFile);
+ parallelRunner.submitCallable(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ try {
+ long olderThan = getExpireSnapshotTime();
+ long start = System.currentTimeMillis();
+ ExpireSnapshots expireSnapshots = table.expireSnapshots();
+ final Table tmpTable = table;
+ expireSnapshots.deleteWith(new Consumer<String>() {
+ @Override
+ public void accept(String file) {
+ if (file.startsWith(tmpTable.location())) {
+ tmpTable.io().deleteFile(file);
+ }
+ }
+ }).expireOlderThan(olderThan).commit();
+ //TODO: emit these metrics to Ingraphs, in addition to metrics for publishing new snapshots and other Iceberg metadata operations.
+ log.info("Spent {} ms to expire snapshots older than {} ({}) in table {}", System.currentTimeMillis() - start,
+ new DateTime(olderThan).toString(), olderThan, tid.toString());
+ } catch (Exception e) {
+ log.error(String.format("Fail to expire snapshots for table %s due to exception ", tid.toString()), e);
+ }
+ return null;
+ }
+ }, tid.toString());
+ }
+
+ private long getExpireSnapshotTime() {
+ PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendYears()
+ .appendSuffix("y")
+ .appendMonths()
+ .appendSuffix("M")
+ .appendDays()
+ .appendSuffix("d")
+ .appendHours()
+ .appendSuffix("h")
+ .appendMinutes()
+ .appendSuffix("m")
+ .toFormatter();
+ return DateTime.now()
+ .minus(periodFormatter.parsePeriod(
+ conf.get(EXPIRE_SNAPSHOTS_LOOKBACK_TIME, DEFAULT_EXPIRE_SNAPSHOTS_LOOKBACK_TIME)))
+ .getMillis();
+ }
+
+ protected void addFiles(GobblinMetadataChangeEvent gmce, Map<String, Collection<HiveSpec>> newSpecsMap, Table table,
+ TableMetadata tableMetadata) throws IOException {
+ Transaction transaction = tableMetadata.transaction.get();
+ tableMetadata.appendFiles = Optional.of(tableMetadata.appendFiles.or(transaction::newAppend));
+ AppendFiles appendFiles = tableMetadata.appendFiles.get();
+ getIcebergDataFilesToBeAddedHelper(gmce, table, newSpecsMap, tableMetadata)
+ .forEach(dataFile -> {
+ appendFiles.appendFile(dataFile);
+ tableMetadata.addedFiles.put(dataFile.path(), "");
+ });
+ }
+
+ private Stream<DataFile> getIcebergDataFilesToBeAddedHelper(GobblinMetadataChangeEvent gmce, Table table, Map<String, Collection<HiveSpec>> newSpecsMap,
+ TableMetadata tableMetadata) throws IOException {
+ return getIcebergDataFilesToBeAdded(gmce.getNewFiles(), table.spec(), newSpecsMap,
+ IcebergUtils.getSchemaIdMap(getSchemaWithOriginId(gmce), table.schema())).stream()
+ .filter(dataFile -> tableMetadata.addedFiles.getIfPresent(dataFile.path()) == null);
+ }
+
+ /**
+ * Method to get dataFiles without metrics information
+ * This method is used to get files to be deleted from iceberg
+ * If oldFilePrefixes is specified in gmce, this method will use those prefixes to find old file in iceberg,
+ * or the method will callmethod {IcebergUtils.getIcebergDataFileWithMetric} to get DataFile for specific file path
+ */
+ private Set<DataFile> getIcebergDataFilesToBeDeleted(GobblinMetadataChangeEvent gmce, Table table,
+ Map<String, Collection<HiveSpec>> newSpecsMap, Map<String, Collection<HiveSpec>> oldSpecsMap,
+ PartitionSpec partitionSpec) throws IOException {
+ Set<DataFile> oldDataFiles = new HashSet<>();
+ if (gmce.getOldFilePrefixes() != null) {
+ Expression exp = Expressions.alwaysFalse();
+ for (String prefix : gmce.getOldFilePrefixes()) {
+ //Use both full path and raw path to delete old files
+ exp = Expressions.or(exp, Expressions.startsWith(ICEBERG_FILE_PATH_COLUMN, prefix));
+ String rawPathPrefix = new Path(prefix).toUri().getRawPath();
+ exp = Expressions.or(exp, Expressions.startsWith(ICEBERG_FILE_PATH_COLUMN, rawPathPrefix));
+ }
+ long start = System.currentTimeMillis();
+ oldDataFiles.addAll(Sets.newHashSet(FindFiles.in(table).withMetadataMatching(exp).collect().iterator()));
+ //Use INFO level log here to get better estimate.
+ //This shouldn't overwhelm the log since we receive less than 3 rewrite_file gmces for one table in one day
+ log.info("Spent {}ms to query all old files in iceberg.", System.currentTimeMillis() - start);
+ } else {
+ for (String file : gmce.getOldFiles()) {
+ String specPath = new Path(file).getParent().toString();
+ // For the use case of recompaction, the old path may contains /daily path, in this case, we find the spec from newSpecsMap
+ StructLike partition = getIcebergPartition(
+ oldSpecsMap.containsKey(specPath) ? oldSpecsMap.get(specPath) : newSpecsMap.get(specPath), file,
+ partitionSpec);
+ oldDataFiles.add(IcebergUtils.getIcebergDataFileWithoutMetric(file, partitionSpec, partition));
+ }
+ }
+ return oldDataFiles;
+ }
+
+ /**
+ * Method to get dataFiles with metrics information
+ * This method is used to get files to be added to iceberg
+ * This method will call method {IcebergUtils.getIcebergDataFileWithMetric} to get DataFile for specific file path
+ */
+ private Set<DataFile> getIcebergDataFilesToBeAdded(List<org.apache.gobblin.metadata.DataFile> files,
+ PartitionSpec partitionSpec, Map<String, Collection<HiveSpec>> newSpecsMap, Map<Integer, Integer> schemaIdMap)
+ throws IOException {
+ Set<DataFile> dataFiles = new HashSet<>();
+ for (org.apache.gobblin.metadata.DataFile file : files) {
+ try {
+ StructLike partition = getIcebergPartition(newSpecsMap.get(new Path(file.getFilePath()).getParent().toString()),
+ file.getFilePath(), partitionSpec);
+ dataFiles.add(IcebergUtils.getIcebergDataFileWithMetric(file, partitionSpec, partition, conf, schemaIdMap));
+ } catch (Exception e) {
+ log.warn("Cannot get DataFile for {} dur to {}", file.getFilePath(), e);
+ }
+ }
+ return dataFiles;
+ }
+
+ private StructLike getIcebergPartition(Collection<HiveSpec> specs, String filePath, PartitionSpec partitionSpec)
+ throws IOException {
+ if (specs == null || specs.isEmpty()) {
+ throw new IOException("Cannot get hive spec for " + filePath);
+ }
+ HivePartition hivePartition = specs.iterator().next().getPartition().orNull();
+ StructLike partition = hivePartition == null ? null
+ : IcebergUtils.getPartition(partitionSpec.partitionType(), hivePartition.getValues());
+ return partition;
+ }
+
+ /**
+ * For flush of each table, we do the following logic:
+ * 1. Commit the appendFiles if it exist
+ * 2. Update the new table property: high watermark of GMCE, data offset range, schema versions
+ * 3. Update the schema
+ * 4. Commit the transaction
+ * 5. reset tableMetadata
+ * @param dbName
+ * @param tableName
+ */
+ @Override
+ public void flush(String dbName, String tableName) throws IOException {
+ Lock writeLock = readWriteLock.writeLock();
+ writeLock.lock();
+ try {
+ TableIdentifier tid = TableIdentifier.of(dbName, tableName);
+ TableMetadata tableMetadata = tableMetadataMap.getOrDefault(tid, new TableMetadata());
+ if (tableMetadata.transaction.isPresent()) {
+ Transaction transaction = tableMetadata.transaction.get();
+ if (tableMetadata.appendFiles.isPresent()) {
+ tableMetadata.appendFiles.get().commit();
+ }
+ if (tableMetadata.deleteFiles.isPresent()) {
+ tableMetadata.deleteFiles.get().commit();
+ }
+ Map<String, String> props = tableMetadata.newProperties.or(
+ Maps.newHashMap(tableMetadata.lastProperties.or(getIcebergTable(tid).properties())));
+ //Set high waterMark
+ Long highWatermark = tableCurrentWaterMarkMap.get(tid);
+ props.put(String.format(GMCE_HIGH_WATERMARK_KEY, tableTopicpartitionMap.get(tid)), highWatermark.toString());
+ //Set low waterMark
+ props.put(String.format(GMCE_LOW_WATERMARK_KEY, tableTopicpartitionMap.get(tid)),
+ tableMetadata.lowWatermark.get().toString());
+ //Set whether to delete metadata files after commit
+ props.put(TableProperties.METADATA_DELETE_AFTER_COMMIT_ENABLED, Boolean.toString(
+ conf.getBoolean(TableProperties.METADATA_DELETE_AFTER_COMMIT_ENABLED,
+ TableProperties.METADATA_DELETE_AFTER_COMMIT_ENABLED_DEFAULT)));
+ props.put(TableProperties.METADATA_PREVIOUS_VERSIONS_MAX, Integer.toString(
+ conf.getInt(TableProperties.METADATA_PREVIOUS_VERSIONS_MAX,
+ TableProperties.METADATA_PREVIOUS_VERSIONS_MAX_DEFAULT)));
+ //Set data offset range
+ boolean containOffsetRange = setDatasetOffsetRange(tableMetadata, props);
+ String topicName = tableName;
+ if (containOffsetRange) {
+ String topicPartitionString = tableMetadata.dataOffsetRange.get().keySet().iterator().next();
+ //In case the topic name is not the table name or the topic name contains '-'
+ topicName = topicPartitionString.substring(0, topicPartitionString.lastIndexOf('-'));
+ }
+ //Update schema
+ updateSchema(tableMetadata, props, topicName);
+ //Update properties
+ UpdateProperties updateProperties = transaction.updateProperties();
+ props.forEach(updateProperties::set);
+ updateProperties.commit();
+ try (AutoCloseableHiveLock lock = this.locks.getTableLock(dbName, tableName)) {
+ transaction.commitTransaction();
+ }
+ Snapshot snapshot = tableMetadata.table.get().currentSnapshot();
+ Map<String, String> currentProps = tableMetadata.table.get().properties();
+ submitSnapshotCommitEvent(snapshot, tableMetadata, dbName, tableName, currentProps, highWatermark);
+ //Reset the table metadata for next accumulation period
+ tableMetadata.reset(currentProps, highWatermark);
+ log.info(String.format("Finish flushing for table %s", tid.toString()));
+ }
+ } catch (RuntimeException e) {
+ throw new RuntimeException(String.format("Fail to flush table %s %s", dbName, tableName), e);
+ } catch (Exception e) {
+ throw new IOException(String.format("Fail to flush table %s %s", dbName, tableName), e);
+ } finally {
+ writeLock.unlock();
+ }
+ }
+
+ private void submitSnapshotCommitEvent(Snapshot snapshot, TableMetadata tableMetadata, String dbName,
+ String tableName, Map<String, String> props, Long highWaterMark) {
+ GobblinEventBuilder gobblinTrackingEvent =
+ new GobblinEventBuilder(IcebergMCEMetadataKeys.ICEBERG_COMMIT_EVENT_NAME);
+ long currentSnapshotID = snapshot.snapshotId();
+ long endToEndLag = System.currentTimeMillis() - tableMetadata.lowestGMCEEmittedTime;
+ TableIdentifier tid = TableIdentifier.of(dbName, tableName);
+ String gmceTopicPartition = tableTopicpartitionMap.get(tid);
+
+ //Add information to automatically trigger repair jon when data loss happen
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.GMCE_TOPIC_NAME, gmceTopicPartition.split("-")[0]);
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.GMCE_TOPIC_PARTITION, gmceTopicPartition.split("-")[1]);
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.GMCE_HIGH_WATERMARK, highWaterMark.toString());
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.GMCE_LOW_WATERMARK,
+ tableMetadata.lowWatermark.get().toString());
+
+ //Add information for lag monitoring
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.LAG_KEY_NAME, Long.toString(endToEndLag));
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.SNAPSHOT_KEY_NAME, Long.toString(currentSnapshotID));
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.MANIFEST_LOCATION, snapshot.manifestListLocation());
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.SNAPSHOT_INFORMATION_KEY_NAME,
+ Joiner.on(",").withKeyValueSeparator("=").join(snapshot.summary()));
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.TABLE_KEY_NAME, tableName);
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.DATABASE_KEY_NAME, dbName);
+ gobblinTrackingEvent.addMetadata(IcebergMCEMetadataKeys.DATASET_HDFS_PATH, tableMetadata.datasetName);
+ for (Map.Entry<String, String> entry : props.entrySet()) {
+ if (entry.getKey().startsWith(OFFSET_RANGE_KEY_PREFIX)) {
+ gobblinTrackingEvent.addMetadata(entry.getKey(), entry.getValue());
+ }
+ }
+ eventSubmitter.submit(gobblinTrackingEvent);
+ }
+
+ private boolean setDatasetOffsetRange(TableMetadata tableMetadata, Map<String, String> props) {
+ if (tableMetadata.dataOffsetRange.isPresent() && !tableMetadata.dataOffsetRange.get().isEmpty()) {
+ for (Map.Entry<String, List<Range>> offsets : tableMetadata.dataOffsetRange.get().entrySet()) {
+ List<Range> ranges = offsets.getValue();
+ String rangeString = ranges.stream()
+ .map(r -> Joiner.on(ConfigurationKeys.RANGE_DELIMITER_KEY).join(r.lowerEndpoint(), r.upperEndpoint()))
+ .collect(Collectors.joining(ConfigurationKeys.LIST_DELIMITER_KEY));
+ props.put(String.format(OFFSET_RANGE_KEY_FORMAT, offsets.getKey()), rangeString);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private void updateSchema(TableMetadata tableMetadata, Map<String, String> props, String topicName) {
+ //Set default schema versions
+ props.put(SCHEMA_CREATION_TIME_KEY, tableMetadata.lastSchemaVersion.or(DEFAULT_CREATION_TIME));
+ // Update Schema
+ try {
+ if (tableMetadata.candidateSchemas.isPresent() && tableMetadata.candidateSchemas.get().size() > 0) {
+ Cache candidates = tableMetadata.candidateSchemas.get();
+ //Only have default schema, so either we calculate schema from event or the schema does not have creation time, directly update it
+ if (candidates.size() == 1 && candidates.getIfPresent(DEFAULT_CREATION_TIME) != null) {
+ updateSchemaHelper(DEFAULT_CREATION_TIME, (Schema) candidates.getIfPresent(DEFAULT_CREATION_TIME), props,
+ tableMetadata.table.get());
+ } else {
+ //update schema if candidates contains the schema that has the same creation time with the latest schema
+ org.apache.avro.Schema latestSchema =
+ (org.apache.avro.Schema) schemaRegistry.getLatestSchemaByTopic(topicName);
+ String creationTime = AvroUtils.getSchemaCreationTime(latestSchema);
+ if (creationTime == null) {
+ log.warn(
+ "Schema from schema registry does not contain creation time, check config for schema registry class");
+ } else if (candidates.getIfPresent(creationTime) != null) {
+ updateSchemaHelper(creationTime, (Schema) candidates.getIfPresent(creationTime), props,
+ tableMetadata.table.get());
+ }
+ }
+ }
+ } catch (SchemaRegistryException e) {
+ log.error("Cannot get schema form schema registry, will not update this schema", e);
+ }
+ }
+
+ private void updateSchemaHelper(String schemaCreationTime, Schema schema, Map<String, String> props, Table table) {
+ try {
+ table.updateSchema().unionByNameWith(schema).commit();
+ props.put(SCHEMA_CREATION_TIME_KEY, schemaCreationTime);
+ } catch (Exception e) {
+ log.error("Cannot update schema to " + schema.toString() + "for table " + table.location(), e);
+ }
+ }
+
+ @Override
+ public void writeEnvelope(RecordEnvelope<GenericRecord> recordEnvelope, Map<String, Collection<HiveSpec>> newSpecsMap,
+ Map<String, Collection<HiveSpec>> oldSpecsMap, HiveSpec tableSpec) throws IOException {
+ Lock readLock = readWriteLock.readLock();
+ readLock.lock();
+ try {
+ GenericRecord genericRecord = recordEnvelope.getRecord();
+ GobblinMetadataChangeEvent gmce =
+ (GobblinMetadataChangeEvent) SpecificData.get().deepCopy(genericRecord.getSchema(), genericRecord);
+ if (whiteistBlacklist.acceptTable(tableSpec.getTable().getDbName(), tableSpec.getTable().getTableName())) {
+ TableIdentifier tid = TableIdentifier.of(tableSpec.getTable().getDbName(), tableSpec.getTable().getTableName());
+ String topicPartition = tableTopicpartitionMap.computeIfAbsent(tid,
+ t -> ((KafkaStreamingExtractor.KafkaWatermark) recordEnvelope.getWatermark()).getTopicPartition().toString());
+ Long currentWatermark = getCurrentWaterMark(tid, topicPartition);
+ Long currentOffset =
+ ((KafkaStreamingExtractor.KafkaWatermark) recordEnvelope.getWatermark()).getLwm().getValue();
+ if (currentOffset > currentWatermark) {
+ if (currentWatermark == DEFAULT_WATERMARK) {
+ //This means we haven't register this table or the GMCE topic partition changed, we need to reset the low watermark
+ tableMetadataMap.computeIfAbsent(tid, t -> new TableMetadata()).lowWatermark =
+ Optional.of(currentOffset - 1);
+ }
+ tableMetadataMap.get(tid).datasetName = gmce.getDatasetIdentifier().getNativeName();
+ write(gmce, newSpecsMap, oldSpecsMap, tableSpec);
+ tableCurrentWaterMarkMap.put(tid,
+ ((KafkaStreamingExtractor.KafkaWatermark) recordEnvelope.getWatermark()).getLwm().getValue());
+ } else {
+ log.warn(String.format("Skip processing record %s since it has lower watermark", genericRecord.toString()));
+ }
+ } else {
+ log.info(String.format("Skip table %s.%s since it's blacklisted", tableSpec.getTable().getDbName(),
+ tableSpec.getTable().getTableName()));
+ }
+ } finally {
+ readLock.unlock();
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ this.closer.close();
+ }
+
+ private class TableMetadata {
+ Optional<Transaction> transaction = Optional.absent();
+ Optional<Table> table = Optional.absent();
+ Optional<AppendFiles> appendFiles = Optional.absent();
+ Optional<DeleteFiles> deleteFiles = Optional.absent();
+ Optional<Map<String, String>> lastProperties = Optional.absent();
+ Optional<Map<String, String>> newProperties = Optional.absent();
+ Optional<Cache<String, Schema>> candidateSchemas = Optional.absent();
+ Optional<Map<String, List<Range>>> dataOffsetRange = Optional.absent();
+ Optional<String> lastSchemaVersion = Optional.absent();
+ Optional<Long> lowWatermark = Optional.absent();
+ String datasetName;
+ Cache<CharSequence, String> addedFiles = CacheBuilder.newBuilder()
+ .expireAfterAccess(conf.getInt(ADDED_FILES_CACHE_EXPIRING_TIME, DEFAULT_ADDED_FILES_CACHE_EXPIRING_TIME),
+ TimeUnit.HOURS)
+ .build();
+ long lowestGMCEEmittedTime = Long.MAX_VALUE;
+
+ public void reset(Map<String, String> props, Long lowWaterMark) {
+ this.lastProperties = Optional.of(props);
+ this.lastSchemaVersion = Optional.of(props.get(SCHEMA_CREATION_TIME_KEY));
+ //clear cache
+ this.transaction = Optional.absent();
+ this.deleteFiles = Optional.absent();
+ this.appendFiles = Optional.absent();
+ this.candidateSchemas = Optional.absent();
+ this.dataOffsetRange = Optional.absent();
+ this.newProperties = Optional.absent();
+ this.lowestGMCEEmittedTime = Long.MAX_VALUE;
+ this.lowWatermark = Optional.of(lowWaterMark);
+ }
+ }
+}
diff --git a/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/MetadataWriter.java b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/MetadataWriter.java
new file mode 100644
index 0000000..03a6d5b
--- /dev/null
+++ b/gobblin-iceberg/src/main/java/org/apache/gobblin/iceberg/writer/MetadataWriter.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.writer;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Map;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.gobblin.hive.spec.HiveSpec;
+import org.apache.gobblin.stream.RecordEnvelope;
+
+
+/**
+ * This is the interface of the writer which is used to calculate and accumulate the desired metadata and register to the metadata store
+ */
+public interface MetadataWriter extends Closeable {
+ /*
+ Register the metadata of specific table to the metadata store
+ */
+ public void flush(String dbName, String tableName) throws IOException;
+
+ /*
+ Compute and cache the metadata from the GMCE
+ */
+ public void writeEnvelope(RecordEnvelope<GenericRecord> recordEnvelope, Map<String, Collection<HiveSpec>> newSpecsMap,
+ Map<String, Collection<HiveSpec>> oldSpecsMap, HiveSpec tableSpec) throws IOException;
+}
diff --git a/gobblin-iceberg/src/test/java/org/apache/gobblin/iceberg/publisher/GobblinMCEPublisherTest.java b/gobblin-iceberg/src/test/java/org/apache/gobblin/iceberg/publisher/GobblinMCEPublisherTest.java
new file mode 100644
index 0000000..63cdce2
--- /dev/null
+++ b/gobblin-iceberg/src/test/java/org/apache/gobblin/iceberg/publisher/GobblinMCEPublisherTest.java
@@ -0,0 +1,268 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.publisher;
+
+import azkaban.jobExecutor.AbstractJob;
+import com.google.common.io.Closer;
+import com.google.common.io.Files;
+import java.io.InputStream;
+import java.util.ArrayList;
+import org.apache.avro.generic.GenericDatumReader;
+import org.apache.avro.io.Decoder;
+import org.apache.avro.io.DecoderFactory;
+import org.apache.gobblin.hive.policy.HiveSnapshotRegistrationPolicy;
+import org.apache.gobblin.iceberg.GobblinMCEProducer;
+import org.apache.gobblin.metadata.GobblinMetadataChangeEvent;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metadata.SchemaSource;
+import gobblin.configuration.WorkUnitState;
+import java.io.File;
+import java.io.IOException;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import org.apache.avro.Schema;
+import org.apache.avro.SchemaBuilder;
+import org.apache.avro.file.DataFileWriter;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericDatumWriter;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.io.DatumWriter;
+import org.apache.commons.io.FileUtils;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.source.workunit.WorkUnit;
+import org.apache.gobblin.writer.FsDataWriterBuilder;
+import org.apache.gobblin.writer.GobblinOrcWriter;
+import org.apache.gobblin.writer.PartitionedDataWriter;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.Metrics;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
+
+
+public class GobblinMCEPublisherTest {
+
+ Schema avroDataSchema = SchemaBuilder.record("test")
+ .fields()
+ .name("id")
+ .type()
+ .longType()
+ .noDefault()
+ .name("data")
+ .type()
+ .optional()
+ .stringType()
+ .endRecord();
+ Schema _avroPartitionSchema;
+ private String dbName = "hivedb";
+
+ static File tmpDir;
+ static File dataDir;
+ static File dataFile;
+ static File datasetDir;
+ static Path orcFilePath;
+ static String orcSchema;
+
+ public static final List<GenericRecord> deserializeAvroRecords(Class clazz, Schema schema, String schemaPath)
+ throws IOException {
+ List<GenericRecord> records = new ArrayList<>();
+
+ GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
+
+ InputStream dataInputStream = clazz.getClassLoader().getResourceAsStream(schemaPath);
+ Decoder decoder = DecoderFactory.get().jsonDecoder(schema, dataInputStream);
+ GenericRecord recordContainer = reader.read(null, decoder);
+ ;
+ try {
+ while (recordContainer != null) {
+ records.add(recordContainer);
+ recordContainer = reader.read(null, decoder);
+ }
+ } catch (IOException ioe) {
+ dataInputStream.close();
+ }
+ return records;
+ }
+ @BeforeClass
+ public void setUp() throws Exception {
+ tmpDir = Files.createTempDir();
+ datasetDir = new File(tmpDir, "/data/tracking/testTable");
+ dataFile = new File(datasetDir, "/hourly/2020/03/17/08/data.avro");
+ Files.createParentDirs(dataFile);
+ dataDir = new File(dataFile.getParent());
+ Assert.assertTrue(dataDir.exists());
+ writeRecord();
+ _avroPartitionSchema =
+ SchemaBuilder.record("partitionTest").fields().name("ds").type().optional().stringType().endRecord();
+
+ //Write ORC file for test
+ Schema schema =
+ new Schema.Parser().parse(this.getClass().getClassLoader().getResourceAsStream("publisherTest/schema.avsc"));
+ orcSchema = schema.toString();
+ List<GenericRecord> recordList = deserializeAvroRecords(this.getClass(), schema, "publisherTest/data.json");
+
+ // Mock WriterBuilder, bunch of mocking behaviors to work-around precondition checks in writer builder
+ FsDataWriterBuilder<Schema, GenericRecord> mockBuilder =
+ (FsDataWriterBuilder<Schema, GenericRecord>) Mockito.mock(FsDataWriterBuilder.class);
+ when(mockBuilder.getSchema()).thenReturn(schema);
+
+ State dummyState = new WorkUnit();
+ String stagingDir = new File(tmpDir, "/orc/staging").getAbsolutePath();
+ String outputDir = new File(tmpDir, "/orc/output").getAbsolutePath();
+ dummyState.setProp(ConfigurationKeys.WRITER_STAGING_DIR, stagingDir);
+ dummyState.setProp(ConfigurationKeys.WRITER_FILE_PATH, "simple");
+ dummyState.setProp(ConfigurationKeys.WRITER_OUTPUT_DIR, outputDir);
+ dummyState.setProp(ConfigurationKeys.WRITER_STAGING_DIR, stagingDir);
+ when(mockBuilder.getFileName(dummyState)).thenReturn("file.orc");
+ orcFilePath = new Path(outputDir, "simple/file.orc");
+
+ // Having a closer to manage the life-cycle of the writer object.
+ // Will verify if scenarios like double-close could survive.
+ Closer closer = Closer.create();
+ GobblinOrcWriter orcWriter = closer.register(new GobblinOrcWriter(mockBuilder, dummyState));
+
+ for (GenericRecord record : recordList) {
+ orcWriter.write(record);
+ }
+
+ orcWriter.commit();
+ orcWriter.close();
+
+ // Verify ORC file contains correct records.
+ FileSystem fs = FileSystem.getLocal(new Configuration());
+ Assert.assertTrue(fs.exists(orcFilePath));
+ }
+
+ @AfterClass
+ public void cleanUp() throws Exception {
+ FileUtils.forceDeleteOnExit(tmpDir);
+ }
+
+ @Test
+ public void testPublishGMCEForAvro() throws IOException {
+ GobblinMCEProducer producer = Mockito.mock(GobblinMCEProducer.class);
+ Mockito.doCallRealMethod()
+ .when(producer)
+ .getGobblinMetadataChangeEvent(anyMap(), anyList(), anyList(), anyMap(), any(), any());
+ Mockito.doAnswer(new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Object[] args = invocation.getArguments();
+ GobblinMetadataChangeEvent gmce =
+ producer.getGobblinMetadataChangeEvent((Map<Path, Metrics>) args[0], null, null,
+ (Map<String, String>) args[1], OperationType.add_files, SchemaSource.SCHEMAREGISTRY);
+ Assert.assertEquals(gmce.getNewFiles().size(), 1);
+ FileSystem fs = FileSystem.get(new Configuration());
+ Assert.assertEquals(gmce.getNewFiles().get(0).getFilePath(),
+ new Path(dataFile.getAbsolutePath()).makeQualified(fs.getUri(), new Path("/")).toString());
+ return null;
+ }
+ }).when(producer).sendGMCE(anyMap(), anyList(), anyList(), anyMap(), any(), any());
+
+ WorkUnitState state = new WorkUnitState();
+ setGMCEPublisherStateForAvroFile(state);
+ Mockito.doCallRealMethod().when(producer).setState(state);
+ producer.setState(state);
+ GobblinMCEPublisher publisher = new GobblinMCEPublisher(state, producer);
+ publisher.publishData(Arrays.asList(state));
+ }
+
+ @Test
+ public void testPublishGMCEForORC() throws IOException {
+ GobblinMCEProducer producer = Mockito.mock(GobblinMCEProducer.class);
+ Mockito.doCallRealMethod()
+ .when(producer)
+ .getGobblinMetadataChangeEvent(anyMap(), anyList(), anyList(), anyMap(), any(), any());
+ Mockito.doAnswer(new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Object[] args = invocation.getArguments();
+ GobblinMetadataChangeEvent gmce =
+ producer.getGobblinMetadataChangeEvent((Map<Path, Metrics>) args[0], null, null,
+ (Map<String, String>) args[1], OperationType.add_files, SchemaSource.SCHEMAREGISTRY);
+ Assert.assertEquals(gmce.getNewFiles().size(), 1);
+ FileSystem fs = FileSystem.get(new Configuration());
+ Charset charset = Charset.forName("UTF-8");
+ CharsetEncoder encoder = charset.newEncoder();
+ Assert.assertEquals(gmce.getNewFiles().get(0).getFilePath(),
+ orcFilePath.makeQualified(fs.getUri(), new Path("/")).toString());
+ Assert.assertEquals(gmce.getNewFiles().get(0).getFileMetrics().getLowerBounds().get(1).getValue(),
+ encoder.encode(CharBuffer.wrap("Alyssa")));
+ Assert.assertEquals(gmce.getNewFiles().get(0).getFileMetrics().getUpperBounds().get(1).getValue(),
+ encoder.encode(CharBuffer.wrap("Bob")));
+ return null;
+ }
+ }).when(producer).sendGMCE(anyMap(), anyList(), anyList(), anyMap(), any(), any());
+
+ WorkUnitState state = new WorkUnitState();
+ setGMCEPublisherStateForOrcFile(state);
+ Mockito.doCallRealMethod().when(producer).setState(state);
+ producer.setState(state);
+ GobblinMCEPublisher publisher = new GobblinMCEPublisher(state, producer);
+ publisher.publishData(Arrays.asList(state));
+ }
+
+ private void setGMCEPublisherStateForOrcFile(WorkUnitState state) {
+ state.setProp(GobblinMCEPublisher.NEW_FILES_LIST, orcFilePath.toString());
+ state.setProp(ConfigurationKeys.WRITER_OUTPUT_FORMAT_KEY, "ORC");
+ state.setProp(GobblinMCEPublisher.OFFSET_RANGE_KEY, "testTopic-1:0-1000");
+ state.setProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY,
+ HiveSnapshotRegistrationPolicy.class.getCanonicalName());
+ state.setProp(ConfigurationKeys.DATA_PUBLISHER_DATASET_DIR, datasetDir.toString());
+ state.setProp(AbstractJob.JOB_ID, "testFlow");
+ state.setProp(PartitionedDataWriter.WRITER_LATEST_SCHEMA, orcSchema);
+ }
+
+ private void setGMCEPublisherStateForAvroFile(WorkUnitState state) {
+ state.setProp(GobblinMCEPublisher.NEW_FILES_LIST, dataFile.toString());
+ state.setProp(ConfigurationKeys.WRITER_OUTPUT_FORMAT_KEY, "AVRO");
+ state.setProp(GobblinMCEPublisher.OFFSET_RANGE_KEY, "testTopic-1:0-1000");
+ state.setProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY,
+ HiveSnapshotRegistrationPolicy.class.getCanonicalName());
+ state.setProp(ConfigurationKeys.DATA_PUBLISHER_DATASET_DIR, datasetDir.toString());
+ state.setProp(AbstractJob.JOB_ID, "testFlow");
+ state.setProp(PartitionedDataWriter.WRITER_LATEST_SCHEMA, _avroPartitionSchema);
+ }
+
+ private String writeRecord() throws IOException {
+ GenericData.Record record = new GenericData.Record(avroDataSchema);
+ record.put("id", 1L);
+ record.put("data", "data");
+ String path = dataFile.toString();
+ DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>();
+ DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
+ dataFileWriter.create(avroDataSchema, dataFile);
+ dataFileWriter.append(record);
+ dataFileWriter.close();
+ return path;
+ }
+}
diff --git a/gobblin-iceberg/src/test/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriterTest.java b/gobblin-iceberg/src/test/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriterTest.java
new file mode 100644
index 0000000..4f1e156
--- /dev/null
+++ b/gobblin-iceberg/src/test/java/org/apache/gobblin/iceberg/writer/GobblinMCEWriterTest.java
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gobblin.iceberg.writer;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.io.Files;
+import java.io.File;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import org.apache.avro.SchemaBuilder;
+import org.apache.avro.file.DataFileWriter;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericDatumWriter;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.io.DatumWriter;
+import org.apache.commons.io.FileUtils;
+import org.apache.gobblin.configuration.State;
+import org.apache.gobblin.hive.HiveMetastoreClientPool;
+import org.apache.gobblin.hive.HivePartition;
+import org.apache.gobblin.hive.HiveRegister;
+import org.apache.gobblin.hive.HiveTable;
+import org.apache.gobblin.hive.policy.HiveRegistrationPolicyBase;
+import org.apache.gobblin.metadata.DataFile;
+import org.apache.gobblin.metadata.DataMetrics;
+import org.apache.gobblin.metadata.DataOrigin;
+import org.apache.gobblin.metadata.DatasetIdentifier;
+import org.apache.gobblin.metadata.GobblinMetadataChangeEvent;
+import org.apache.gobblin.metadata.OperationType;
+import org.apache.gobblin.metadata.SchemaSource;
+import org.apache.gobblin.metrics.kafka.KafkaSchemaRegistry;
+import org.apache.gobblin.source.extractor.extract.LongWatermark;
+import org.apache.gobblin.source.extractor.extract.kafka.KafkaPartition;
+import org.apache.gobblin.source.extractor.extract.kafka.KafkaStreamTestUtils;
+import org.apache.gobblin.source.extractor.extract.kafka.KafkaStreamingExtractor;
+import org.apache.gobblin.stream.RecordEnvelope;
+import org.apache.gobblin.util.ClustersNames;
+import org.apache.gobblin.util.ConfigUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.iceberg.FindFiles;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.hive.HiveMetastoreTest;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+
+public class GobblinMCEWriterTest extends HiveMetastoreTest {
+
+ org.apache.avro.Schema avroDataSchema = SchemaBuilder.record("test")
+ .fields()
+ .name("id")
+ .type()
+ .longType()
+ .noDefault()
+ .name("data")
+ .type()
+ .optional()
+ .stringType()
+ .endRecord();
+ org.apache.avro.Schema _avroPartitionSchema;
+ private String dbName = "hivedb";
+ private String tableName = "testTable";
+
+ private GobblinMCEWriter gobblinMCEWriter;
+
+ GobblinMetadataChangeEvent gmce;
+ static File tmpDir;
+ static File dataDir;
+ static File hourlyDataFile_2;
+ static File hourlyDataFile_1;
+ static File dailyDataFile;
+
+ @AfterClass
+ public void clean() throws Exception {
+ stopMetastore();
+ gobblinMCEWriter.close();
+ FileUtils.forceDeleteOnExit(tmpDir);
+ }
+ @BeforeClass
+ public void setUp() throws Exception {
+ Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
+ startMetastore();
+ State state = ConfigUtils.configToState(ConfigUtils.propertiesToConfig(hiveConf.getAllProperties()));
+ Optional<String> metastoreUri = Optional.fromNullable(state.getProperties().getProperty(HiveRegister.HIVE_METASTORE_URI_KEY));
+ HiveMetastoreClientPool hc = HiveMetastoreClientPool.get(state.getProperties(), metastoreUri);
+ tmpDir = Files.createTempDir();
+ hourlyDataFile_1 = new File(tmpDir, "data/tracking/testTable/hourly/2020/03/17/08/data.avro");
+ Files.createParentDirs(hourlyDataFile_1);
+ hourlyDataFile_2 = new File(tmpDir, "data/tracking/testTable/hourly/2020/03/17/09/data.avro");
+ Files.createParentDirs(hourlyDataFile_2);
+ dailyDataFile = new File(tmpDir, "data/tracking/testTable/daily/2020/03/17/data.avro");
+ Files.createParentDirs(dailyDataFile);
+ dataDir = new File(hourlyDataFile_1.getParent());
+ Assert.assertTrue(dataDir.exists());
+ writeRecord(hourlyDataFile_1);
+ writeRecord(hourlyDataFile_2);
+ writeRecord(dailyDataFile);
+ gmce = GobblinMetadataChangeEvent.newBuilder()
+ .setDatasetIdentifier(DatasetIdentifier.newBuilder()
+ .setDataOrigin(DataOrigin.EI)
+ .setDataPlatformUrn("urn:li:dataPlatform:hdfs")
+ .setNativeName("/data/tracking/testTable")
+ .build())
+ .setTopicPartitionOffsetsRange(ImmutableMap.<String, String>builder().put("testTopic-1", "0-1000").build())
+ .setFlowId("testFlow")
+ .setNewFiles(Lists.newArrayList(DataFile.newBuilder()
+ .setFilePath(hourlyDataFile_1.toString())
+ .setFileFormat("avro")
+ .setFileMetrics(DataMetrics.newBuilder().setRecordCount(10L).build())
+ .build()))
+ .setSchemaSource(SchemaSource.EVENT)
+ .setOperationType(OperationType.add_files)
+ .setTableSchema(avroDataSchema.toString())
+ .setCluster(ClustersNames.getInstance().getClusterName())
+ .setPartitionColumns(Lists.newArrayList("testpartition"))
+ .setRegistrationPolicy(TestHiveRegistrationPolicy.class.getName())
+ .setRegistrationProperties(ImmutableMap.<String, String>builder().put("hive.database.name", dbName).build())
+ .build();
+ state.setProp(KafkaSchemaRegistry.KAFKA_SCHEMA_REGISTRY_CLASS,
+ KafkaStreamTestUtils.MockSchemaRegistry.class.getName());
+ state.setProp("default.hive.registration.policy",
+ TestHiveRegistrationPolicy.class.getName());
+ gobblinMCEWriter = new GobblinMCEWriter(new GobblinMCEWriterBuilder(), state);
+ ((IcebergMetadataWriter) gobblinMCEWriter.getMetadataWriters().iterator().next()).setCatalog(
+ HiveMetastoreTest.catalog);
+ _avroPartitionSchema =
+ SchemaBuilder.record("partitionTest").fields().name("ds").type().optional().stringType().endRecord();
+ }
+
+ @Test
+ public void testWriteAddFileGMCE() throws IOException {
+ gobblinMCEWriter.writeEnvelope(new RecordEnvelope<>(gmce,
+ new KafkaStreamingExtractor.KafkaWatermark(
+ new KafkaPartition.Builder().withTopicName("GobblinMetadataChangeEvent_test").withId(1).build(),
+ new LongWatermark(10L))));
+ Assert.assertEquals(catalog.listTables(Namespace.of(dbName)).size(), 1);
+ Table table = catalog.loadTable(catalog.listTables(Namespace.of(dbName)).get(0));
+ Assert.assertFalse(table.properties().containsKey("offset.range.testTopic-1"));
+ gmce.setTopicPartitionOffsetsRange(ImmutableMap.<String, String>builder().put("testTopic-1", "1000-2000").build());
+ gobblinMCEWriter.writeEnvelope(new RecordEnvelope<>(gmce,
+ new KafkaStreamingExtractor.KafkaWatermark(
+ new KafkaPartition.Builder().withTopicName("GobblinMetadataChangeEvent_test").withId(1).build(),
+ new LongWatermark(20L))));
+ gobblinMCEWriter.flush();
+ table = catalog.loadTable(catalog.listTables(Namespace.of(dbName)).get(0));
+ Assert.assertEquals(table.properties().get("offset.range.testTopic-1"), "0-2000");
+ Assert.assertEquals(table.currentSnapshot().allManifests().size(), 1);
+ // Assert low watermark and high watermark set properly
+ Assert.assertEquals(table.properties().get("gmce.low.watermark.GobblinMetadataChangeEvent_test-1"), "9");
+ Assert.assertEquals(table.properties().get("gmce.high.watermark.GobblinMetadataChangeEvent_test-1"), "20");
+
+ /*test flush twice*/
+ gmce.setTopicPartitionOffsetsRange(ImmutableMap.<String, String>builder().put("testTopic-1", "2000-3000").build());
+ gmce.setNewFiles(Lists.newArrayList(DataFile.newBuilder()
+ .setFilePath(hourlyDataFile_2.toString())
+ .setFileFormat("avro")
+ .setFileMetrics(DataMetrics.newBuilder().setRecordCount(10L).build())
+ .build()));
+ gobblinMCEWriter.writeEnvelope(new RecordEnvelope<>(gmce,
+ new KafkaStreamingExtractor.KafkaWatermark(
+ new KafkaPartition.Builder().withTopicName("GobblinMetadataChangeEvent_test").withId(1).build(),
+ new LongWatermark(30L))));
+ gobblinMCEWriter.flush();
+ table = catalog.loadTable(catalog.listTables(Namespace.of(dbName)).get(0));
+ Assert.assertEquals(table.properties().get("offset.range.testTopic-1"), "0-3000");
+ Assert.assertEquals(table.currentSnapshot().allManifests().size(), 2);
+ Assert.assertEquals(table.properties().get("gmce.low.watermark.GobblinMetadataChangeEvent_test-1"), "20");
+ Assert.assertEquals(table.properties().get("gmce.high.watermark.GobblinMetadataChangeEvent_test-1"), "30");
+
+ /* Test it will skip event with lower watermark*/
+ gmce.setTopicPartitionOffsetsRange(ImmutableMap.<String, String>builder().put("testTopic-1", "3000-4000").build());
+ gobblinMCEWriter.writeEnvelope(new RecordEnvelope<>(gmce,
+ new KafkaStreamingExtractor.KafkaWatermark(
+ new KafkaPartition.Builder().withTopicName("GobblinMetadataChangeEvent_test").withId(1).build(),
+ new LongWatermark(30L))));
+ gobblinMCEWriter.flush();
+ table = catalog.loadTable(catalog.listTables(Namespace.of(dbName)).get(0));
+ Assert.assertEquals(table.properties().get("offset.range.testTopic-1"), "0-3000");
+ Assert.assertEquals(table.currentSnapshot().allManifests().size(), 2);
+ }
+
+ @Test(dependsOnMethods = {"testWriteAddFileGMCE"})
+ public void testWriteRewriteFileGMCE() throws IOException {
+ gmce.setTopicPartitionOffsetsRange(null);
+ FileSystem fs = FileSystem.get(new Configuration());
+ String filePath = new Path(hourlyDataFile_1.getParentFile().getAbsolutePath()).toString();
+ String filePath_1 = new Path(hourlyDataFile_2.getParentFile().getAbsolutePath()).toString();
+ DataFile dailyFile = DataFile.newBuilder()
+ .setFilePath(dailyDataFile.toString())
+ .setFileFormat("avro")
+ .setFileMetrics(DataMetrics.newBuilder().setRecordCount(10L).build())
+ .build();
+ gmce.setNewFiles(Lists.newArrayList(dailyFile));
+ gmce.setOldFilePrefixes(Lists.newArrayList(filePath, filePath_1));
+ gmce.setOperationType(OperationType.rewrite_files);
+ Table table = catalog.loadTable(catalog.listTables(Namespace.of(dbName)).get(0));
+ Iterator<org.apache.iceberg.DataFile>
+ result = FindFiles.in(table).withMetadataMatching(Expressions.startsWith("file_path", filePath_1)).collect().iterator();
+ Assert.assertEquals(table.currentSnapshot().allManifests().size(), 2);
+ Assert.assertTrue(result.hasNext());
+ gobblinMCEWriter.writeEnvelope(new RecordEnvelope<>(gmce,
+ new KafkaStreamingExtractor.KafkaWatermark(
+ new KafkaPartition.Builder().withTopicName("GobblinMetadataChangeEvent_test").withId(1).build(),
+ new LongWatermark(40L))));
+ gobblinMCEWriter.flush();
+ table = catalog.loadTable(catalog.listTables(Namespace.of(dbName)).get(0));
+ String dailyFilePath = new Path(dailyDataFile.toString()).toString();
+ result = FindFiles.in(table).withMetadataMatching(Expressions.startsWith("file_path", dailyFilePath)).collect().iterator();
+ Assert.assertEquals(result.next().path(), dailyFilePath);
+ Assert.assertFalse(result.hasNext());
+ result = FindFiles.in(table).withMetadataMatching(Expressions.startsWith("file_path", filePath)).collect().iterator();
+ Assert.assertFalse(result.hasNext());
+ result = FindFiles.in(table).withMetadataMatching(Expressions.startsWith("file_path", filePath_1)).collect().iterator();
+ Assert.assertFalse(result.hasNext());
+ }
+
+ private String writeRecord(File file) throws IOException {
+ GenericData.Record record = new GenericData.Record(avroDataSchema);
+ record.put("id", 1L);
+ record.put("data", "data");
+ String path = file.toString();
+ DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>();
+ DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
+ dataFileWriter.create(avroDataSchema, file);
+ dataFileWriter.append(record);
+ dataFileWriter.close();
+ return path;
+ }
+
+ public static class TestHiveRegistrationPolicy extends HiveRegistrationPolicyBase {
+
+ public TestHiveRegistrationPolicy(State props) throws IOException {
+ super(props);
+ }
+ protected Optional<HivePartition> getPartition(Path path, HiveTable table) throws IOException {
+ return Optional.of(new HivePartition.Builder().withPartitionValues(Lists.newArrayList("2020-03-17-03"))
+ .withDbName("hivedb").withTableName("testTable").build());
+ }
+ protected Iterable<String> getDatabaseNames(Path path) {
+ return Lists.newArrayList("hivedb");
+ }
+ protected List<String> getTableNames(Optional<String> dbPrefix, Path path) {
+ return Lists.newArrayList("testTable");
+ }
+ }
+}
+
diff --git a/gobblin-iceberg/src/test/resources/publisherTest/data.json b/gobblin-iceberg/src/test/resources/publisherTest/data.json
new file mode 100644
index 0000000..6a41a43
--- /dev/null
+++ b/gobblin-iceberg/src/test/resources/publisherTest/data.json
@@ -0,0 +1,8 @@
+{
+ "id": 1,
+ "name": "Alyssa"
+}
+{
+ "id": 2,
+ "name": "Bob"
+}
\ No newline at end of file
diff --git a/gobblin-iceberg/src/test/resources/publisherTest/schema.avsc b/gobblin-iceberg/src/test/resources/publisherTest/schema.avsc
new file mode 100644
index 0000000..ab62e54
--- /dev/null
+++ b/gobblin-iceberg/src/test/resources/publisherTest/schema.avsc
@@ -0,0 +1,15 @@
+{
+ "namespace": "org.apache.gobblin.orc",
+ "type": "record",
+ "name": "ORCTest",
+ "fields": [
+ {
+ "name": "id",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "type": "string"
+ }
+ ]
+}
diff --git a/gobblin-metrics-libs/gobblin-metrics-base/src/main/avro/DatasetIdentifier.avsc b/gobblin-metrics-libs/gobblin-metrics-base/src/main/avro/DatasetIdentifier.avsc
new file mode 100644
index 0000000..8a1daa9
--- /dev/null
+++ b/gobblin-metrics-libs/gobblin-metrics-base/src/main/avro/DatasetIdentifier.avsc
@@ -0,0 +1,39 @@
+[
+ {
+ "type": "enum",
+ "name": "DataOrigin",
+ "namespace": "org.apache.gobblin.metadata",
+ "doc": "Where the record was originally produced. When we copy EI data to PROD database, the origin = EI. When we copy PROD data to DEV database, the origin = PROD",
+ "symbols": ["PROD", "CORP", "EI", "DEV"],
+ "symbolDocs": {
+ "PROD": "data are generated in production tier or by services in PROD",
+ "CORP": "data are generated in corporate tier or by services in CORP",
+ "EI": "data are generated in engineering integration tier or by service in EI",
+ "DEV": "data are generated in development tier or by service in DEV"
+ }
+ },
+ {
+ "type": "record",
+ "name": "DatasetIdentifier",
+ "namespace": "org.apache.gobblin.metadata",
+ "doc": "This is the unique identifier of a dataset, which contains three parts: dataPlatform, name, origin/fabric",
+ "fields": [
+ {
+ "name": "dataPlatformUrn",
+ "type": "string",
+ "doc": "The platform or type of the metadata object: espresso,kafka,oracle,voldemort,hdfs,hive,dalids,teradata,... for example, urn:li:dataPlatform:espresso, urn:li:dataPlatform:dalids"
+ },
+ {
+ "name": "nativeName",
+ "type": "string",
+ "doc": "The native name: <db>.<table>, /dir/subdir/<name>, or <name>"
+ },
+ {
+ "name": "dataOrigin",
+ "type": "DataOrigin",
+ "doc": "Origin/Source tier where the record is generated? This can be different from Deployment. For example, PROD data can be copied to a TEST server, then DataOrigin=PROD while the dataset instance belongs to TEST",
+ "default": "PROD"
+ }
+ ]
+ }
+]
\ No newline at end of file
diff --git a/gobblin-metrics-libs/gobblin-metrics-base/src/main/avro/GobblinMetadataChangeEvent.avsc b/gobblin-metrics-libs/gobblin-metrics-base/src/main/avro/GobblinMetadataChangeEvent.avsc
new file mode 100644
index 0000000..2226934
--- /dev/null
+++ b/gobblin-metrics-libs/gobblin-metrics-base/src/main/avro/GobblinMetadataChangeEvent.avsc
@@ -0,0 +1,281 @@
+[
+ {
+ "namespace": "org.apache.gobblin.metadata",
+ "type": "record",
+ "name": "IntegerLongPair",
+ "fields": [
+ {
+ "name": "key",
+ "type": "int"
+ },
+ {
+ "name": "value",
+ "type": "long"
+ }
+ ]
+ },
+ {
+ "namespace": "org.apache.gobblin.metadata",
+ "type": "record",
+ "name": "IntegerBytesPair",
+ "fields": [
+ {
+ "name": "key",
+ "type": "int"
+ },
+ {
+ "name": "value",
+ "type": "bytes"
+ }
+ ]
+ },
+ {
+ "namespace": "org.apache.gobblin.metadata",
+ "type": "record",
+ "name": "DataMetrics",
+ "fields": [
+ {
+ "name": "record_count",
+ "type": "long"
+ },
+ {
+ "name": "column_sizes",
+ "type": [
+ "null",
+ {
+ "type": "array",
+ "items": "org.apache.gobblin.metadata.IntegerLongPair",
+ "logicalType": "map"
+ }
+ ],
+ "default": null,
+ "doc": "Map from column id to the total size on disk of all regions that store the column. Does not include bytes necessary to read other columns, like footers. Leave null for row-oriented formats (Avro)."
+ },
+ {
+ "name": "value_counts",
+ "type": [
+ "null",
+ {
+ "type": "array",
+ "items": "org.apache.gobblin.metadata.IntegerLongPair",
+ "logicalType": "map"
+ }
+ ],
+ "default": null,
+ "doc": "Map from column id to number of values in the column (including null values)."
+ },
+ {
+ "name": "null_value_counts",
+ "type": [
+ "null",
+ {
+ "type": "array",
+ "items": "org.apache.gobblin.metadata.IntegerLongPair",
+ "logicalType": "map"
+ }
+ ],
+ "default": null,
+ "doc": "Map from column id to number of null values in the column."
+ },
+ {
+ "name": "lower_bounds",
+ "type": [
+ "null",
+ {
+ "type": "array",
+ "items": "org.apache.gobblin.metadata.IntegerBytesPair",
+ "logicalType": "map"
+ }
+ ],
+ "default": null,
+ "doc": "Map from column id to lower bound in the column serialized as binary. Each value must be less than or equal to all values in the column for the file."
+ },
+ {
+ "name": "upper_bounds",
+ "type": [
+ "null",
+ {
+ "type": "array",
+ "items": "org.apache.gobblin.metadata.IntegerBytesPair",
+ "logicalType": "map"
+ }
+ ],
+ "default": null,
+ "doc": "Map from column id to upper bound in the column serialized as binary. Each value must be greater than or equal to all values in the column for the file."
+ }
+ ]
+ },
+ {
+ "type": "record",
+ "name": "GobblinMetadataChangeEvent",
+ "namespace": "org.apache.gobblin.metadata",
+ "doc": "Schema for GMCE",
+ "fields": [
+ {
+ "name": "datasetIdentifier",
+ "type": "org.apache.gobblin.metadata.DatasetIdentifier",
+ "doc": "The dataset for this metadata change event",
+ "optional": false
+ },
+ {
+ "name": "GMCEmittedTime",
+ "type": "long",
+ "doc": "This is emitted timestamp of this event",
+ "default": 0
+ },
+ {
+ "name": "minLogAppendTimestampForData",
+ "type": "long",
+ "doc": "This is min log_append time for the data message (used to track end-end lag)",
+ "default": 0
+ },
+ {
+ "name": "minHeaderTimestampForData",
+ "type": "long",
+ "doc": "This is min audit.header timeStamp for the data message (used to track end-end lag)",
+ "default": 0
+ },
+ {
+ "name": "operationType",
+ "type": {
+ "type":"enum",
+ "name":"OperationType",
+ "symbols": [
+ "add_files",
+ "drop_files",
+ "rewrite_files"
+ ]
+ },
+ "doc": "This is the operation type which indicates change for the specific files, for purger we don't need to do hive registration",
+ "optional": false
+ },
+ {
+ "name": "newFiles",
+ "type": ["null",{
+ "type": "array",
+ "items": {
+ "type": "record",
+ "name": "DataFile",
+ "fields": [
+ {
+ "name": "file_path",
+ "type": "string"
+ },
+ {
+ "name": "file_format",
+ "type": "string"
+ },
+ {
+ "name": "file_metrics",
+ "type": "org.apache.gobblin.metadata.DataMetrics"
+ }
+ ]
+ }
+ }],
+ "default": null,
+ "doc": " This is an array of the new files to be added, key is the path to the file, and value is the attributes i.e. min/max value of the new adding files",
+ "optional": true
+ },
+ {
+ "name": "oldFiles",
+ "type": ["null", {
+ "type":"array",
+ "items": "string"
+ }],
+ "default": null,
+ "doc": " This is an array of paths to the old files to be deleted",
+ "optional": true
+ },
+ {
+ "name": "registrationPolicy",
+ "type": ["null","string"],
+ "doc": "The class name for hive registration policy which we are using to compute the HiveSpec. For now, the most common policy we used in gobblin is LiHiveHourlyRegistrationPolicy, LiHiveDailyRegistrationPolicy, etc",
+ "default": null,
+ "optional": true
+ },
+ {
+ "name": "registrationPolicyForOldData",
+ "type": ["null","string"],
+ "doc": "Define the class to calculate the partition value for old data files",
+ "default": null,
+ "optional": true
+ },
+ {
+ "name": "topicPartitionOffsetsRange",
+ "type": ["null",{
+ "type":"map",
+ "values": "string"
+ }],
+ "default": null,
+ "doc": "a map for the topic partition offset range of the data, will be used for audit",
+ "optional": true
+ },
+ {
+ "name": "partitionColumns",
+ "type": {
+ "type":"array",
+ "items": "string"
+ },
+ "doc": "The name of the partition column.",
+ "default": ["datepartition"],
+ "optional": true
+ },
+ {
+ "name": "schemaSource",
+ "type": {
+ "type":"enum",
+ "name": "SchemaSource",
+ "symbols": ["EVENT", "SCHEMAREGISTRY","NONE"]
+ },
+ "doc": "This defines where the table schema comes from, the event or the schema registry, or don't need to register the schema",
+ "optional": false
+ },
+ {
+ "name": "tableSchema",
+ "type": ["null","string"],
+ "doc": "The avro schema for the data",
+ "default": null,
+ "optional": true
+ },
+ {
+ "name": "cluster",
+ "type": "string",
+ "doc": "The cluster from where this event is emitted",
+ "optional": false
+ },
+ {
+ "name": "registrationProperties",
+ "type": ["null",{
+ "type":"map",
+ "values": "string"
+ }],
+ "default": null,
+ "doc": "Properties needed for hive registration",
+ "optional": true
+ },
+ {
+ "name": "flowId",
+ "type": "string",
+ "doc": "The flow id of the pipeline which emit the record",
+ "optional": false
+ },
+ {
+ "name": "oldFilePrefixes",
+ "type": ["null",{
+ "type":"array",
+ "items": "string"
+ }],
+ "doc": "The prefixes for old files, used to find the old file to be deleted. If this field is defined, oldFiles will not be used",
+ "default": null,
+ "optional": true
+ },
+ {
+ "name": "avroSchemaWithIcebergSchemaID",
+ "type": ["null","string"],
+ "doc": "The avro schema with iceberg schema id for the data, this is used to match the field id in the file metrics to the field name",
+ "default": null,
+ "optional": true
+ }
+ ]
+ }
+]
diff --git a/gobblin-modules/gobblin-kafka-common/build.gradle b/gobblin-modules/gobblin-kafka-common/build.gradle
index 8cd83a4..00954b9 100644
--- a/gobblin-modules/gobblin-kafka-common/build.gradle
+++ b/gobblin-modules/gobblin-kafka-common/build.gradle
@@ -56,6 +56,17 @@ configurations {
// HADOOP-5254 and MAPREDUCE-5664
all*.exclude group: 'xml-apis'
all*.exclude group: 'xerces'
+ tests
+}
+
+task testJar(type: Jar, dependsOn: testClasses) {
+ baseName = "${project.archivesBaseName}-test"
+ from sourceSets.test.output
+}
+
+artifacts {
+ tests testJar
+ archives testJar
}
test {
diff --git a/gradle/scripts/defaultBuildProperties.gradle b/gradle/scripts/defaultBuildProperties.gradle
index d58fb2a..fec6ef9 100644
--- a/gradle/scripts/defaultBuildProperties.gradle
+++ b/gradle/scripts/defaultBuildProperties.gradle
@@ -31,6 +31,7 @@ def BuildProperties BUILD_PROPERTIES = new BuildProperties(project)
.register(new BuildProperty("gobblinFlavor", "standard", "Build flavor (see http://gobblin.readthedocs.io/en/latest/developer-guide/GobblinModules/)"))
.register(new BuildProperty("hadoopVersion", "2.3.0", "Hadoop dependencies version"))
.register(new BuildProperty("hiveVersion", "1.0.1", "Hive dependencies version"))
+ .register(new BuildProperty("icebergVersion", "0.10.0", "Iceberg dependencies version"))
.register(new BuildProperty("jdkVersion", JavaVersion.VERSION_1_8.toString(),
"Java languange compatibility; supported versions: " + JavaVersion.VERSION_1_8))
.register(new BuildProperty("kafka08Version", "0.8.2.2", "Kafka 0.8 dependencies version"))
@@ -66,6 +67,7 @@ BUILD_PROPERTIES.ensureDefined('bytemanVersion')
BUILD_PROPERTIES.ensureDefined('confluentVersion')
BUILD_PROPERTIES.ensureDefined('hadoopVersion')
BUILD_PROPERTIES.ensureDefined('hiveVersion')
+BUILD_PROPERTIES.ensureDefined('icebergVersion')
BUILD_PROPERTIES.ensureDefined('kafka08Version')
BUILD_PROPERTIES.ensureDefined('kafka09Version')
BUILD_PROPERTIES.ensureDefined('kafka1Version')
diff --git a/gradle/scripts/dependencyDefinitions.gradle b/gradle/scripts/dependencyDefinitions.gradle
index 99fe31f..b1dab68 100644
--- a/gradle/scripts/dependencyDefinitions.gradle
+++ b/gradle/scripts/dependencyDefinitions.gradle
@@ -75,6 +75,7 @@ ext.externalDependency = [
"httpmime": "org.apache.httpcomponents:httpmime:4.5.2",
"httpcore": "org.apache.httpcomponents:httpcore:4.4.11",
"httpasyncclient": "org.apache.httpcomponents:httpasyncclient:4.1.3",
+ "icebergHive": "org.apache.iceberg:iceberg-hive-runtime:" + icebergVersion,
"jgit": "org.eclipse.jgit:org.eclipse.jgit:5.1.1.201809181055-r",
"jmh": "org.openjdk.jmh:jmh-core:1.17.3",
"jmhAnnotations": "org.openjdk.jmh:jmh-generator-annprocess:1.17.3",
diff --git a/maven-nexus/upload-to-nexus.sh b/maven-nexus/upload-to-nexus.sh
index 4847f22..2c15aee 100755
--- a/maven-nexus/upload-to-nexus.sh
+++ b/maven-nexus/upload-to-nexus.sh
@@ -50,7 +50,7 @@ echo "CLEANING"
upload_all=0
-for P in :gobblin-admin :gobblin-api :gobblin-azkaban :gobblin-compaction :gobblin-config-management:gobblin-config-core :gobblin-config-management:gobblin-config-client :gobblin-core :gobblin-data-management :gobblin-distribution :gobblin-example :gobblin-metastore :gobblin-metrics :gobblin-oozie :gobblin-rest-service:gobblin-rest-api :gobblin-rest-service:gobblin-rest-client :gobblin-rest-service:gobblin-rest-server :gobblin-runtime :gobblin-salesforce :gobblin-scheduler :gobblin-test [...]
+for P in :gobblin-admin :gobblin-api :gobblin-azkaban :gobblin-compaction :gobblin-config-management:gobblin-config-core :gobblin-config-management:gobblin-config-client :gobblin-core :gobblin-data-management :gobblin-distribution :gobblin-example :gobblin-metastore :gobblin-metrics :gobblin-oozie :gobblin-rest-service:gobblin-rest-api :gobblin-rest-service:gobblin-rest-client :gobblin-rest-service:gobblin-rest-server :gobblin-runtime :gobblin-salesforce :gobblin-scheduler :gobblin-test [...]
echo "----------------------------"
if [ "$upload_all" -eq 0 ] ; then
read -p "UPLOAD $P [y(es)|n(o)|a(ll)]" ans
diff --git a/maven-sonatype/upload-to-sonatype.sh b/maven-sonatype/upload-to-sonatype.sh
index 4cb81ae..b5b8af8 100755
--- a/maven-sonatype/upload-to-sonatype.sh
+++ b/maven-sonatype/upload-to-sonatype.sh
@@ -50,7 +50,7 @@ echo "CLEANING"
upload_all=0
-for P in :gobblin-admin :gobblin-api :gobblin-azkaban :gobblin-compaction :gobblin-config-management:gobblin-config-core :gobblin-config-management:gobblin-config-client :gobblin-core :gobblin-data-management :gobblin-distribution :gobblin-example :gobblin-metastore :gobblin-metrics :gobblin-oozie :gobblin-rest-service:gobblin-rest-api :gobblin-rest-service:gobblin-rest-client :gobblin-rest-service:gobblin-rest-server :gobblin-runtime :gobblin-salesforce :gobblin-scheduler :gobblin-test [...]
+for P in :gobblin-admin :gobblin-api :gobblin-azkaban :gobblin-compaction :gobblin-config-management:gobblin-config-core :gobblin-config-management:gobblin-config-client :gobblin-core :gobblin-data-management :gobblin-distribution :gobblin-example :gobblin-metastore :gobblin-metrics :gobblin-oozie :gobblin-rest-service:gobblin-rest-api :gobblin-rest-service:gobblin-rest-client :gobblin-rest-service:gobblin-rest-server :gobblin-iceberg :gobblin-runtime :gobblin-salesforce :gobblin-schedul [...]
echo "----------------------------"
if [ "$upload_all" -eq 0 ] ; then
read -p "UPLOAD $P [y(es)|n(o)|a(ll)]" ans
diff --git a/settings.gradle b/settings.gradle
index e7a36de..210f5b2 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -25,6 +25,7 @@ def modules = ['gobblin-admin',
'gobblin-distribution',
'gobblin-example',
'gobblin-hive-registration',
+ 'gobblin-iceberg',
'gobblin-metrics-libs',
'gobblin-metastore',
'gobblin-modules',