Utils.java revision 12209:69cb11a71ab8
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
24package jdk.testlibrary;
25
26import static jdk.testlibrary.Asserts.assertTrue;
27
28import java.io.IOException;
29import java.net.InetAddress;
30import java.net.ServerSocket;
31import java.net.UnknownHostException;
32import java.util.ArrayList;
33import java.util.List;
34import java.util.Arrays;
35import java.util.Collections;
36import java.util.regex.Pattern;
37import java.util.regex.Matcher;
38import java.util.concurrent.TimeUnit;
39import java.util.function.BooleanSupplier;
40import java.util.function.Function;
41
42/**
43 * Common library for various test helper functions.
44 */
45public 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    /**
73    * Returns the value of JTREG default test timeout in milliseconds
74    * converted to {@code long}.
75    */
76    public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
77
78    private Utils() {
79        // Private constructor to prevent class instantiation
80    }
81
82    /**
83     * Returns the list of VM options.
84     *
85     * @return List of VM options
86     */
87    public static List<String> getVmOptions() {
88        return Arrays.asList(safeSplitString(VM_OPTIONS));
89    }
90
91    /**
92     * Returns the list of VM options with -J prefix.
93     *
94     * @return The list of VM options with -J prefix
95     */
96    public static List<String> getForwardVmOptions() {
97        String[] opts = safeSplitString(VM_OPTIONS);
98        for (int i = 0; i < opts.length; i++) {
99            opts[i] = "-J" + opts[i];
100        }
101        return Arrays.asList(opts);
102    }
103
104    /**
105     * Returns the default JTReg arguments for a jvm running a test.
106     * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
107     * @return An array of options, or an empty array if no opptions.
108     */
109    public static String[] getTestJavaOpts() {
110        List<String> opts = new ArrayList<String>();
111        Collections.addAll(opts, safeSplitString(VM_OPTIONS));
112        Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
113        return opts.toArray(new String[0]);
114    }
115
116    /**
117     * Combines given arguments with default JTReg arguments for a jvm running a test.
118     * This is the combination of JTReg arguments test.vm.opts and test.java.opts
119     * @return The combination of JTReg test java options and user args.
120     */
121    public static String[] addTestJavaOpts(String... userArgs) {
122        List<String> opts = new ArrayList<String>();
123        Collections.addAll(opts, getTestJavaOpts());
124        Collections.addAll(opts, userArgs);
125        return opts.toArray(new String[0]);
126    }
127
128    /**
129     * Removes any options specifying which GC to use, for example "-XX:+UseG1GC".
130     * Removes any options matching: -XX:(+/-)Use*GC
131     * Used when a test need to set its own GC version. Then any
132     * GC specified by the framework must first be removed.
133     * @return A copy of given opts with all GC options removed.
134     */
135    private static final Pattern useGcPattern = Pattern.compile(
136            "(?:\\-XX\\:[\\+\\-]Use.+GC)"
137            + "|(?:\\-Xconcgc)");
138    public static List<String> removeGcOpts(List<String> opts) {
139        List<String> optsWithoutGC = new ArrayList<String>();
140        for (String opt : opts) {
141            if (useGcPattern.matcher(opt).matches()) {
142                System.out.println("removeGcOpts: removed " + opt);
143            } else {
144                optsWithoutGC.add(opt);
145            }
146        }
147        return optsWithoutGC;
148    }
149
150    /**
151     * Splits a string by white space.
152     * Works like String.split(), but returns an empty array
153     * if the string is null or empty.
154     */
155    private static String[] safeSplitString(String s) {
156        if (s == null || s.trim().isEmpty()) {
157            return new String[] {};
158        }
159        return s.trim().split("\\s+");
160    }
161
162    /**
163     * @return The full command line for the ProcessBuilder.
164     */
165    public static String getCommandLine(ProcessBuilder pb) {
166        StringBuilder cmd = new StringBuilder();
167        for (String s : pb.command()) {
168            cmd.append(s).append(" ");
169        }
170        return cmd.toString();
171    }
172
173    /**
174     * Returns the free port on the local host.
175     * The function will spin until a valid port number is found.
176     *
177     * @return The port number
178     * @throws InterruptedException if any thread has interrupted the current thread
179     * @throws IOException if an I/O error occurs when opening the socket
180     */
181    public static int getFreePort() throws InterruptedException, IOException {
182        int port = -1;
183
184        while (port <= 0) {
185            Thread.sleep(100);
186
187            ServerSocket serverSocket = null;
188            try {
189                serverSocket = new ServerSocket(0);
190                port = serverSocket.getLocalPort();
191            } finally {
192                serverSocket.close();
193            }
194        }
195
196        return port;
197    }
198
199    /**
200     * Returns the name of the local host.
201     *
202     * @return The host name
203     * @throws UnknownHostException if IP address of a host could not be determined
204     */
205    public static String getHostname() throws UnknownHostException {
206        InetAddress inetAddress = InetAddress.getLocalHost();
207        String hostName = inetAddress.getHostName();
208
209        assertTrue((hostName != null && !hostName.isEmpty()),
210                "Cannot get hostname");
211
212        return hostName;
213    }
214
215    /**
216     * Uses "jcmd -l" to search for a jvm pid. This function will wait
217     * forever (until jtreg timeout) for the pid to be found.
218     * @param key Regular expression to search for
219     * @return The found pid.
220     */
221    public static int waitForJvmPid(String key) throws Throwable {
222        final long iterationSleepMillis = 250;
223        System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
224        System.out.flush();
225        while (true) {
226            int pid = tryFindJvmPid(key);
227            if (pid >= 0) {
228                return pid;
229            }
230            Thread.sleep(iterationSleepMillis);
231        }
232    }
233
234    /**
235     * Searches for a jvm pid in the output from "jcmd -l".
236     *
237     * Example output from jcmd is:
238     * 12498 sun.tools.jcmd.JCmd -l
239     * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
240     *
241     * @param key A regular expression to search for.
242     * @return The found pid, or -1 if Enot found.
243     * @throws Exception If multiple matching jvms are found.
244     */
245    public static int tryFindJvmPid(String key) throws Throwable {
246        OutputAnalyzer output = null;
247        try {
248            JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
249            jcmdLauncher.addToolArg("-l");
250            output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
251            output.shouldHaveExitValue(0);
252
253            // Search for a line starting with numbers (pid), follwed by the key.
254            Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
255            Matcher matcher = pattern.matcher(output.getStdout());
256
257            int pid = -1;
258            if (matcher.find()) {
259                pid = Integer.parseInt(matcher.group(1));
260                System.out.println("findJvmPid.pid: " + pid);
261                if (matcher.find()) {
262                    throw new Exception("Found multiple JVM pids for key: " + key);
263                }
264            }
265            return pid;
266        } catch (Throwable t) {
267            System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
268            throw t;
269        }
270    }
271
272    /**
273     * Adjusts the provided timeout value for the TIMEOUT_FACTOR
274     * @param tOut the timeout value to be adjusted
275     * @return The timeout value adjusted for the value of "test.timeout.factor"
276     *         system property
277     */
278    public static long adjustTimeout(long tOut) {
279        return Math.round(tOut * Utils.TIMEOUT_FACTOR);
280    }
281
282    /**
283     * Wait for condition to be true
284     *
285     * @param condition, a condition to wait for
286     */
287    public static final void waitForCondition(BooleanSupplier condition) {
288        waitForCondition(condition, -1L, 100L);
289    }
290
291    /**
292     * Wait until timeout for condition to be true
293     *
294     * @param condition, a condition to wait for
295     * @param timeout a time in milliseconds to wait for condition to be true
296     * specifying -1 will wait forever
297     * @return condition value, to determine if wait was successfull
298     */
299    public static final boolean waitForCondition(BooleanSupplier condition,
300            long timeout) {
301        return waitForCondition(condition, timeout, 100L);
302    }
303
304    /**
305     * Wait until timeout for condition to be true for specified time
306     *
307     * @param condition, a condition to wait for
308     * @param timeout a time in milliseconds to wait for condition to be true,
309     * specifying -1 will wait forever
310     * @param sleepTime a time to sleep value in milliseconds
311     * @return condition value, to determine if wait was successfull
312     */
313    public static final boolean waitForCondition(BooleanSupplier condition,
314            long timeout, long sleepTime) {
315        long startTime = System.currentTimeMillis();
316        while (!(condition.getAsBoolean() || (timeout != -1L
317                && ((System.currentTimeMillis() - startTime) > timeout)))) {
318            try {
319                Thread.sleep(sleepTime);
320            } catch (InterruptedException e) {
321                Thread.currentThread().interrupt();
322                throw new Error(e);
323            }
324        }
325        return condition.getAsBoolean();
326    }
327
328    /**
329     * Interface same as java.lang.Runnable but with
330     * method {@code run()} able to throw any Throwable.
331     */
332    public static interface ThrowingRunnable {
333        void run() throws Throwable;
334    }
335
336    /**
337     * Filters out an exception that may be thrown by the given
338     * test according to the given filter.
339     *
340     * @param test - method that is invoked and checked for exception.
341     * @param filter - function that checks if the thrown exception matches
342     *                 criteria given in the filter's implementation.
343     * @return - exception that matches the filter if it has been thrown or
344     *           {@code null} otherwise.
345     * @throws Throwable - if test has thrown an exception that does not
346     *                     match the filter.
347     */
348    public static Throwable filterException(ThrowingRunnable test,
349            Function<Throwable, Boolean> filter) throws Throwable {
350        try {
351            test.run();
352        } catch (Throwable t) {
353            if (filter.apply(t)) {
354                return t;
355            } else {
356                throw t;
357            }
358        }
359        return null;
360    }
361}
362