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