1 /*
   2  * Copyright (c) 2013, 2014, 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      * Returns the default JTReg arguments for a jvm running a test without
 119      * options that matches regular expressions in {@code filters}.
 120      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 121      * @param filters Regular expressions used to filter out options.
 122      * @return An array of options, or an empty array if no options.
 123      */
 124     public static String[] getFilteredTestJavaOpts(String... filters) {
 125         String options[] = getTestJavaOpts();
 126 
 127         if (filters.length == 0) {
 128             return options;
 129         }
 130 
 131         List<String> filteredOptions = new ArrayList<>(options.length);
 132         Pattern patterns[] = new Pattern[filters.length];
 133         for (int i = 0; i < filters.length; i++) {
 134             patterns[i] = Pattern.compile(filters[i]);
 135         }
 136 
 137         for (String option : options) {
 138             boolean matched = false;
 139             for (int i = 0; i < patterns.length && !matched; i++) {
 140                 Matcher matcher = patterns[i].matcher(option);
 141                 matched = matcher.find();
 142             }
 143             if (!matched) {
 144                 filteredOptions.add(option);
 145             }
 146         }
 147 
 148         return filteredOptions.toArray(new String[filteredOptions.size()]);
 149     }
 150 
 151     /**
 152      * Combines given arguments with default JTReg arguments for a jvm running a test.
 153      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 154      * @return The combination of JTReg test java options and user args.
 155      */
 156     public static String[] addTestJavaOpts(String... userArgs) {
 157         List<String> opts = new ArrayList<String>();
 158         Collections.addAll(opts, getTestJavaOpts());
 159         Collections.addAll(opts, userArgs);
 160         return opts.toArray(new String[0]);
 161     }
 162 
 163     /**
 164      * Removes any options specifying which GC to use, for example "-XX:+UseG1GC".
 165      * Removes any options matching: -XX:(+/-)Use*GC
 166      * Used when a test need to set its own GC version. Then any
 167      * GC specified by the framework must first be removed.
 168      * @return A copy of given opts with all GC options removed.
 169      */
 170     private static final Pattern useGcPattern = Pattern.compile(
 171             "(?:\\-XX\\:[\\+\\-]Use.+GC)"
 172             + "|(?:\\-Xconcgc)");
 173     public static List<String> removeGcOpts(List<String> opts) {
 174         List<String> optsWithoutGC = new ArrayList<String>();
 175         for (String opt : opts) {
 176             if (useGcPattern.matcher(opt).matches()) {
 177                 System.out.println("removeGcOpts: removed " + opt);
 178             } else {
 179                 optsWithoutGC.add(opt);
 180             }
 181         }
 182         return optsWithoutGC;
 183     }
 184 
 185     /**
 186      * Splits a string by white space.
 187      * Works like String.split(), but returns an empty array
 188      * if the string is null or empty.
 189      */
 190     private static String[] safeSplitString(String s) {
 191         if (s == null || s.trim().isEmpty()) {
 192             return new String[] {};
 193         }
 194         return s.trim().split("\\s+");
 195     }
 196 
 197     /**
 198      * @return The full command line for the ProcessBuilder.
 199      */
 200     public static String getCommandLine(ProcessBuilder pb) {
 201         StringBuilder cmd = new StringBuilder();
 202         for (String s : pb.command()) {
 203             cmd.append(s).append(" ");
 204         }
 205         return cmd.toString();
 206     }
 207 
 208     /**
 209      * Returns the free port on the local host.
 210      * The function will spin until a valid port number is found.
 211      *
 212      * @return The port number
 213      * @throws InterruptedException if any thread has interrupted the current thread
 214      * @throws IOException if an I/O error occurs when opening the socket
 215      */
 216     public static int getFreePort() throws InterruptedException, IOException {
 217         int port = -1;
 218 
 219         while (port <= 0) {
 220             Thread.sleep(100);
 221 
 222             ServerSocket serverSocket = null;
 223             try {
 224                 serverSocket = new ServerSocket(0);
 225                 port = serverSocket.getLocalPort();
 226             } finally {
 227                 serverSocket.close();
 228             }
 229         }
 230 
 231         return port;
 232     }
 233 
 234     /**
 235      * Returns the name of the local host.
 236      *
 237      * @return The host name
 238      * @throws UnknownHostException if IP address of a host could not be determined
 239      */
 240     public static String getHostname() throws UnknownHostException {
 241         InetAddress inetAddress = InetAddress.getLocalHost();
 242         String hostName = inetAddress.getHostName();
 243 
 244         assertTrue((hostName != null && !hostName.isEmpty()),
 245                 "Cannot get hostname");
 246 
 247         return hostName;
 248     }
 249 
 250     /**
 251      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 252      * forever (until jtreg timeout) for the pid to be found.
 253      * @param key Regular expression to search for
 254      * @return The found pid.
 255      */
 256     public static int waitForJvmPid(String key) throws Throwable {
 257         final long iterationSleepMillis = 250;
 258         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 259         System.out.flush();
 260         while (true) {
 261             int pid = tryFindJvmPid(key);
 262             if (pid >= 0) {
 263                 return pid;
 264             }
 265             Thread.sleep(iterationSleepMillis);
 266         }
 267     }
 268 
 269     /**
 270      * Searches for a jvm pid in the output from "jcmd -l".
 271      *
 272      * Example output from jcmd is:
 273      * 12498 sun.tools.jcmd.JCmd -l
 274      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 275      *
 276      * @param key A regular expression to search for.
 277      * @return The found pid, or -1 if Enot found.
 278      * @throws Exception If multiple matching jvms are found.
 279      */
 280     public static int tryFindJvmPid(String key) throws Throwable {
 281         OutputAnalyzer output = null;
 282         try {
 283             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 284             jcmdLauncher.addToolArg("-l");
 285             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 286             output.shouldHaveExitValue(0);
 287 
 288             // Search for a line starting with numbers (pid), follwed by the key.
 289             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 290             Matcher matcher = pattern.matcher(output.getStdout());
 291 
 292             int pid = -1;
 293             if (matcher.find()) {
 294                 pid = Integer.parseInt(matcher.group(1));
 295                 System.out.println("findJvmPid.pid: " + pid);
 296                 if (matcher.find()) {
 297                     throw new Exception("Found multiple JVM pids for key: " + key);
 298                 }
 299             }
 300             return pid;
 301         } catch (Throwable t) {
 302             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 303             throw t;
 304         }
 305     }
 306 
 307     /**
 308      * Returns file content as a list of strings
 309      *
 310      * @param file File to operate on
 311      * @return List of strings
 312      * @throws IOException
 313      */
 314     public static List<String> fileAsList(File file) throws IOException {
 315         assertTrue(file.exists() && file.isFile(),
 316                 file.getAbsolutePath() + " does not exist or not a file");
 317         List<String> output = new ArrayList<>();
 318         try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
 319             while (reader.ready()) {
 320                 output.add(reader.readLine().replace(NEW_LINE, ""));
 321             }
 322         }
 323         return output;
 324     }
 325 
 326     /**
 327      * Adjusts the provided timeout value for the TIMEOUT_FACTOR
 328      * @param tOut the timeout value to be adjusted
 329      * @return The timeout value adjusted for the value of "test.timeout.factor"
 330      *         system property
 331      */
 332     public static long adjustTimeout(long tOut) {
 333         return Math.round(tOut * Utils.TIMEOUT_FACTOR);
 334     }
 335 }