You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "tsreaper (via GitHub)" <gi...@apache.org> on 2024/12/10 07:54:16 UTC

Re: [PR] [iceberg] Introduce feature to migrate table from iceberg to paimon [paimon]

tsreaper commented on code in PR #4639:
URL: https://github.com/apache/paimon/pull/4639#discussion_r1877446113


##########
paimon-core/src/main/java/org/apache/paimon/iceberg/IcebergMigrator.java:
##########
@@ -0,0 +1,344 @@
+/*
+ * 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.paimon.iceberg;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.fs.FileIO;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.iceberg.manifest.IcebergDataFileMeta;
+import org.apache.paimon.iceberg.manifest.IcebergManifestEntry;
+import org.apache.paimon.iceberg.manifest.IcebergManifestFile;
+import org.apache.paimon.iceberg.manifest.IcebergManifestFileMeta;
+import org.apache.paimon.iceberg.manifest.IcebergManifestList;
+import org.apache.paimon.iceberg.metadata.IcebergDataField;
+import org.apache.paimon.iceberg.metadata.IcebergMetadata;
+import org.apache.paimon.iceberg.metadata.IcebergPartitionField;
+import org.apache.paimon.iceberg.metadata.IcebergPartitionSpec;
+import org.apache.paimon.iceberg.metadata.IcebergSchema;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.migrate.FileMetaUtils;
+import org.apache.paimon.migrate.Migrator;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.types.DataField;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.stream.Collectors;
+
+import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool;
+
+/** migrate hive table to paimon table. */
+public class IcebergMigrator implements Migrator {
+    private static final Logger LOG = LoggerFactory.getLogger(IcebergMigrator.class);
+    private static final String VERSION_HINT_FILENAME = "version-hint.text";
+
+    private final ThreadPoolExecutor executor;
+
+    private final Catalog paimonCatalog;
+    private final FileIO paimonFileIO;
+    private final String paimonDatabaseName;
+    private final String paimonTableNameame;
+
+    private final int icebergNewestSnapshotId;
+    // Path factory for iceberg metadata
+    private final IcebergPathFactory icebergPathFactory;
+    // metadata for newest iceberg snapshot
+    private final IcebergMetadata icebergMetadata;
+
+    private boolean ignoreDelete = false;
+
+    public IcebergMigrator(
+            Catalog paimonCatalog,
+            Path icebergMetaPath,
+            String paimonDatabaseName,
+            String paimonTableNameame,
+            boolean ignoreDelete,
+            Integer parallelism) {
+        this.paimonCatalog = paimonCatalog;
+        this.paimonFileIO = paimonCatalog.fileIO();
+        this.paimonDatabaseName = paimonDatabaseName;
+        this.paimonTableNameame = paimonTableNameame;
+
+        this.icebergPathFactory = new IcebergPathFactory(icebergMetaPath);
+        this.icebergNewestSnapshotId = getIcebergNewestSnapshotId();
+        this.icebergMetadata =
+                IcebergMetadata.fromPath(
+                        paimonFileIO, icebergPathFactory.toMetadataPath(icebergNewestSnapshotId));
+        this.ignoreDelete = ignoreDelete;
+
+        this.executor = createCachedThreadPool(parallelism, "ICEBERG_MIGRATOR");
+    }
+
+    @Override
+    public void executeMigrate() throws Exception {
+        Schema paimonSchema = icebergSchemaToPaimonSchema(icebergMetadata);
+        Identifier paimonIdentifier = Identifier.create(paimonDatabaseName, paimonTableNameame);
+
+        paimonCatalog.createDatabase(paimonDatabaseName, false);

Review Comment:
   Why false? User must migrate to a non-existing database?



##########
paimon-core/src/main/java/org/apache/paimon/iceberg/IcebergMigrator.java:
##########
@@ -0,0 +1,344 @@
+/*
+ * 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.paimon.iceberg;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.fs.FileIO;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.iceberg.manifest.IcebergDataFileMeta;
+import org.apache.paimon.iceberg.manifest.IcebergManifestEntry;
+import org.apache.paimon.iceberg.manifest.IcebergManifestFile;
+import org.apache.paimon.iceberg.manifest.IcebergManifestFileMeta;
+import org.apache.paimon.iceberg.manifest.IcebergManifestList;
+import org.apache.paimon.iceberg.metadata.IcebergDataField;
+import org.apache.paimon.iceberg.metadata.IcebergMetadata;
+import org.apache.paimon.iceberg.metadata.IcebergPartitionField;
+import org.apache.paimon.iceberg.metadata.IcebergPartitionSpec;
+import org.apache.paimon.iceberg.metadata.IcebergSchema;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.migrate.FileMetaUtils;
+import org.apache.paimon.migrate.Migrator;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.types.DataField;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.stream.Collectors;
+
+import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool;
+
+/** migrate hive table to paimon table. */
+public class IcebergMigrator implements Migrator {
+    private static final Logger LOG = LoggerFactory.getLogger(IcebergMigrator.class);
+    private static final String VERSION_HINT_FILENAME = "version-hint.text";
+
+    private final ThreadPoolExecutor executor;
+
+    private final Catalog paimonCatalog;
+    private final FileIO paimonFileIO;
+    private final String paimonDatabaseName;
+    private final String paimonTableNameame;
+
+    private final int icebergNewestSnapshotId;
+    // Path factory for iceberg metadata
+    private final IcebergPathFactory icebergPathFactory;
+    // metadata for newest iceberg snapshot
+    private final IcebergMetadata icebergMetadata;
+
+    private boolean ignoreDelete = false;
+
+    public IcebergMigrator(
+            Catalog paimonCatalog,
+            Path icebergMetaPath,
+            String paimonDatabaseName,
+            String paimonTableNameame,
+            boolean ignoreDelete,
+            Integer parallelism) {
+        this.paimonCatalog = paimonCatalog;
+        this.paimonFileIO = paimonCatalog.fileIO();
+        this.paimonDatabaseName = paimonDatabaseName;
+        this.paimonTableNameame = paimonTableNameame;

Review Comment:
   ```suggestion
           this.paimonTableName = paimonTableName;
   ```



##########
paimon-core/src/main/java/org/apache/paimon/iceberg/IcebergMigrator.java:
##########
@@ -0,0 +1,344 @@
+/*
+ * 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.paimon.iceberg;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.fs.FileIO;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.iceberg.manifest.IcebergDataFileMeta;
+import org.apache.paimon.iceberg.manifest.IcebergManifestEntry;
+import org.apache.paimon.iceberg.manifest.IcebergManifestFile;
+import org.apache.paimon.iceberg.manifest.IcebergManifestFileMeta;
+import org.apache.paimon.iceberg.manifest.IcebergManifestList;
+import org.apache.paimon.iceberg.metadata.IcebergDataField;
+import org.apache.paimon.iceberg.metadata.IcebergMetadata;
+import org.apache.paimon.iceberg.metadata.IcebergPartitionField;
+import org.apache.paimon.iceberg.metadata.IcebergPartitionSpec;
+import org.apache.paimon.iceberg.metadata.IcebergSchema;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.migrate.FileMetaUtils;
+import org.apache.paimon.migrate.Migrator;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.types.DataField;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.stream.Collectors;
+
+import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool;
+
+/** migrate hive table to paimon table. */
+public class IcebergMigrator implements Migrator {
+    private static final Logger LOG = LoggerFactory.getLogger(IcebergMigrator.class);
+    private static final String VERSION_HINT_FILENAME = "version-hint.text";
+
+    private final ThreadPoolExecutor executor;
+
+    private final Catalog paimonCatalog;
+    private final FileIO paimonFileIO;
+    private final String paimonDatabaseName;
+    private final String paimonTableNameame;
+
+    private final int icebergNewestSnapshotId;
+    // Path factory for iceberg metadata
+    private final IcebergPathFactory icebergPathFactory;
+    // metadata for newest iceberg snapshot
+    private final IcebergMetadata icebergMetadata;
+
+    private boolean ignoreDelete = false;
+
+    public IcebergMigrator(
+            Catalog paimonCatalog,
+            Path icebergMetaPath,
+            String paimonDatabaseName,
+            String paimonTableNameame,
+            boolean ignoreDelete,
+            Integer parallelism) {
+        this.paimonCatalog = paimonCatalog;
+        this.paimonFileIO = paimonCatalog.fileIO();
+        this.paimonDatabaseName = paimonDatabaseName;
+        this.paimonTableNameame = paimonTableNameame;
+
+        this.icebergPathFactory = new IcebergPathFactory(icebergMetaPath);
+        this.icebergNewestSnapshotId = getIcebergNewestSnapshotId();
+        this.icebergMetadata =
+                IcebergMetadata.fromPath(
+                        paimonFileIO, icebergPathFactory.toMetadataPath(icebergNewestSnapshotId));
+        this.ignoreDelete = ignoreDelete;
+
+        this.executor = createCachedThreadPool(parallelism, "ICEBERG_MIGRATOR");
+    }
+
+    @Override
+    public void executeMigrate() throws Exception {
+        Schema paimonSchema = icebergSchemaToPaimonSchema(icebergMetadata);
+        Identifier paimonIdentifier = Identifier.create(paimonDatabaseName, paimonTableNameame);
+
+        paimonCatalog.createDatabase(paimonDatabaseName, false);
+        paimonCatalog.createTable(paimonIdentifier, paimonSchema, false);
+
+        try {
+            FileStoreTable paimonTable = (FileStoreTable) paimonCatalog.getTable(paimonIdentifier);
+
+            IcebergManifestFile manifestFile =
+                    IcebergManifestFile.create(paimonTable, icebergPathFactory);
+            IcebergManifestList manifestList =
+                    IcebergManifestList.create(paimonTable, icebergPathFactory);
+
+            List<IcebergManifestFileMeta> icebergManifestFileMetas =
+                    manifestList.read(icebergMetadata.currentSnapshot().manifestList());
+
+            // check manifest file with 'DELETE' kind
+            icebergManifestFileMetas = checkAndFilterManifestFiles(icebergManifestFileMetas);
+
+            // get all live iceberg entries
+            List<IcebergManifestEntry> icebergEntries =
+                    icebergManifestFileMetas.stream()
+                            .flatMap(fileMeta -> manifestFile.read(fileMeta).stream())
+                            .filter(IcebergManifestEntry::isLive)
+                            .collect(Collectors.toList());
+            if (icebergEntries.isEmpty()) {
+                LOG.info(
+                        "No live manifest entry in iceberg table for snapshot {}, iceberg table meta path is {}.",
+                        icebergNewestSnapshotId,
+                        icebergPathFactory.toMetadataPath(icebergNewestSnapshotId));
+                return;
+            }
+
+            List<IcebergDataFileMeta> icebergDataFileMetas =
+                    icebergEntries.stream()
+                            .map(IcebergManifestEntry::file)
+                            .collect(Collectors.toList());
+
+            // Again, check if the file is a Delete File
+            icebergDataFileMetas = checkAndFilterDataFiles(icebergDataFileMetas);
+
+            LOG.info(
+                    "Begin to create Migrate Task, the number of iceberg data files is {}",
+                    icebergDataFileMetas.size());
+
+            List<MigrateTask> tasks = new ArrayList<>();
+            Map<Path, Path> rollback = new ConcurrentHashMap<>();
+            if (paimonTable.partitionKeys().isEmpty()) {
+                tasks.add(importUnPartitionedTable(icebergDataFileMetas, paimonTable, rollback));
+            } else {
+                tasks.addAll(importPartitionedTable(icebergDataFileMetas, paimonTable, rollback));
+            }
+
+            List<Future<CommitMessage>> futures =
+                    tasks.stream().map(executor::submit).collect(Collectors.toList());
+            List<CommitMessage> commitMessages = new ArrayList<>();
+            try {
+                for (Future<CommitMessage> future : futures) {
+                    commitMessages.add(future.get());
+                }
+            } catch (Exception e) {
+                futures.forEach(f -> f.cancel(true));
+                for (Future<?> future : futures) {
+                    // wait all task cancelled or finished
+                    while (!future.isDone()) {
+                        //noinspection BusyWait
+                        Thread.sleep(100);
+                    }
+                }
+                // roll back all renamed path
+                for (Map.Entry<Path, Path> entry : rollback.entrySet()) {
+                    Path newPath = entry.getKey();
+                    Path origin = entry.getValue();
+                    if (paimonFileIO.exists(newPath)) {
+                        paimonFileIO.rename(newPath, origin);
+                    }
+                }
+
+                throw new RuntimeException("Migrating failed because exception happens", e);
+            }
+            try (BatchTableCommit commit = paimonTable.newBatchWriteBuilder().newCommit()) {
+                commit.commit(new ArrayList<>(commitMessages));
+                LOG.info("paimon commit success! Iceberg data files has been migrated to paimon.");
+            }
+        } catch (Exception e) {
+            paimonCatalog.dropTable(paimonIdentifier, true);
+            throw new RuntimeException("Migrating failed", e);
+        }
+    }
+
+    @Override
+    public void deleteOriginTable(boolean delete) throws Exception {}
+
+    @Override
+    public void renameTable(boolean ignoreIfNotExists) throws Exception {}
+
+    public int getIcebergNewestSnapshotId() {
+        Path versionHintPath =
+                new Path(icebergPathFactory.metadataDirectory(), VERSION_HINT_FILENAME);
+        try {
+            return Integer.parseInt(paimonFileIO.readFileUtf8(versionHintPath));
+        } catch (IOException e) {
+            throw new RuntimeException(
+                    "read iceberg version-hint.text failed. Iceberg metadata path: "
+                            + icebergPathFactory.metadataDirectory());
+        }
+    }
+
+    public Schema icebergSchemaToPaimonSchema(IcebergMetadata icebergMetadata) {
+        // get iceberg current schema
+        IcebergSchema icebergSchema =
+                icebergMetadata.schemas().get(icebergMetadata.currentSchemaId());
+
+        // get iceberg current partition spec
+        int currentPartitionSpecId = icebergMetadata.defaultSpecId();
+        IcebergPartitionSpec currentIcebergPartitionSpec =
+                icebergMetadata.partitionSpecs().get(currentPartitionSpecId);
+
+        List<DataField> dataFields =
+                icebergSchema.fields().stream()
+                        .map(IcebergDataField::toDatafield)
+                        .collect(Collectors.toList());
+
+        List<String> partitionKeys =
+                currentIcebergPartitionSpec.fields().stream()
+                        .map(IcebergPartitionField::name)
+                        .collect(Collectors.toList());
+
+        return new Schema(
+                dataFields, partitionKeys, Collections.emptyList(), Collections.emptyMap(), null);
+    }
+
+    private List<IcebergManifestFileMeta> checkAndFilterManifestFiles(
+            List<IcebergManifestFileMeta> icebergManifestFileMetas) {
+        if (!ignoreDelete) {

Review Comment:
   Why do we need such an option? If there are deletion vectors in Iceberg, and user uses this option, then the resulting data will be incorrect. Incorrect data are useless to the users.
   



##########
paimon-core/src/main/java/org/apache/paimon/iceberg/metadata/IcebergDataField.java:
##########
@@ -190,6 +199,70 @@ private static Object toTypeObject(DataType dataType, int fieldId, int depth) {
         }
     }
 
+    public DataType getDataType() {

Review Comment:
   This class already has a `dataType` member. Check if `dataType` is null, if not just return that object, otherwise calculate data type from `type` string.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org