Skip to content

Commit

Permalink
[Opt](multi-catalog)Improve performance by introducing cache of list …
Browse files Browse the repository at this point in the history
…directory files when getting split for each query.
  • Loading branch information
kaka11chen committed Nov 13, 2024
1 parent 00e5ab8 commit 65ef2e1
Show file tree
Hide file tree
Showing 17 changed files with 813 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2134,6 +2134,10 @@ public class Config extends ConfigBase {
"Max cache number of external table row count"})
public static long max_external_table_row_count_cache_num = 100000;

@ConfField(description = {"每个查询 list 文件目录数。",
"Max cache number of partition directories at query level."})
public static long per_query_list_dir_cache_num = 10000;

/**
* Max cache loader thread-pool size.
* Max thread pool size for loading external meta cache
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import com.github.benmanes.caffeine.cache.AsyncCacheLoader;
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
Expand Down Expand Up @@ -85,6 +86,11 @@ public <K, V> LoadingCache<K, V> buildCache(CacheLoader<K, V> cacheLoader,
return builder.build(cacheLoader);
}

public <K, V> Cache<K, V> buildCache() {
Caffeine<Object, Object> builder = buildWithParams();
return builder.build();
}

// Build an async loading cache
public <K, V> AsyncLoadingCache<K, V> buildAsyncCache(AsyncCacheLoader<K, V> cacheLoader,
ExecutorService executor) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.apache.doris.datasource.SchemaCacheValue;
import org.apache.doris.datasource.hudi.HudiUtils;
import org.apache.doris.datasource.iceberg.IcebergUtils;
import org.apache.doris.fs.FileSystemDirectoryLister;
import org.apache.doris.mtmv.MTMVBaseTableIf;
import org.apache.doris.mtmv.MTMVMaxTimestampSnapshot;
import org.apache.doris.mtmv.MTMVRefreshContext;
Expand Down Expand Up @@ -952,7 +953,8 @@ private List<HiveMetaStoreCache.FileCacheValue> getFilesForPartitions(
LOG.debug("Chosen partition for table {}. [{}]", name, partition.toString());
}
}
return cache.getFilesByPartitionsWithoutCache(hivePartitions, bindBrokerName);
return cache.getFilesByPartitionsWithoutCache(hivePartitions, bindBrokerName,
new FileSystemDirectoryLister(), null);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.apache.doris.catalog.ListPartitionItem;
import org.apache.doris.catalog.PartitionItem;
import org.apache.doris.catalog.PartitionKey;
import org.apache.doris.catalog.TableIf;
import org.apache.doris.catalog.Type;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.CacheFactory;
Expand All @@ -39,7 +40,10 @@
import org.apache.doris.datasource.ExternalMetaCacheMgr;
import org.apache.doris.datasource.hive.AcidInfo.DeleteDeltaInfo;
import org.apache.doris.datasource.property.PropertyConverter;
import org.apache.doris.fs.DirectoryLister;
import org.apache.doris.fs.FileSystemCache;
import org.apache.doris.fs.FileSystemDirectoryLister;
import org.apache.doris.fs.RemoteIterator;
import org.apache.doris.fs.remote.RemoteFile;
import org.apache.doris.fs.remote.RemoteFileSystem;
import org.apache.doris.fs.remote.dfs.DFSFileSystem;
Expand Down Expand Up @@ -81,6 +85,8 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
Expand Down Expand Up @@ -195,7 +201,7 @@ protected ExecutorService getExecutor() {

@Override
public FileCacheValue load(FileCacheKey key) {
return loadFiles(key);
return loadFiles(key, new FileSystemDirectoryLister(), null);
}
};

Expand Down Expand Up @@ -348,7 +354,9 @@ private Map<PartitionCacheKey, HivePartition> loadPartitions(Iterable<? extends
private FileCacheValue getFileCache(String location, String inputFormat,
JobConf jobConf,
List<String> partitionValues,
String bindBrokerName) throws UserException {
String bindBrokerName,
DirectoryLister directoryLister,
TableIf table) throws UserException {
FileCacheValue result = new FileCacheValue();
RemoteFileSystem fs = Env.getCurrentEnv().getExtMetaCacheMgr().getFsCache().getRemoteFileSystem(
new FileSystemCache.FileSystemCacheKey(LocationPath.getFSIdentity(
Expand All @@ -363,34 +371,28 @@ private FileCacheValue getFileCache(String location, String inputFormat,
// /user/hive/warehouse/region_tmp_union_all2/2
// So we need to recursively list data location.
// https://blog.actorsfit.com/a?ID=00550-ce56ec63-1bff-4b0c-a6f7-447b93efaa31
List<RemoteFile> remoteFiles = new ArrayList<>();
boolean isRecursiveDirectories = Boolean.valueOf(
catalog.getProperties().getOrDefault("hive.recursive_directories", "false"));
Status status = fs.listFiles(location, isRecursiveDirectories, remoteFiles);
if (status.ok()) {
for (RemoteFile remoteFile : remoteFiles) {
try {
RemoteIterator<RemoteFile> iterator = directoryLister.listFilesRecursively(fs, table, location);
while (iterator.hasNext()) {
RemoteFile remoteFile = iterator.next();
String srcPath = remoteFile.getPath().toString();
LocationPath locationPath = new LocationPath(srcPath, catalog.getProperties());
result.addFile(remoteFile, locationPath);
}
} else if (status.getErrCode().equals(ErrCode.NOT_FOUND)) {
} catch (FileNotFoundException e) {
// User may manually remove partition under HDFS, in this case,
// Hive doesn't aware that the removed partition is missing.
// Here is to support this case without throw an exception.
LOG.warn(String.format("File %s not exist.", location));
if (!Boolean.valueOf(catalog.getProperties()
.getOrDefault("hive.ignore_absent_partitions", "true"))) {
throw new UserException("Partition location does not exist: " + location);
}
} else {
throw new RuntimeException(status.getErrMsg());
} catch (IOException e) {
throw new RuntimeException(e);
}
// Must copy the partitionValues to avoid concurrent modification of key and value
result.setPartitionValues(Lists.newArrayList(partitionValues));
return result;
}

private FileCacheValue loadFiles(FileCacheKey key) {
private FileCacheValue loadFiles(FileCacheKey key, DirectoryLister directoryLister, TableIf table) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
Expand All @@ -415,7 +417,7 @@ private FileCacheValue loadFiles(FileCacheKey key) {
FileInputFormat.setInputPaths(jobConf, finalLocation.get());
try {
FileCacheValue result = getFileCache(finalLocation.get(), key.inputFormat, jobConf,
key.getPartitionValues(), key.bindBrokerName);
key.getPartitionValues(), key.bindBrokerName, directoryLister, table);
// Replace default hive partition with a null_string.
for (int i = 0; i < result.getValuesSize(); i++) {
if (HIVE_DEFAULT_PARTITION.equals(result.getPartitionValues().get(i))) {
Expand Down Expand Up @@ -469,19 +471,25 @@ public HivePartitionValues getPartitionValues(PartitionValueCacheKey key) {
}

public List<FileCacheValue> getFilesByPartitionsWithCache(List<HivePartition> partitions,
String bindBrokerName) {
return getFilesByPartitions(partitions, true, true, bindBrokerName);
String bindBrokerName,
DirectoryLister directoryLister,
TableIf table) {
return getFilesByPartitions(partitions, true, true, bindBrokerName, directoryLister, table);
}

public List<FileCacheValue> getFilesByPartitionsWithoutCache(List<HivePartition> partitions,
String bindBrokerName) {
return getFilesByPartitions(partitions, false, true, bindBrokerName);
String bindBrokerName,
DirectoryLister directoryLister,
TableIf table) {
return getFilesByPartitions(partitions, false, true, bindBrokerName, directoryLister, table);
}

public List<FileCacheValue> getFilesByPartitions(List<HivePartition> partitions,
boolean withCache,
boolean concurrent,
String bindBrokerName) {
String bindBrokerName,
DirectoryLister directoryLister,
TableIf table) {
long start = System.currentTimeMillis();
List<FileCacheKey> keys = partitions.stream().map(p -> p.isDummyPartition()
? FileCacheKey.createDummyCacheKey(
Expand All @@ -497,13 +505,15 @@ public List<FileCacheValue> getFilesByPartitions(List<HivePartition> partitions,
} else {
if (concurrent) {
List<Future<FileCacheValue>> pList = keys.stream().map(
key -> fileListingExecutor.submit(() -> loadFiles(key))).collect(Collectors.toList());
key -> fileListingExecutor.submit(() -> loadFiles(key, directoryLister, table)))
.collect(Collectors.toList());
fileLists = Lists.newArrayListWithExpectedSize(keys.size());
for (Future<FileCacheValue> p : pList) {
fileLists.add(p.get());
}
} else {
fileLists = keys.stream().map(this::loadFiles).collect(Collectors.toList());
fileLists = keys.stream().map((key) -> loadFiles(key, directoryLister, table))
.collect(Collectors.toList());
}
}
} catch (ExecutionException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.apache.doris.datasource.hive.HiveProperties;
import org.apache.doris.datasource.hive.HiveTransaction;
import org.apache.doris.datasource.hive.source.HiveSplit.HiveSplitCreator;
import org.apache.doris.fs.DirectoryLister;
import org.apache.doris.nereids.trees.plans.logical.LogicalFileScan.SelectedPartitions;
import org.apache.doris.planner.PlanNodeId;
import org.apache.doris.qe.ConnectContext;
Expand Down Expand Up @@ -84,6 +85,8 @@ public class HiveScanNode extends FileQueryScanNode {
@Setter
private SelectedPartitions selectedPartitions = null;

private DirectoryLister directoryLister;

private boolean partitionInit = false;
private final AtomicReference<UserException> batchException = new AtomicReference<>(null);
private List<HivePartition> prunedPartitions;
Expand All @@ -98,17 +101,21 @@ public class HiveScanNode extends FileQueryScanNode {
* eg: s3 tvf
* These scan nodes do not have corresponding catalog/database/table info, so no need to do priv check
*/
public HiveScanNode(PlanNodeId id, TupleDescriptor desc, boolean needCheckColumnPriv) {
public HiveScanNode(PlanNodeId id, TupleDescriptor desc, boolean needCheckColumnPriv,
DirectoryLister directoryLister) {
super(id, desc, "HIVE_SCAN_NODE", StatisticalType.HIVE_SCAN_NODE, needCheckColumnPriv);
hmsTable = (HMSExternalTable) desc.getTable();
brokerName = hmsTable.getCatalog().bindBrokerName();
this.directoryLister = directoryLister;
}

public HiveScanNode(PlanNodeId id, TupleDescriptor desc, String planNodeName,
StatisticalType statisticalType, boolean needCheckColumnPriv) {
StatisticalType statisticalType, boolean needCheckColumnPriv,
DirectoryLister directoryLister) {
super(id, desc, planNodeName, statisticalType, needCheckColumnPriv);
hmsTable = (HMSExternalTable) desc.getTable();
brokerName = hmsTable.getCatalog().bindBrokerName();
this.directoryLister = directoryLister;
}

@Override
Expand Down Expand Up @@ -269,7 +276,8 @@ private void getFileSplitByPartitions(HiveMetaStoreCache cache, List<HivePartiti
fileCaches = getFileSplitByTransaction(cache, partitions, bindBrokerName);
} else {
boolean withCache = Config.max_external_file_cache_num > 0;
fileCaches = cache.getFilesByPartitions(partitions, withCache, partitions.size() > 1, bindBrokerName);
fileCaches = cache.getFilesByPartitions(partitions, withCache, partitions.size() > 1, bindBrokerName,
directoryLister, hmsTable);
}
if (tableSample != null) {
List<HiveMetaStoreCache.HiveFileStatus> hiveFileStatuses = selectFiles(fileCaches);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.apache.doris.datasource.hive.HivePartition;
import org.apache.doris.datasource.hive.source.HiveScanNode;
import org.apache.doris.datasource.hudi.HudiUtils;
import org.apache.doris.fs.DirectoryLister;
import org.apache.doris.planner.ListPartitionPrunerV2;
import org.apache.doris.planner.PlanNodeId;
import org.apache.doris.qe.ConnectContext;
Expand Down Expand Up @@ -121,8 +122,8 @@ public class HudiScanNode extends HiveScanNode {
* These scan nodes do not have corresponding catalog/database/table info, so no need to do priv check
*/
public HudiScanNode(PlanNodeId id, TupleDescriptor desc, boolean needCheckColumnPriv,
Optional<TableScanParams> scanParams, Optional<IncrementalRelation> incrementalRelation) {
super(id, desc, "HUDI_SCAN_NODE", StatisticalType.HUDI_SCAN_NODE, needCheckColumnPriv);
Optional<TableScanParams> scanParams, Optional<IncrementalRelation> incrementalRelation, DirectoryLister directoryLister) {
super(id, desc, "HUDI_SCAN_NODE", StatisticalType.HUDI_SCAN_NODE, needCheckColumnPriv, directoryLister);
isCowOrRoTable = hmsTable.isHoodieCowTable();
if (LOG.isDebugEnabled()) {
if (isCowOrRoTable) {
Expand Down
31 changes: 31 additions & 0 deletions fe/fe-core/src/main/java/org/apache/doris/fs/DirectoryLister.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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.
// This file is copied from
// https://github.com/trinodb/trino/blob/438/plugin/trino-hive/src/main/java/io/trino/plugin/hive/fs/DirectoryLister.java
// and modified by Doris

package org.apache.doris.fs;

import org.apache.doris.catalog.TableIf;
import org.apache.doris.fs.remote.RemoteFile;

import java.io.IOException;

public interface DirectoryLister {
RemoteIterator<RemoteFile> listFilesRecursively(FileSystem fs, TableIf table, String location)
throws IOException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// 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.doris.fs;

import org.apache.doris.backup.Status;
import org.apache.doris.catalog.TableIf;
import org.apache.doris.fs.remote.RemoteFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileSystemDirectoryLister implements DirectoryLister {
public RemoteIterator<RemoteFile> listFilesRecursively(FileSystem fs, TableIf table, String location)
throws IOException {
List<RemoteFile> result = new ArrayList<>();
Status status = fs.listFiles(location, true, result);
if (!status.ok()) {
throw new IOException(status.getErrMsg());
}
return new RemoteFileRemoteIterator(result);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// 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.doris.fs;

import org.apache.doris.fs.remote.RemoteFile;

import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;

public class RemoteFileRemoteIterator
implements RemoteIterator<RemoteFile> {
private final List<RemoteFile> remoteFileList;
private int currentIndex = 0;

public RemoteFileRemoteIterator(List<RemoteFile> remoteFileList) {
this.remoteFileList = Objects.requireNonNull(remoteFileList, "iterator is null");
}

@Override
public boolean hasNext() throws IOException {
return currentIndex < remoteFileList.size();
}

@Override
public RemoteFile next() throws IOException {
if (!hasNext()) {
throw new NoSuchElementException("No more elements in RemoteFileRemoteIterator");
}
return remoteFileList.get(currentIndex++);
}
}
Loading

0 comments on commit 65ef2e1

Please sign in to comment.