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