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