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