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     private Utils() {
  61         // Private constructor to prevent class instantiation
  62     }
  63 
  64     /**
  65      * Returns the list of VM options.
  66      *
  67      * @return List of VM options
  68      */
  69     public static List<String> getVmOptions() {
  70         return Arrays.asList(safeSplitString(VM_OPTIONS));
  71     }
  72 
  73     /**
  74      * Returns the list of VM options with -J prefix.
  75      *
  76      * @return The list of VM options with -J prefix
  77      */
  78     public static List<String> getForwardVmOptions() {
  79         String[] opts = safeSplitString(VM_OPTIONS);
  80         for (int i = 0; i < opts.length; i++) {
  81             opts[i] = "-J" + opts[i];
  82         }
  83         return Arrays.asList(opts);
  84     }
  85 
  86     /**
  87      * Returns the default JTReg arguments for a jvm running a test.
  88      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
  89      * @return An array of options, or an empty array if no opptions.
  90      */
  91     public static String[] getTestJavaOpts() {
  92         List<String> opts = new ArrayList<String>();
  93         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
  94         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
  95         return opts.toArray(new String[0]);
  96     }
  97 
  98     /**
  99      * Combines given arguments with 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 The combination of JTReg test java options and user args.
 102      */
 103     public static String[] addTestJavaOpts(String... userArgs) {
 104         List<String> opts = new ArrayList<String>();
 105         Collections.addAll(opts, getTestJavaOpts());
 106         Collections.addAll(opts, userArgs);
 107         return opts.toArray(new String[0]);
 108     }
 109 
 110     /**
 111      * Splits a string by white space.
 112      * Works like String.split(), but returns an empty array
 113      * if the string is null or empty.
 114      */
 115     private static String[] safeSplitString(String s) {
 116         if (s == null || s.trim().isEmpty()) {
 117             return new String[] {};
 118         }
 119         return s.trim().split("\\s+");
 120     }
 121 
 122     /**
 123      * @return The full command line for the ProcessBuilder.
 124      */
 125     public static String getCommandLine(ProcessBuilder pb) {
 126         StringBuilder cmd = new StringBuilder();
 127         for (String s : pb.command()) {
 128             cmd.append(s).append(" ");
 129         }
 130         return cmd.toString();
 131     }
 132 
 133     /**
 134      * Returns the free port on the local host.
 135      * The function will spin until a valid port number is found.
 136      *
 137      * @return The port number
 138      * @throws InterruptedException if any thread has interrupted the current thread
 139      * @throws IOException if an I/O error occurs when opening the socket
 140      */
 141     public static int getFreePort() throws InterruptedException, IOException {
 142         int port = -1;
 143 
 144         while (port <= 0) {
 145             Thread.sleep(100);
 146 
 147             ServerSocket serverSocket = null;
 148             try {
 149                 serverSocket = new ServerSocket(0);
 150                 port = serverSocket.getLocalPort();
 151             } finally {
 152                 serverSocket.close();
 153             }
 154         }
 155 
 156         return port;
 157     }
 158 
 159     /**
 160      * Returns the name of the local host.
 161      *
 162      * @return The host name
 163      * @throws UnknownHostException if IP address of a host could not be determined
 164      */
 165     public static String getHostname() throws UnknownHostException {
 166         InetAddress inetAddress = InetAddress.getLocalHost();
 167         String hostName = inetAddress.getHostName();
 168 
 169         assertTrue((hostName != null && !hostName.isEmpty()),
 170                 "Cannot get hostname");
 171 
 172         return hostName;
 173     }
 174 
 175     /**
 176      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 177      * forever (until jtreg timeout) for the pid to be found.
 178      * @param key Regular expression to search for
 179      * @return The found pid.
 180      */
 181     public static int waitForJvmPid(String key) throws Throwable {
 182         final long iterationSleepMillis = 250;
 183         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 184         System.out.flush();
 185         while (true) {
 186             int pid = tryFindJvmPid(key);
 187             if (pid >= 0) {
 188                 return pid;
 189             }
 190             Thread.sleep(iterationSleepMillis);
 191         }
 192     }
 193 
 194     /**
 195      * Searches for a jvm pid in the output from "jcmd -l".
 196      *
 197      * Example output from jcmd is:
 198      * 12498 sun.tools.jcmd.JCmd -l
 199      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 200      *
 201      * @param key A regular expression to search for.
 202      * @return The found pid, or -1 if Enot found.
 203      * @throws Exception If multiple matching jvms are found.
 204      */
 205     public static int tryFindJvmPid(String key) throws Throwable {
 206         ProcessBuilder pb = null;
 207         OutputAnalyzer output = null;
 208         try {
 209             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 210             jcmdLauncher.addToolArg("-l");
 211             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 212             output.shouldHaveExitValue(0);
 213 
 214             // Search for a line starting with numbers (pid), follwed by the key.
 215             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 216             Matcher matcher = pattern.matcher(output.getStdout());
 217 
 218             int pid = -1;
 219             if (matcher.find()) {
 220                 pid = Integer.parseInt(matcher.group(1));
 221                 System.out.println("findJvmPid.pid: " + pid);
 222                 if (matcher.find()) {
 223                     throw new Exception("Found multiple JVM pids for key: " + key);
 224                 }
 225             }
 226             return pid;
 227         } catch (Throwable t) {
 228             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 229             throw t;
 230         }
 231     }
 232 }