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     public static List<String> removeGcOpts(List<String> opts) {
 133         List<String> optsWithoutGC = new ArrayList<String>();
 134         for (String opt : opts) {
 135             if (useGcPattern.matcher(opt).matches()) {
 136                 System.out.println("removeGcOpts: removed " + opt);
 137             } else {
 138                 optsWithoutGC.add(opt);
 139             }
 140         }
 141         return optsWithoutGC;
 142     }
 143 
 144     /**
 145      * Splits a string by white space.
 146      * Works like String.split(), but returns an empty array
 147      * if the string is null or empty.
 148      */
 149     private static String[] safeSplitString(String s) {
 150         if (s == null || s.trim().isEmpty()) {
 151             return new String[] {};
 152         }
 153         return s.trim().split("\\s+");
 154     }
 155 
 156     /**
 157      * @return The full command line for the ProcessBuilder.
 158      */
 159     public static String getCommandLine(ProcessBuilder pb) {
 160         StringBuilder cmd = new StringBuilder();
 161         for (String s : pb.command()) {
 162             cmd.append(s).append(" ");
 163         }
 164         return cmd.toString();
 165     }
 166 
 167     /**
 168      * Returns the free port on the local host.
 169      * The function will spin until a valid port number is found.
 170      *
 171      * @return The port number
 172      * @throws InterruptedException if any thread has interrupted the current thread
 173      * @throws IOException if an I/O error occurs when opening the socket
 174      */
 175     public static int getFreePort() throws InterruptedException, IOException {
 176         int port = -1;
 177 
 178         while (port <= 0) {
 179             Thread.sleep(100);
 180 
 181             ServerSocket serverSocket = null;
 182             try {
 183                 serverSocket = new ServerSocket(0);
 184                 port = serverSocket.getLocalPort();
 185             } finally {
 186                 serverSocket.close();
 187             }
 188         }
 189 
 190         return port;
 191     }
 192 
 193     /**
 194      * Returns the name of the local host.
 195      *
 196      * @return The host name
 197      * @throws UnknownHostException if IP address of a host could not be determined
 198      */
 199     public static String getHostname() throws UnknownHostException {
 200         InetAddress inetAddress = InetAddress.getLocalHost();
 201         String hostName = inetAddress.getHostName();
 202 
 203         assertTrue((hostName != null && !hostName.isEmpty()),
 204                 "Cannot get hostname");
 205 
 206         return hostName;
 207     }
 208 
 209     /**
 210      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 211      * forever (until jtreg timeout) for the pid to be found.
 212      * @param key Regular expression to search for
 213      * @return The found pid.
 214      */
 215     public static int waitForJvmPid(String key) throws Throwable {
 216         final long iterationSleepMillis = 250;
 217         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 218         System.out.flush();
 219         while (true) {
 220             int pid = tryFindJvmPid(key);
 221             if (pid >= 0) {
 222                 return pid;
 223             }
 224             Thread.sleep(iterationSleepMillis);
 225         }
 226     }
 227 
 228     /**
 229      * Searches for a jvm pid in the output from "jcmd -l".
 230      *
 231      * Example output from jcmd is:
 232      * 12498 sun.tools.jcmd.JCmd -l
 233      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 234      *
 235      * @param key A regular expression to search for.
 236      * @return The found pid, or -1 if Enot found.
 237      * @throws Exception If multiple matching jvms are found.
 238      */
 239     public static int tryFindJvmPid(String key) throws Throwable {
 240         OutputAnalyzer output = null;
 241         try {
 242             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 243             jcmdLauncher.addToolArg("-l");
 244             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 245             output.shouldHaveExitValue(0);
 246 
 247             // Search for a line starting with numbers (pid), follwed by the key.
 248             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 249             Matcher matcher = pattern.matcher(output.getStdout());
 250 
 251             int pid = -1;
 252             if (matcher.find()) {
 253                 pid = Integer.parseInt(matcher.group(1));
 254                 System.out.println("findJvmPid.pid: " + pid);
 255                 if (matcher.find()) {
 256                     throw new Exception("Found multiple JVM pids for key: " + key);
 257                 }
 258             }
 259             return pid;
 260         } catch (Throwable t) {
 261             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 262             throw t;
 263         }
 264     }
 265 
 266     /**
 267      * Returns file content as a list of strings
 268      *
 269      * @param file File to operate on
 270      * @return List of strings
 271      * @throws IOException
 272      */
 273     public static List<String> fileAsList(File file) throws IOException {
 274         assertTrue(file.exists() && file.isFile(),
 275                 file.getAbsolutePath() + " does not exist or not a file");
 276         List<String> output = new ArrayList<>();
 277         try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
 278             while (reader.ready()) {
 279                 output.add(reader.readLine().replace(NEW_LINE, ""));
 280             }
 281         }
 282         return output;
 283     }
 284 
 285     /**
 286      * Adjusts the provided timeout value for the TIMEOUT_FACTOR
 287      * @param tOut the timeout value to be adjusted
 288      * @return The timeout value adjusted for the value of "test.timeout.factor"
 289      *         system property
 290      */
 291     public static long adjustTimeout(long tOut) {
 292         return Math.round(tOut * Utils.TIMEOUT_FACTOR);
 293     }
 294 }