1 /*
   2  * Copyright (c) 2013, 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.testlibrary;
  25 
  26 import static jdk.testlibrary.Asserts.assertTrue;
  27 
  28 import java.io.BufferedReader;
  29 import java.io.File;
  30 import java.io.FileReader;
  31 import java.io.IOException;
  32 import java.net.InetAddress;
  33 import java.net.ServerSocket;
  34 import java.net.UnknownHostException;
  35 import java.util.ArrayList;
  36 import java.util.List;
  37 import java.util.Arrays;
  38 import java.util.Collections;
  39 import java.util.regex.Pattern;
  40 import java.util.regex.Matcher;
  41 import java.util.concurrent.TimeUnit;
  42 
  43 /**
  44  * Common library for various test helper functions.
  45  */
  46 public final class Utils {
  47 
  48     /**
  49      * Returns the sequence used by operating system to separate lines.
  50      */
  51     public static final String NEW_LINE = System.getProperty("line.separator");
  52 
  53     /**
  54      * Returns the value of 'test.vm.opts'system property.
  55      */
  56     public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
  57 
  58     /**
  59      * Returns the value of 'test.java.opts'system property.
  60      */
  61     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
  62 
  63     /**
  64     * Returns the value of 'test.timeout.factor' system property
  65     * converted to {@code double}.
  66     */
  67     public static final double TIMEOUT_FACTOR;
  68     static {
  69         String toFactor = System.getProperty("test.timeout.factor", "1.0");
  70        TIMEOUT_FACTOR = Double.parseDouble(toFactor);
  71     }
  72 
  73     /**
  74     * Returns the value of JTREG default test timeout in milliseconds
  75     * converted to {@code long}.
  76     */
  77     public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
  78 
  79     private Utils() {
  80         // Private constructor to prevent class instantiation
  81     }
  82 
  83     /**
  84      * Returns the list of VM options.
  85      *
  86      * @return List of VM options
  87      */
  88     public static List<String> getVmOptions() {
  89         return Arrays.asList(safeSplitString(VM_OPTIONS));
  90     }
  91 
  92     /**
  93      * Returns the list of VM options with -J prefix.
  94      *
  95      * @return The list of VM options with -J prefix
  96      */
  97     public static List<String> getForwardVmOptions() {
  98         String[] opts = safeSplitString(VM_OPTIONS);
  99         for (int i = 0; i < opts.length; i++) {
 100             opts[i] = "-J" + opts[i];
 101         }
 102         return Arrays.asList(opts);
 103     }
 104 
 105     /**
 106      * Returns the default JTReg arguments for a jvm running a test.
 107      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 108      * @return An array of options, or an empty array if no opptions.
 109      */
 110     public static String[] getTestJavaOpts() {
 111         List<String> opts = new ArrayList<String>();
 112         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
 113         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
 114         return opts.toArray(new String[0]);
 115     }
 116 
 117     /**
 118      * Combines given arguments with default JTReg arguments for a jvm running a test.
 119      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 120      * @return The combination of JTReg test java options and user args.
 121      */
 122     public static String[] addTestJavaOpts(String... userArgs) {
 123         List<String> opts = new ArrayList<String>();
 124         Collections.addAll(opts, getTestJavaOpts());
 125         Collections.addAll(opts, userArgs);
 126         return opts.toArray(new String[0]);
 127     }
 128 
 129     /**
 130      * Removes any options specifying which GC to use, for example "-XX:+UseG1GC".
 131      * Removes any options matching: -XX:(+/-)Use*GC
 132      * Used when a test need to set its own GC version. Then any
 133      * GC specified by the framework must first be removed.
 134      * @return A copy of given opts with all GC options removed.
 135      */
 136     private static final Pattern useGcPattern = Pattern.compile(
 137             "(?:\\-XX\\:[\\+\\-]Use.+GC)"
 138             + "|(?:\\-Xconcgc)");
 139     public static List<String> removeGcOpts(List<String> opts) {
 140         List<String> optsWithoutGC = new ArrayList<String>();
 141         for (String opt : opts) {
 142             if (useGcPattern.matcher(opt).matches()) {
 143                 System.out.println("removeGcOpts: removed " + opt);
 144             } else {
 145                 optsWithoutGC.add(opt);
 146             }
 147         }
 148         return optsWithoutGC;
 149     }
 150 
 151     /**
 152      * Splits a string by white space.
 153      * Works like String.split(), but returns an empty array
 154      * if the string is null or empty.
 155      */
 156     private static String[] safeSplitString(String s) {
 157         if (s == null || s.trim().isEmpty()) {
 158             return new String[] {};
 159         }
 160         return s.trim().split("\\s+");
 161     }
 162 
 163     /**
 164      * @return The full command line for the ProcessBuilder.
 165      */
 166     public static String getCommandLine(ProcessBuilder pb) {
 167         StringBuilder cmd = new StringBuilder();
 168         for (String s : pb.command()) {
 169             cmd.append(s).append(" ");
 170         }
 171         return cmd.toString();
 172     }
 173 
 174     /**
 175      * Returns the free port on the local host.
 176      * The function will spin until a valid port number is found.
 177      *
 178      * @return The port number
 179      * @throws InterruptedException if any thread has interrupted the current thread
 180      * @throws IOException if an I/O error occurs when opening the socket
 181      */
 182     public static int getFreePort() throws InterruptedException, IOException {
 183         int port = -1;
 184 
 185         while (port <= 0) {
 186             Thread.sleep(100);
 187 
 188             ServerSocket serverSocket = null;
 189             try {
 190                 serverSocket = new ServerSocket(0);
 191                 port = serverSocket.getLocalPort();
 192             } finally {
 193                 serverSocket.close();
 194             }
 195         }
 196 
 197         return port;
 198     }
 199 
 200     /**
 201      * Returns the name of the local host.
 202      *
 203      * @return The host name
 204      * @throws UnknownHostException if IP address of a host could not be determined
 205      */
 206     public static String getHostname() throws UnknownHostException {
 207         InetAddress inetAddress = InetAddress.getLocalHost();
 208         String hostName = inetAddress.getHostName();
 209 
 210         assertTrue((hostName != null && !hostName.isEmpty()),
 211                 "Cannot get hostname");
 212 
 213         return hostName;
 214     }
 215 
 216     /**
 217      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 218      * forever (until jtreg timeout) for the pid to be found.
 219      * @param key Regular expression to search for
 220      * @return The found pid.
 221      */
 222     public static int waitForJvmPid(String key) throws Throwable {
 223         final long iterationSleepMillis = 250;
 224         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 225         System.out.flush();
 226         while (true) {
 227             int pid = tryFindJvmPid(key);
 228             if (pid >= 0) {
 229                 return pid;
 230             }
 231             Thread.sleep(iterationSleepMillis);
 232         }
 233     }
 234 
 235     /**
 236      * Searches for a jvm pid in the output from "jcmd -l".
 237      *
 238      * Example output from jcmd is:
 239      * 12498 sun.tools.jcmd.JCmd -l
 240      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 241      *
 242      * @param key A regular expression to search for.
 243      * @return The found pid, or -1 if Enot found.
 244      * @throws Exception If multiple matching jvms are found.
 245      */
 246     public static int tryFindJvmPid(String key) throws Throwable {
 247         OutputAnalyzer output = null;
 248         try {
 249             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 250             jcmdLauncher.addToolArg("-l");
 251             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 252             output.shouldHaveExitValue(0);
 253 
 254             // Search for a line starting with numbers (pid), follwed by the key.
 255             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 256             Matcher matcher = pattern.matcher(output.getStdout());
 257 
 258             int pid = -1;
 259             if (matcher.find()) {
 260                 pid = Integer.parseInt(matcher.group(1));
 261                 System.out.println("findJvmPid.pid: " + pid);
 262                 if (matcher.find()) {
 263                     throw new Exception("Found multiple JVM pids for key: " + key);
 264                 }
 265             }
 266             return pid;
 267         } catch (Throwable t) {
 268             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 269             throw t;
 270         }
 271     }
 272 
 273     /**
 274      * Returns file content as a list of strings
 275      *
 276      * @param file File to operate on
 277      * @return List of strings
 278      * @throws IOException
 279      */
 280     public static List<String> fileAsList(File file) throws IOException {
 281         assertTrue(file.exists() && file.isFile(),
 282                 file.getAbsolutePath() + " does not exist or not a file");
 283         List<String> output = new ArrayList<>();
 284         try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
 285             while (reader.ready()) {
 286                 output.add(reader.readLine().replace(NEW_LINE, ""));
 287             }
 288         }
 289         return output;
 290     }
 291 
 292     /**
 293      * Adjusts the provided timeout value for the TIMEOUT_FACTOR
 294      * @param tOut the timeout value to be adjusted
 295      * @return The timeout value adjusted for the value of "test.timeout.factor"
 296      *         system property
 297      */
 298     public static long adjustTimeout(long tOut) {
 299         return Math.round(tOut * Utils.TIMEOUT_FACTOR);
 300     }
 301 }