1 /*
  2  * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 import java.io.BufferedReader;
 25 import java.io.File;
 26 import java.io.IOException;
 27 import java.nio.file.Path;
 28 import java.util.List;
 29 import java.util.logging.LogRecord;
 30 import java.util.logging.Logger;
 31 import java.util.logging.StreamHandler;
 32 import java.util.stream.Stream;
 33 
 34 import org.junit.jupiter.params.provider.Arguments;
 35 import org.junit.jupiter.params.provider.MethodSource;
 36 import org.junit.jupiter.params.ParameterizedTest;
 37 import static org.junit.jupiter.api.Assertions.assertEquals;
 38 import static org.junit.jupiter.api.Assertions.fail;
 39 
 40 /*
 41  * @test
 42  * @summary verify logging of ProcessBuilder.start()
 43  * @run junit/othervm ProcessStartLoggingTest
 44  */
 45 public class ProcessStartLoggingTest {
 46 
 47     private final static int NORMAL_STATUS = 0;
 48     private final static int ERROR_STATUS = 1;
 49 
 50     private static final String TEST_JDK = System.getProperty("test.jdk");
 51     private static final String TEST_SRC = System.getProperty("test.src");
 52 
 53     private static Object HOLD_LOGGER;
 54 
 55     /**
 56      * Launch a process with the arguments.
 57      * @param args 1 or strings passed directly to ProcessBuilder as command and arguments.
 58      */
 59     public static void main(String[] args) throws InterruptedException {
 60         if (System.getProperty("ThrowingHandler") != null) {
 61             HOLD_LOGGER = ProcessStartLoggingTest.ThrowingHandler.installHandler();
 62         }
 63         String directory = System.getProperty("directory");
 64         try {
 65             ProcessBuilder pb = new ProcessBuilder(args);
 66             pb.directory((directory == null) ? null : new File(directory));
 67             Process p = pb.start();
 68             int status = p.waitFor();
 69             if (status != 0) {
 70                 System.out.println("exitValue: " + status);
 71             }
 72         } catch (IOException ioe) {
 73             System.out.println("ProcessBuilder.start() threw IOException: " + ioe);
 74         }
 75     }
 76 
 77     /**
 78      * Test various log level settings, and none.
 79      * @return a stream of arguments for parameterized test
 80      */
 81     private static Stream<Arguments> logParamProvider() {
 82 
 83         return Stream.of(
 84                 // Logging enabled with level TRACE
 85                 Arguments.of(List.of("-Djava.util.logging.config.file=" +
 86                                         Path.of(TEST_SRC, "ProcessLogging-FINER.properties").toString(),
 87                                 "-Ddirectory=."),
 88                         List.of("echo", "echo0"),
 89                         NORMAL_STATUS,
 90                         "dir: ., cmd: \"echo\" \"echo0\""),
 91                 // Logging enabled with level DEBUG
 92                 Arguments.of(List.of("-Djava.util.logging.config.file=" +
 93                                         Path.of(TEST_SRC, "ProcessLogging-FINE.properties").toString(),
 94                                 "-Ddirectory=."),
 95                         List.of("echo", "echo1"),
 96                         NORMAL_STATUS,
 97                         "dir: ., cmd: \"echo\""),
 98                 // Logging disabled due to level INFO
 99                 Arguments.of(List.of("-Djava.util.logging.config.file=" +
100                                 Path.of(TEST_SRC, "ProcessLogging-INFO.properties").toString()),
101                         List.of("echo", "echo2"),
102                         NORMAL_STATUS,
103                         ""),
104                 // Console logger DEBUG
105                 Arguments.of(List.of("--limit-modules", "java.base",
106                                 "-Djdk.system.logger.level=DEBUG"),
107                         List.of("echo", "echo3"),
108                         NORMAL_STATUS,
109                         "dir: null, cmd: \"echo\""),
110                 // Console logger TRACE
111                 Arguments.of(List.of("--limit-modules", "java.base",
112                                 "-Djdk.system.logger.level=TRACE",
113                                 "-Ddirectory=."),
114                         List.of("echo", "echo4"),
115                         NORMAL_STATUS,
116                         "dir: ., cmd: \"echo\" \"echo4\""),
117                 // No Logging configured
118                 Arguments.of(List.of(),
119                         List.of("echo", "echo5"),
120                         NORMAL_STATUS,
121                         ""),
122                 // Throwing Handler
123                 Arguments.of(List.of("-DThrowingHandler",
124                                 "-Djava.util.logging.config.file=" +
125                                         Path.of(TEST_SRC, "ProcessLogging-FINE.properties").toString()),
126                         List.of("echo", "echo6"),
127                         ERROR_STATUS,
128                         "Exception in thread \"main\" java.lang.RuntimeException: Exception in publish")
129         );
130     }
131 
132     /**
133      * Check that the logger output of a launched process contains the expected message.
134      *
135      * @param logArgs       Arguments to configure logging in the java test process
136      * @param childArgs     the args passed to the child to be invoked as a Process
137      * @param expectMessage log should contain the message
138      */
139     @ParameterizedTest
140     @MethodSource("logParamProvider")
141     public void checkLogger(List<String> logArgs, List<String> childArgs,
142                             int expectedStatus, String expectMessage) {
143         ProcessBuilder pb = new ProcessBuilder();
144         pb.redirectErrorStream(true);
145 
146         List<String> cmd = pb.command();
147         cmd.add(Path.of(TEST_JDK,"bin", "java").toString());
148         cmd.addAll(logArgs);
149         cmd.add(this.getClass().getName());
150         cmd.addAll(childArgs);
151         try {
152             Process process = pb.start();
153             try (BufferedReader reader = process.inputReader()) {
154                 List<String> lines = reader.lines().toList();
155                 boolean match = (expectMessage.isEmpty())
156                         ? lines.size() == 0
157                         : lines.stream().filter(s -> s.contains(expectMessage)).findFirst().isPresent();
158                 if (!match) {
159                     // Output lines for debug
160                     System.err.println("Expected> \"" + expectMessage + "\"");
161                     lines.forEach(l -> System.err.println("Actual>   \"" + l+ "\""));
162                     fail("Unexpected log contents");
163                 }
164             }
165             int result = process.waitFor();
166             assertEquals(expectedStatus, result, "Exit status");
167         } catch (IOException | InterruptedException ex) {
168             fail(ex);
169         }
170     }
171 
172     /**
173      * A LoggingHandler that throws an Exception.
174      */
175     public static class ThrowingHandler extends StreamHandler {
176 
177         // Install this handler for java.lang.ProcessBuilder
178         public static Logger installHandler() {
179             Logger logger = Logger.getLogger("java.lang.ProcessBuilder");
180             logger.addHandler(new ProcessStartLoggingTest.ThrowingHandler());
181             return logger;
182         }
183 
184         @Override
185         public synchronized void publish(LogRecord record) {
186             throw new RuntimeException("Exception in publish");
187         }
188     }
189 }