EpsilonPrime commented on code in PR #1: URL: https://github.com/apache/arrow-datafusion-comet/pull/1#discussion_r1465519630
########## common/src/main/java/org/apache/comet/parquet/ColumnIndexReader.java: ########## @@ -0,0 +1,230 @@ +/* + * 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.comet.parquet; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.parquet.crypto.AesCipher; +import org.apache.parquet.crypto.InternalColumnDecryptionSetup; +import org.apache.parquet.crypto.InternalFileDecryptor; +import org.apache.parquet.crypto.ModuleCipherFactory; +import org.apache.parquet.format.BlockCipher; +import org.apache.parquet.format.Util; +import org.apache.parquet.format.converter.ParquetMetadataConverter; +import org.apache.parquet.hadoop.metadata.BlockMetaData; +import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData; +import org.apache.parquet.hadoop.metadata.ColumnPath; +import org.apache.parquet.internal.column.columnindex.ColumnIndex; +import org.apache.parquet.internal.column.columnindex.OffsetIndex; +import org.apache.parquet.internal.filter2.columnindex.ColumnIndexStore; +import org.apache.parquet.internal.hadoop.metadata.IndexReference; +import org.apache.parquet.io.SeekableInputStream; + +class ColumnIndexReader implements ColumnIndexStore { + private static final Logger LOG = LoggerFactory.getLogger(ColumnIndexReader.class); + + // Used for columns are not in this parquet file + private static final IndexStore MISSING_INDEX_STORE = + new IndexStore() { + @Override + public ColumnIndex getColumnIndex() { + return null; + } + + @Override + public OffsetIndex getOffsetIndex() { + return null; + } + }; + + private static final ColumnIndexReader EMPTY = + new ColumnIndexReader(new BlockMetaData(), Collections.emptySet(), null, null) { + @Override + public ColumnIndex getColumnIndex(ColumnPath column) { + return null; + } + + @Override + public OffsetIndex getOffsetIndex(ColumnPath column) { + throw new MissingOffsetIndexException(column); + } + }; + + private final InternalFileDecryptor fileDecryptor; + private final SeekableInputStream inputStream; + private final Map<ColumnPath, IndexStore> store; + + /** + * Creates a column index store which lazily reads column/offset indexes for the columns in paths. + * Paths are the set of columns used for the projection. + */ + static ColumnIndexReader create( + BlockMetaData block, + Set<ColumnPath> paths, + InternalFileDecryptor fileDecryptor, + SeekableInputStream inputStream) { + try { + return new ColumnIndexReader(block, paths, fileDecryptor, inputStream); + } catch (MissingOffsetIndexException e) { + return EMPTY; + } + } + + private ColumnIndexReader( + BlockMetaData block, + Set<ColumnPath> paths, + InternalFileDecryptor fileDecryptor, + SeekableInputStream inputStream) { + this.fileDecryptor = fileDecryptor; + this.inputStream = inputStream; + Map<ColumnPath, IndexStore> store = new HashMap<>(); + for (ColumnChunkMetaData column : block.getColumns()) { + ColumnPath path = column.getPath(); + if (paths.contains(path)) { + store.put(path, new IndexStoreImpl(column)); + } + } + this.store = store; + } + + @Override + public ColumnIndex getColumnIndex(ColumnPath column) { + return store.getOrDefault(column, MISSING_INDEX_STORE).getColumnIndex(); + } + + @Override + public OffsetIndex getOffsetIndex(ColumnPath column) { + return store.getOrDefault(column, MISSING_INDEX_STORE).getOffsetIndex(); + } + + private interface IndexStore { + ColumnIndex getColumnIndex(); + + OffsetIndex getOffsetIndex(); + } + + private class IndexStoreImpl implements IndexStore { + private final ColumnChunkMetaData meta; + private ColumnIndex columnIndex; + private boolean columnIndexRead; + private final OffsetIndex offsetIndex; + + IndexStoreImpl(ColumnChunkMetaData meta) { + this.meta = meta; + OffsetIndex oi; + try { + oi = readOffsetIndex(meta); + } catch (IOException e) { + // If the I/O issue still stands it will fail the reading later; + // otherwise we fail the filtering only with a missing offset index. + LOG.warn("Unable to read offset index for column {}", meta.getPath(), e); + oi = null; + } + if (oi == null) { + throw new MissingOffsetIndexException(meta.getPath()); + } + offsetIndex = oi; + } + + @Override + public ColumnIndex getColumnIndex() { + if (!columnIndexRead) { + try { + columnIndex = readColumnIndex(meta); + } catch (IOException e) { + // If the I/O issue still stands it will fail the reading later; + // otherwise we fail the filtering only with a missing column index. + LOG.warn("Unable to read column index for column {}", meta.getPath(), e); + } + columnIndexRead = true; + } + return columnIndex; + } + + @Override + public OffsetIndex getOffsetIndex() { + return offsetIndex; + } + } + + // Visible for testing + ColumnIndex readColumnIndex(ColumnChunkMetaData column) throws IOException { + IndexReference ref = column.getColumnIndexReference(); + if (ref == null) { + return null; + } + inputStream.seek(ref.getOffset()); + + BlockCipher.Decryptor columnIndexDecryptor = null; + byte[] columnIndexAAD = null; + if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { + InternalColumnDecryptionSetup columnDecryptionSetup = + fileDecryptor.getColumnSetup(column.getPath()); + if (columnDecryptionSetup.isEncrypted()) { + columnIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); + columnIndexAAD = + AesCipher.createModuleAAD( + fileDecryptor.getFileAAD(), + ModuleCipherFactory.ModuleType.ColumnIndex, + column.getRowGroupOrdinal(), + columnDecryptionSetup.getOrdinal(), + -1); + } + } + return ParquetMetadataConverter.fromParquetColumnIndex( + column.getPrimitiveType(), + Util.readColumnIndex(inputStream, columnIndexDecryptor, columnIndexAAD)); + } + + // Visible for testing Review Comment: Can this comment be replaced with an annotation? ########## common/src/main/java/org/apache/comet/NativeBase.java: ########## @@ -0,0 +1,278 @@ +/* + * 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.comet; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.spark.sql.comet.util.Utils; + +import static org.apache.comet.Constants.LOG_CONF_NAME; +import static org.apache.comet.Constants.LOG_CONF_PATH; + +/** Base class for JNI bindings. MUST be inherited by all classes that introduce JNI APIs. */ +public abstract class NativeBase { + static final String ARROW_UNSAFE_MEMORY_ACCESS = "arrow.enable_unsafe_memory_access"; + static final String ARROW_NULL_CHECK_FOR_GET = "arrow.enable_null_check_for_get"; + + private static final Logger LOG = LoggerFactory.getLogger(NativeBase.class); + private static final String NATIVE_LIB_NAME = "comet"; + + private static final String libraryToLoad = System.mapLibraryName(NATIVE_LIB_NAME); + private static boolean loaded = false; + private static final String searchPattern = "libcomet-"; + + static { + if (!isLoaded()) { + load(); + } + } + + public static synchronized boolean isLoaded() { + return loaded; + } + + // Only for testing + static synchronized void setLoaded(boolean b) { + loaded = b; + } + + static synchronized void load() { + if (loaded) { + return; + } + + cleanupOldTempLibs(); + + // Check if the arch used by JDK is the same as arch on the host machine, in particular, + // whether x86_64 JDK is used in arm64 Mac + if (!checkArch()) { + LOG.warn( + "Comet is disabled. JDK compiled for x86_64 is used in a Mac based on Apple Silicon. " + + "In order to use Comet, Please install a JDK version for ARM64 architecture"); + return; + } + + // Try to load Comet library from the java.library.path. + try { + System.loadLibrary(libraryToLoad); + loaded = true; + } catch (UnsatisfiedLinkError ex) { + // Doesn't exist, so proceed to loading bundled library. + bundleLoadLibrary(); + } + + initWithLogConf(); + // Only set the Arrow properties when debugging mode is off + if (!(boolean) CometConf.COMET_DEBUG_ENABLED().get()) { + setArrowProperties(); + } + } + + /** + * Use the bundled native libraries. Functionally equivalent to <code>System.loadLibrary</code>. + */ + private static void bundleLoadLibrary() { + String resourceName = resourceName(); + InputStream is = NativeBase.class.getResourceAsStream(resourceName); + if (is == null) { + throw new UnsupportedOperationException( + "Unsupported OS/arch, cannot find " + + resourceName + + ". Please try building from source."); + } + + File tempLib = null; + File tempLibLock = null; + try { + // Create the .lck file first to avoid a race condition + // with other concurrently running Java processes using Comet. + tempLibLock = File.createTempFile(searchPattern, "." + os().libExtension + ".lck"); + tempLib = new File(tempLibLock.getAbsolutePath().replaceFirst(".lck$", "")); + // copy to tempLib + Files.copy(is, tempLib.toPath(), StandardCopyOption.REPLACE_EXISTING); + System.load(tempLib.getAbsolutePath()); + loaded = true; + } catch (IOException e) { + throw new IllegalStateException("Cannot unpack libcomet: " + e); + } finally { + if (!loaded) { + if (tempLib != null && tempLib.exists()) { + if (!tempLib.delete()) { + LOG.error( + "Cannot unpack libcomet / cannot delete a temporary native library " + tempLib); + } + } + if (tempLibLock != null && tempLibLock.exists()) { + if (!tempLibLock.delete()) { + LOG.error( + "Cannot unpack libcomet / cannot delete a temporary lock file " + tempLibLock); + } + } + } else { + tempLib.deleteOnExit(); + tempLibLock.deleteOnExit(); + } + } + } + + private static void initWithLogConf() { + String logConfPath = System.getProperty(LOG_CONF_PATH(), Utils.getConfPath(LOG_CONF_NAME())); + + // If both the system property and the environmental variable failed to find a log + // configuration, then fall back to using the deployed default + if (logConfPath == null) { + LOG.info( + "Couldn't locate log file from either COMET_CONF_DIR or comet.log.file.path. " + + "Using default log configuration which emits to stdout"); + logConfPath = ""; + } else { + LOG.info("Using {} for native library logging", logConfPath); + } + init(logConfPath); + } + + private static void cleanupOldTempLibs() { + String tempFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); + File dir = new File(tempFolder); + + File[] tempLibFiles = + dir.listFiles( + new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.startsWith(searchPattern) && !name.endsWith(".lck"); + } + }); + + if (tempLibFiles != null) { + for (File tempLibFile : tempLibFiles) { + File lckFile = new File(tempLibFile.getAbsolutePath() + ".lck"); + if (!lckFile.exists()) { + try { + tempLibFile.delete(); + } catch (SecurityException e) { + LOG.error("Failed to delete old temp lib", e); + } + } + } + } + } + + // Set Arrow related properties upon initializing native, such as enabling unsafe memory access + // as well as disabling null check for get, for performance reasons. + private static void setArrowProperties() { + setPropertyIfNull(ARROW_UNSAFE_MEMORY_ACCESS, "true"); + setPropertyIfNull(ARROW_NULL_CHECK_FOR_GET, "false"); + } + + private static void setPropertyIfNull(String key, String value) { + if (System.getProperty(key) == null) { + LOG.info("Setting system property {} to {}", key, value); + System.setProperty(key, value); + } else { + LOG.info( + "Skip setting system property {} to {}, because it is already set to {}", Review Comment: Skipped -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
