Path: blob/master/test/jdk/java/lang/System/LoggerFinder/internal/BootstrapLogger/BootstrapLoggerTest.java
41161 views
/*1* Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.PrintStream;24import java.lang.ref.Reference;25import java.lang.ref.ReferenceQueue;26import java.lang.ref.WeakReference;27import java.lang.reflect.Array;28import java.lang.reflect.Field;29import java.lang.reflect.Method;30import java.lang.System.Logger;31import java.lang.System.Logger.Level;32import java.security.AllPermission;33import java.security.CodeSource;34import java.security.Permission;35import java.security.PermissionCollection;36import java.security.Permissions;37import java.security.Policy;38import java.security.ProtectionDomain;39import java.util.concurrent.atomic.AtomicBoolean;40import java.util.List;41import java.util.Optional;42import java.util.Set;43import java.util.stream.Collectors;44import java.util.stream.Stream;45import jdk.internal.logger.BootstrapLogger;46import jdk.internal.logger.LazyLoggers;4748/*49* @test50* @bug 8140364 818929151* @author danielfuchs52* @summary JDK implementation specific unit test for JDK internal artifacts.53Tests the behavior of bootstrap loggers (and SimpleConsoleLoggers54* too).55* @modules java.base/jdk.internal.logger:+open56* java.logging57* @build BootstrapLoggerUtils LogStream58* @run main/othervm BootstrapLoggerTest NO_SECURITY59* @run main/othervm -Djava.security.manager=allow BootstrapLoggerTest SECURE60* @run main/othervm/timeout=120 -Djava.security.manager=allow BootstrapLoggerTest SECURE_AND_WAIT61*/62public class BootstrapLoggerTest {6364static final Policy DEFAULT_POLICY = Policy.getPolicy();65static final Method isAlive;66static final Field logManagerInitialized;67static {68try {69// private reflection hook that allows us to test whether70// the BootstrapExecutor is alive.71isAlive = BootstrapLogger.class72.getDeclaredMethod("isAlive");73isAlive.setAccessible(true);74// private reflection hook that allows us to test whether the LogManager75// has initialized and registered with the BootstrapLogger class76logManagerInitialized = BootstrapLogger.class77.getDeclaredField("logManagerConfigured");78logManagerInitialized.setAccessible(true);79} catch (Exception ex) {80throw new ExceptionInInitializerError(ex);81}82}8384static enum TestCase {85NO_SECURITY, SECURE, SECURE_AND_WAIT86}8788public static void main(String[] args) throws Exception {89if (args == null || args.length == 0) {90args = new String[] { TestCase.SECURE_AND_WAIT.name() };91}92if (args.length > 1) throw new RuntimeException("Only one argument allowed");93TestCase test = TestCase.valueOf(args[0]);94System.err.println("Testing: " + test);959697// private reflection hook that allows us to simulate a non booted VM98final AtomicBoolean vmBooted = new AtomicBoolean(false);99BootstrapLoggerUtils.setBootedHook(() -> vmBooted.get());100101// We replace System.err to check the messages that have been logged102// by the JUL ConsoleHandler and default SimpleConsoleLogger103// implementaion104final LogStream err = new LogStream();105System.setErr(new PrintStream(err));106107if (BootstrapLogger.isBooted()) {108throw new RuntimeException("VM should not be booted!");109}110Logger logger = LazyLoggers.getLogger("foo.bar", Thread.class.getModule());111112if (test != TestCase.NO_SECURITY) {113LogStream.err.println("Setting security manager");114Policy.setPolicy(new SimplePolicy());115System.setSecurityManager(new SecurityManager());116}117118Level[] levels = {Level.INFO, Level.WARNING, Level.INFO};119int index = 0;120logger.log(levels[index], "Early message #" + (index+1)); index++;121logger.log(levels[index], "Early message #" + (index+1)); index++;122LogStream.err.println("VM Booted: " + vmBooted.get());123LogStream.err.println("LogManager initialized: " + logManagerInitialized.get(null));124logger.log(levels[index], "Early message #" + (index+1)); index++;125if (err.drain().contains("Early message")) {126// We're expecting that logger will be a LazyLogger wrapping a127// BootstrapLogger. The Bootstrap logger will stack the log messages128// it receives until the VM is booted.129// Since our private hook pretend that the VM is not booted yet,130// the logged messages shouldn't have reached System.err yet.131throw new RuntimeException("Early message logged while VM is not booted!");132}133134// Now pretend that the VM is booted. Nothing should happen yet, until135// we try to log a new message.136vmBooted.getAndSet(true);137LogStream.err.println("VM Booted: " + vmBooted.get());138LogStream.err.println("LogManager initialized: " + logManagerInitialized.get(null));139if (!BootstrapLogger.isBooted()) {140throw new RuntimeException("VM should now be booted!");141}142if (((Boolean)logManagerInitialized.get(null)).booleanValue()) {143throw new RuntimeException("LogManager shouldn't be initialized yet!");144}145146// Logging a message should cause the BootstrapLogger to replace itself147// by a 'real' logger in the LazyLogger. But since the LogManager isn't148// initialized yet, this should be a SimpleConsoleLogger...149logger.log(Level.INFO, "LOG#4: VM now booted: {0}", vmBooted.get());150logger.log(Level.DEBUG, "LOG#5: hi!");151SimplePolicy.allowAll.set(Boolean.TRUE);152WeakReference<Thread> threadRef = null;153ReferenceQueue<Thread> queue = new ReferenceQueue<>();154try {155Set<Thread> set = Thread.getAllStackTraces().keySet().stream()156.filter((t) -> t.getName().startsWith("BootstrapMessageLoggerTask-"))157.collect(Collectors.toSet());158set.stream().forEach(t -> LogStream.err.println("Found: " + t));159if (set.size() > 1) {160throw new RuntimeException("Too many bootstrap threads found");161}162Optional<Thread> t = set.stream().findFirst();163if (t.isPresent()) {164threadRef = new WeakReference<>(t.get(), queue);165}166} finally{167SimplePolicy.allowAll.set(Boolean.FALSE);168}169if (!BootstrapLogger.isBooted()) {170throw new RuntimeException("VM should still be booted!");171}172if (((Boolean)logManagerInitialized.get(null)).booleanValue()) {173throw new RuntimeException("LogManager shouldn't be initialized yet!");174}175176// Now check that the early messages we had printed before the VM was177// booted have appeared on System.err...178String afterBoot = err.drain();179for (int i=0; i<levels.length; i++) {180String m = levels[i].getName()+": Early message #"+(i+1);181if (!afterBoot.contains(m)) {182throw new RuntimeException("System.err does not contain: "+m);183}184}185// check that the message logged *after* the VM was booted also printed.186if (!afterBoot.contains("INFO: LOG#4")) {187throw new RuntimeException("System.err does not contain: "188+ "INFO: LOG#4");189}190// check that the debug message was not printed.191if (afterBoot.contains("LOG#5")) {192throw new RuntimeException("System.err contain: " + "LOG#5");193}194LogStream.err.println("VM Booted: " + vmBooted.get());195LogStream.err.println("LogManager initialized: " + logManagerInitialized.get(null));196if (!BootstrapLogger.isBooted()) {197throw new RuntimeException("VM should still be booted!");198}199if (((Boolean)logManagerInitialized.get(null)).booleanValue()) {200throw new RuntimeException("LogManager shouldn't be initialized yet!");201}202203// Now we're going to use reflection to access JUL, and change204// the level of the "foo" logger.205// We're using reflection so that the test can also run in206// configurations where java.util.logging is not present.207boolean hasJUL = false;208SimplePolicy.allowAll.set(Boolean.TRUE);209try {210Class<?> loggerClass = Class.forName("java.util.logging.Logger");211Class<?> levelClass = Class.forName("java.util.logging.Level");212Class<?> handlerClass = Class.forName("java.util.logging.Handler");213214// java.util.logging.Logger.getLogger("foo")215// .setLevel(java.util.logging.Level.FINEST);216Object fooLogger = loggerClass.getMethod("getLogger", String.class)217.invoke(null, "foo");218loggerClass.getMethod("setLevel", levelClass)219.invoke(fooLogger, levelClass.getField("FINEST").get(null));220221// java.util.logging.Logger.getLogger("").getHandlers()[0]222// .setLevel(java.util.logging.Level.ALL);223Object rootLogger = loggerClass.getMethod("getLogger", String.class)224.invoke(null, "");225Object handlers = loggerClass.getMethod("getHandlers").226invoke(rootLogger);227handlerClass.getMethod("setLevel", levelClass)228.invoke(Array.get(handlers, 0), levelClass.getField("ALL")229.get(null));230231hasJUL = true;232} catch (ClassNotFoundException x) {233LogStream.err.println("JUL is not present: class " + x.getMessage()234+ " not found");235hasJUL = false;236} finally {237SimplePolicy.allowAll.set(Boolean.FALSE);238}239240logger.log(Level.DEBUG, "hi now!");241String debug = err.drain();242if (hasJUL) {243if (!((Boolean)logManagerInitialized.get(null)).booleanValue()) {244throw new RuntimeException("LogManager should be initialized now!");245}246if (!debug.contains("FINE: hi now!")) {247throw new RuntimeException("System.err does not contain: "248+ "FINE: hi now!");249}250} else {251if (debug.contains("hi now!")) {252throw new RuntimeException("System.err contains: " + "hi now!");253}254if (((Boolean)logManagerInitialized.get(null)).booleanValue()) {255throw new RuntimeException("LogManager shouldn't be initialized yet!");256}257Logger baz = System.getLogger("foo.bar.baz");258if (((Boolean)logManagerInitialized.get(null)).booleanValue()) {259throw new RuntimeException("LogManager shouldn't be initialized yet!");260}261}262Logger bazbaz = null;263SimplePolicy.allowAll.set(Boolean.TRUE);264try {265bazbaz = java.lang.System.LoggerFinder266.getLoggerFinder().getLogger("foo.bar.baz.baz", BootstrapLoggerTest.class.getModule());267} finally {268SimplePolicy.allowAll.set(Boolean.FALSE);269}270if (!((Boolean)logManagerInitialized.get(null)).booleanValue()) {271throw new RuntimeException("LogManager should be initialized now!");272}273Logger bazbaz2 = System.getLogger("foo.bar.baz.baz");274if (bazbaz2.getClass() != bazbaz.getClass()) {275throw new RuntimeException("bazbaz2.class != bazbaz.class ["276+ bazbaz2.getClass() + " != "277+ bazbaz.getClass() + "]");278}279if (hasJUL != bazbaz2.getClass().getName()280.equals("sun.util.logging.internal.LoggingProviderImpl$JULWrapper")) {281throw new RuntimeException("Unexpected class for bazbaz: "282+ bazbaz.getClass().getName()283+ "\n\t expected: "284+ "sun.util.logging.internal.LoggingProviderImpl$JULWrapper");285}286287// Now we're going to check that the thread of the BootstrapLogger288// executor terminates, and that the Executor is GC'ed after that.289// This will involve a bit of waiting, hence the timeout=120 in290// the @run line.291// If this test fails in timeout - we could envisage skipping this part,292// or adding some System property to configure the keep alive delay293// of the executor.294SimplePolicy.allowAll.set(Boolean.TRUE);295try {296// Though unlikely, it is not impossible that the bootstrap logger297// executor may have released its first thread and spawned a new one.298// If that happened then the executor itself might have been GC'ed299// as well and a new one might have been created.300// The code below will lookup the executor threads again and301// join them.302// Only one may be active at a given time, but that might not303// be the one referenced by threadRef.304// We're just making sure all of them have stopped running305// before verifying that the executor is eventually GC'ed.306final WeakReference<Thread> previous = threadRef;307Stream<WeakReference<Thread>> stream = Thread.getAllStackTraces().keySet().stream()308.filter((t) -> t.getName().startsWith("BootstrapMessageLoggerTask-"))309.filter((t) -> previous == null ? true : t != previous.get())310.map((t) -> new WeakReference<>(t, queue));311List<WeakReference<Thread>> threads = stream.collect(Collectors.toList());312if (previous != null) threads.add(previous);313threads.forEach(t -> LogStream.err.println(t.get()));314stream = null;315316if (test == TestCase.SECURE_AND_WAIT) {317// First wait for all executor threads to terminate318for (var ref : threads) {319Thread t = ref.get();320if (t != null) {321if (!(Boolean)isAlive.invoke(null) && t.isAlive()) {322throw new RuntimeException("Executor already terminated");323} else {324LogStream.err.println("Executor still alive as expected: " + t.getName());325}326LogStream.err.println("Waiting for " + t.getName() + " to terminate (join)");327t.join(60_000);328t = null;329} else {330LogStream.err.println("WeakReference<Thread> is already cleared.");331long count = Thread.getAllStackTraces().keySet().stream()332.filter((tr) -> tr.getName().startsWith("BootstrapMessageLoggerTask-"))333.count();334if (count != 0) {335LogStream.err.println("There are " + count + " threads still lingering.");336}337}338}339// Then wait until all the executor threads are GC'ed340while (!threads.isEmpty()) {341LogStream.err.println("Calling System.gc()");342System.gc();343LogStream.err.println("Waiting for BootstrapMessageLoggerTask to be gc'ed");344Reference<?> tref;345while ((tref = queue.remove(1000)) == null) {346LogStream.err.println("Calling System.gc()");347System.gc();348}349350threads.remove(tref);351LogStream.err.println("BootstrapMessageLoggerTask has been gc'ed: "352+ threads.size() + " remaining...");353}354// Then wait for the executor to be gc'ed...355LogStream.err.println("Waiting for the executor to be gc'ed: Calling System.gc()");356System.gc();357for (int i=0; i<10; i++) {358if (!(Boolean)isAlive.invoke(null)) break;359// It would be unexpected that we reach here...360Thread.sleep(1000);361LogStream.err.println("Calling System.gc()");362System.gc();363}364365if ((Boolean)isAlive.invoke(null)) {366throw new RuntimeException("Executor still alive");367} else {368LogStream.err.println("Executor terminated as expected.");369}370} else {371LogStream.err.println("Not checking executor termination for " + test);372}373} finally {374SimplePolicy.allowAll.set(Boolean.FALSE);375}376LogStream.err.println(test.name() + ": PASSED");377}378379final static class SimplePolicy extends Policy {380static final ThreadLocal<Boolean> allowAll = new ThreadLocal<Boolean>() {381@Override382protected Boolean initialValue() {383return Boolean.FALSE;384}385};386387Permissions getPermissions() {388Permissions perms = new Permissions();389if (allowAll.get()) {390perms.add(new AllPermission());391}392return perms;393}394395@Override396public boolean implies(ProtectionDomain domain, Permission permission) {397return getPermissions(domain).implies(permission) ||398DEFAULT_POLICY.implies(domain, permission);399}400401@Override402public PermissionCollection getPermissions(CodeSource codesource) {403return getPermissions();404}405406@Override407public PermissionCollection getPermissions(ProtectionDomain domain) {408return getPermissions();409}410411}412}413414415