This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new c912d231993 [fix](fe) Sync downloaded FE images to disk before
renaming them (#71077)
c912d231993 is described below
commit c912d231993fe7cad29893951b1f65796319c50e
Author: Tran Ngoc Tuan <[email protected]>
AuthorDate: Mon Nov 30 08:18:11 2026 +0700
[fix](fe) Sync downloaded FE images to disk before renaming them (#71077)
### Background
After each checkpoint, the master FE writes a new metadata image,
`image.N`, and pushes it to every other FE through `/put`. Each FE
downloads it with `MetaHelper.getRemoteFile` into `image.N.part`, checks
its size and MD5, and renames it to `image.N` with
`MetaHelper.complete`. An FE that starts behind the master pulls the
image the same way. At startup an FE loads only its newest `image.N` and
then replays the journal from there.
### What problem does this PR solve?
Issue Number: close #71076
Related PR: #9180 (added `force(true)` to the image the master writes,
but not to downloaded copies)
PR Type: Bugfix
Problem Summary:
A downloaded image is renamed to its final name without ever being
synced to disk. If the host loses power within the kernel's writeback
window after the rename, `image.N` is left truncated, and the FE then
fails on every restart with `IllegalStateException` in
`MetaReader.read`. With two FEs this also leaves the cluster without a
master. This PR syncs the downloaded file before the MD5 check and the
rename, and syncs the image directory after renames, so a power loss
leaves either the previous image or a complete new one. The issue has
the evidence: the truncated file is an exact prefix of the master's
copy, cut at a 4 KiB boundary.
### Details
- **Frequency:** Intermittent. It needs a host power loss, not a process
kill, within seconds of a follower storing a new image; preemptible or
spot VMs that are reclaimed with about 30 s notice make it realistic.
Observed once on 4.1.5; timeline in the issue.
- **Root cause:** `MetaHelper.getRemoteFile` calls
`IOUtils.copyBytes(..., close=true)`, which closes the output stream
right after the copy, so the data is never forced to disk. The MD5 check
then reads the file back from the page cache, so it passes, and
`MetaHelper.complete` renames the unsynced file to `image.N`.
- **Why existing tests missed it:** `MetaHelperTest` covers file-name
validation and response parsing only, and `MetaServiceTest` mocks
`MetaHelper.getRemoteFile`. No unit test downloads a file. In
`regression-test/suites/`, `meta_action_p0/test_dump_image.groovy` dumps
an image but does not reach the download path.
- **Fix:** keep the output stream open after the copy and call
`getChannel().force(true)` before the MD5 check, as `MetaWriter`,
`MetaHeader` and `MetaFooter` already do for the master's image. Add
`MetaHelper.syncDirectory` and call it after the rename in
`MetaHelper.complete` and `Env.saveImage`, so the new name is durable
too; it throws on failure, which fails the push or the checkpoint like
other I/O errors there. The MD5 input stream, which was never closed, is
now closed.
- **Other paths and branches:** every caller of `getRemoteFile` and
`complete` is fixed by this change: `MetaService.put` (image pushed by
the master), `Env.getNewImage` (image pulled at startup) and
`Env.getVersionFileFromHelper` (`VERSION` pulled at startup). The
master's checkpoint path already synced the file contents and now also
syncs the directory. The unsynced download is on `branch-3.1`,
`branch-4.0`, `branch-4.1` and `branch-4.2`, and predates the FE module
split in #4099.
### Testing
- `MetaHelperTest#testDownloadAndComplete` and
`#testDownloadRejectsMd5Mismatch` (new): download an image from a local
HTTP server through `getRemoteFile` and `complete`, and check that the
content is intact, no `.part` file is left, and a wrong MD5 is rejected.
They cover the reordered stream handling, not durability itself.
- `MetaHelperTest#testSyncDirectory` (new): syncing an existing
directory succeeds and a missing one throws.
- Not run locally: the FE was not compiled and the new tests did not run
(no prebuilt thirdparty locally); the FE unit test pipeline runs them.
The power-loss case itself needs a fault-injecting file system such as
dm-flakey or LazyFS.
### Release note
Fix an FE failing to start after a host power loss, because an image it
had just downloaded from the master was left truncated on disk.
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: the FE was not compiled
locally and the new unit tests have not run yet
### AI Disclosure
- Tool: Claude Code (Claude Opus 5.5)
- Generated: the code change, the tests, the issue and this description
- Human review: The author reviewed the code change, the tests and this
description.
- Prompts: The author asked to investigate an FE that could not start
after its VM was preempted, confirm the root cause from the FE's files
and logs read-only, research the Doris code on `master`, and then
prepare an upstream fix with an issue and a linked PR.
---
.../main/java/org/apache/doris/catalog/Env.java | 1 +
.../java/org/apache/doris/master/MetaHelper.java | 32 +++++++++---
.../org/apache/doris/master/MetaHelperTest.java | 60 ++++++++++++++++++++++
3 files changed, 86 insertions(+), 7 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
index 09d1a529cfb..0c2da26eb38 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
@@ -2819,6 +2819,7 @@ public class Env {
curFile.delete();
throw new IOException();
}
+ MetaHelper.syncDirectory(new File(this.imageDir));
return curFile.getAbsolutePath();
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/master/MetaHelper.java
b/fe/fe-core/src/main/java/org/apache/doris/master/MetaHelper.java
index 73fceec8b39..2bad7273265 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/master/MetaHelper.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/master/MetaHelper.java
@@ -37,8 +37,9 @@ import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.OutputStream;
import java.net.HttpURLConnection;
+import java.nio.channels.FileChannel;
+import java.nio.file.StandardOpenOption;
import java.util.Map;
public class MetaHelper {
@@ -93,10 +94,18 @@ public class MetaHelper {
if (!file.renameTo(newFile)) {
throw new IOException("Complete file " + filename + " failed");
}
+ syncDirectory(dir);
return newFile; // Return the newly renamed file
}
+ // Flush a directory's entries to disk, so that a file created or renamed
in it survives a power loss.
+ public static void syncDirectory(File dir) throws IOException {
+ try (FileChannel channel = FileChannel.open(dir.toPath(),
StandardOpenOption.READ)) {
+ channel.force(true);
+ }
+ }
+
public static File getFile(String filename, File dir) throws IOException {
checkIsValidFileName(filename);
File file = new File(dir, filename + MetaHelper.PART_SUFFIX);
@@ -163,7 +172,7 @@ public class MetaHelper {
throws IOException {
HttpURLConnection conn = null;
checkFile(file);
- OutputStream out = new FileOutputStream(file);
+ FileOutputStream out = new FileOutputStream(file);
try {
conn = HttpURLUtil.getConnectionWithNodeIdent(urlStr);
conn.setConnectTimeout(timeout);
@@ -179,18 +188,27 @@ public class MetaHelper {
throw new IOException(getResponse(conn));
}
String remoteMd5 = conn.getHeaderField(X_IMAGE_MD5);
- BufferedInputStream bin = new
BufferedInputStream(conn.getInputStream());
-
- // Do not limit speed in client side.
- long bytes = IOUtils.copyBytes(bin, out, BUFFER_BYTES,
CHECKPOINT_LIMIT_BYTES, true);
+ long bytes;
+ try (BufferedInputStream bin = new
BufferedInputStream(conn.getInputStream())) {
+ // Do not limit speed in client side.
+ // Keep the output open so that its contents can be synced
below.
+ bytes = IOUtils.copyBytes(bin, out, BUFFER_BYTES,
CHECKPOINT_LIMIT_BYTES, false);
+ }
if ((imageSize > 0) && (bytes != imageSize)) {
throw new IOException("Unexpected image size, expected: " +
imageSize + ", actual: " + bytes);
}
+ // The caller renames the file to its final name next. Sync the
contents first,
+ // otherwise a power loss can leave a truncated file under the
final name.
+ out.getChannel().force(true);
+
// if remoteMd5 not null ,we need check md5
if (remoteMd5 != null) {
- String localMd5 = DigestUtils.md5Hex(new
FileInputStream(file));
+ String localMd5;
+ try (FileInputStream in = new FileInputStream(file)) {
+ localMd5 = DigestUtils.md5Hex(in);
+ }
if (!remoteMd5.equals(localMd5)) {
throw new IOException("Unexpected image md5, expected: " +
remoteMd5 + ", actual: " + localMd5);
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java
b/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java
index b0716ec2b8e..4c4e29d7afc 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java
@@ -18,22 +18,82 @@
package org.apache.doris.master;
import org.apache.doris.common.Config;
+import org.apache.doris.common.util.HttpURLUtil;
import org.apache.doris.httpv2.entity.ResponseBody;
import org.apache.doris.httpv2.rest.RestApiStatusCode;
import org.apache.doris.persist.StorageInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sun.net.httpserver.HttpServer;
+import org.apache.commons.codec.digest.DigestUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
public class MetaHelperTest {
+ @Test
+ public void testDownloadAndComplete(@TempDir File dir) throws Exception {
+ byte[] image = "synthetic image
content".getBytes(StandardCharsets.UTF_8);
+ File downloaded = downloadAndComplete(dir, image,
DigestUtils.md5Hex(image));
+
+ Assertions.assertArrayEquals(image,
Files.readAllBytes(downloaded.toPath()));
+ Assertions.assertFalse(new File(dir, "image.1.part").exists());
+ }
+
+ @Test
+ public void testDownloadRejectsMd5Mismatch(@TempDir File dir) {
+ byte[] image = "synthetic image
content".getBytes(StandardCharsets.UTF_8);
+ IOException e = Assertions.assertThrows(IOException.class,
+ () -> downloadAndComplete(dir, image,
DigestUtils.md5Hex("other content")));
+ Assertions.assertTrue(e.getMessage().contains("Unexpected image md5"),
e.getMessage());
+ Assertions.assertFalse(new File(dir, "image.1").exists());
+ }
+
+ @Test
+ public void testSyncDirectory(@TempDir File dir) throws IOException {
+ MetaHelper.syncDirectory(dir);
+ Assertions.assertThrows(IOException.class, () ->
MetaHelper.syncDirectory(new File(dir, "missing")));
+ }
+
+ private File downloadAndComplete(File dir, byte[] image, String md5)
throws Exception {
+ File imageDir = dir.getCanonicalFile();
+ HttpServer server = HttpServer.create(new
InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+ server.createContext("/image", exchange -> {
+ exchange.getResponseHeaders().add(MetaHelper.X_IMAGE_SIZE,
String.valueOf(image.length));
+ exchange.getResponseHeaders().add(MetaHelper.X_IMAGE_MD5, md5);
+ exchange.sendResponseHeaders(200, image.length);
+ try (OutputStream body = exchange.getResponseBody()) {
+ body.write(image);
+ }
+ });
+ server.start();
+ String url = "http://127.0.0.1:" + server.getAddress().getPort() +
"/image?version=1";
+ try (MockedStatic<HttpURLUtil> httpUtil =
Mockito.mockStatic(HttpURLUtil.class)) {
+ httpUtil.when(() -> HttpURLUtil.getConnectionWithNodeIdent(url))
+ .thenAnswer(invocation -> (HttpURLConnection) new
URL(url).openConnection());
+ MetaHelper.getRemoteFile(url, 10_000,
MetaHelper.getFile("image.1", imageDir));
+ return MetaHelper.complete("image.1", imageDir);
+ } finally {
+ server.stop(0);
+ }
+ }
+
@Test
public void test() throws JsonProcessingException {
ResponseBody<StorageInfo> bodyBefore = buildResponseBody();
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]