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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package sun.management.jdp;
  26 
  27 import java.io.IOException;
  28 import java.net.InetAddress;
  29 import java.net.UnknownHostException;
  30 import java.util.UUID;
  31 
  32 import java.lang.management.ManagementFactory;
  33 import java.lang.management.RuntimeMXBean;
  34 import java.lang.reflect.Field;
  35 import java.lang.reflect.Method;
  36 import sun.management.VMManagement;
  37 import sun.misc.ManagedLocalsThread;
  38 
  39 /**
  40  * JdpController is responsible to create and manage a broadcast loop
  41  *
  42  * <p> Other part of code has no access to broadcast loop and have to use
  43  * provided static methods
  44  * {@link #startDiscoveryService(InetAddress,int,String,String) startDiscoveryService}
  45  * and {@link #stopDiscoveryService() stopDiscoveryService}</p>
  46  * <p>{@link #startDiscoveryService(InetAddress,int,String,String) startDiscoveryService} could be called multiple
  47  * times as it stops the running service if it is necessary. Call to {@link #stopDiscoveryService() stopDiscoveryService}
  48  * ignored if service isn't run</p>
  49  *
  50  *
  51  * </p>
  52  *
  53  * <p> System properties below could be used to control broadcast loop behavior.
  54  * Property below have to be set explicitly in command line. It's not possible to
  55  * set it in management.config file.  Careless changes of these properties could
  56  * lead to security or network issues.
  57  * <ul>
  58  *     <li>com.sun.management.jdp.ttl         - set ttl for broadcast packet</li>
  59  *     <li>com.sun.management.jdp.pause       - set broadcast interval in seconds</li>
  60  *     <li>com.sun.management.jdp.source_addr - an address of interface to use for broadcast</li>
  61  * </ul>
  62   </p>
  63  * <p>null parameters values are filtered out on {@link JdpPacketWriter} level and
  64  * corresponding keys are not placed to packet.</p>
  65  */
  66 public final class JdpController {
  67 
  68     private static class JDPControllerRunner implements Runnable {
  69 
  70         private final JdpJmxPacket packet;
  71         private final JdpBroadcaster bcast;
  72         private final int pause;
  73         private volatile boolean shutdown = false;
  74 
  75         private JDPControllerRunner(JdpBroadcaster bcast, JdpJmxPacket packet, int pause) {
  76             this.bcast = bcast;
  77             this.packet = packet;
  78             this.pause = pause;
  79         }
  80 
  81         @Override
  82         public void run() {
  83             try {
  84                 while (!shutdown) {
  85                     bcast.sendPacket(packet);
  86                     try {
  87                         Thread.sleep(this.pause);
  88                     } catch (InterruptedException e) {
  89                         // pass
  90                     }
  91                 }
  92 
  93             } catch (IOException e) {
  94               // pass;
  95             }
  96 
  97             // It's not possible to re-use controller,
  98             // nevertheless reset shutdown variable
  99             try {
 100                 stop();
 101                 bcast.shutdown();
 102             } catch (IOException ex) {
 103                 // pass - ignore IOException during shutdown
 104             }
 105         }
 106 
 107         public void stop() {
 108             shutdown = true;
 109         }
 110     }
 111     private static JDPControllerRunner controller = null;
 112 
 113     private JdpController(){
 114         // Don't allow to instantiate this class.
 115     }
 116 
 117     // Utility to handle optional system properties
 118     // Parse an integer from string or return default if provided string is null
 119     private static int getInteger(String val, int dflt, String msg) throws JdpException {
 120         try {
 121             return (val == null) ? dflt : Integer.parseInt(val);
 122         } catch (NumberFormatException ex) {
 123             throw new JdpException(msg);
 124         }
 125     }
 126 
 127     // Parse an inet address from string or return default if provided string is null
 128     private static InetAddress getInetAddress(String val, InetAddress dflt, String msg) throws JdpException {
 129         try {
 130             return (val == null) ? dflt : InetAddress.getByName(val);
 131         } catch (UnknownHostException ex) {
 132             throw new JdpException(msg);
 133         }
 134     }
 135 
 136     // Get the process id of the current running Java process
 137     private static Integer getProcessId() {
 138         try {
 139             // Get the current process id using a reflection hack
 140             RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
 141             Field jvm = runtime.getClass().getDeclaredField("jvm");
 142             jvm.setAccessible(true);
 143 
 144             VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
 145             Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
 146             pid_method.setAccessible(true);
 147             Integer pid = (Integer) pid_method.invoke(mgmt);
 148             return pid;
 149         } catch(Exception ex) {
 150             return null;
 151         }
 152     }
 153 
 154 
 155     /**
 156      * Starts discovery service
 157      *
 158      * @param address - multicast group address
 159      * @param port - udp port to use
 160      * @param instanceName - name of running JVM instance
 161      * @param url - JMX service url
 162      * @throws IOException
 163      */
 164     public static synchronized void startDiscoveryService(InetAddress address, int port, String instanceName, String url)
 165             throws IOException, JdpException {
 166 
 167         // Limit packet to local subnet by default
 168         int ttl = getInteger(
 169                 System.getProperty("com.sun.management.jdp.ttl"), 1,
 170                 "Invalid jdp packet ttl");
 171 
 172         // Broadcast once a 5 seconds by default
 173         int pause = getInteger(
 174                 System.getProperty("com.sun.management.jdp.pause"), 5,
 175                 "Invalid jdp pause");
 176 
 177         // Converting seconds to milliseconds
 178         pause = pause * 1000;
 179 
 180         // Allow OS to choose broadcast source
 181         InetAddress sourceAddress = getInetAddress(
 182                 System.getProperty("com.sun.management.jdp.source_addr"), null,
 183                 "Invalid source address provided");
 184 
 185         // Generate session id
 186         UUID id = UUID.randomUUID();
 187 
 188         JdpJmxPacket packet = new JdpJmxPacket(id, url);
 189 
 190         // Don't broadcast whole command line for security reason.
 191         // Strip everything after first space
 192         String javaCommand = System.getProperty("sun.java.command");
 193         if (javaCommand != null) {
 194             String[] arr = javaCommand.split(" ", 2);
 195             packet.setMainClass(arr[0]);
 196         }
 197 
 198         // Put optional explicit java instance name to packet, if user doesn't specify
 199         // it the key is skipped. PacketWriter is responsible to skip keys having null value.
 200         packet.setInstanceName(instanceName);
 201 
 202         // Set rmi server hostname if it explicitly specified by user with
 203         // java.rmi.server.hostname
 204         String rmiHostname = System.getProperty("java.rmi.server.hostname");
 205         packet.setRmiHostname(rmiHostname);
 206 
 207         // Set broadcast interval
 208         packet.setBroadcastInterval(Integer.toString(pause));
 209 
 210         // Set process id
 211         Integer pid = getProcessId();
 212         if (pid != null) {
 213            packet.setProcessId(pid.toString());
 214         }
 215 
 216         JdpBroadcaster bcast = new JdpBroadcaster(address, sourceAddress, port, ttl);
 217 
 218         // Stop discovery service if it's already running
 219         stopDiscoveryService();
 220 
 221         controller = new JDPControllerRunner(bcast, packet, pause);
 222 
 223         Thread t = new ManagedLocalsThread(controller, "JDP broadcaster");
 224         t.setDaemon(true);
 225         t.start();
 226     }
 227 
 228     /**
 229      * Stop running discovery service,
 230      * it's safe to attempt to stop not started service
 231      */
 232     public static synchronized void stopDiscoveryService() {
 233         if ( controller != null ){
 234              controller.stop();
 235              controller = null;
 236         }
 237     }
 238 }