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