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