1 /*
   2  * Copyright (c) 2013, 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 
  24 package jdk.test.lib;
  25 
  26 import static jdk.test.lib.Asserts.assertTrue;
  27 import java.io.IOException;
  28 import java.lang.reflect.Field;
  29 import java.net.InetAddress;
  30 import java.net.ServerSocket;
  31 import java.net.UnknownHostException;
  32 import java.nio.file.Files;
  33 import java.nio.file.Path;
  34 import java.nio.file.Paths;
  35 import java.util.ArrayList;
  36 import java.util.Arrays;
  37 import java.util.Collections;
  38 import java.util.List;
  39 import java.util.Random;
  40 import java.util.function.BooleanSupplier;
  41 import java.util.concurrent.TimeUnit;
  42 import java.util.regex.Matcher;
  43 import java.util.regex.Pattern;
  44 import java.util.stream.Collectors;
  45 import sun.misc.Unsafe;
  46 
  47 /**
  48  * Common library for various test helper functions.
  49  */
  50 public final class Utils {
  51 
  52     /**
  53      * Returns the sequence used by operating system to separate lines.
  54      */
  55     public static final String NEW_LINE = System.getProperty("line.separator");
  56 
  57     /**
  58      * Returns the value of 'test.vm.opts' system property.
  59      */
  60     public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
  61 
  62     /**
  63      * Returns the value of 'test.java.opts' system property.
  64      */
  65     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
  66 
  67     private static Unsafe unsafe = null;
  68 
  69     /**
  70      * Defines property name for seed value.
  71      */
  72     public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed";
  73 
  74     /* (non-javadoc)
  75      * Random generator with (or without) predefined seed. Depends on
  76      * "jdk.test.lib.random.seed" property value.
  77      */
  78     private static volatile Random RANDOM_GENERATOR;
  79 
  80     /**
  81      * Contains the seed value used for {@link java.util.Random} creation.
  82      */
  83     public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong());
  84     /**
  85     * Returns the value of 'test.timeout.factor' system property
  86     * converted to {@code double}.
  87     */
  88     public static final double TIMEOUT_FACTOR;
  89     static {
  90         String toFactor = System.getProperty("test.timeout.factor", "1.0");
  91         TIMEOUT_FACTOR = Double.parseDouble(toFactor);
  92     }
  93 
  94     /**
  95     * Returns the value of JTREG default test timeout in milliseconds
  96     * converted to {@code long}.
  97     */
  98     public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
  99 
 100     private Utils() {
 101         // Private constructor to prevent class instantiation
 102     }
 103 
 104     /**
 105      * Returns the list of VM options.
 106      *
 107      * @return List of VM options
 108      */
 109     public static List<String> getVmOptions() {
 110         return Arrays.asList(safeSplitString(VM_OPTIONS));
 111     }
 112 
 113     /**
 114      * Returns the list of VM options with -J prefix.
 115      *
 116      * @return The list of VM options with -J prefix
 117      */
 118     public static List<String> getForwardVmOptions() {
 119         String[] opts = safeSplitString(VM_OPTIONS);
 120         for (int i = 0; i < opts.length; i++) {
 121             opts[i] = "-J" + opts[i];
 122         }
 123         return Arrays.asList(opts);
 124     }
 125 
 126     /**
 127      * Returns the default JTReg arguments for a jvm running a test.
 128      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 129      * @return An array of options, or an empty array if no options.
 130      */
 131     public static String[] getTestJavaOpts() {
 132         List<String> opts = new ArrayList<String>();
 133         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
 134         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
 135         return opts.toArray(new String[0]);
 136     }
 137 
 138     /**
 139      * Returns the default JTReg arguments for a jvm running a test without
 140      * options that matches regular expressions in {@code filters}.
 141      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 142      * @param filters Regular expressions used to filter out options.
 143      * @return An array of options, or an empty array if no options.
 144      */
 145     public static String[] getFilteredTestJavaOpts(String... filters) {
 146         String options[] = getTestJavaOpts();
 147 
 148         if (filters.length == 0) {
 149             return options;
 150         }
 151 
 152         List<String> filteredOptions = new ArrayList<String>(options.length);
 153         Pattern patterns[] = new Pattern[filters.length];
 154         for (int i = 0; i < filters.length; i++) {
 155             patterns[i] = Pattern.compile(filters[i]);
 156         }
 157 
 158         for (String option : options) {
 159             boolean matched = false;
 160             for (int i = 0; i < patterns.length && !matched; i++) {
 161                 Matcher matcher = patterns[i].matcher(option);
 162                 matched = matcher.find();
 163             }
 164             if (!matched) {
 165                 filteredOptions.add(option);
 166             }
 167         }
 168 
 169         return filteredOptions.toArray(new String[filteredOptions.size()]);
 170     }
 171 
 172     /**
 173      * Combines given arguments with default JTReg arguments for a jvm running a test.
 174      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 175      * @return The combination of JTReg test java options and user args.
 176      */
 177     public static String[] addTestJavaOpts(String... userArgs) {
 178         List<String> opts = new ArrayList<String>();
 179         Collections.addAll(opts, getTestJavaOpts());
 180         Collections.addAll(opts, userArgs);
 181         return opts.toArray(new String[0]);
 182     }
 183 
 184     /**
 185      * Splits a string by white space.
 186      * Works like String.split(), but returns an empty array
 187      * if the string is null or empty.
 188      */
 189     private static String[] safeSplitString(String s) {
 190         if (s == null || s.trim().isEmpty()) {
 191             return new String[] {};
 192         }
 193         return s.trim().split("\\s+");
 194     }
 195 
 196     /**
 197      * @return The full command line for the ProcessBuilder.
 198      */
 199     public static String getCommandLine(ProcessBuilder pb) {
 200         StringBuilder cmd = new StringBuilder();
 201         for (String s : pb.command()) {
 202             cmd.append(s).append(" ");
 203         }
 204         return cmd.toString();
 205     }
 206 
 207     /**
 208      * Returns the free port on the local host.
 209      * The function will spin until a valid port number is found.
 210      *
 211      * @return The port number
 212      * @throws InterruptedException if any thread has interrupted the current thread
 213      * @throws IOException if an I/O error occurs when opening the socket
 214      */
 215     public static int getFreePort() throws InterruptedException, IOException {
 216         int port = -1;
 217 
 218         while (port <= 0) {
 219             Thread.sleep(100);
 220 
 221             ServerSocket serverSocket = null;
 222             try {
 223                 serverSocket = new ServerSocket(0);
 224                 port = serverSocket.getLocalPort();
 225             } finally {
 226                 serverSocket.close();
 227             }
 228         }
 229 
 230         return port;
 231     }
 232 
 233     /**
 234      * Returns the name of the local host.
 235      *
 236      * @return The host name
 237      * @throws UnknownHostException if IP address of a host could not be determined
 238      */
 239     public static String getHostname() throws UnknownHostException {
 240         InetAddress inetAddress = InetAddress.getLocalHost();
 241         String hostName = inetAddress.getHostName();
 242 
 243         assertTrue((hostName != null && !hostName.isEmpty()),
 244                 "Cannot get hostname");
 245 
 246         return hostName;
 247     }
 248 
 249     /**
 250      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 251      * forever (until jtreg timeout) for the pid to be found.
 252      * @param key Regular expression to search for
 253      * @return The found pid.
 254      */
 255     public static int waitForJvmPid(String key) throws Throwable {
 256         final long iterationSleepMillis = 250;
 257         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 258         System.out.flush();
 259         while (true) {
 260             int pid = tryFindJvmPid(key);
 261             if (pid >= 0) {
 262                 return pid;
 263             }
 264             Thread.sleep(iterationSleepMillis);
 265         }
 266     }
 267 
 268     /**
 269      * Searches for a jvm pid in the output from "jcmd -l".
 270      *
 271      * Example output from jcmd is:
 272      * 12498 sun.tools.jcmd.JCmd -l
 273      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 274      *
 275      * @param key A regular expression to search for.
 276      * @return The found pid, or -1 if not found.
 277      * @throws Exception If multiple matching jvms are found.
 278      */
 279     public static int tryFindJvmPid(String key) throws Throwable {
 280         OutputAnalyzer output = null;
 281         try {
 282             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 283             jcmdLauncher.addToolArg("-l");
 284             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 285             output.shouldHaveExitValue(0);
 286 
 287             // Search for a line starting with numbers (pid), follwed by the key.
 288             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 289             Matcher matcher = pattern.matcher(output.getStdout());
 290 
 291             int pid = -1;
 292             if (matcher.find()) {
 293                 pid = Integer.parseInt(matcher.group(1));
 294                 System.out.println("findJvmPid.pid: " + pid);
 295                 if (matcher.find()) {
 296                     throw new Exception("Found multiple JVM pids for key: " + key);
 297                 }
 298             }
 299             return pid;
 300         } catch (Throwable t) {
 301             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 302             throw t;
 303         }
 304     }
 305 
 306     /**
 307      * Return the contents of the named file as a single String,
 308      * or null if not found.
 309      * @param filename name of the file to read
 310      * @return String contents of file, or null if file not found.
 311      * @throws  IOException
 312      *          if an I/O error occurs reading from the file or a malformed or
 313      *          unmappable byte sequence is read
 314      */
 315     public static String fileAsString(String filename) throws IOException {
 316         Path filePath = Paths.get(filename);
 317         return Files.exists(filePath)
 318             ? Files.lines(filePath).collect(Collectors.joining(NEW_LINE))
 319             : null;
 320     }
 321 
 322     /**
 323      * @return Unsafe instance.
 324      */
 325     public static synchronized Unsafe getUnsafe() {
 326         if (unsafe == null) {
 327             try {
 328                 Field f = Unsafe.class.getDeclaredField("theUnsafe");
 329                 f.setAccessible(true);
 330                 unsafe = (Unsafe) f.get(null);
 331             } catch (NoSuchFieldException | IllegalAccessException e) {
 332                 throw new RuntimeException("Unable to get Unsafe instance.", e);
 333             }
 334         }
 335         return unsafe;
 336     }
 337     private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 338 
 339     /**
 340      * Returns hex view of byte array
 341      *
 342      * @param bytes byte array to process
 343      * @return Space separated hexadecimal string representation of bytes
 344      */
 345 
 346     public static String toHexString(byte[] bytes) {
 347         char[] hexView = new char[bytes.length * 3];
 348         int i = 0;
 349         for (byte b : bytes) {
 350             hexView[i++] = hexArray[(b >> 4) & 0x0F];
 351             hexView[i++] = hexArray[b & 0x0F];
 352             hexView[i++] = ' ';
 353         }
 354         return new String(hexView);
 355     }
 356 
 357     /**
 358      * Returns {@link java.util.Random} generator initialized with particular seed.
 359      * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME}
 360      * In case no seed is provided, the method uses a random number.
 361      * The used seed printed to stdout.
 362      * @return {@link java.util.Random} generator with particular seed.
 363      */
 364     public static Random getRandomInstance() {
 365         if (RANDOM_GENERATOR == null) {
 366             synchronized (Utils.class) {
 367                 if (RANDOM_GENERATOR == null) {
 368                     RANDOM_GENERATOR = new Random(SEED);
 369                     System.out.printf("For random generator using seed: %d%n", SEED);
 370                     System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED);
 371                 }
 372             }
 373         }
 374         return RANDOM_GENERATOR;
 375     }
 376 
 377     /**
 378      * Wait for condition to be true
 379      *
 380      * @param condition, a condition to wait for
 381      */
 382     public static final void waitForCondition(BooleanSupplier condition) {
 383         waitForCondition(condition, -1L, 100L);
 384     }
 385 
 386     /**
 387      * Wait until timeout for condition to be true
 388      *
 389      * @param condition, a condition to wait for
 390      * @param timeout a time in milliseconds to wait for condition to be true
 391      * specifying -1 will wait forever
 392      * @return condition value, to determine if wait was successful
 393      */
 394     public static final boolean waitForCondition(BooleanSupplier condition,
 395             long timeout) {
 396         return waitForCondition(condition, timeout, 100L);
 397     }
 398 
 399     /**
 400      * Wait until timeout for condition to be true for specified time
 401      *
 402      * @param condition, a condition to wait for
 403      * @param timeout a time in milliseconds to wait for condition to be true,
 404      * specifying -1 will wait forever
 405      * @param sleepTime a time to sleep value in milliseconds
 406      * @return condition value, to determine if wait was successful
 407      */
 408     public static final boolean waitForCondition(BooleanSupplier condition,
 409             long timeout, long sleepTime) {
 410         long startTime = System.currentTimeMillis();
 411         while (!(condition.getAsBoolean() || (timeout != -1L
 412                 && ((System.currentTimeMillis() - startTime) > timeout)))) {
 413             try {
 414                 Thread.sleep(sleepTime);
 415             } catch (InterruptedException e) {
 416                 Thread.currentThread().interrupt();
 417                 throw new Error(e);
 418             }
 419         }
 420         return condition.getAsBoolean();
 421     }
 422 
 423     /**
 424      * Adjusts the provided timeout value for the TIMEOUT_FACTOR
 425      * @param tOut the timeout value to be adjusted
 426      * @return The timeout value adjusted for the value of "test.timeout.factor"
 427      *         system property
 428      */
 429     public static long adjustTimeout(long tOut) {
 430         return Math.round(tOut * Utils.TIMEOUT_FACTOR);
 431     }
 432 }