4040import java .util .concurrent .ScheduledFuture ;
4141import java .util .concurrent .TimeUnit ;
4242import java .util .concurrent .TimeoutException ;
43+ import java .util .concurrent .atomic .AtomicReference ;
4344import java .util .stream .Collectors ;
4445
4546import org .apache .cloudstack .utils .security .KeyStoreUtils ;
47+ import org .apache .commons .collections .CollectionUtils ;
4648import org .apache .commons .io .IOUtils ;
4749import org .apache .logging .log4j .LogManager ;
4850import 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