1 /* 2 * Copyright (c) 2013, 2015, 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.test.lib; 25 26 import static jdk.test.lib.Asserts.assertTrue; 27 import java.io.BufferedReader; 28 import java.io.File; 29 import java.io.FileReader; 30 import java.io.IOException; 31 import java.lang.reflect.Field; 32 import java.net.InetAddress; 33 import java.net.ServerSocket; 34 import java.net.UnknownHostException; 35 import java.nio.file.Files; 36 import java.nio.file.Path; 37 import java.nio.file.Paths; 38 import java.util.ArrayList; 39 import java.util.Arrays; 40 import java.util.Collections; 41 import java.util.List; 42 import java.util.Random; 43 import java.util.function.BooleanSupplier; 44 import java.util.concurrent.TimeUnit; 45 import java.util.regex.Matcher; 46 import java.util.regex.Pattern; 47 import java.util.stream.Collectors; 48 import sun.misc.Unsafe; 49 50 /** 51 * Common library for various test helper functions. 52 */ 53 public final class Utils { 54 55 /** 56 * Returns the sequence used by operating system to separate lines. 57 */ 58 public static final String NEW_LINE = System.getProperty("line.separator"); 59 60 /** 61 * Returns the value of 'test.vm.opts'system property. 62 */ 63 public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); 64 65 /** 66 * Returns the value of 'test.java.opts'system property. 67 */ 68 public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); 69 70 private static Unsafe unsafe = null; 71 72 /** 73 * Defines property name for seed value. 74 */ 75 public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; 76 77 /* (non-javadoc) 78 * Random generator with (or without) predefined seed. Depends on 79 * "jdk.test.lib.random.seed" property value. 80 */ 81 private static volatile Random RANDOM_GENERATOR; 82 83 /** 84 * Contains the seed value used for {@link java.util.Random} creation. 85 */ 86 public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong()); 87 /** 88 * Returns the value of 'test.timeout.factor' system property 89 * converted to {@code double}. 90 */ 91 public static final double TIMEOUT_FACTOR; 92 static { 93 String toFactor = System.getProperty("test.timeout.factor", "1.0"); 94 TIMEOUT_FACTOR = Double.parseDouble(toFactor); 95 } 96 97 /** 98 * Returns the value of JTREG default test timeout in milliseconds 99 * converted to {@code long}. 100 */ 101 public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); 102 103 private Utils() { 104 // Private constructor to prevent class instantiation 105 } 106 107 /** 108 * Returns the list of VM options. 109 * 110 * @return List of VM options 111 */ 112 public static List<String> getVmOptions() { 113 return Arrays.asList(safeSplitString(VM_OPTIONS)); 114 } 115 116 /** 117 * Returns the list of VM options with -J prefix. 118 * 119 * @return The list of VM options with -J prefix 120 */ 121 public static List<String> getForwardVmOptions() { 122 String[] opts = safeSplitString(VM_OPTIONS); 123 for (int i = 0; i < opts.length; i++) { 124 opts[i] = "-J" + opts[i]; 125 } 126 return Arrays.asList(opts); 127 } 128 129 /** 130 * Returns the default JTReg arguments for a jvm running a test. 131 * This is the combination of JTReg arguments test.vm.opts and test.java.opts. 132 * @return An array of options, or an empty array if no opptions. 133 */ 134 public static String[] getTestJavaOpts() { 135 List<String> opts = new ArrayList<String>(); 136 Collections.addAll(opts, safeSplitString(VM_OPTIONS)); 137 Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); 138 return opts.toArray(new String[0]); 139 } 140 141 /** 142 * Returns the default JTReg arguments for a jvm running a test without 143 * options that matches regular expressions in {@code filters}. 144 * This is the combination of JTReg arguments test.vm.opts and test.java.opts. 145 * @param filters Regular expressions used to filter out options. 146 * @return An array of options, or an empty array if no options. 147 */ 148 public static String[] getFilteredTestJavaOpts(String... filters) { 149 String options[] = getTestJavaOpts(); 150 151 if (filters.length == 0) { 152 return options; 153 } 154 155 List<String> filteredOptions = new ArrayList<String>(options.length); 156 Pattern patterns[] = new Pattern[filters.length]; 157 for (int i = 0; i < filters.length; i++) { 158 patterns[i] = Pattern.compile(filters[i]); 159 } 160 161 for (String option : options) { 162 boolean matched = false; 163 for (int i = 0; i < patterns.length && !matched; i++) { 164 Matcher matcher = patterns[i].matcher(option); 165 matched = matcher.find(); 166 } 167 if (!matched) { 168 filteredOptions.add(option); 169 } 170 } 171 172 return filteredOptions.toArray(new String[filteredOptions.size()]); 173 } 174 175 /** 176 * Combines given arguments with default JTReg arguments for a jvm running a test. 177 * This is the combination of JTReg arguments test.vm.opts and test.java.opts 178 * @return The combination of JTReg test java options and user args. 179 */ 180 public static String[] addTestJavaOpts(String... userArgs) { 181 List<String> opts = new ArrayList<String>(); 182 Collections.addAll(opts, getTestJavaOpts()); 183 Collections.addAll(opts, userArgs); 184 return opts.toArray(new String[0]); 185 } 186 187 /** 188 * Splits a string by white space. 189 * Works like String.split(), but returns an empty array 190 * if the string is null or empty. 191 */ 192 private static String[] safeSplitString(String s) { 193 if (s == null || s.trim().isEmpty()) { 194 return new String[] {}; 195 } 196 return s.trim().split("\\s+"); 197 } 198 199 /** 200 * @return The full command line for the ProcessBuilder. 201 */ 202 public static String getCommandLine(ProcessBuilder pb) { 203 StringBuilder cmd = new StringBuilder(); 204 for (String s : pb.command()) { 205 cmd.append(s).append(" "); 206 } 207 return cmd.toString(); 208 } 209 210 /** 211 * Returns the free port on the local host. 212 * The function will spin until a valid port number is found. 213 * 214 * @return The port number 215 * @throws InterruptedException if any thread has interrupted the current thread 216 * @throws IOException if an I/O error occurs when opening the socket 217 */ 218 public static int getFreePort() throws InterruptedException, IOException { 219 int port = -1; 220 221 while (port <= 0) { 222 Thread.sleep(100); 223 224 ServerSocket serverSocket = null; 225 try { 226 serverSocket = new ServerSocket(0); 227 port = serverSocket.getLocalPort(); 228 } finally { 229 serverSocket.close(); 230 } 231 } 232 233 return port; 234 } 235 236 /** 237 * Returns the name of the local host. 238 * 239 * @return The host name 240 * @throws UnknownHostException if IP address of a host could not be determined 241 */ 242 public static String getHostname() throws UnknownHostException { 243 InetAddress inetAddress = InetAddress.getLocalHost(); 244 String hostName = inetAddress.getHostName(); 245 246 assertTrue((hostName != null && !hostName.isEmpty()), 247 "Cannot get hostname"); 248 249 return hostName; 250 } 251 252 /** 253 * Uses "jcmd -l" to search for a jvm pid. This function will wait 254 * forever (until jtreg timeout) for the pid to be found. 255 * @param key Regular expression to search for 256 * @return The found pid. 257 */ 258 public static int waitForJvmPid(String key) throws Throwable { 259 final long iterationSleepMillis = 250; 260 System.out.println("waitForJvmPid: Waiting for key '" + key + "'"); 261 System.out.flush(); 262 while (true) { 263 int pid = tryFindJvmPid(key); 264 if (pid >= 0) { 265 return pid; 266 } 267 Thread.sleep(iterationSleepMillis); 268 } 269 } 270 271 /** 272 * Searches for a jvm pid in the output from "jcmd -l". 273 * 274 * Example output from jcmd is: 275 * 12498 sun.tools.jcmd.JCmd -l 276 * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar 277 * 278 * @param key A regular expression to search for. 279 * @return The found pid, or -1 if Enot found. 280 * @throws Exception If multiple matching jvms are found. 281 */ 282 public static int tryFindJvmPid(String key) throws Throwable { 283 OutputAnalyzer output = null; 284 try { 285 JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd"); 286 jcmdLauncher.addToolArg("-l"); 287 output = ProcessTools.executeProcess(jcmdLauncher.getCommand()); 288 output.shouldHaveExitValue(0); 289 290 // Search for a line starting with numbers (pid), follwed by the key. 291 Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n"); 292 Matcher matcher = pattern.matcher(output.getStdout()); 293 294 int pid = -1; 295 if (matcher.find()) { 296 pid = Integer.parseInt(matcher.group(1)); 297 System.out.println("findJvmPid.pid: " + pid); 298 if (matcher.find()) { 299 throw new Exception("Found multiple JVM pids for key: " + key); 300 } 301 } 302 return pid; 303 } catch (Throwable t) { 304 System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t)); 305 throw t; 306 } 307 } 308 309 /** 310 * Return the contents of the named file as a single String, 311 * or null if not found. 312 * @param filename name of the file to read 313 * @return String contents of file, or null if file not found. 314 * @throws IOException 315 * if an I/O error occurs reading from the file or a malformed or 316 * unmappable byte sequence is read 317 */ 318 public static String fileAsString(String filename) throws IOException { 319 Path filePath = Paths.get(filename); 320 return Files.exists(filePath) 321 ? Files.lines(filePath).collect(Collectors.joining(NEW_LINE)) 322 : null; 323 } 324 325 /** 326 * @return Unsafe instance. 327 */ 328 public static synchronized Unsafe getUnsafe() { 329 if (unsafe == null) { 330 try { 331 Field f = Unsafe.class.getDeclaredField("theUnsafe"); 332 f.setAccessible(true); 333 unsafe = (Unsafe) f.get(null); 334 } catch (NoSuchFieldException | IllegalAccessException e) { 335 throw new RuntimeException("Unable to get Unsafe instance.", e); 336 } 337 } 338 return unsafe; 339 } 340 private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; 341 342 /** 343 * Returns hex view of byte array 344 * 345 * @param bytes byte array to process 346 * @return Space separated hexadecimal string representation of bytes 347 */ 348 349 public static String toHexString(byte[] bytes) { 350 char[] hexView = new char[bytes.length * 3]; 351 int i = 0; 352 for (byte b : bytes) { 353 hexView[i++] = hexArray[(b >> 4) & 0x0F]; 354 hexView[i++] = hexArray[b & 0x0F]; 355 hexView[i++] = ' '; 356 } 357 return new String(hexView); 358 } 359 360 /** 361 * Returns {@link java.util.Random} generator initialized with particular seed. 362 * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME} 363 * In case no seed is provided, the method uses a random number. 364 * The used seed printed to stdout. 365 * @return {@link java.util.Random} generator with particular seed. 366 */ 367 public static Random getRandomInstance() { 368 if (RANDOM_GENERATOR == null) { 369 synchronized (Utils.class) { 370 if (RANDOM_GENERATOR == null) { 371 RANDOM_GENERATOR = new Random(SEED); 372 System.out.printf("For random generator using seed: %d%n", SEED); 373 System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED); 374 } 375 } 376 } 377 return RANDOM_GENERATOR; 378 } 379 380 /** 381 * Wait for condition to be true 382 * 383 * @param condition, a condition to wait for 384 */ 385 public static final void waitForCondition(BooleanSupplier condition) { 386 waitForCondition(condition, -1L, 100L); 387 } 388 389 /** 390 * Wait until timeout for condition to be true 391 * 392 * @param condition, a condition to wait for 393 * @param timeout a time in milliseconds to wait for condition to be true 394 * specifying -1 will wait forever 395 * @return condition value, to determine if wait was successfull 396 */ 397 public static final boolean waitForCondition(BooleanSupplier condition, 398 long timeout) { 399 return waitForCondition(condition, timeout, 100L); 400 } 401 402 /** 403 * Wait until timeout for condition to be true for specified time 404 * 405 * @param condition, a condition to wait for 406 * @param timeout a time in milliseconds to wait for condition to be true, 407 * specifying -1 will wait forever 408 * @param sleepTime a time to sleep value in milliseconds 409 * @return condition value, to determine if wait was successfull 410 */ 411 public static final boolean waitForCondition(BooleanSupplier condition, 412 long timeout, long sleepTime) { 413 long startTime = System.currentTimeMillis(); 414 while (!(condition.getAsBoolean() || (timeout != -1L 415 && ((System.currentTimeMillis() - startTime) > timeout)))) { 416 try { 417 Thread.sleep(sleepTime); 418 } catch (InterruptedException e) { 419 Thread.currentThread().interrupt(); 420 throw new Error(e); 421 } 422 } 423 return condition.getAsBoolean(); 424 } 425 426 /** 427 * Adjusts the provided timeout value for the TIMEOUT_FACTOR 428 * @param tOut the timeout value to be adjusted 429 * @return The timeout value adjusted for the value of "test.timeout.factor" 430 * system property 431 */ 432 public static long adjustTimeout(long tOut) { 433 return Math.round(tOut * Utils.TIMEOUT_FACTOR); 434 } 435 }