Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for posix_madvise to Java 21 MMapDirectory #13196

Merged
merged 27 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
670b06c
Add support for posix_madvise to Java 21 MMapDirectory
uschindler Mar 21, 2024
1ca24fe
Cleanup and retrieve page size on linux; TODO: the constant seems sys…
uschindler Mar 21, 2024
7cec218
fix bug in warning
uschindler Mar 21, 2024
9a6faca
Remove page size retrieval again and use a safe boundary (2 MiB)
uschindler Mar 21, 2024
4d9a442
fix logger name
uschindler Mar 21, 2024
d311b97
static final MH
ChrisHegarty Mar 21, 2024
5873d7c
Add IOContext.randomAccess (#3)
ChrisHegarty Mar 21, 2024
9ed1da7
Revert "static final MH"
uschindler Mar 22, 2024
242e5e9
Make merge context always win
uschindler Mar 22, 2024
a729f02
Cleanup code and move IOContext mapping to Posix, as the constants we…
uschindler Mar 22, 2024
1e4c5c3
Set randomAccess=true on LOAD. (#4)
jpountz Mar 22, 2024
c9e5ae4
Another run at static final
ChrisHegarty Mar 22, 2024
3dcf7c9
Remove NoopNativeAccess and use an Optional
uschindler Mar 22, 2024
6b19c3a
Merge branch 'dev/posix_madvise' of https://github.com/uschindler/luc…
uschindler Mar 22, 2024
135a8d2
Merge remote-tracking branch 'uwe/dev/posix_madvise' into dev/posix_m…
ChrisHegarty Mar 22, 2024
0d0aeb1
optional
ChrisHegarty Mar 22, 2024
4430a76
javadoc
ChrisHegarty Mar 22, 2024
5c97ca0
remove logger and uppercase MH
ChrisHegarty Mar 22, 2024
20fd5a1
Add getter on MMapDirectory to make madvise status queryable
uschindler Mar 22, 2024
e6485b8
Merge branch 'dev/posix_madvise' of https://github.com/uschindler/luc…
uschindler Mar 22, 2024
cab9014
add minimal test with input IOContext.RANDOM to ensure basic code pat…
ChrisHegarty Mar 22, 2024
1bdad0f
typo
ChrisHegarty Mar 22, 2024
86bfdc6
Add more Javadocs, improve instructions when native access is misisng…
uschindler Mar 22, 2024
648f578
fix typo
uschindler Mar 22, 2024
265c82b
Merge branch 'main' into dev/posix_madvise
ChrisHegarty Mar 23, 2024
94073e1
Merge branch 'main' of https://gitbox.apache.org/repos/asf/lucene int…
uschindler Mar 25, 2024
3919323
add CHANGES.txt
uschindler Mar 25, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions gradle/testing/defaults-tests.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ allprojects {
if (rootProject.vectorIncubatorJavaVersions.contains(rootProject.runtimeJavaVersion)) {
jvmArgs '--add-modules', 'jdk.incubator.vector'
}

jvmArgs '--enable-native-access=' + (project.path == ':lucene:core' ? 'ALL-UNNAMED' : 'org.apache.lucene.core')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🙏


def loggingConfigFile = layout.projectDirectory.file("${resources}/logging.properties")
def tempDir = layout.projectDirectory.dir(testsTmpDir.toString())
Expand Down
37 changes: 30 additions & 7 deletions lucene/core/src/java/org/apache/lucene/store/IOContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,32 @@ public enum Context {
/** This flag indicates that the file will be opened, then fully read sequentially then closed. */
public final boolean readOnce;

/**
* This flag indicates that the file will be accessed randomly. If this flag is set, then readOnce
* will be false.
*/
public final boolean randomAccess;

/**
* This flag is used for files that are a small fraction of the total index size and are expected
* to be heavily accessed in random-access fashion. Some {@link Directory} implementations may
* choose to load such files into physical memory (e.g. Java heap) as a way to provide stronger
* guarantees on query latency.
* guarantees on query latency. If this flag is set, then {@link #randomAccess} will be true.
*/
public final boolean load;
rmuir marked this conversation as resolved.
Show resolved Hide resolved

public static final IOContext DEFAULT = new IOContext(Context.DEFAULT);

public static final IOContext READONCE = new IOContext(true, false);
public static final IOContext READONCE = new IOContext(true, false, false);

public static final IOContext READ = new IOContext(false, false, false);

public static final IOContext READ = new IOContext(false, false);
public static final IOContext LOAD = new IOContext(false, true, true);

public static final IOContext LOAD = new IOContext(false, true);
public static final IOContext RANDOM = new IOContext(false, false, true);

public IOContext() {
this(false, false);
this(false, false, false);
}

public IOContext(FlushInfo flushInfo) {
Expand All @@ -72,18 +80,26 @@ public IOContext(FlushInfo flushInfo) {
this.mergeInfo = null;
this.readOnce = false;
this.load = false;
this.randomAccess = false;
this.flushInfo = flushInfo;
}

public IOContext(Context context) {
this(context, null);
}

private IOContext(boolean readOnce, boolean load) {
private IOContext(boolean readOnce, boolean load, boolean randomAccess) {
if (readOnce && randomAccess) {
throw new IllegalArgumentException("cannot be both readOnce and randomAccess");
}
if (load && randomAccess == false) {
throw new IllegalArgumentException("cannot be load but not randomAccess");
}
this.context = Context.READ;
this.mergeInfo = null;
this.readOnce = readOnce;
this.load = load;
this.randomAccess = randomAccess;
this.flushInfo = null;
}

Expand All @@ -98,6 +114,7 @@ private IOContext(Context context, MergeInfo mergeInfo) {
this.context = context;
this.readOnce = false;
this.load = false;
this.randomAccess = false;
this.mergeInfo = mergeInfo;
this.flushInfo = null;
}
Expand All @@ -115,12 +132,13 @@ public IOContext(IOContext ctxt, boolean readOnce) {
this.mergeInfo = ctxt.mergeInfo;
this.flushInfo = ctxt.flushInfo;
this.readOnce = readOnce;
this.randomAccess = ctxt.randomAccess;
this.load = false;
}

@Override
public int hashCode() {
return Objects.hash(context, flushInfo, mergeInfo, readOnce, load);
return Objects.hash(context, flushInfo, mergeInfo, readOnce, load, randomAccess);
}

@Override
Expand All @@ -134,6 +152,7 @@ public boolean equals(Object obj) {
if (!Objects.equals(mergeInfo, other.mergeInfo)) return false;
if (readOnce != other.readOnce) return false;
if (load != other.load) return false;
if (randomAccess != other.randomAccess) return false;
return true;
}

Expand All @@ -147,6 +166,10 @@ public String toString() {
+ flushInfo
+ ", readOnce="
+ readOnce
+ ", load="
+ load
+ ", randomAccess="
+ randomAccess
+ "]";
}
}
17 changes: 17 additions & 0 deletions lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@
* of box with some compilation tricks. For more information about the foreign memory API read
* documentation of the {@link java.lang.foreign} package.
*
* <p>On some platforms like Linux and MacOS X, this class will invoke the syscall {@code madvise()}
* to advise how OS kernel should handle paging after opening a file. For this to work, Java code
* must be able to call native code. If this is not allowed, a warning is logged. To enable native
* access for Lucene in a modularized application, pass {@code
* --enable-native-access=org.apache.lucene.core} to the Java command line. If Lucene is running in
* a classpath-based application, use {@code --enable-native-access=ALL-UNNAMED}.
*
* <p><b>NOTE:</b> Accessing this class either directly or indirectly from a thread while it's
* interrupted can close the underlying channel immediately if at the same time the thread is
* blocked on IO. The channel will remain closed and subsequent access to {@link MMapDirectory} will
Expand Down Expand Up @@ -204,6 +211,8 @@ IndexInput openInput(Path path, IOContext context, int chunkSizePower, boolean p

long getDefaultMaxChunkSize();

boolean supportsMadvise();

default IOException convertMapFailedIOException(
IOException ioe, String resourceDescription, long bufSize) {
final String originalMessage;
Expand Down Expand Up @@ -269,6 +278,14 @@ private static MMapIndexInputProvider lookupProvider() {
}
}

/**
* Returns true, if MMapDirectory uses the platform's {@code madvise()} syscall to advise how OS
* kernel should handle paging after opening a file.
*/
public static boolean supportsMadvise() {
return PROVIDER.supportsMadvise();
}

static {
PROVIDER = lookupProvider();
DEFAULT_MAX_CHUNK_SIZE = PROVIDER.getDefaultMaxChunkSize();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,19 @@
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.Unwrappable;

@SuppressWarnings("preview")
final class MemorySegmentIndexInputProvider implements MMapDirectory.MMapIndexInputProvider {

private final Optional<NativeAccess> nativeAccess;

MemorySegmentIndexInputProvider() {
this.nativeAccess = NativeAccess.getImplementation();
}

@Override
public IndexInput openInput(Path path, IOContext context, int chunkSizePower, boolean preload)
throws IOException {
Expand All @@ -45,7 +52,7 @@ public IndexInput openInput(Path path, IOContext context, int chunkSizePower, bo
MemorySegmentIndexInput.newInstance(
resourceDescription,
arena,
map(arena, resourceDescription, fc, chunkSizePower, preload, fileSize),
map(arena, resourceDescription, fc, context, chunkSizePower, preload, fileSize),
fileSize,
chunkSizePower);
success = true;
Expand All @@ -62,10 +69,16 @@ public long getDefaultMaxChunkSize() {
return Constants.JRE_IS_64BIT ? (1L << 34) : (1L << 28);
}

@Override
public boolean supportsMadvise() {
return nativeAccess.isPresent();
}

private final MemorySegment[] map(
Arena arena,
String resourceDescription,
FileChannel fc,
IOContext context,
int chunkSizePower,
boolean preload,
long length)
Expand All @@ -90,8 +103,12 @@ private final MemorySegment[] map(
} catch (IOException ioe) {
throw convertMapFailedIOException(ioe, resourceDescription, segSize);
}
// if preload apply it without madvise.
// if chunk size is too small (2 MiB), disable madvise support (incorrect alignment)
if (preload) {
segment.load();
} else if (nativeAccess.isPresent() && chunkSizePower >= 21) {
nativeAccess.get().madvise(segment, context);
}
segments[segNr] = segment;
startOffset += segSize;
Expand Down
39 changes: 39 additions & 0 deletions lucene/core/src/java21/org/apache/lucene/store/NativeAccess.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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.lucene.store;

import java.io.IOException;
import java.lang.foreign.MemorySegment;
import java.util.Optional;
import org.apache.lucene.util.Constants;

@SuppressWarnings("preview")
abstract class NativeAccess {

/** Invoke the {@code madvise} call for the given {@link MemorySegment}. */
public abstract void madvise(MemorySegment segment, IOContext context) throws IOException;

/**
* Return the NativeAccess instance for this platform. At moment we only support Linux and MacOS
*/
public static Optional<NativeAccess> getImplementation() {
if (Constants.LINUX || Constants.MAC_OS_X) {
ChrisHegarty marked this conversation as resolved.
Show resolved Hide resolved
return PosixNativeAccess.getInstance();
}
return Optional.empty();
}
}
Loading