1 /*
   2  * Copyright (c) 2015, Red Hat Inc
   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 import java.io.File;
  25 import java.net.InetAddress;
  26 import java.net.NetworkInterface;
  27 import java.net.SocketException;
  28 import java.util.ArrayList;
  29 import java.util.List;
  30 import java.util.stream.Collectors;
  31 
  32 import jdk.test.lib.thread.ProcessThread;
  33 import jdk.testlibrary.ProcessTools;
  34 
  35 /**
  36  * NOTE:
  37  *    This test requires at least a setup similar to the following in
  38  *    /etc/hosts file (or the windows equivalent). I.e. it expects it to
  39  *    be multi-homed and not both being the loop-back interface.
  40  *    For example:
  41  *    ----->8-------- /etc/hosts ----------->8---
  42  *    127.0.0.1   localhost
  43  *    192.168.0.1 localhost
  44  *    ----->8-------- /etc/hosts ----------->8---
  45  *
  46  * @test
  47  * @bug     6425769
  48  * @summary Test JMX agent host address binding. Same ports but different
  49  *          interfaces to bind to (using plain sockets and SSL sockets).
  50  *
  51  * @library /lib/testlibrary
  52  * @library /test/lib
  53  * @modules java.management.rmi
  54  *
  55  * @build jdk.testlibrary.* JMXAgentInterfaceBinding
  56  * @run main/timeout=5 JMXInterfaceBindingTest
  57  */
  58 public class JMXInterfaceBindingTest {
  59 
  60     public static final int COMMUNICATION_ERROR_EXIT_VAL = 1;
  61     public static final int STOP_PROCESS_EXIT_VAL = 143;
  62     public static final int JMX_PORT = 9111;
  63     public static final int RMI_PORT = 9112;
  64     public static final String READY_MSG = "MainThread: Ready for connections";
  65     public static final String TEST_CLASS = JMXAgentInterfaceBinding.class.getSimpleName();
  66     public static final String KEYSTORE_LOC = System.getProperty("test.src", ".") +
  67                                               File.separator +
  68                                               "ssl" +
  69                                               File.separator +
  70                                               "keystore";
  71     public static final String TRUSTSTORE_LOC = System.getProperty("test.src", ".") +
  72                                                 File.separator +
  73                                                 "ssl" +
  74                                                 File.separator +
  75                                                 "truststore";
  76     public static final String TEST_CLASSPATH = System.getProperty("test.classes", ".");
  77 
  78     public void run(List<InetAddress> addrs) {
  79         System.out.println("DEBUG: Running tests with plain sockets.");
  80         runTests(addrs, false);
  81         System.out.println("DEBUG: Running tests with SSL sockets.");
  82         runTests(addrs, true);
  83     }
  84 
  85     private void runTests(List<InetAddress> addrs, boolean useSSL) {
  86         List<ProcessThread> jvms = new ArrayList<>(addrs.size());
  87         int i = 1;
  88         for (InetAddress addr : addrs) {
  89             String address = JMXAgentInterfaceBinding.wrapAddress(addr.getHostAddress());
  90             System.out.println();
  91             String msg = String.format("DEBUG: Launching java tester for triplet (HOSTNAME,JMX_PORT,RMI_PORT) == (%s,%d,%d)",
  92                     address,
  93                     JMX_PORT,
  94                     RMI_PORT);
  95             System.out.println(msg);
  96             ProcessThread jvm = runJMXBindingTest(address, useSSL);
  97             jvms.add(jvm);
  98             jvm.start();
  99             System.out.println("DEBUG: Started " + (i++) + " Process(es).");
 100         }
 101         int failedProcesses = 0;
 102         for (ProcessThread pt: jvms) {
 103             try {
 104                 pt.stopProcess();
 105                 pt.join();
 106             } catch (InterruptedException e) {
 107                 System.err.println("Failed to stop process: " + pt.getName());
 108                 throw new RuntimeException("Test failed", e);
 109             }
 110             int exitValue = pt.getOutput().getExitValue();
 111             // If there is a communication error (the case we care about)
 112             // we get a exit code of 1
 113             if (exitValue == COMMUNICATION_ERROR_EXIT_VAL) {
 114                 // Failure case since the java processes should still be
 115                 // running.
 116                 System.err.println("Test FAILURE on " + pt.getName());
 117                 failedProcesses++;
 118             } else if (exitValue == STOP_PROCESS_EXIT_VAL) {
 119                 System.out.println("DEBUG: OK. Spawned java process terminated with expected exit code of " + STOP_PROCESS_EXIT_VAL);
 120             } else {
 121                 System.err.println("Test FAILURE on " + pt.getName() + " reason: Unexpected exit code => " + exitValue);
 122                 failedProcesses++;
 123             }
 124         }
 125         if (failedProcesses > 0) {
 126             throw new RuntimeException("Test FAILED. " + failedProcesses + " out of " + addrs.size() + " process(es) failed to start the JMX agent.");
 127         }
 128     }
 129 
 130     private ProcessThread runJMXBindingTest(String address, boolean useSSL) {
 131         List<String> args = new ArrayList<>();
 132         args.add("-classpath");
 133         args.add(TEST_CLASSPATH);
 134         args.add("-Dcom.sun.management.jmxremote.host=" + address);
 135         args.add("-Dcom.sun.management.jmxremote.port=" + JMX_PORT);
 136         args.add("-Dcom.sun.management.jmxremote.rmi.port=" + RMI_PORT);
 137         args.add("-Dcom.sun.management.jmxremote.authenticate=false");
 138         args.add("-Dcom.sun.management.jmxremote.ssl=" + Boolean.toString(useSSL));
 139         if (useSSL) {
 140             args.add("-Dcom.sun.management.jmxremote.registry.ssl=true");
 141             args.add("-Djavax.net.ssl.keyStore=" + KEYSTORE_LOC);
 142             args.add("-Djavax.net.ssl.trustStore=" + TRUSTSTORE_LOC);
 143             args.add("-Djavax.net.ssl.keyStorePassword=password");
 144             args.add("-Djavax.net.ssl.trustStorePassword=trustword");
 145         }
 146         args.add(TEST_CLASS);
 147         args.add(address);
 148         args.add(Integer.toString(JMX_PORT));
 149         args.add(Integer.toString(RMI_PORT));
 150         args.add(Boolean.toString(useSSL));
 151         try {
 152             ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(args.toArray(new String[] {}));
 153             System.out.println(ProcessTools.getCommandLine(builder));
 154             ProcessThread jvm = new ProcessThread("JMX-Tester-" + address, JMXInterfaceBindingTest::isJMXAgentResponseAvailable, builder);
 155             return jvm;
 156         } catch (Exception e) {
 157             throw new RuntimeException("Test failed", e);
 158         }
 159 
 160     }
 161 
 162     private static boolean isJMXAgentResponseAvailable(String line) {
 163         if (line.equals(READY_MSG)) {
 164             System.out.println("DEBUG: Found expected READY_MSG.");
 165             return true;
 166         } else if (line.startsWith("Error:")) {
 167             // Allow for a JVM process that exits with
 168             // "Error: JMX connector server communication error: ..."
 169             // to continue as well since we handle that case elsewhere.
 170             // This has the effect that the test does not timeout and
 171             // fails with an exception in the test.
 172             System.err.println("PROBLEM: JMX agent of target JVM did not start as it should.");
 173             return true;
 174         } else {
 175             return false;
 176         }
 177     }
 178 
 179     public static void main(String[] args) {
 180         List<InetAddress> addrs = getAddressesForLocalHost();
 181         if (addrs.size() < 2) {
 182             System.out.println("Ignoring manual test since no more than one IPs are configured for 'localhost'");
 183             return;
 184         }
 185         JMXInterfaceBindingTest test = new JMXInterfaceBindingTest();
 186         test.run(addrs);
 187         System.out.println("All tests PASSED.");
 188     }
 189 
 190     private static List<InetAddress> getAddressesForLocalHost() {
 191 
 192         try {
 193             return NetworkInterface.networkInterfaces()
 194                 .flatMap(NetworkInterface::inetAddresses)
 195                 .filter(JMXInterfaceBindingTest::isNonloopbackLocalhost)
 196                 .collect(Collectors.toList());
 197         } catch (SocketException e) {
 198             throw new RuntimeException("Test failed", e);
 199         }
 200     }
 201 
 202     // we need 'real' localhost addresses only (eg. not loopback ones)
 203     // so we can bind the remote JMX connector to them
 204     private static boolean isNonloopbackLocalhost(InetAddress i) {
 205         if (!i.isLoopbackAddress()) {
 206             return i.getHostName().toLowerCase().equals("localhost");
 207         }
 208         return false;
 209     }
 210 }