Skip to content

Commit 6c909aa

Browse files
committed
kvm: log the progress of qemu-img convert in the Agent log
Claude-Session: https://claude.ai/code/session_01CUwgtFEPLkr62vbUayjCDZ
1 parent caf1091 commit 6c909aa

3 files changed

Lines changed: 179 additions & 1 deletion

File tree

‎plugins/hypervisors/kvm/src/main/java/org/apache/cloudstack/utils/qemu/QemuImg.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,8 @@ public void convert(final QemuImgFile srcFile, final QemuImgFile destFile, QemuI
509509
}
510510

511511
script.add("convert");
512+
// report the progress, so that it can be followed in the Agent log (see QemuImgProgressLogger)
513+
script.add("-p");
512514

513515
if (destImageOpts != null) {
514516
// a destination described by image options always exists already; qemu-img requires -n with --target-image-opts
@@ -587,7 +589,7 @@ public void convert(final QemuImgFile srcFile, final QemuImgFile destFile, QemuI
587589
script.add(destFile.getFileName());
588590
}
589591

590-
final String result = script.execute();
592+
final String result = script.execute(new QemuImgProgressLogger(String.format("qemu-img convert from [%s] to [%s]", srcFile.getFileName(), destFile.getFileName())));
591593
if (result != null) {
592594
throw new QemuImgException(result);
593595
}
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
package org.apache.cloudstack.utils.qemu;
18+
19+
import java.io.BufferedReader;
20+
import java.io.IOException;
21+
import java.util.concurrent.CountDownLatch;
22+
import java.util.concurrent.TimeUnit;
23+
import java.util.regex.Matcher;
24+
import java.util.regex.Pattern;
25+
26+
import com.cloud.utils.script.OutputInterpreter;
27+
28+
/**
29+
* Reads the output of "qemu-img convert -p" while the command runs and writes the progress to the Agent log, so that
30+
* an operator can follow a long volume copy or migration. Any output that is not a progress line is kept and returned
31+
* as the error message when the command fails.
32+
*/
33+
public class QemuImgProgressLogger extends OutputInterpreter {
34+
protected static final Pattern PROGRESS_PATTERN = Pattern.compile("\\((\\d{1,3}(?:\\.\\d+)?)/100%\\)");
35+
protected static final int PROGRESS_STEP_PERCENT = 10;
36+
protected static final long PROGRESS_MAX_SILENCE_MS = TimeUnit.MINUTES.toMillis(5);
37+
private static final int MAX_KEPT_OUTPUT_CHARS = 4096;
38+
private static final long WAIT_FOR_OUTPUT_END_SECONDS = 5;
39+
40+
private final String description;
41+
private final StringBuilder otherOutput = new StringBuilder();
42+
private final CountDownLatch outputEnded = new CountDownLatch(1);
43+
private int lastLoggedStep = -1;
44+
private long lastLoggedTime;
45+
private double lastProgress = -1;
46+
47+
public QemuImgProgressLogger(String description) {
48+
this.description = description;
49+
}
50+
51+
@Override
52+
public boolean drain() {
53+
return true;
54+
}
55+
56+
@Override
57+
public String interpret(BufferedReader reader) throws IOException {
58+
lastLoggedTime = System.currentTimeMillis();
59+
try {
60+
String line;
61+
// qemu-img ends each progress report with a carriage return, which readLine() also treats as a line end
62+
while ((line = reader.readLine()) != null) {
63+
processLine(line);
64+
}
65+
} finally {
66+
outputEnded.countDown();
67+
}
68+
return null;
69+
}
70+
71+
protected void processLine(String line) {
72+
Matcher matcher = PROGRESS_PATTERN.matcher(line);
73+
if (!matcher.find()) {
74+
keepOutput(line);
75+
return;
76+
}
77+
lastProgress = Double.parseDouble(matcher.group(1));
78+
int step = (int) (lastProgress / PROGRESS_STEP_PERCENT);
79+
long now = System.currentTimeMillis();
80+
if (step > lastLoggedStep || now - lastLoggedTime >= PROGRESS_MAX_SILENCE_MS) {
81+
lastLoggedStep = Math.max(step, lastLoggedStep);
82+
lastLoggedTime = now;
83+
logger.info("Progress of {}: {}%.", description, String.format("%.2f", lastProgress));
84+
}
85+
}
86+
87+
private synchronized void keepOutput(String line) {
88+
if (line.trim().isEmpty() || otherOutput.length() >= MAX_KEPT_OUTPUT_CHARS) {
89+
return;
90+
}
91+
otherOutput.append(line.trim()).append(' ');
92+
}
93+
94+
@Override
95+
public String processError(BufferedReader reader) throws IOException {
96+
try {
97+
if (!outputEnded.await(WAIT_FOR_OUTPUT_END_SECONDS, TimeUnit.SECONDS)) {
98+
logger.debug("Still reading the output of {} after it failed.", description);
99+
}
100+
} catch (InterruptedException e) {
101+
Thread.currentThread().interrupt();
102+
}
103+
String kept;
104+
synchronized (this) {
105+
kept = otherOutput.toString().trim();
106+
}
107+
if (lastProgress >= 0) {
108+
logger.warn("{} failed at {}%.", description, String.format("%.2f", lastProgress));
109+
}
110+
return kept.isEmpty() ? "qemu-img convert failed without an error message" : kept;
111+
}
112+
113+
public double getLastProgress() {
114+
return lastProgress;
115+
}
116+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
package org.apache.cloudstack.utils.qemu;
18+
19+
import java.io.BufferedReader;
20+
import java.io.IOException;
21+
import java.io.StringReader;
22+
23+
import org.junit.Assert;
24+
import org.junit.Test;
25+
26+
public class QemuImgProgressLoggerTest {
27+
28+
private BufferedReader readerOf(String output) {
29+
return new BufferedReader(new StringReader(output));
30+
}
31+
32+
@Test
33+
public void interpretTestReadsProgressSeparatedByCarriageReturns() throws IOException {
34+
QemuImgProgressLogger progressLogger = new QemuImgProgressLogger("test");
35+
36+
String result = progressLogger.interpret(readerOf(" (0.00/100%)\r (1.00/100%)\r (55.50/100%)\r (100.00/100%)\n"));
37+
38+
Assert.assertNull(result);
39+
Assert.assertEquals(100.0, progressLogger.getLastProgress(), 0.001);
40+
}
41+
42+
@Test
43+
public void processErrorTestReturnsOutputThatIsNotProgress() throws IOException {
44+
QemuImgProgressLogger progressLogger = new QemuImgProgressLogger("test");
45+
progressLogger.interpret(readerOf(" (0.00/100%)\r (12.00/100%)\rqemu-img: error while writing at byte 1024: No space left on device\n"));
46+
47+
String error = progressLogger.processError(readerOf(""));
48+
49+
Assert.assertEquals("qemu-img: error while writing at byte 1024: No space left on device", error);
50+
Assert.assertEquals(12.0, progressLogger.getLastProgress(), 0.001);
51+
}
52+
53+
@Test
54+
public void processErrorTestReturnsDefaultMessageWhenThereIsNoOutput() throws IOException {
55+
QemuImgProgressLogger progressLogger = new QemuImgProgressLogger("test");
56+
progressLogger.interpret(readerOf(""));
57+
58+
Assert.assertEquals("qemu-img convert failed without an error message", progressLogger.processError(readerOf("")));
59+
}
60+
}

0 commit comments

Comments
 (0)