1 /* 2 * Copyright (c) 2015, 2016, 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 import java.io.ByteArrayInputStream; 24 import java.io.ByteArrayOutputStream; 25 import java.io.FilePermission; 26 import java.io.IOException; 27 import java.lang.ref.Reference; 28 import java.lang.ref.ReferenceQueue; 29 import java.lang.ref.WeakReference; 30 import java.lang.reflect.Field; 31 import java.nio.file.Files; 32 import java.nio.file.Paths; 33 import java.security.CodeSource; 34 import java.security.Permission; 35 import java.security.PermissionCollection; 36 import java.security.Permissions; 37 import java.security.Policy; 38 import java.security.ProtectionDomain; 39 import java.util.Arrays; 40 import java.util.Collections; 41 import java.util.Enumeration; 42 import java.util.HashSet; 43 import java.util.List; 44 import java.util.Objects; 45 import java.util.Properties; 46 import java.util.Set; 47 import java.util.TreeSet; 48 import java.util.UUID; 49 import java.util.concurrent.Callable; 50 import java.util.concurrent.atomic.AtomicBoolean; 51 import java.util.function.BiFunction; 52 import java.util.function.Function; 53 import java.util.logging.FileHandler; 54 import java.util.logging.LogManager; 55 import java.util.logging.Logger; 56 import java.util.logging.LoggingPermission; 57 import java.util.stream.Collectors; 58 import java.util.stream.Stream; 59 60 /** 61 * @test 62 * @bug 8033661 63 * @summary tests LogManager.updateConfiguration(bin) 64 * @modules java.logging/java.util.logging:open 65 * @run main/othervm UpdateConfigurationTest UNSECURE 66 * @run main/othervm UpdateConfigurationTest SECURE 67 * @author danielfuchs 68 */ 69 public class UpdateConfigurationTest { 70 71 /** 72 * We will test the handling of abstract logger nodes with file handlers in 73 * two configurations: 74 * UNSECURE: No security manager. 75 * SECURE: With the security manager present - and the required 76 * permissions granted. 77 */ 78 public static enum TestCase { 79 UNSECURE, SECURE; 80 public void run(Properties propertyFile, boolean last) throws Exception { 81 System.out.println("Running test case: " + name()); 82 Configure.setUp(this); 83 test(this.name() + " " + propertyFile.getProperty("test.name"), 84 propertyFile, last); 85 } 86 } 87 88 89 private static final String PREFIX = 90 "FileHandler-" + UUID.randomUUID() + ".log"; 91 private static final String userDir = System.getProperty("user.dir", "."); 92 private static final boolean userDirWritable = Files.isWritable(Paths.get(userDir)); 93 94 static enum ConfigMode { APPEND, REPLACE, DEFAULT; 95 boolean append() { return this == APPEND; } 96 Function<String, BiFunction<String,String,String>> remapper() { 97 switch(this) { 98 case APPEND: 99 return (k) -> ((o,n) -> (n == null ? o : n)); 100 case REPLACE: 101 return (k) -> ((o,n) -> n); 102 } 103 return null; 104 } 105 } 106 107 private static final List<Properties> properties; 108 static { 109 // The test will be run with each of the configurations below. 110 // The 'child' logger is forgotten after each test 111 112 Properties props1 = new Properties(); 113 props1.setProperty("test.name", "props1"); 114 props1.setProperty("test.config.mode", ConfigMode.REPLACE.name()); 115 props1.setProperty(FileHandler.class.getName() + ".pattern", PREFIX); 116 props1.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE)); 117 props1.setProperty(FileHandler.class.getName() + ".level", "ALL"); 118 props1.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter"); 119 props1.setProperty("com.foo.handlers", FileHandler.class.getName()); 120 props1.setProperty("com.bar.level", "FINEST"); 121 122 Properties props2 = new Properties(); 123 props2.setProperty("test.name", "props2"); 124 props2.setProperty("test.config.mode", ConfigMode.DEFAULT.name()); 125 props2.setProperty(FileHandler.class.getName() + ".pattern", PREFIX); 126 props2.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE)); 127 props2.setProperty(FileHandler.class.getName() + ".level", "ALL"); 128 props2.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter"); 129 props2.setProperty("com.foo.handlers", FileHandler.class.getName()); 130 props2.setProperty("com.foo.handlers.ensureCloseOnReset", "true"); 131 props2.setProperty("com.level", "FINE"); 132 133 Properties props3 = new Properties(); 134 props3.setProperty("test.name", "props3"); 135 props3.setProperty("test.config.mode", ConfigMode.APPEND.name()); 136 props3.setProperty(FileHandler.class.getName() + ".pattern", PREFIX); 137 props3.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE)); 138 props3.setProperty(FileHandler.class.getName() + ".level", "ALL"); 139 props3.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter"); 140 props3.setProperty("com.foo.handlers", ""); // specify "" to override the value in the previous conf 141 props3.setProperty("com.foo.handlers.ensureCloseOnReset", "false"); 142 props3.setProperty("com.bar.level", "FINER"); 143 144 145 properties = Collections.unmodifiableList(Arrays.asList( 146 props1, props2, props3, props1)); 147 } 148 149 static Properties previous; 150 static Properties current; 151 static final Field propsField; 152 static { 153 LogManager manager = LogManager.getLogManager(); 154 try { 155 propsField = LogManager.class.getDeclaredField("props"); 156 propsField.setAccessible(true); 157 previous = current = (Properties) propsField.get(manager); 158 } catch (NoSuchFieldException | IllegalAccessException ex) { 159 throw new ExceptionInInitializerError(ex); 160 } 161 } 162 163 static Properties getProperties() { 164 try { 165 return (Properties) propsField.get(LogManager.getLogManager()); 166 } catch (IllegalAccessException x) { 167 throw new RuntimeException(x); 168 } 169 } 170 171 static String trim(String value) { 172 return value == null ? null : value.trim(); 173 } 174 175 176 /** 177 * Tests one of the configuration defined above. 178 * <p> 179 * This is the main test method (the rest is infrastructure). 180 * <p> 181 * Creates a child of the com.foo logger (com.foo.child), resets 182 * the configuration, and verifies that com.foo has no handler. 183 * Then reapplies the configuration and verifies that the handler 184 * for com.foo has been reestablished, depending on whether 185 * java.util.logging.LogManager.reconfigureHandlers is present and 186 * true. 187 * <p> 188 * Finally releases the logger com.foo.child, so that com.foo can 189 * be garbage collected, and the next configuration can be 190 * tested. 191 */ 192 static void test(ConfigMode mode, String name, Properties props, boolean last) 193 throws Exception { 194 195 // Then create a child of the com.foo logger. 196 Logger fooChild = Logger.getLogger("com.foo.child"); 197 fooChild.info("hello world"); 198 Logger barChild = Logger.getLogger("com.bar.child"); 199 barChild.info("hello world"); 200 201 ReferenceQueue<Logger> queue = new ReferenceQueue(); 202 WeakReference<Logger> fooRef = new WeakReference<>(Logger.getLogger("com.foo"), queue); 203 if (fooRef.get() != fooChild.getParent()) { 204 throw new RuntimeException("Unexpected parent logger: " 205 + fooChild.getParent() +"\n\texpected: " + fooRef.get()); 206 } 207 WeakReference<Logger> barRef = new WeakReference<>(Logger.getLogger("com.bar"), queue); 208 if (barRef.get() != barChild.getParent()) { 209 throw new RuntimeException("Unexpected parent logger: " 210 + barChild.getParent() +"\n\texpected: " + barRef.get()); 211 } 212 Reference<? extends Logger> ref2; 213 int max = 10; 214 barChild = null; 215 System.gc(); 216 while ((ref2 = queue.poll()) == null) { 217 System.gc(); 218 Thread.sleep(100); 219 if (--max == 0) break; 220 } 221 222 Throwable failed = null; 223 try { 224 if (ref2 != null) { 225 String refName = ref2 == fooRef ? "fooRef" : ref2 == barRef ? "barRef" : "unknown"; 226 if (ref2 != barRef) { 227 throw new RuntimeException("Unexpected logger reference cleared: " + refName); 228 } else { 229 System.out.println("Reference " + refName + " cleared as expected"); 230 } 231 } else if (ref2 == null) { 232 throw new RuntimeException("Expected 'barRef' to be cleared"); 233 } 234 // Now lets try to check that ref2 has expected handlers, and 235 // attempt to configure again. 236 String p = current.getProperty("com.foo.handlers", "").trim(); 237 assertEquals(p.isEmpty() ? 0 : 1, fooChild.getParent().getHandlers().length, 238 "["+name+"] fooChild.getParent().getHandlers().length"); 239 Configure.doPrivileged(() -> Configure.updateConfigurationWith(props, mode.remapper())); 240 String p2 = previous.getProperty("com.foo.handlers", "").trim(); 241 assertEquals(p, p2, "["+name+"] com.foo.handlers"); 242 String n = trim(props.getProperty("com.foo.handlers", null)); 243 boolean hasHandlers = mode.append() 244 ? (n == null ? !p.isEmpty() : !n.isEmpty()) 245 : n != null && !n.isEmpty(); 246 assertEquals( hasHandlers ? 1 : 0, 247 fooChild.getParent().getHandlers().length, 248 "["+name+"] fooChild.getParent().getHandlers().length" 249 + "[p=\""+p+"\", n=" + (n==null?null:"\""+n+"\"") + "]"); 250 251 checkProperties(mode, previous, current, props); 252 253 } catch (Throwable t) { 254 failed = t; 255 } finally { 256 if (last || failed != null) { 257 final Throwable suppressed = failed; 258 Configure.doPrivileged(LogManager.getLogManager()::reset); 259 Configure.doPrivileged(() -> { 260 try { 261 StringBuilder builder = new StringBuilder(); 262 Files.list(Paths.get(userDir)) 263 .filter((f) -> f.toString().contains(PREFIX)) 264 .filter((f) -> f.toString().endsWith(".lck")) 265 .forEach((f) -> { 266 builder.append(f.toString()).append('\n'); 267 }); 268 if (!builder.toString().isEmpty()) { 269 throw new RuntimeException("Lock files not cleaned:\n" 270 + builder.toString()); 271 } 272 } catch(RuntimeException | Error x) { 273 if (suppressed != null) x.addSuppressed(suppressed); 274 throw x; 275 } catch(Exception x) { 276 if (suppressed != null) x.addSuppressed(suppressed); 277 throw new RuntimeException(x); 278 } 279 }); 280 281 if (suppressed == null) { 282 // Now we need to forget the child, so that loggers are released, 283 // and so that we can run the test with the next configuration... 284 // No need to do that if failed!=null however, as the first 285 // ref might not have been cleared yet and failing here would 286 // hide the original failure. 287 fooChild = null; 288 System.out.println("Setting fooChild to: " + fooChild); 289 while ((ref2 = queue.poll()) == null) { 290 System.gc(); 291 Thread.sleep(1000); 292 } 293 if (ref2 != fooRef) { 294 throw new RuntimeException("Unexpected reference: " 295 + ref2 +"\n\texpected: " + fooRef); 296 } 297 if (ref2.get() != null) { 298 throw new RuntimeException("Referent not cleared: " + ref2.get()); 299 } 300 System.out.println("Got fooRef after reset(), fooChild is " + fooChild); 301 } 302 } 303 } 304 if (failed != null) { 305 // should rarely happen... 306 throw new RuntimeException(failed); 307 } 308 309 } 310 311 private static void checkProperties(ConfigMode mode, 312 Properties previous, Properties current, Properties props) { 313 Set<String> set = new HashSet<>(); 314 315 // Check that all property names from 'props' are in current. 316 set.addAll(props.stringPropertyNames()); 317 set.removeAll(current.keySet()); 318 if (!set.isEmpty()) { 319 throw new RuntimeException("Missing properties in current: " + set); 320 } 321 set.clear(); 322 set.addAll(current.stringPropertyNames()); 323 set.removeAll(previous.keySet()); 324 set.removeAll(props.keySet()); 325 if (!set.isEmpty()) { 326 throw new RuntimeException("Superfluous properties in current: " + set); 327 } 328 set.clear(); 329 Stream<String> allnames = 330 Stream.concat( 331 Stream.concat(previous.stringPropertyNames().stream(), 332 props.stringPropertyNames().stream()), 333 current.stringPropertyNames().stream()) 334 .collect(Collectors.toCollection(TreeSet::new)) 335 .stream(); 336 if (mode.append()) { 337 // Check that all previous property names are in current. 338 set.addAll(previous.stringPropertyNames()); 339 set.removeAll(current.keySet()); 340 if (!set.isEmpty()) { 341 throw new RuntimeException("Missing properties in current: " + set 342 + "\n\tprevious: " + previous 343 + "\n\tcurrent: " + current 344 + "\n\tprops: " + props); 345 346 } 347 allnames.forEach((k) -> { 348 String p = previous.getProperty(k, "").trim(); 349 String n = current.getProperty(k, "").trim(); 350 if (props.containsKey(k)) { 351 assertEquals(props.getProperty(k), n, k); 352 } else { 353 assertEquals(p, n, k); 354 } 355 }); 356 } else { 357 // Check that only properties from 'props' are in current. 358 set.addAll(current.stringPropertyNames()); 359 set.removeAll(props.keySet()); 360 if (!set.isEmpty()) { 361 throw new RuntimeException("Superfluous properties in current: " + set); 362 } 363 allnames.forEach((k) -> { 364 String p = previous.getProperty(k, ""); 365 String n = current.getProperty(k, ""); 366 if (props.containsKey(k)) { 367 assertEquals(props.getProperty(k), n, k); 368 } else { 369 assertEquals("", n, k); 370 } 371 }); 372 } 373 374 } 375 376 public static void main(String... args) throws Exception { 377 378 379 if (args == null || args.length == 0) { 380 args = new String[] { 381 TestCase.UNSECURE.name(), 382 TestCase.SECURE.name(), 383 }; 384 } 385 386 try { 387 for (String testName : args) { 388 TestCase test = TestCase.valueOf(testName); 389 for (int i=0; i<properties.size();i++) { 390 Properties propertyFile = properties.get(i); 391 test.run(propertyFile, i == properties.size() - 1); 392 } 393 } 394 } finally { 395 if (userDirWritable) { 396 Configure.doPrivileged(() -> { 397 // cleanup - delete files that have been created 398 try { 399 Files.list(Paths.get(userDir)) 400 .filter((f) -> f.toString().contains(PREFIX)) 401 .forEach((f) -> { 402 try { 403 System.out.println("deleting " + f); 404 Files.delete(f); 405 } catch(Throwable t) { 406 System.err.println("Failed to delete " + f + ": " + t); 407 } 408 }); 409 } catch(Throwable t) { 410 System.err.println("Cleanup failed to list files: " + t); 411 t.printStackTrace(); 412 } 413 }); 414 } 415 } 416 } 417 418 static class Configure { 419 static Policy policy = null; 420 static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() { 421 @Override 422 protected AtomicBoolean initialValue() { 423 return new AtomicBoolean(false); 424 } 425 }; 426 static void setUp(TestCase test) { 427 switch (test) { 428 case SECURE: 429 if (policy == null && System.getSecurityManager() != null) { 430 throw new IllegalStateException("SecurityManager already set"); 431 } else if (policy == null) { 432 policy = new SimplePolicy(TestCase.SECURE, allowAll); 433 Policy.setPolicy(policy); 434 System.setSecurityManager(new SecurityManager()); 435 } 436 if (System.getSecurityManager() == null) { 437 throw new IllegalStateException("No SecurityManager."); 438 } 439 if (policy == null) { 440 throw new IllegalStateException("policy not configured"); 441 } 442 break; 443 case UNSECURE: 444 if (System.getSecurityManager() != null) { 445 throw new IllegalStateException("SecurityManager already set"); 446 } 447 break; 448 default: 449 new InternalError("No such testcase: " + test); 450 } 451 } 452 453 static void updateConfigurationWith(Properties propertyFile, 454 Function<String,BiFunction<String,String,String>> remapper) { 455 try { 456 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 457 propertyFile.store(bytes, propertyFile.getProperty("test.name")); 458 ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray()); 459 LogManager.getLogManager().updateConfiguration(bais, remapper); 460 } catch (IOException ex) { 461 throw new RuntimeException(ex); 462 } 463 } 464 465 static void doPrivileged(Runnable run) { 466 final boolean old = allowAll.get().getAndSet(true); 467 try { 468 Properties before = getProperties(); 469 try { 470 run.run(); 471 } finally { 472 Properties after = getProperties(); 473 if (before != after) { 474 previous = before; 475 current = after; 476 } 477 } 478 } finally { 479 allowAll.get().set(old); 480 } 481 } 482 static <T> T callPrivileged(Callable<T> call) throws Exception { 483 final boolean old = allowAll.get().getAndSet(true); 484 try { 485 Properties before = getProperties(); 486 try { 487 return call.call(); 488 } finally { 489 Properties after = getProperties(); 490 if (before != after) { 491 previous = before; 492 current = after; 493 } 494 } 495 } finally { 496 allowAll.get().set(old); 497 } 498 } 499 } 500 501 @FunctionalInterface 502 public static interface FileHandlerSupplier { 503 public FileHandler test() throws Exception; 504 } 505 506 static final class TestAssertException extends RuntimeException { 507 TestAssertException(String msg) { 508 super(msg); 509 } 510 } 511 512 private static void assertEquals(long expected, long received, String msg) { 513 if (expected != received) { 514 throw new TestAssertException("Unexpected result for " + msg 515 + ".\n\texpected: " + expected 516 + "\n\tactual: " + received); 517 } else { 518 System.out.println("Got expected " + msg + ": " + received); 519 } 520 } 521 522 private static void assertEquals(String expected, String received, String msg) { 523 if (!Objects.equals(expected, received)) { 524 throw new TestAssertException("Unexpected result for " + msg 525 + ".\n\texpected: " + expected 526 + "\n\tactual: " + received); 527 } else { 528 System.out.println("Got expected " + msg + ": " + received); 529 } 530 } 531 532 533 public static void test(String name, Properties props, boolean last) throws Exception { 534 ConfigMode configMode = ConfigMode.valueOf(props.getProperty("test.config.mode")); 535 System.out.println("\nTesting: " + name + " mode=" + configMode); 536 if (!userDirWritable) { 537 throw new RuntimeException("Not writable: "+userDir); 538 } 539 switch(configMode) { 540 case REPLACE: 541 case APPEND: 542 case DEFAULT: 543 test(configMode, name, props, last); break; 544 default: 545 throw new RuntimeException("Unknwown mode: " + configMode); 546 } 547 } 548 549 final static class PermissionsBuilder { 550 final Permissions perms; 551 public PermissionsBuilder() { 552 this(new Permissions()); 553 } 554 public PermissionsBuilder(Permissions perms) { 555 this.perms = perms; 556 } 557 public PermissionsBuilder add(Permission p) { 558 perms.add(p); 559 return this; 560 } 561 public PermissionsBuilder addAll(PermissionCollection col) { 562 if (col != null) { 563 for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) { 564 perms.add(e.nextElement()); 565 } 566 } 567 return this; 568 } 569 public Permissions toPermissions() { 570 final PermissionsBuilder builder = new PermissionsBuilder(); 571 builder.addAll(perms); 572 return builder.perms; 573 } 574 } 575 576 public static class SimplePolicy extends Policy { 577 578 final Permissions permissions; 579 final Permissions allPermissions; 580 final ThreadLocal<AtomicBoolean> allowAll; // actually: this should be in a thread locale 581 public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) { 582 this.allowAll = allowAll; 583 permissions = new Permissions(); 584 permissions.add(new LoggingPermission("control", null)); 585 permissions.add(new FilePermission(PREFIX+".lck", "read,write,delete")); 586 permissions.add(new FilePermission(PREFIX, "read,write")); 587 588 // these are used for configuring the test itself... 589 allPermissions = new Permissions(); 590 allPermissions.add(new java.security.AllPermission()); 591 592 } 593 594 @Override 595 public boolean implies(ProtectionDomain domain, Permission permission) { 596 if (allowAll.get().get()) return allPermissions.implies(permission); 597 return permissions.implies(permission); 598 } 599 600 @Override 601 public PermissionCollection getPermissions(CodeSource codesource) { 602 return new PermissionsBuilder().addAll(allowAll.get().get() 603 ? allPermissions : permissions).toPermissions(); 604 } 605 606 @Override 607 public PermissionCollection getPermissions(ProtectionDomain domain) { 608 return new PermissionsBuilder().addAll(allowAll.get().get() 609 ? allPermissions : permissions).toPermissions(); 610 } 611 } 612 613 }