1 /*
   2  * Copyright (c) 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 
  24 package gc.logging;
  25 
  26 import jdk.test.lib.Utils;
  27 
  28 import javax.management.InstanceNotFoundException;
  29 import javax.management.MBeanException;
  30 import javax.management.MBeanServer;
  31 import javax.management.MalformedObjectNameException;
  32 import javax.management.ObjectName;
  33 import javax.management.ReflectionException;
  34 import java.lang.management.ManagementFactory;
  35 import java.util.LinkedList;
  36 import java.util.List;
  37 import java.util.Random;
  38 
  39 
  40 /**
  41  * @test TestUnifiedLoggingSwitchStress
  42  * @key gc stress
  43  * @summary Switches gc log level on fly while stressing memory/gc
  44  * @requires !vm.flightRecorder
  45  * @library /test/lib /
  46  * @modules java.management java.base/jdk.internal.misc
  47  *
  48  * @run main/othervm -Xmx256M -Xms256M
  49  *                   gc.logging.TestUnifiedLoggingSwitchStress 60
  50  */
  51 
  52 class MemoryStresser implements Runnable {
  53     public static volatile boolean shouldStop = false;
  54 
  55     private final List<byte[]> liveObjects = new LinkedList<>();
  56     private final List<byte[]> liveHObjects = new LinkedList<>();
  57     private int maxSimpleAllocationMemory = 0;
  58     private int usedMemory = 0;
  59 
  60     /**
  61      * Maximum amount of huge allocations
  62      */
  63     private static int H_ALLOCATION_MAX_COUNT = 4;
  64     /**
  65      * Maximum regions in one huge allocation
  66      */
  67     private static int H_ALLOCATION_REGION_SIZE = 2;
  68     private static final int G1_REGION_SIZE = 1024 * 1024;
  69     /**
  70      * Maximum size of simple allocation
  71      */
  72     private static final int MAX_SIMPLE_ALLOCATION_SIZE = (int) (G1_REGION_SIZE / 2 * 0.9);
  73 
  74     /**
  75      * Maximum size of dead (i.e. one which is made unreachable right after allocation) object
  76      */
  77     private static final int DEAD_OBJECT_MAX_SIZE = G1_REGION_SIZE / 10;
  78     private static final Random RND = Utils.getRandomInstance();
  79 
  80     /**
  81      * @param maxMemory maximum memory that could be allocated
  82      */
  83     public MemoryStresser(int maxMemory) {
  84         maxSimpleAllocationMemory = maxMemory - G1_REGION_SIZE * H_ALLOCATION_MAX_COUNT * H_ALLOCATION_REGION_SIZE;
  85     }
  86 
  87     public final Runnable[] actions = new Runnable[]{
  88             // Huge allocation
  89             () -> {
  90                 if (liveHObjects.size() < H_ALLOCATION_MAX_COUNT) {
  91                     int allocationSize = RND.nextInt((int) (G1_REGION_SIZE * (H_ALLOCATION_REGION_SIZE - 0.5)
  92                             * 0.9));
  93                     liveHObjects.add(new byte[allocationSize + G1_REGION_SIZE / 2]);
  94                 }
  95             },
  96 
  97             // Huge deallocation
  98             () -> {
  99                 if (liveHObjects.size() > 0) {
 100                     int elementNum = RND.nextInt(liveHObjects.size());
 101                     liveHObjects.remove(elementNum);
 102                 }
 103             },
 104 
 105             // Simple allocation
 106             () -> {
 107                 if (maxSimpleAllocationMemory - usedMemory != 0) {
 108                     int arraySize = RND.nextInt(Math.min(maxSimpleAllocationMemory - usedMemory,
 109                             MAX_SIMPLE_ALLOCATION_SIZE));
 110                     if (arraySize != 0) {
 111                         liveObjects.add(new byte[arraySize]);
 112                         usedMemory += arraySize;
 113                     }
 114                 }
 115             },
 116 
 117             // Simple deallocation
 118             () -> {
 119                 if (liveObjects.size() != 0) {
 120                     int elementNum = RND.nextInt(liveObjects.size());
 121                     int shouldFree = liveObjects.get(elementNum).length;
 122                     liveObjects.remove(elementNum);
 123                     usedMemory -= shouldFree;
 124                 }
 125             },
 126 
 127             // Dead object allocation
 128             () -> {
 129                 int size = RND.nextInt(DEAD_OBJECT_MAX_SIZE);
 130                 byte[] deadObject = new byte[size];
 131             }
 132     };
 133 
 134     @Override
 135     public void run() {
 136         while (!shouldStop) {
 137             actions[RND.nextInt(actions.length)].run();
 138             Thread.yield();
 139         }
 140 
 141         System.out.println("Memory Stresser finished");
 142     }
 143 }
 144 
 145 class LogLevelSwitcher implements Runnable {
 146 
 147     public static volatile boolean shouldStop = false;
 148     private final int logCount; // how many various log files will be used
 149     private final String logFilePrefix; // name of log file will be logFilePrefix + index
 150     private final Random RND = Utils.getRandomInstance();
 151     private final MBeanServer MBS = ManagementFactory.getPlatformMBeanServer();
 152 
 153     /**
 154      * @param logFilePrefix prefix for log files
 155      * @param logCount     amount of log files
 156      */
 157     public LogLevelSwitcher(String logFilePrefix, int logCount) {
 158         this.logCount = logCount;
 159         this.logFilePrefix = logFilePrefix;
 160 
 161     }
 162 
 163     private static final String[] LOG_LEVELS = {"error", "warning", "info", "debug", "trace"};
 164 
 165     @Override
 166     public void run() {
 167 
 168         while (!shouldStop) {
 169             int fileNum = RND.nextInt(logCount);
 170             int logLevel = RND.nextInt(LOG_LEVELS.length);
 171 
 172             String outputCommand = String.format("output=%s_%d.log", logFilePrefix, fileNum);
 173             String logLevelCommand = "what='gc*=" + LOG_LEVELS[logLevel] + "'";
 174 
 175             try {
 176                 Object out = MBS.invoke(new ObjectName("com.sun.management:type=DiagnosticCommand"),
 177                                         "vmLog",
 178                                         new Object[]{new String[]{outputCommand, logLevelCommand}},
 179                                         new String[]{String[].class.getName()});
 180 
 181                 if (!out.toString().isEmpty()) {
 182                     System.out.format("WARNING: Diagnostic command vmLog with arguments %s,%s returned not empty"
 183                                     + " output %s\n",
 184                             outputCommand, logLevelCommand, out);
 185                 }
 186             } catch (InstanceNotFoundException | MBeanException | ReflectionException | MalformedObjectNameException e) {
 187                 System.out.println("Got exception trying to change log level:" + e);
 188                 e.printStackTrace();
 189                 throw new Error(e);
 190             }
 191             Thread.yield();
 192         }
 193         System.out.println("Log Switcher finished");
 194     }
 195 }
 196 
 197 
 198 public class TestUnifiedLoggingSwitchStress {
 199     /**
 200      * Count of memory stressing threads
 201      */
 202     private static final int MEMORY_STRESSERS_COUNT = 3;
 203     /**
 204      * Count of log switching threads
 205      */
 206     private static final int LOG_LEVEL_SWITCHERS_COUNT = 2;
 207     /**
 208      * Count of log files created by each log switching thread
 209      */
 210     private static final int LOG_FILES_COUNT = 2;
 211     /**
 212      * Maximum amount memory allocated by each stressing thread
 213      */
 214     private static final int MAX_MEMORY_PER_STRESSER = (int) (Runtime.getRuntime().freeMemory()
 215             / MEMORY_STRESSERS_COUNT * 0.7);
 216 
 217     public static void main(String[] args) throws InterruptedException {
 218         if (args.length != 1) {
 219             throw new Error("Test Bug: Expected duration (in seconds) wasn't provided as command line argument");
 220         }
 221         long duration = Integer.parseInt(args[0]) * 1000;
 222 
 223         long startTime = System.currentTimeMillis();
 224 
 225         List<Thread> threads = new LinkedList<>();
 226 
 227         for (int i = 0; i < LOG_LEVEL_SWITCHERS_COUNT; i++) {
 228             threads.add(new Thread(new LogLevelSwitcher("Output_" + i, LOG_FILES_COUNT)));
 229         }
 230 
 231         for (int i = 0; i < MEMORY_STRESSERS_COUNT; i++) {
 232             threads.add(new Thread(new MemoryStresser(MAX_MEMORY_PER_STRESSER)));
 233         }
 234 
 235         threads.stream().forEach(Thread::start);
 236 
 237         while (System.currentTimeMillis() - startTime < duration) {
 238             Thread.yield();
 239         }
 240 
 241         MemoryStresser.shouldStop = true;
 242         LogLevelSwitcher.shouldStop = true;
 243     }
 244 }