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