Skip to content

Commit 781e2fc

Browse files
committed
Fix potential leaks in executePipedCommands
1 parent 56a39e6 commit 781e2fc

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

utils/src/main/java/com/cloud/utils/script/Script.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,11 @@
4040
import java.util.concurrent.ScheduledFuture;
4141
import java.util.concurrent.TimeUnit;
4242
import java.util.concurrent.TimeoutException;
43+
import java.util.concurrent.atomic.AtomicReference;
4344
import java.util.stream.Collectors;
4445

4546
import org.apache.cloudstack.utils.security.KeyStoreUtils;
47+
import org.apache.commons.collections.CollectionUtils;
4648
import org.apache.commons.io.IOUtils;
4749
import org.apache.logging.log4j.LogManager;
4850
import org.apache.logging.log4j.Logger;
@@ -712,9 +714,11 @@ public static Pair<Integer, String> executePipedCommands(List<String[]> commands
712714
if (timeout <= 0) {
713715
timeout = DEFAULT_TIMEOUT;
714716
}
717+
final AtomicReference<List<Process>> processesRef = new AtomicReference<>();
715718
Callable<Pair<Integer, String>> commandRunner = () -> {
716719
List<ProcessBuilder> builders = commands.stream().map(ProcessBuilder::new).collect(Collectors.toList());
717720
List<Process> processes = ProcessBuilder.startPipeline(builders);
721+
processesRef.set(processes);
718722
Process last = processes.get(processes.size()-1);
719723
try (BufferedReader reader = new BufferedReader(new InputStreamReader(last.getInputStream()))) {
720724
String line;
@@ -741,6 +745,20 @@ public static Pair<Integer, String> executePipedCommands(List<String[]> commands
741745
result.second(ERR_TIMEOUT);
742746
} catch (InterruptedException | ExecutionException e) {
743747
LOGGER.error("Error executing piped commands", e);
748+
} finally {
749+
List<Process> processes = processesRef.get();
750+
if (CollectionUtils.isNotEmpty(processes)) {
751+
for (Process process : processes) {
752+
if (process == null) {
753+
continue;
754+
}
755+
LOGGER.trace(String.format("Cleaning up process [%s] from piped commands.", process.pid()));
756+
IOUtils.closeQuietly(process.getErrorStream());
757+
IOUtils.closeQuietly(process.getOutputStream());
758+
IOUtils.closeQuietly(process.getInputStream());
759+
process.destroyForcibly();
760+
}
761+
}
744762
}
745763
return result;
746764
}

0 commit comments

Comments
 (0)