Utils.java revision 2239:ed4e02fb36c3
1/*
2 * Copyright (c) 2013, 2016, 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
24package jdk.test.lib;
25
26import java.io.File;
27import java.io.IOException;
28import java.net.InetAddress;
29import java.net.MalformedURLException;
30import java.net.ServerSocket;
31import java.net.URL;
32import java.net.URLClassLoader;
33import java.net.UnknownHostException;
34import java.nio.file.Files;
35import java.nio.file.Path;
36import java.nio.file.Paths;
37import java.util.ArrayList;
38import java.util.Arrays;
39import java.util.Collection;
40import java.util.Collections;
41import java.util.Iterator;
42import java.util.Map;
43import java.util.HashMap;
44import java.util.List;
45import java.util.Objects;
46import java.util.Random;
47import java.util.function.BooleanSupplier;
48import java.util.concurrent.TimeUnit;
49import java.util.function.Consumer;
50import java.util.function.Function;
51import java.util.regex.Matcher;
52import java.util.regex.Pattern;
53
54import static jdk.test.lib.Asserts.assertTrue;
55import jdk.test.lib.process.ProcessTools;
56import jdk.test.lib.process.OutputAnalyzer;
57
58/**
59 * Common library for various test helper functions.
60 */
61public final class Utils {
62
63    /**
64     * Returns the value of 'test.class.path' system property.
65     */
66    public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", ".");
67
68    /**
69     * Returns the sequence used by operating system to separate lines.
70     */
71    public static final String NEW_LINE = System.getProperty("line.separator");
72
73    /**
74     * Returns the value of 'test.vm.opts' system property.
75     */
76    public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
77
78    /**
79     * Returns the value of 'test.java.opts' system property.
80     */
81    public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
82
83    /**
84     * Returns the value of 'test.src' system property.
85     */
86    public static final String TEST_SRC = System.getProperty("test.src", "").trim();
87
88    /**
89     * Defines property name for seed value.
90     */
91    public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed";
92
93    /* (non-javadoc)
94     * Random generator with (or without) predefined seed. Depends on
95     * "jdk.test.lib.random.seed" property value.
96     */
97    private static volatile Random RANDOM_GENERATOR;
98
99    /**
100     * Contains the seed value used for {@link java.util.Random} creation.
101     */
102    public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong());
103    /**
104    * Returns the value of 'test.timeout.factor' system property
105    * converted to {@code double}.
106    */
107    public static final double TIMEOUT_FACTOR;
108    static {
109        String toFactor = System.getProperty("test.timeout.factor", "1.0");
110        TIMEOUT_FACTOR = Double.parseDouble(toFactor);
111    }
112
113    /**
114    * Returns the value of JTREG default test timeout in milliseconds
115    * converted to {@code long}.
116    */
117    public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
118
119    private Utils() {
120        // Private constructor to prevent class instantiation
121    }
122
123    /**
124     * Returns the list of VM options.
125     *
126     * @return List of VM options
127     */
128    public static List<String> getVmOptions() {
129        return Arrays.asList(safeSplitString(VM_OPTIONS));
130    }
131
132    /**
133     * Returns the list of VM options with -J prefix.
134     *
135     * @return The list of VM options with -J prefix
136     */
137    public static List<String> getForwardVmOptions() {
138        String[] opts = safeSplitString(VM_OPTIONS);
139        for (int i = 0; i < opts.length; i++) {
140            opts[i] = "-J" + opts[i];
141        }
142        return Arrays.asList(opts);
143    }
144
145    /**
146     * Returns the default JTReg arguments for a jvm running a test.
147     * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
148     * @return An array of options, or an empty array if no options.
149     */
150    public static String[] getTestJavaOpts() {
151        List<String> opts = new ArrayList<String>();
152        Collections.addAll(opts, safeSplitString(VM_OPTIONS));
153        Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
154        return opts.toArray(new String[0]);
155    }
156
157    /**
158     * Combines given arguments with default JTReg arguments for a jvm running a test.
159     * This is the combination of JTReg arguments test.vm.opts and test.java.opts
160     * @return The combination of JTReg test java options and user args.
161     */
162    public static String[] addTestJavaOpts(String... userArgs) {
163        List<String> opts = new ArrayList<String>();
164        Collections.addAll(opts, getTestJavaOpts());
165        Collections.addAll(opts, userArgs);
166        return opts.toArray(new String[0]);
167    }
168
169    /**
170     * Removes any options specifying which GC to use, for example "-XX:+UseG1GC".
171     * Removes any options matching: -XX:(+/-)Use*GC
172     * Used when a test need to set its own GC version. Then any
173     * GC specified by the framework must first be removed.
174     * @return A copy of given opts with all GC options removed.
175     */
176    private static final Pattern useGcPattern = Pattern.compile(
177            "(?:\\-XX\\:[\\+\\-]Use.+GC)"
178            + "|(?:\\-Xconcgc)");
179    public static List<String> removeGcOpts(List<String> opts) {
180        List<String> optsWithoutGC = new ArrayList<String>();
181        for (String opt : opts) {
182            if (useGcPattern.matcher(opt).matches()) {
183                System.out.println("removeGcOpts: removed " + opt);
184            } else {
185                optsWithoutGC.add(opt);
186            }
187        }
188        return optsWithoutGC;
189    }
190
191    /**
192     * Returns the default JTReg arguments for a jvm running a test without
193     * options that matches regular expressions in {@code filters}.
194     * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
195     * @param filters Regular expressions used to filter out options.
196     * @return An array of options, or an empty array if no options.
197     */
198    public static String[] getFilteredTestJavaOpts(String... filters) {
199        String options[] = getTestJavaOpts();
200
201        if (filters.length == 0) {
202            return options;
203        }
204
205        List<String> filteredOptions = new ArrayList<String>(options.length);
206        Pattern patterns[] = new Pattern[filters.length];
207        for (int i = 0; i < filters.length; i++) {
208            patterns[i] = Pattern.compile(filters[i]);
209        }
210
211        for (String option : options) {
212            boolean matched = false;
213            for (int i = 0; i < patterns.length && !matched; i++) {
214                Matcher matcher = patterns[i].matcher(option);
215                matched = matcher.find();
216            }
217            if (!matched) {
218                filteredOptions.add(option);
219            }
220        }
221
222        return filteredOptions.toArray(new String[filteredOptions.size()]);
223    }
224
225    /**
226     * Splits a string by white space.
227     * Works like String.split(), but returns an empty array
228     * if the string is null or empty.
229     */
230    private static String[] safeSplitString(String s) {
231        if (s == null || s.trim().isEmpty()) {
232            return new String[] {};
233        }
234        return s.trim().split("\\s+");
235    }
236
237    /**
238     * @return The full command line for the ProcessBuilder.
239     */
240    public static String getCommandLine(ProcessBuilder pb) {
241        StringBuilder cmd = new StringBuilder();
242        for (String s : pb.command()) {
243            cmd.append(s).append(" ");
244        }
245        return cmd.toString();
246    }
247
248    /**
249     * Returns the free port on the local host.
250     * The function will spin until a valid port number is found.
251     *
252     * @return The port number
253     * @throws InterruptedException if any thread has interrupted the current thread
254     * @throws IOException if an I/O error occurs when opening the socket
255     */
256    public static int getFreePort() throws InterruptedException, IOException {
257        int port = -1;
258
259        while (port <= 0) {
260            Thread.sleep(100);
261
262            ServerSocket serverSocket = null;
263            try {
264                serverSocket = new ServerSocket(0);
265                port = serverSocket.getLocalPort();
266            } finally {
267                serverSocket.close();
268            }
269        }
270
271        return port;
272    }
273
274    /**
275     * Returns the name of the local host.
276     *
277     * @return The host name
278     * @throws UnknownHostException if IP address of a host could not be determined
279     */
280    public static String getHostname() throws UnknownHostException {
281        InetAddress inetAddress = InetAddress.getLocalHost();
282        String hostName = inetAddress.getHostName();
283
284        assertTrue((hostName != null && !hostName.isEmpty()),
285                "Cannot get hostname");
286
287        return hostName;
288    }
289
290    /**
291     * Uses "jcmd -l" to search for a jvm pid. This function will wait
292     * forever (until jtreg timeout) for the pid to be found.
293     * @param key Regular expression to search for
294     * @return The found pid.
295     */
296    public static int waitForJvmPid(String key) throws Throwable {
297        final long iterationSleepMillis = 250;
298        System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
299        System.out.flush();
300        while (true) {
301            int pid = tryFindJvmPid(key);
302            if (pid >= 0) {
303                return pid;
304            }
305            Thread.sleep(iterationSleepMillis);
306        }
307    }
308
309    /**
310     * Searches for a jvm pid in the output from "jcmd -l".
311     *
312     * Example output from jcmd is:
313     * 12498 sun.tools.jcmd.JCmd -l
314     * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
315     *
316     * @param key A regular expression to search for.
317     * @return The found pid, or -1 if not found.
318     * @throws Exception If multiple matching jvms are found.
319     */
320    public static int tryFindJvmPid(String key) throws Throwable {
321        OutputAnalyzer output = null;
322        try {
323            JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
324            jcmdLauncher.addToolArg("-l");
325            output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
326            output.shouldHaveExitValue(0);
327
328            // Search for a line starting with numbers (pid), follwed by the key.
329            Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
330            Matcher matcher = pattern.matcher(output.getStdout());
331
332            int pid = -1;
333            if (matcher.find()) {
334                pid = Integer.parseInt(matcher.group(1));
335                System.out.println("findJvmPid.pid: " + pid);
336                if (matcher.find()) {
337                    throw new Exception("Found multiple JVM pids for key: " + key);
338                }
339            }
340            return pid;
341        } catch (Throwable t) {
342            System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
343            throw t;
344        }
345    }
346
347    /**
348     * Adjusts the provided timeout value for the TIMEOUT_FACTOR
349     * @param tOut the timeout value to be adjusted
350     * @return The timeout value adjusted for the value of "test.timeout.factor"
351     *         system property
352     */
353    public static long adjustTimeout(long tOut) {
354        return Math.round(tOut * Utils.TIMEOUT_FACTOR);
355    }
356
357    /**
358     * Return the contents of the named file as a single String,
359     * or null if not found.
360     * @param filename name of the file to read
361     * @return String contents of file, or null if file not found.
362     * @throws  IOException
363     *          if an I/O error occurs reading from the file or a malformed or
364     *          unmappable byte sequence is read
365     */
366    public static String fileAsString(String filename) throws IOException {
367        Path filePath = Paths.get(filename);
368        if (!Files.exists(filePath)) return null;
369        return new String(Files.readAllBytes(filePath));
370    }
371
372    private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
373
374    /**
375     * Returns hex view of byte array
376     *
377     * @param bytes byte array to process
378     * @return Space separated hexadecimal string representation of bytes
379     */
380
381    public static String toHexString(byte[] bytes) {
382        char[] hexView = new char[bytes.length * 3];
383        int i = 0;
384        for (byte b : bytes) {
385            hexView[i++] = hexArray[(b >> 4) & 0x0F];
386            hexView[i++] = hexArray[b & 0x0F];
387            hexView[i++] = ' ';
388        }
389        return new String(hexView);
390    }
391
392    /**
393     * Returns {@link java.util.Random} generator initialized with particular seed.
394     * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME}
395     * In case no seed is provided, the method uses a random number.
396     * The used seed printed to stdout.
397     * @return {@link java.util.Random} generator with particular seed.
398     */
399    public static Random getRandomInstance() {
400        if (RANDOM_GENERATOR == null) {
401            synchronized (Utils.class) {
402                if (RANDOM_GENERATOR == null) {
403                    RANDOM_GENERATOR = new Random(SEED);
404                    System.out.printf("For random generator using seed: %d%n", SEED);
405                    System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED);
406                }
407            }
408        }
409        return RANDOM_GENERATOR;
410    }
411
412    /**
413     * Returns random element of non empty collection
414     *
415     * @param <T> a type of collection element
416     * @param collection collection of elements
417     * @return random element of collection
418     * @throws IllegalArgumentException if collection is empty
419     */
420    public static <T> T getRandomElement(Collection<T> collection)
421            throws IllegalArgumentException {
422        if (collection.isEmpty()) {
423            throw new IllegalArgumentException("Empty collection");
424        }
425        Random random = getRandomInstance();
426        int elementIndex = 1 + random.nextInt(collection.size() - 1);
427        Iterator<T> iterator = collection.iterator();
428        while (--elementIndex != 0) {
429            iterator.next();
430        }
431        return iterator.next();
432    }
433
434    /**
435     * Returns random element of non empty array
436     *
437     * @param <T> a type of array element
438     * @param array array of elements
439     * @return random element of array
440     * @throws IllegalArgumentException if array is empty
441     */
442    public static <T> T getRandomElement(T[] array)
443            throws IllegalArgumentException {
444        if (array == null || array.length == 0) {
445            throw new IllegalArgumentException("Empty or null array");
446        }
447        Random random = getRandomInstance();
448        return array[random.nextInt(array.length)];
449    }
450
451    /**
452     * Wait for condition to be true
453     *
454     * @param condition, a condition to wait for
455     */
456    public static final void waitForCondition(BooleanSupplier condition) {
457        waitForCondition(condition, -1L, 100L);
458    }
459
460    /**
461     * Wait until timeout for condition to be true
462     *
463     * @param condition, a condition to wait for
464     * @param timeout a time in milliseconds to wait for condition to be true
465     * specifying -1 will wait forever
466     * @return condition value, to determine if wait was successful
467     */
468    public static final boolean waitForCondition(BooleanSupplier condition,
469            long timeout) {
470        return waitForCondition(condition, timeout, 100L);
471    }
472
473    /**
474     * Wait until timeout for condition to be true for specified time
475     *
476     * @param condition, a condition to wait for
477     * @param timeout a time in milliseconds to wait for condition to be true,
478     * specifying -1 will wait forever
479     * @param sleepTime a time to sleep value in milliseconds
480     * @return condition value, to determine if wait was successful
481     */
482    public static final boolean waitForCondition(BooleanSupplier condition,
483            long timeout, long sleepTime) {
484        long startTime = System.currentTimeMillis();
485        while (!(condition.getAsBoolean() || (timeout != -1L
486                && ((System.currentTimeMillis() - startTime) > timeout)))) {
487            try {
488                Thread.sleep(sleepTime);
489            } catch (InterruptedException e) {
490                Thread.currentThread().interrupt();
491                throw new Error(e);
492            }
493        }
494        return condition.getAsBoolean();
495    }
496
497    /**
498     * Interface same as java.lang.Runnable but with
499     * method {@code run()} able to throw any Throwable.
500     */
501    public static interface ThrowingRunnable {
502        void run() throws Throwable;
503    }
504
505    /**
506     * Filters out an exception that may be thrown by the given
507     * test according to the given filter.
508     *
509     * @param test - method that is invoked and checked for exception.
510     * @param filter - function that checks if the thrown exception matches
511     *                 criteria given in the filter's implementation.
512     * @return - exception that matches the filter if it has been thrown or
513     *           {@code null} otherwise.
514     * @throws Throwable - if test has thrown an exception that does not
515     *                     match the filter.
516     */
517    public static Throwable filterException(ThrowingRunnable test,
518            Function<Throwable, Boolean> filter) throws Throwable {
519        try {
520            test.run();
521        } catch (Throwable t) {
522            if (filter.apply(t)) {
523                return t;
524            } else {
525                throw t;
526            }
527        }
528        return null;
529    }
530
531    /**
532     * Ensures a requested class is loaded
533     * @param aClass class to load
534     */
535    public static void ensureClassIsLoaded(Class<?> aClass) {
536        if (aClass == null) {
537            throw new Error("Requested null class");
538        }
539        try {
540            Class.forName(aClass.getName(), /* initialize = */ true,
541                    ClassLoader.getSystemClassLoader());
542        } catch (ClassNotFoundException e) {
543            throw new Error("Class not found", e);
544        }
545    }
546    /**
547     * @param parent a class loader to be the parent for the returned one
548     * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg
549     *         property and with the given parent
550     */
551    public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) {
552        URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator))
553                .map(Paths::get)
554                .map(Path::toUri)
555                .map(x -> {
556                    try {
557                        return x.toURL();
558                    } catch (MalformedURLException ex) {
559                        throw new Error("Test issue. JTREG property"
560                                + " 'test.class.path'"
561                                + " is not defined correctly", ex);
562                    }
563                }).toArray(URL[]::new);
564        return new URLClassLoader(urls, parent);
565    }
566
567    /**
568     * Runs runnable and checks that it throws expected exception. If exceptionException is null it means
569     * that we expect no exception to be thrown.
570     * @param runnable what we run
571     * @param expectedException expected exception
572     */
573    public static void runAndCheckException(Runnable runnable, Class<? extends Throwable> expectedException) {
574        runAndCheckException(runnable, t -> {
575            if (t == null) {
576                if (expectedException != null) {
577                    throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName());
578                }
579            } else {
580                String message = "Got unexpected exception " + t.getClass().getSimpleName();
581                if (expectedException == null) {
582                    throw new AssertionError(message, t);
583                } else if (!expectedException.isAssignableFrom(t.getClass())) {
584                    message += " instead of " + expectedException.getSimpleName();
585                    throw new AssertionError(message, t);
586                }
587            }
588        });
589    }
590
591    /**
592     * Runs runnable and makes some checks to ensure that it throws expected exception.
593     * @param runnable what we run
594     * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise
595     */
596    public static void runAndCheckException(Runnable runnable, Consumer<Throwable> checkException) {
597        try {
598            runnable.run();
599            checkException.accept(null);
600        } catch (Throwable t) {
601            checkException.accept(t);
602        }
603    }
604
605    /**
606     * Converts to VM type signature
607     *
608     * @param type Java type to convert
609     * @return string representation of VM type
610     */
611    public static String toJVMTypeSignature(Class<?> type) {
612        if (type.isPrimitive()) {
613            if (type == boolean.class) {
614                return "Z";
615            } else if (type == byte.class) {
616                return "B";
617            } else if (type == char.class) {
618                return "C";
619            } else if (type == double.class) {
620                return "D";
621            } else if (type == float.class) {
622                return "F";
623            } else if (type == int.class) {
624                return "I";
625            } else if (type == long.class) {
626                return "J";
627            } else if (type == short.class) {
628                return "S";
629            } else if (type == void.class) {
630                return "V";
631            } else {
632                throw new Error("Unsupported type: " + type);
633            }
634        }
635        String result = type.getName().replaceAll("\\.", "/");
636        if (!type.isArray()) {
637            return "L" + result + ";";
638        }
639        return result;
640    }
641
642    public static Object[] getNullValues(Class<?>... types) {
643        Object[] result = new Object[types.length];
644        int i = 0;
645        for (Class<?> type : types) {
646            result[i++] = NULL_VALUES.get(type);
647        }
648        return result;
649    }
650    private static Map<Class<?>, Object> NULL_VALUES = new HashMap<>();
651    static {
652        NULL_VALUES.put(boolean.class, false);
653        NULL_VALUES.put(byte.class, (byte) 0);
654        NULL_VALUES.put(short.class, (short) 0);
655        NULL_VALUES.put(char.class, '\0');
656        NULL_VALUES.put(int.class, 0);
657        NULL_VALUES.put(long.class, 0L);
658        NULL_VALUES.put(float.class, 0.0f);
659        NULL_VALUES.put(double.class, 0.0d);
660    }
661
662    /**
663     * Returns mandatory property value
664     * @param propName is a name of property to request
665     * @return a String with requested property value
666     */
667    public static String getMandatoryProperty(String propName) {
668        Objects.requireNonNull(propName, "Requested null property");
669        String prop = System.getProperty(propName);
670        Objects.requireNonNull(prop,
671                String.format("A mandatory property '%s' isn't set", propName));
672        return prop;
673    }
674}
675
676