1 /*
   2  * Copyright (c) 2012, 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 
  24 import java.io.File;
  25 import java.io.IOException;
  26 import java.lang.reflect.InvocationTargetException;
  27 import java.lang.reflect.Method;
  28 import java.net.BindException;
  29 import java.net.ConnectException;
  30 import java.net.ServerSocket;
  31 import java.rmi.RemoteException;
  32 import java.rmi.registry.LocateRegistry;
  33 import java.rmi.registry.Registry;
  34 import java.util.ArrayList;
  35 import java.util.Arrays;
  36 import java.util.List;
  37 import java.util.Objects;
  38 import java.util.Random;
  39 import java.util.Set;
  40 import java.util.concurrent.TimeUnit;
  41 import java.util.concurrent.TimeoutException;
  42 import java.util.concurrent.atomic.AtomicBoolean;
  43 import java.util.function.Consumer;
  44 import java.util.stream.Collectors;
  45 
  46 import javax.management.*;
  47 import javax.management.remote.*;
  48 import javax.net.ssl.SSLHandshakeException;
  49 
  50 import jdk.testlibrary.ProcessTools;
  51 import jdk.testlibrary.JDKToolLauncher;
  52 import sun.management.Agent;
  53 import sun.management.AgentConfigurationError;
  54 
  55 /**
  56  * @test
  57  * @bug 7110104
  58  * @library /lib/testlibrary
  59  * @build jdk.testlibrary.* JMXStartStopTest JMXStartStopDoSomething
  60  * @run main/othervm/timeout=600 -XX:+UsePerfData JMXStartStopTest
  61  * @summary Makes sure that enabling/disabling the management agent through JCMD
  62  *          achieves the desired results
  63  */
  64 public class JMXStartStopTest {
  65 
  66     private static final String TEST_SRC = System.getProperty("test.src");
  67 
  68     private static final boolean verbose = false;
  69 
  70     /**
  71      * Dynamically allocates distinct ports from the ephemeral range 49152-65535
  72      */
  73     private static class PortAllocator {
  74 
  75         private final static int LOWER_BOUND = 49152;
  76         private final static int UPPER_BOUND = 65535;
  77 
  78         private final static Random RND = new Random(System.currentTimeMillis());
  79 
  80         private static int[] allocatePorts(final int numPorts) {
  81             int[] ports = new int[numPorts];
  82             for (int i = 0; i < numPorts; i++) {
  83                 int port = -1;
  84                 while (port == -1) {
  85                     port = RND.nextInt(UPPER_BOUND - LOWER_BOUND + 1) + LOWER_BOUND;
  86                     for (int j = 0; j < i; j++) {
  87                         if (ports[j] == port) {
  88                             port = -1;
  89                             break;
  90                         }
  91                     }
  92                 }
  93                 ports[i] = port;
  94             }
  95             return ports;
  96         }
  97     }
  98 
  99     private static void dbg_print(String msg) {
 100         if (verbose) {
 101             System.out.println("DBG: " + msg);
 102         }
 103     }
 104 
 105     private static int listMBeans(MBeanServerConnection server,
 106             ObjectName pattern,
 107             QueryExp query)
 108             throws Exception {
 109 
 110         Set<ObjectName> names = server.queryNames(pattern,query);
 111         for (ObjectName name : names) {
 112             MBeanInfo info = server.getMBeanInfo(name);
 113             dbg_print("Got MBean: " + name);
 114 
 115             MBeanAttributeInfo[] attrs = info.getAttributes();
 116             if (attrs == null)
 117                 continue;
 118             for (MBeanAttributeInfo attr : attrs) {
 119                 if (attr.isReadable()) {
 120                     server.getAttribute(name, attr.getName());
 121                 }
 122             }
 123         }
 124         return names.size();
 125     }
 126 
 127     private static void testConnectLocal(long pid)
 128             throws Exception {
 129 
 130         String jmxUrlStr = null;
 131 
 132         try {
 133             jmxUrlStr = sun.management.ConnectorAddressLink.importFrom((int)pid);
 134             dbg_print("Local Service URL: " +jmxUrlStr);
 135             if ( jmxUrlStr == null ) {
 136                 throw new Exception("No Service URL. Local agent not started?");
 137             }
 138 
 139             JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
 140 
 141             JMXConnector c = JMXConnectorFactory.connect(url, null);
 142 
 143             MBeanServerConnection conn = c.getMBeanServerConnection();
 144             ObjectName pattern = new ObjectName("java.lang:type=Memory,*");
 145 
 146             int count = listMBeans(conn,pattern,null);
 147             if (count == 0)
 148                 throw new Exception("Expected at least one matching "+
 149                                     "MBean for "+pattern);
 150 
 151         } catch (IOException e) {
 152             dbg_print("Cannot find process : " + pid);
 153             throw e;
 154         }
 155     }
 156 
 157     private static void testNoConnect(int port) throws Exception {
 158         testNoConnect(port, 0);
 159     }
 160 
 161     private static void testNoConnect(int port, int rmiPort) throws Exception {
 162         try {
 163             testConnect(port, rmiPort);
 164             throw new Exception("Didn't expect the management agent running");
 165         } catch (Exception e) {
 166             Throwable t = e;
 167             while (t != null) {
 168                 if (t instanceof RemoteException ||
 169                     t instanceof SSLHandshakeException ||
 170                     t instanceof ConnectException) {
 171                     break;
 172                 }
 173                 t = t.getCause();
 174             }
 175             if (t == null) {
 176                 throw new Exception("Unexpected exception", e);
 177             }
 178         }
 179     }
 180 
 181     private static void testConnect(int port) throws Exception {
 182         testConnect(port, 0);
 183     }
 184 
 185     private static void testConnect(int port, int rmiPort) throws Exception {
 186 
 187         dbg_print("RmiRegistry lookup...");
 188 
 189         dbg_print("Using port: " + port);
 190 
 191         dbg_print("Using rmi port: " + rmiPort);
 192 
 193         Registry registry = LocateRegistry.getRegistry(port);
 194 
 195         // "jmxrmi"
 196         String[] relist = registry.list();
 197         for (int i = 0; i < relist.length; ++i) {
 198             dbg_print("Got registry: " + relist[i]);
 199         }
 200 
 201         String jmxUrlStr = (rmiPort != 0) ?
 202             String.format(
 203                         "service:jmx:rmi://localhost:%d/jndi/rmi://localhost:%d/jmxrmi",
 204                         rmiPort,
 205                 port) :
 206             String.format(
 207                         "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
 208                         port);
 209 
 210         JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
 211 
 212         JMXConnector c = JMXConnectorFactory.connect(url, null);
 213 
 214         MBeanServerConnection conn = c.getMBeanServerConnection();
 215         ObjectName pattern = new ObjectName("java.lang:type=Memory,*");
 216 
 217         int count = listMBeans(conn,pattern,null);
 218         if (count == 0)
 219             throw new Exception("Expected at least one matching " +
 220                                 "MBean for " + pattern);
 221     }
 222 
 223     private static class Failure {
 224         private final Throwable cause;
 225         private final String msg;
 226 
 227         public Failure(Throwable cause, String msg) {
 228             this.cause = cause;
 229             this.msg = msg;
 230         }
 231 
 232         public Failure(String msg) {
 233             this(null, msg);
 234         }
 235 
 236         public Throwable getCause() {
 237             return cause;
 238         }
 239 
 240         public String getMsg() {
 241             return msg;
 242         }
 243 
 244         @Override
 245         public int hashCode() {
 246             int hash = 7;
 247             hash = 97 * hash + Objects.hashCode(this.cause);
 248             hash = 97 * hash + Objects.hashCode(this.msg);
 249             return hash;
 250         }
 251 
 252         @Override
 253         public boolean equals(Object obj) {
 254             if (obj == null) {
 255                 return false;
 256             }
 257             if (getClass() != obj.getClass()) {
 258                 return false;
 259             }
 260             final Failure other = (Failure) obj;
 261             if (!Objects.equals(this.cause, other.cause)) {
 262                 return false;
 263             }
 264             if (!Objects.equals(this.msg, other.msg)) {
 265                 return false;
 266             }
 267             return true;
 268         }
 269 
 270         @Override
 271         public String toString() {
 272             if (cause != null) {
 273                 return msg + "\n" + cause;
 274             } else {
 275                 return msg;
 276             }
 277         }
 278     }
 279 
 280     private static List<Failure> failures = new ArrayList<>();
 281 
 282     public static void main(String args[]) throws Exception {
 283         for (Method m : JMXStartStopTest.class.getDeclaredMethods()) {
 284             if (m.getName().startsWith("test_")) {
 285                 long t1 = System.currentTimeMillis();
 286                 try {
 287                     boolean retry = false;
 288                     do {
 289                         try {
 290                             m.invoke(null);
 291                             retry = false;
 292                         } catch (InvocationTargetException e) {
 293                             if (e.getCause() instanceof BindException ||
 294                                 e.getCause() instanceof java.rmi.ConnectException) {
 295                                 System.out.println("Failed to allocate ports. Retrying ...");
 296                                 retry = true;
 297                             } else {
 298                                 throw e;
 299                             }
 300                         }
 301                     } while (retry);
 302                     System.out.println("=== PASSED");
 303                 } catch (Throwable e) {
 304                     failures.add(new Failure(e, m.getName() + " failed"));
 305                 } finally {
 306                     System.out.println("(took " + (System.currentTimeMillis() - t1) + "ms)\n");
 307                 }
 308             }
 309         }
 310 
 311         if (!failures.isEmpty()) {
 312             for(Failure f : failures) {
 313                 System.err.println(f.getMsg());
 314                 f.getCause().printStackTrace(System.err);
 315             }
 316             throw new Error();
 317         }
 318     }
 319 
 320     private static class Something {
 321         private Process p;
 322         private final ProcessBuilder pb;
 323         private final String name;
 324         private final AtomicBoolean started = new AtomicBoolean(false);
 325         private volatile long pid = -1;
 326 
 327         public Something(ProcessBuilder pb, String name) {
 328             this.pb = pb;
 329             this.name = name;
 330         }
 331 
 332         public synchronized void start() throws InterruptedException, IOException, TimeoutException {
 333             if (started.compareAndSet(false, true)) {
 334                 try {
 335                     AtomicBoolean error = new AtomicBoolean(false);
 336                     p = ProcessTools.startProcess(
 337                             "JMXStartStopDoSomething{" + name + "}",
 338                             pb,
 339                             (line) -> {
 340                                 boolean ok = line.equals("main enter");
 341                                 error.set(line.contains("BindException"));
 342 
 343                                 return ok || error.get();
 344                             },
 345                             5,
 346                             TimeUnit.SECONDS
 347                     );
 348                     if (error.get()) {
 349                         throw new BindException("Starting process failed due to " +
 350                                                 "the requested port not being available");
 351                     }
 352                     pid = p.getPid();
 353                 } catch (TimeoutException e) {
 354                     p.destroy();
 355                     p.waitFor();
 356                     throw e;
 357                 }
 358             }
 359         }
 360 
 361         public long getPid() {
 362             return pid;
 363         }
 364 
 365         public synchronized void stop()
 366                 throws IOException, InterruptedException {
 367             if (started.compareAndSet(true, false)) {
 368                 p.getOutputStream().write(0);
 369                 p.getOutputStream().flush();
 370                 int ec = p.waitFor();
 371                 if (ec != 0) {
 372                     StringBuilder msg = new StringBuilder();
 373                     msg.append("Test application '").append(name);
 374                     msg.append("' failed with exit code: ");
 375                     msg.append(ec);
 376 
 377                     failures.add(new Failure(msg.toString()));
 378                 }
 379             }
 380         }
 381     }
 382 
 383     /**
 384      * Runs the test application "JMXStartStopDoSomething"
 385      * @param name Test run name
 386      * @param args Additional arguments
 387      * @return Returns a {@linkplain Something} instance representing the run
 388      * @throws IOException
 389      * @throws InterruptedException
 390      * @throws TimeoutException
 391      */
 392     private static Something doSomething(String name, String ... args)
 393             throws Exception {
 394         List<String> pbArgs = new ArrayList<>(Arrays.asList(
 395                 "-cp",
 396                 System.getProperty("test.class.path")
 397         ));
 398         pbArgs.addAll(Arrays.asList(args));
 399         pbArgs.add("JMXStartStopDoSomething");
 400 
 401         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
 402                 pbArgs.toArray(new String[pbArgs.size()])
 403         );
 404         Something s = new Something(pb, name);
 405         s.start();
 406         return s;
 407     }
 408 
 409     /**
 410      * Run the "jcmd" command
 411      *
 412      * @param command Command with parameters; space separated string
 413      * @throws IOException
 414      * @throws InterruptedException
 415      */
 416     private static void jcmd(String ... command) throws IOException, InterruptedException {
 417         if (command.length == 0) {
 418             jcmd(null, c->{});
 419         } else {
 420             jcmd(null, command);
 421         }
 422     }
 423 
 424     /**
 425      * Run the "jcmd" command
 426      *
 427      * @param c {@linkplain Consumer} instance
 428      * @param command Command with parameters; space separated string
 429      * @throws IOException
 430      * @throws InterruptedException
 431      */
 432     private static void jcmd(Consumer<String> c, String ... command) throws IOException, InterruptedException {
 433         jcmd("JMXStartStopDoSomething", c, command);
 434     }
 435 
 436     /**
 437      * Run the "jcmd" command
 438      *
 439      * @param target The target application name (or PID)
 440      * @param c {@linkplain Consumer} instance
 441      * @param command Command with parameters; space separated string
 442      * @throws IOException
 443      * @throws InterruptedException
 444      */
 445     private static void jcmd(String target, final Consumer<String> c, String ... command) throws IOException, InterruptedException {
 446         dbg_print("[jcmd] " + (command.length > 0 ? command[0] : "list"));
 447 
 448         JDKToolLauncher l = JDKToolLauncher.createUsingTestJDK("jcmd");
 449         l.addToolArg(target);
 450         for (String cmd : command) {
 451             l.addToolArg(cmd);
 452         }
 453 
 454         AtomicBoolean portUnavailable = new AtomicBoolean(false);
 455         Process p = ProcessTools.startProcess(
 456             "jcmd",
 457             new ProcessBuilder(l.getCommand()),
 458             line -> {
 459                 if (line.contains("BindException") ||
 460                     line.contains(Agent.getText(AgentConfigurationError.CONNECTOR_SERVER_IO_ERROR))) {
 461                     portUnavailable.set(true);
 462                 } else {
 463                     c.accept(line);
 464                 }
 465             }
 466         );
 467 
 468         p.waitFor();
 469         dbg_print("[jcmd] --------");
 470         if (portUnavailable.get()) {
 471             String cmd = Arrays.asList(l.getCommand()).stream()
 472                     .collect(
 473                             Collectors.joining(" ", "", ": Unable to bind address")
 474                     );
 475             throw new BindException(cmd);
 476         }
 477     }
 478 
 479     private static final String CMD_STOP = "ManagementAgent.stop";
 480     private static final String CMD_START = "ManagementAgent.start";
 481     private static final String CMD_START_LOCAL = "ManagementAgent.start_local";
 482 
 483     static void test_01() throws Exception {
 484         // Run an app with JMX enabled stop it and
 485         // restart on other port
 486 
 487         System.out.println("**** Test one ****");
 488         int ports[] = PortAllocator.allocatePorts(2);
 489 
 490         Something s = doSomething(
 491                 "test_01",
 492                 "-Dcom.sun.management.jmxremote.port=" + ports[0],
 493                 "-Dcom.sun.management.jmxremote.authenticate=false",
 494                 "-Dcom.sun.management.jmxremote.ssl=false");
 495 
 496         try {
 497             testConnect(ports[0]);
 498 
 499             jcmd(CMD_STOP);
 500             testNoConnect(ports[0]);
 501 
 502             jcmd(CMD_START, "jmxremote.port=" + ports[1]);
 503             testConnect(ports[1]);
 504         } finally {
 505             s.stop();
 506         }
 507     }
 508 
 509     static void test_02() throws Exception {
 510         // Run an app without JMX enabled
 511         // start JMX by jcmd
 512 
 513         System.out.println("**** Test two ****");
 514 
 515         int[] ports = PortAllocator.allocatePorts(1);
 516         Something s = doSomething("test_02");
 517         try {
 518             jcmd(CMD_START,
 519                     "jmxremote.port=" + ports[0],
 520                     "jmxremote.authenticate=false",
 521                     "jmxremote.ssl=false");
 522 
 523             testConnect(ports[0]);
 524         } finally {
 525 //            debugPortUsage(pa);
 526             s.stop();
 527         }
 528     }
 529 
 530     static void test_03() throws Exception {
 531         // Run an app without JMX enabled
 532         // start JMX by jcmd on one port than on other one
 533 
 534         System.out.println("**** Test three ****");
 535 
 536         int[] ports = PortAllocator.allocatePorts(2);
 537         Something s = doSomething("test_03");
 538         try {
 539             jcmd(CMD_START,
 540                     "jmxremote.port=" + ports[0],
 541                     "jmxremote.authenticate=false",
 542                     "jmxremote.ssl=false");
 543 
 544             // Second agent shouldn't start
 545             jcmd(CMD_START,
 546                     "jmxremote.port=" + ports[1],
 547                     "jmxremote.authenticate=false",
 548                     "jmxremote.ssl=false");
 549 
 550             // First agent should connect
 551             testConnect(ports[0]);
 552 
 553             // Second agent should not connect
 554             testNoConnect(ports[1]);
 555         } finally {
 556             s.stop();
 557         }
 558     }
 559 
 560     static void test_04() throws Exception {
 561         // Run an app without JMX enabled
 562         // start JMX by jcmd on one port, specify rmi port explicitly
 563 
 564         System.out.println("**** Test four ****");
 565 
 566         int[] ports = PortAllocator.allocatePorts(2);
 567         Something s = doSomething("test_04");
 568         try {
 569             jcmd(CMD_START,
 570                     "jmxremote.port=" + ports[0],
 571                     "jmxremote.rmi.port=" + ports[1],
 572                     "jmxremote.authenticate=false",
 573                     "jmxremote.ssl=false");
 574 
 575             testConnect(ports[0], ports[1]);
 576         } finally {
 577             s.stop();
 578         }
 579     }
 580 
 581     static void test_05() throws Exception {
 582         // Run an app without JMX enabled, it will enable local server
 583         // but should leave remote server disabled
 584 
 585         System.out.println("**** Test five ****");
 586         int[] ports = PortAllocator.allocatePorts(1);
 587         Something s = doSomething("test_05");
 588         try {
 589             jcmd(CMD_START_LOCAL);
 590 
 591             testNoConnect(ports[0]);
 592             testConnectLocal(s.getPid());
 593         } finally {
 594             s.stop();
 595         }
 596     }
 597 
 598     static void test_06() throws Exception {
 599         // Run an app without JMX enabled
 600         // start JMX by jcmd on one port, specify rmi port explicitly
 601         // attempt to start it again with the same port
 602         // Check for valid messages in the output
 603 
 604         System.out.println("**** Test six ****");
 605 
 606         int[] ports = PortAllocator.allocatePorts(2);
 607         Something s = doSomething("test_06");
 608         try {
 609             jcmd(CMD_START,
 610                     "jmxremote.port=" + ports[0],
 611                     "jmxremote.authenticate=false",
 612                     "jmxremote.ssl=false");
 613 
 614             testConnect(ports[0], ports[1]);
 615 
 616             final AtomicBoolean checks = new AtomicBoolean(false);
 617             jcmd(
 618                     line -> {
 619                         if (line.contains("java.lang.RuntimeException: Invalid agent state")) {
 620                             checks.set(true);
 621                         }
 622                     },
 623                     CMD_START,
 624                     "jmxremote.port=" + ports[0],
 625                     "jmxremote.authenticate=false",
 626                     "jmxremote.ssl=false");
 627 
 628             if (!checks.get()) {
 629                 throw new Exception("Starting agent on port " + ports[0] + " should "
 630                         + "report an invalid agent state");
 631             }
 632         } finally {
 633             s.stop();
 634         }
 635     }
 636 
 637     static void test_07() throws Exception {
 638         // Run an app without JMX enabled
 639         // start JMX by jcmd on one port, specify rmi port explicitly
 640         // attempt to start it again with other port
 641         // Check for valid messages in the output
 642 
 643         System.out.println("**** Test seven ****");
 644 
 645         int[] ports = PortAllocator.allocatePorts(2);
 646         Something s = doSomething("test_07");
 647         try {
 648             jcmd(CMD_START,
 649                     "jmxremote.port=" + ports[0],
 650                     "jmxremote.authenticate=false",
 651                     "jmxremote.ssl=false");
 652 
 653             testConnect(ports[0], ports[1]);
 654 
 655             final AtomicBoolean checks = new AtomicBoolean(false);
 656 
 657             jcmd(
 658                     line -> {
 659                         if (line.contains("java.lang.RuntimeException: Invalid agent state")) {
 660                             checks.set(true);
 661                         }
 662                     },
 663                     CMD_START,
 664                     "jmxremote.port=" + ports[1],
 665                     "jmxremote.authenticate=false",
 666                     "jmxremote.ssl=false");
 667 
 668             if (!checks.get()) {
 669                 throw new Exception("Starting agent on poprt " + ports[1] + " should "
 670                         + "report an invalid agent state");
 671             }
 672         } finally {
 673             s.stop();
 674         }
 675     }
 676 
 677     static void test_08() throws Exception {
 678         // Run an app without JMX enabled
 679         // start JMX by jcmd on one port, specify rmi port explicitly
 680         // attempt to stop it twice
 681         // Check for valid messages in the output
 682 
 683         System.out.println("**** Test eight ****");
 684 
 685         int[] ports = PortAllocator.allocatePorts(2);
 686         Something s = doSomething("test_08");
 687         try {
 688             jcmd(CMD_START,
 689                     "jmxremote.port=" + ports[0],
 690                     "jmxremote.authenticate=false",
 691                     "jmxremote.ssl=false");
 692 
 693             testConnect(ports[0], ports[1]);
 694 
 695             jcmd(CMD_STOP);
 696             jcmd(CMD_STOP);
 697         } finally {
 698             s.stop();
 699         }
 700     }
 701 
 702     static void test_09() throws Exception {
 703         // Run an app without JMX enabled
 704         // attempt to start JMX using a non-available port
 705         // Check for valid messages in the output
 706 
 707         System.out.println("**** Test nine ****");
 708 
 709         Something s = doSomething("test_09");
 710 
 711         try (ServerSocket ss = new ServerSocket(0)) {
 712             int localPort = ss.getLocalPort();
 713             int[] ports;
 714             do {
 715                 ports = PortAllocator.allocatePorts(1);
 716             } while (localPort == ports[0]);
 717 
 718             final AtomicBoolean checks = new AtomicBoolean(false);
 719 
 720             int retryCntr = 1;
 721             do {
 722                 final AtomicBoolean retry = new AtomicBoolean(false);
 723 
 724                 try {
 725                     jcmd(
 726                         line -> {
 727                             if (line.contains(Agent.getText(AgentConfigurationError.AGENT_EXCEPTION))) {
 728                                 retry.set(true);
 729                             }
 730                         },
 731                         CMD_START,
 732                         "jmxremote.port=" + ports[0],
 733                         "jmxremote.rmi.port=" + localPort,
 734                         "jmxremote.authenticate=false",
 735                         "jmxremote.ssl=false"
 736                     );
 737                 } catch (BindException e) {
 738                     checks.set(true);
 739                 }
 740                 if (!retry.get()) {
 741                     break;
 742                 }
 743                 System.out.println("Attempt " + retryCntr + " >>>");
 744                 System.out.println("Unexpected reply from the agent. Retrying in 500ms ...");
 745                 Thread.sleep(500);
 746             } while (retryCntr++ < 10);
 747 
 748             if (!checks.get()) {
 749                 throw new Exception("Starting agent on port " + ports[0] + " should "
 750                         + "report port in use");
 751             }
 752         } finally {
 753             s.stop();
 754         }
 755 
 756     }
 757 
 758     static void test_10() throws Exception {
 759         // Run an app without JMX enabled, but with some properties set
 760         // in command line.
 761         // make sure these properties overridden corectly
 762 
 763         System.out.println("**** Test ten ****");
 764 
 765         int[] ports = PortAllocator.allocatePorts(2);
 766         Something s = doSomething(
 767                 "test_10",
 768                 "-Dcom.sun.management.jmxremote.authenticate=false",
 769                 "-Dcom.sun.management.jmxremote.ssl=true");
 770 
 771         try {
 772             testNoConnect(ports[0]);
 773             jcmd(
 774                     CMD_START,
 775                     "jmxremote.port=" + ports[1],
 776                     "jmxremote.authenticate=false",
 777                     "jmxremote.ssl=false"
 778             );
 779             testConnect(ports[1]);
 780         } finally {
 781             s.stop();
 782         }
 783     }
 784 
 785     static void test_11() throws Exception {
 786         // Run an app with JMX enabled and with some properties set
 787         // in command line.
 788         // stop JMX agent and then start it again with different property values
 789         // make sure these properties overridden corectly
 790 
 791         System.out.println("**** Test eleven ****");
 792         int[] ports = PortAllocator.allocatePorts(2);
 793         Something s = doSomething(
 794                 "test_11",
 795                 "-Dcom.sun.management.jmxremote.port=" + ports[0],
 796                 "-Dcom.sun.management.jmxremote.authenticate=false",
 797                 "-Dcom.sun.management.jmxremote.ssl=true");
 798 
 799         try {
 800             testNoConnect(ports[0]);
 801 
 802             jcmd(CMD_STOP);
 803 
 804             testNoConnect(ports[0]);
 805 
 806             jcmd(
 807                     CMD_START,
 808                     "jmxremote.port=" + ports[1],
 809                     "jmxremote.authenticate=false",
 810                     "jmxremote.ssl=false"
 811             );
 812 
 813             testConnect(ports[1]);
 814         } finally {
 815             s.stop();
 816         }
 817     }
 818 
 819     static void test_12() throws Exception {
 820         // Run an app with JMX enabled and with some properties set
 821         // in command line.
 822         // stop JMX agent and then start it again with different property values
 823         // specifing some property in management config file and some of them
 824         // in command line
 825         // make sure these properties overridden corectly
 826 
 827         System.out.println("**** Test twelve ****");
 828 
 829         int[] ports = PortAllocator.allocatePorts(2);
 830         Something s = doSomething("test_12",
 831                 "-Dcom.sun.management.config.file="
 832                 + TEST_SRC + File.separator + "management_cl.properties",
 833                 "-Dcom.sun.management.jmxremote.authenticate=false"
 834         );
 835 
 836         try {
 837             testNoConnect(ports[0]);
 838 
 839             jcmd(CMD_STOP);
 840 
 841             testNoConnect(ports[0]);
 842 
 843             jcmd(CMD_START,
 844                     "config.file=" + TEST_SRC + File.separator
 845                     + "management_jcmd.properties",
 846                     "jmxremote.authenticate=false",
 847                     "jmxremote.port=" + ports[1]
 848             );
 849 
 850             testConnect(ports[1]);
 851         } finally {
 852             s.stop();
 853         }
 854     }
 855 
 856     static void test_13() throws Exception {
 857         // Run an app with JMX enabled and with some properties set
 858         // in command line.
 859         // stop JMX agent and then start it again with different property values
 860         // stop JMX agent again and then start it without property value
 861         // make sure these properties overridden corectly
 862 
 863         System.out.println("**** Test thirteen ****");
 864         int[] ports = PortAllocator.allocatePorts(1);
 865         Something s = doSomething(
 866                 "test_13",
 867                 "-Dcom.sun.management.jmxremote.port=" + ports[0],
 868                 "-Dcom.sun.management.jmxremote.authenticate=false",
 869                 "-Dcom.sun.management.jmxremote.ssl=true");
 870 
 871         try {
 872             testNoConnect(ports[0]);
 873 
 874             jcmd(CMD_STOP);
 875             jcmd(CMD_START,
 876                     "jmxremote.ssl=false",
 877                     "jmxremote.port=" + ports[0]
 878             );
 879             testConnect(ports[0]);
 880 
 881             jcmd(CMD_STOP);
 882             jcmd(CMD_START,
 883                     "jmxremote.port=" + ports[0]
 884             );
 885 
 886             testNoConnect(ports[0]);
 887         } finally {
 888             s.stop();
 889         }
 890     }
 891 
 892     static void test_14() throws Exception {
 893         // Run an app with JMX enabled
 894         // stop remote agent
 895         // make sure local agent is not affected
 896 
 897         System.out.println("**** Test fourteen ****");
 898         int[] ports = PortAllocator.allocatePorts(1);
 899         Something s = doSomething(
 900                 "test_14",
 901                 "-Dcom.sun.management.jmxremote.port=" + ports[0],
 902                 "-Dcom.sun.management.jmxremote.authenticate=false",
 903                 "-Dcom.sun.management.jmxremote.ssl=false");
 904         try {
 905             testConnect(ports[0]);
 906             jcmd(CMD_STOP);
 907             testConnectLocal(s.getPid());
 908         } finally {
 909             s.stop();
 910         }
 911     }
 912 
 913     static void test_15() throws Exception {
 914         // Run an app with JMX disabled
 915         // start local agent only
 916 
 917         System.out.println("**** Test fifteen ****");
 918 
 919         int[] ports = PortAllocator.allocatePorts(1);
 920         Something s = doSomething("test_15");
 921 
 922         try {
 923             testNoConnect(ports[0]);
 924             jcmd(CMD_START + "_local");
 925 
 926             testConnectLocal(s.getPid());
 927 
 928         } finally {
 929             s.stop();
 930         }
 931     }
 932 
 933 }