1 /*
   2  * Copyright (c) 2003, 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 /*
  25  * @test
  26  * @bug 4886838 4886830 8025204
  27  * @summary Tests that idle timeouts happen at appropriate times
  28  * @author Eamonn McManus
  29  *
  30  * @modules java.management.rmi
  31  *          java.management/com.sun.jmx.remote.util
  32  *
  33  * @run clean IdleTimeoutTest
  34  * @run build IdleTimeoutTest
  35  * @run main IdleTimeoutTest
  36  */
  37 
  38 import java.util.Arrays;
  39 import java.util.ArrayList;
  40 import java.util.Iterator;
  41 import java.util.List;
  42 import java.util.HashMap;
  43 import java.util.Map;
  44 import javax.management.MBeanServer;
  45 import javax.management.MBeanServerConnection;
  46 import javax.management.MBeanServerFactory;
  47 import javax.management.MBeanServerNotification;
  48 import javax.management.Notification;
  49 import javax.management.NotificationListener;
  50 import javax.management.ObjectName;
  51 import javax.management.remote.JMXConnector;
  52 import javax.management.remote.JMXConnectorFactory;
  53 import javax.management.remote.JMXConnectorServer;
  54 import javax.management.remote.JMXConnectorServerFactory;
  55 import javax.management.remote.JMXServiceURL;
  56 import com.sun.jmx.remote.util.EnvHelp;
  57 
  58 public class IdleTimeoutTest {
  59 
  60     static boolean isPresent(String cn) {
  61         try {
  62             Class.forName(cn);
  63             return true;
  64         } catch (ClassNotFoundException x) {
  65             return false;
  66         }
  67     }
  68 
  69     public static void main(String[] args) throws Exception {
  70         boolean ok = true;
  71         List protos;
  72         if (args.length > 0)
  73             protos = Arrays.asList(args);
  74         else {
  75             protos = new ArrayList(Arrays.asList(new String[] {"rmi"}));
  76             if (isPresent("javax.management.remote.rmi._RMIConnectionImpl_Tie"))
  77                 protos.add("iiop");
  78             if (isPresent("javax.management.remote.jmxmp.JMXMPConnectorServer"))
  79                 protos.add("jmxmp");
  80         }
  81         for (Iterator it = protos.iterator(); it.hasNext(); ) {
  82             String proto = (String) it.next();
  83             int liCount;
  84             if (proto.equals("jmxmp")) liCount=1;
  85             else liCount=2;
  86             if (test(proto,4,liCount))
  87                 System.out.println("Test for protocol " + proto + " passed");
  88             else {
  89                 System.out.println("Test for protocol " + proto + " FAILED");
  90                 ok = false;
  91             }
  92         }
  93         if (!ok) {
  94             throw new RuntimeException("Some tests failed - see log for details");
  95         }
  96     }
  97 
  98     private static long getIdleTimeout(MBeanServer mbs, JMXServiceURL url)
  99         throws Exception
 100     {
 101         JMXConnectorServer server =
 102             JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
 103         server.start();
 104         try {
 105             url = server.getAddress();
 106 
 107             // Force initialization (class loading, JIT, etc...)
 108             //
 109             JMXConnector client = JMXConnectorFactory.connect(url);
 110             try {
 111                 String connId = client.getConnectionId();
 112                 MBeanServerConnection conn = client.getMBeanServerConnection();
 113             } finally {
 114                 client.close();
 115             }
 116 
 117             // Do the time measurement
 118             //
 119             final long firstTime = System.currentTimeMillis();
 120             final long endtime;
 121             client = JMXConnectorFactory.connect(url);
 122             try {
 123                 String connId = client.getConnectionId();
 124                 MBeanServerConnection conn = client.getMBeanServerConnection();
 125                 endtime = System.currentTimeMillis();
 126             } finally {
 127                 client.close();
 128             }
 129 
 130             // multipled by 10 for a slow machine, plus 1500 for a fast one.
 131             return 10*(endtime - firstTime) + 1500;
 132         } finally {
 133             server.stop();
 134         }
 135     }
 136 
 137     private static class NotificationCounter
 138         implements NotificationListener {
 139         private final int[]  listenerCount;
 140         private final String listenerName;
 141         NotificationCounter(int[] counter, String name) {
 142             listenerCount=counter;
 143             listenerName=name;
 144         }
 145 
 146         public void handleNotification(Notification n,
 147                                        Object h) {
 148             MBeanServerNotification mbsn =
 149                 (MBeanServerNotification) n;
 150             System.out.println(listenerName + " got notification: "
 151                                + mbsn.getMBeanName());
 152             synchronized (listenerCount) {
 153                 listenerCount[0]++;
 154                 listenerCount.notify();
 155             }
 156         }
 157         public String toString() {
 158             return listenerName;
 159         }
 160     }
 161 
 162     private static boolean test(String proto,int opCount,int liCount)
 163         throws Exception {
 164         System.out.println("Idle timeout test for protocol " + proto);
 165         ObjectName delegateName =
 166             ObjectName.getInstance("JMImplementation:" +
 167                                    "type=MBeanServerDelegate");
 168         MBeanServer mbs = MBeanServerFactory.createMBeanServer();
 169         JMXServiceURL url = new JMXServiceURL("service:jmx:" + proto + "://");
 170 
 171         final long timeout = getIdleTimeout(mbs,url);
 172         System.out.println("Timeout for " + proto + " is: " +
 173                            timeout + " ms");
 174 
 175         Map idleMap = new HashMap();
 176         idleMap.put(EnvHelp.SERVER_CONNECTION_TIMEOUT, new Long(timeout));
 177         JMXConnectorServer server =
 178             JMXConnectorServerFactory.newJMXConnectorServer(url,idleMap,mbs);
 179 
 180         final int[] listenerCount = new int[1];
 181         final NotificationListener countListeners[] =
 182             new NotificationListener[liCount];
 183         int i;
 184         for (i=0; i<countListeners.length; i++) {
 185             countListeners[i] =
 186                 new NotificationCounter(listenerCount,"Listener"+i);
 187         }
 188 
 189         server.start();
 190         try {
 191             url = server.getAddress();
 192             final long firstTime = System.currentTimeMillis();
 193             JMXConnector client = JMXConnectorFactory.connect(url);
 194             long elapsed, startIdle=0;
 195             try {
 196                 String connId = client.getConnectionId();
 197                 MBeanServerConnection conn =
 198                     client.getMBeanServerConnection();
 199                 elapsed   = System.currentTimeMillis() - firstTime;
 200                 System.out.println("Idle Time: " + elapsed + "ms");
 201 
 202                 for (i=0; i<countListeners.length; i++) {
 203                     System.out.println("add " + countListeners[i] +
 204                                        ": starting at " + elapsed + "ms");
 205                     conn.addNotificationListener(delegateName,
 206                                                  countListeners[i],
 207                                                  null,null);
 208                 }
 209 
 210                 System.out.println("connId=" + connId);
 211                 for (i = 0; i < opCount; i++) {
 212                     elapsed   = System.currentTimeMillis() - firstTime;
 213                     System.out.println("Operation[" + (i+1)
 214                                        +"]: starting at " +
 215                                        elapsed + "ms");
 216                     final String name = "d:type=mlet,instance=" + i;
 217                     mbs.createMBean("javax.management.loading.MLet",
 218                                     new ObjectName(name));
 219                     if (i == (opCount-1))
 220                         startIdle = System.currentTimeMillis();
 221                     Thread.sleep(2);
 222                 }
 223 
 224                 // Wait for notifs to arrive before doing removeNListener
 225                 long startTime = System.currentTimeMillis();
 226                 long deadline = startTime + 10000;
 227 
 228                 System.out.println("Waiting for notifs: starting at " +
 229                                    (startTime - firstTime) + "ms");
 230 
 231                 final int expectedCount = opCount*countListeners.length;
 232                 while (System.currentTimeMillis() < deadline) {
 233                     synchronized (listenerCount) {
 234                         if (listenerCount[0] >= expectedCount)
 235                             break;
 236                         listenerCount.wait();
 237                     }
 238                 }
 239 
 240                 long elapsedWait = System.currentTimeMillis() - startTime;
 241                 System.out.println("Waited " + elapsedWait +
 242                                    "ms for notifs to arrive");
 243 
 244                 if (listenerCount[0] != expectedCount) {
 245                     System.out.println("Did not get expected " +
 246                                        expectedCount + " notifications: "
 247                                        + listenerCount[0]);
 248                     return false;
 249                 }
 250 
 251                 elapsed   = System.currentTimeMillis() - firstTime;
 252 
 253                 System.out.println("idle time since last operation: " +
 254                                    (elapsed + firstTime - startIdle) + "ms");
 255                 System.out.println("Requesting conn id at: " +
 256                                    elapsed + "ms");
 257                 final String cid = client.getConnectionId();
 258 
 259                 elapsed   = System.currentTimeMillis() - firstTime;
 260                 System.out.println("Got conn id <" + cid + "> at: " +
 261                                    elapsed + "ms");
 262 
 263                 if (!connId.equals(cid)) {
 264                     System.out.println("Client id changed: <" + connId +
 265                                        "> -> <" + cid +
 266                                        ">");
 267                     return false;
 268                 }
 269 
 270                 List ids = Arrays.asList(server.getConnectionIds());
 271                 if (!ids.contains(connId)) {
 272                     System.out.println("Server ids don't contain our id: " +
 273                                        ids + " - " + connId);
 274                     return false;
 275                 }
 276 
 277                 for (i=0;i<countListeners.length;i++) {
 278                     System.out.println("Removing notification listener: " +
 279                                        countListeners[i]);
 280                     conn.removeNotificationListener(delegateName,
 281                                                     countListeners[i]);
 282                 }
 283 
 284                 System.out.println("Waiting for id list to drop ours");
 285                 // pass or timed out by test harness - see 8025204
 286                 do {
 287                    Thread.sleep(100);
 288                    ids = Arrays.asList(server.getConnectionIds());
 289                 } while (ids.contains(connId));
 290 
 291                 conn.getDefaultDomain();
 292                 if (connId.equals(client.getConnectionId())) {
 293                     System.out.println("Client id did not change: <" + connId +
 294                                        ">: idle timeout did not happen?");
 295                     return false;
 296                 } else {
 297                     System.out.println("Client id changed as expected: <" +
 298                                        connId + "> -> <" +
 299                                        client.getConnectionId() + ">");
 300                 }
 301             } finally {
 302                 client.close();
 303                 System.out.println("Connection id list on server after " +
 304                                    "client close: " +
 305                                    Arrays.asList(server.getConnectionIds()));
 306             }
 307         } finally {
 308             server.stop();
 309         }
 310         System.out.println("*** ------------------------------------------");
 311         System.out.println("*** Test passed for " + proto);
 312         System.out.println("*** ------------------------------------------");
 313         return true;
 314     }
 315 }