1 /*
   2  * Copyright (c) 2003, 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 
  26 package sun.management;
  27 
  28 import java.lang.management.*;
  29 
  30 import javax.management.DynamicMBean;
  31 import javax.management.InstanceAlreadyExistsException;
  32 import javax.management.InstanceNotFoundException;
  33 import javax.management.MBeanServer;
  34 import javax.management.MBeanRegistrationException;
  35 import javax.management.NotCompliantMBeanException;
  36 import javax.management.ObjectName;
  37 import javax.management.RuntimeOperationsException;
  38 import java.security.AccessController;
  39 import java.security.PrivilegedActionException;
  40 import java.security.PrivilegedExceptionAction;
  41 
  42 import sun.util.logging.LoggingSupport;
  43 
  44 import java.util.ArrayList;
  45 import java.util.Collections;
  46 import java.util.HashMap;
  47 import java.util.List;
  48 import com.sun.management.DiagnosticCommandMBean;
  49 import com.sun.management.OSMBeanFactory;
  50 import com.sun.management.HotSpotDiagnosticMXBean;
  51 
  52 import static java.lang.management.ManagementFactory.*;
  53 
  54 /**
  55  * ManagementFactoryHelper provides static factory methods to create
  56  * instances of the management interface.
  57  */
  58 public class ManagementFactoryHelper {
  59     private ManagementFactoryHelper() {};
  60 
  61     private static VMManagement jvm;
  62 
  63     private static ClassLoadingImpl    classMBean = null;
  64     private static MemoryImpl          memoryMBean = null;
  65     private static ThreadImpl          threadMBean = null;
  66     private static RuntimeImpl         runtimeMBean = null;
  67     private static CompilationImpl     compileMBean = null;
  68     private static OperatingSystemImpl osMBean = null;
  69 
  70     public static synchronized ClassLoadingMXBean getClassLoadingMXBean() {
  71         if (classMBean == null) {
  72             classMBean = new ClassLoadingImpl(jvm);
  73         }
  74         return classMBean;
  75     }
  76 
  77     public static synchronized MemoryMXBean getMemoryMXBean() {
  78         if (memoryMBean == null) {
  79             memoryMBean = new MemoryImpl(jvm);
  80         }
  81         return memoryMBean;
  82     }
  83 
  84     public static synchronized ThreadMXBean getThreadMXBean() {
  85         if (threadMBean == null) {
  86             threadMBean = new ThreadImpl(jvm);
  87         }
  88         return threadMBean;
  89     }
  90 
  91     public static synchronized RuntimeMXBean getRuntimeMXBean() {
  92         if (runtimeMBean == null) {
  93             runtimeMBean = new RuntimeImpl(jvm);
  94         }
  95         return runtimeMBean;
  96     }
  97 
  98     public static synchronized CompilationMXBean getCompilationMXBean() {
  99         if (compileMBean == null && jvm.getCompilerName() != null) {
 100             compileMBean = new CompilationImpl(jvm);
 101         }
 102         return compileMBean;
 103     }
 104 
 105     public static synchronized OperatingSystemMXBean getOperatingSystemMXBean() {
 106         if (osMBean == null) {
 107             osMBean = (OperatingSystemImpl)
 108                           OSMBeanFactory.getOperatingSystemMXBean(jvm);
 109         }
 110         return osMBean;
 111     }
 112 
 113     public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {
 114         MemoryPoolMXBean[] pools = MemoryImpl.getMemoryPools();
 115         List<MemoryPoolMXBean> list = new ArrayList<>(pools.length);
 116         for (MemoryPoolMXBean p : pools) {
 117             list.add(p);
 118         }
 119         return list;
 120     }
 121 
 122     public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {
 123         MemoryManagerMXBean[]  mgrs = MemoryImpl.getMemoryManagers();
 124         List<MemoryManagerMXBean> result = new ArrayList<>(mgrs.length);
 125         for (MemoryManagerMXBean m : mgrs) {
 126             result.add(m);
 127         }
 128         return result;
 129     }
 130 
 131     public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
 132         MemoryManagerMXBean[]  mgrs = MemoryImpl.getMemoryManagers();
 133         List<GarbageCollectorMXBean> result = new ArrayList<>(mgrs.length);
 134         for (MemoryManagerMXBean m : mgrs) {
 135             if (GarbageCollectorMXBean.class.isInstance(m)) {
 136                  result.add(GarbageCollectorMXBean.class.cast(m));
 137             }
 138         }
 139         return result;
 140     }
 141 
 142     public static PlatformLoggingMXBean getPlatformLoggingMXBean() {
 143         if (LoggingSupport.isAvailable()) {
 144             return PlatformLoggingImpl.instance;
 145         } else {
 146             return null;
 147         }
 148     }
 149 
 150     /**
 151      * The logging MXBean object is an instance of
 152      * PlatformLoggingMXBean and java.util.logging.LoggingMXBean
 153      * but it can't directly implement two MXBean interfaces
 154      * as a compliant MXBean implements exactly one MXBean interface,
 155      * or if it implements one interface that is a subinterface of
 156      * all the others; otherwise, it is a non-compliant MXBean
 157      * and MBeanServer will throw NotCompliantMBeanException.
 158      * See the Definition of an MXBean section in javax.management.MXBean spec.
 159      *
 160      * To create a compliant logging MXBean, define a LoggingMXBean interface
 161      * that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean
 162     */
 163     public interface LoggingMXBean
 164         extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean {
 165     }
 166 
 167     static class PlatformLoggingImpl implements LoggingMXBean
 168     {
 169         final static PlatformLoggingMXBean instance = new PlatformLoggingImpl();
 170         final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging";
 171 
 172         private volatile ObjectName objname;  // created lazily
 173         @Override
 174         public ObjectName getObjectName() {
 175             ObjectName result = objname;
 176             if (result == null) {
 177                 synchronized (this) {
 178                     result = objname;
 179                     if (result == null) {
 180                         result = Util.newObjectName(LOGGING_MXBEAN_NAME);
 181                         objname = result;
 182                     }
 183                 }
 184             }
 185             return result;
 186         }
 187 
 188         @Override
 189         public java.util.List<String> getLoggerNames() {
 190             return LoggingSupport.getLoggerNames();
 191         }
 192 
 193         @Override
 194         public String getLoggerLevel(String loggerName) {
 195             return LoggingSupport.getLoggerLevel(loggerName);
 196         }
 197 
 198         @Override
 199         public void setLoggerLevel(String loggerName, String levelName) {
 200             LoggingSupport.setLoggerLevel(loggerName, levelName);
 201         }
 202 
 203         @Override
 204         public String getParentLoggerName(String loggerName) {
 205             return LoggingSupport.getParentLoggerName(loggerName);
 206         }
 207     }
 208 
 209     private static List<BufferPoolMXBean> bufferPools = null;
 210     public static synchronized List<BufferPoolMXBean> getBufferPoolMXBeans() {
 211         if (bufferPools == null) {
 212             bufferPools = new ArrayList<>(2);
 213             bufferPools.add(createBufferPoolMXBean(sun.misc.SharedSecrets.getJavaNioAccess()
 214                 .getDirectBufferPool()));
 215             bufferPools.add(createBufferPoolMXBean(sun.nio.ch.FileChannelImpl
 216                 .getMappedBufferPool()));
 217         }
 218         return bufferPools;
 219     }
 220 
 221     private final static String BUFFER_POOL_MXBEAN_NAME = "java.nio:type=BufferPool";
 222 
 223     /**
 224      * Creates management interface for the given buffer pool.
 225      */
 226     private static BufferPoolMXBean
 227         createBufferPoolMXBean(final sun.misc.JavaNioAccess.BufferPool pool)
 228     {
 229         return new BufferPoolMXBean() {
 230             private volatile ObjectName objname;  // created lazily
 231             @Override
 232             public ObjectName getObjectName() {
 233                 ObjectName result = objname;
 234                 if (result == null) {
 235                     synchronized (this) {
 236                         result = objname;
 237                         if (result == null) {
 238                             result = Util.newObjectName(BUFFER_POOL_MXBEAN_NAME +
 239                                 ",name=" + pool.getName());
 240                             objname = result;
 241                         }
 242                     }
 243                 }
 244                 return result;
 245             }
 246             @Override
 247             public String getName() {
 248                 return pool.getName();
 249             }
 250             @Override
 251             public long getCount() {
 252                 return pool.getCount();
 253             }
 254             @Override
 255             public long getTotalCapacity() {
 256                 return pool.getTotalCapacity();
 257             }
 258             @Override
 259             public long getMemoryUsed() {
 260                 return pool.getMemoryUsed();
 261             }
 262         };
 263     }
 264 
 265     private static HotSpotDiagnostic hsDiagMBean = null;
 266     private static HotspotRuntime hsRuntimeMBean = null;
 267     private static HotspotClassLoading hsClassMBean = null;
 268     private static HotspotThread hsThreadMBean = null;
 269     private static HotspotCompilation hsCompileMBean = null;
 270     private static HotspotMemory hsMemoryMBean = null;
 271     private static DiagnosticCommandImpl hsDiagCommandMBean = null;
 272 
 273     public static synchronized HotSpotDiagnosticMXBean getDiagnosticMXBean() {
 274         if (hsDiagMBean == null) {
 275             hsDiagMBean = new HotSpotDiagnostic();
 276         }
 277         return hsDiagMBean;
 278     }
 279 
 280     /**
 281      * This method is for testing only.
 282      */
 283     public static synchronized HotspotRuntimeMBean getHotspotRuntimeMBean() {
 284         if (hsRuntimeMBean == null) {
 285             hsRuntimeMBean = new HotspotRuntime(jvm);
 286         }
 287         return hsRuntimeMBean;
 288     }
 289 
 290     /**
 291      * This method is for testing only.
 292      */
 293     public static synchronized HotspotClassLoadingMBean getHotspotClassLoadingMBean() {
 294         if (hsClassMBean == null) {
 295             hsClassMBean = new HotspotClassLoading(jvm);
 296         }
 297         return hsClassMBean;
 298     }
 299 
 300     /**
 301      * This method is for testing only.
 302      */
 303     public static synchronized HotspotThreadMBean getHotspotThreadMBean() {
 304         if (hsThreadMBean == null) {
 305             hsThreadMBean = new HotspotThread(jvm);
 306         }
 307         return hsThreadMBean;
 308     }
 309 
 310     /**
 311      * This method is for testing only.
 312      */
 313     public static synchronized HotspotMemoryMBean getHotspotMemoryMBean() {
 314         if (hsMemoryMBean == null) {
 315             hsMemoryMBean = new HotspotMemory(jvm);
 316         }
 317         return hsMemoryMBean;
 318     }
 319 
 320     public static synchronized DiagnosticCommandMBean getDiagnosticCommandMBean() {
 321         // Remote Diagnostic Commands may not be supported
 322         if (hsDiagCommandMBean == null && jvm.isRemoteDiagnosticCommandsSupported()) {
 323             hsDiagCommandMBean = new DiagnosticCommandImpl(jvm);
 324         }
 325         return hsDiagCommandMBean;
 326     }
 327 
 328     /**
 329      * This method is for testing only.
 330      */
 331     public static synchronized HotspotCompilationMBean getHotspotCompilationMBean() {
 332         if (hsCompileMBean == null) {
 333             hsCompileMBean = new HotspotCompilation(jvm);
 334         }
 335         return hsCompileMBean;
 336     }
 337 
 338     /**
 339      * Registers a given MBean if not registered in the MBeanServer;
 340      * otherwise, just return.
 341      */
 342     private static void addMBean(MBeanServer mbs, Object mbean, String mbeanName) {
 343         try {
 344             final ObjectName objName = Util.newObjectName(mbeanName);
 345 
 346             // inner class requires these fields to be final
 347             final MBeanServer mbs0 = mbs;
 348             final Object mbean0 = mbean;
 349             AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
 350                 public Void run() throws MBeanRegistrationException,
 351                                          NotCompliantMBeanException {
 352                     try {
 353                         mbs0.registerMBean(mbean0, objName);
 354                         return null;
 355                     } catch (InstanceAlreadyExistsException e) {
 356                         // if an instance with the object name exists in
 357                         // the MBeanServer ignore the exception
 358                     }
 359                     return null;
 360                 }
 361             });
 362         } catch (PrivilegedActionException e) {
 363             throw Util.newException(e.getException());
 364         }
 365     }
 366 
 367     private final static String HOTSPOT_CLASS_LOADING_MBEAN_NAME =
 368         "sun.management:type=HotspotClassLoading";
 369 
 370     private final static String HOTSPOT_COMPILATION_MBEAN_NAME =
 371         "sun.management:type=HotspotCompilation";
 372 
 373     private final static String HOTSPOT_MEMORY_MBEAN_NAME =
 374         "sun.management:type=HotspotMemory";
 375 
 376     private static final String HOTSPOT_RUNTIME_MBEAN_NAME =
 377         "sun.management:type=HotspotRuntime";
 378 
 379     private final static String HOTSPOT_THREAD_MBEAN_NAME =
 380         "sun.management:type=HotspotThreading";
 381 
 382     final static String HOTSPOT_DIAGNOSTIC_COMMAND_MBEAN_NAME =
 383         "com.sun.management:type=DiagnosticCommand";
 384 
 385     public static HashMap<ObjectName, DynamicMBean> getPlatformDynamicMBeans() {
 386         HashMap<ObjectName, DynamicMBean> map = new HashMap<>();
 387         DiagnosticCommandMBean diagMBean = getDiagnosticCommandMBean();
 388         if (diagMBean != null) {
 389             map.put(Util.newObjectName(HOTSPOT_DIAGNOSTIC_COMMAND_MBEAN_NAME), diagMBean);
 390         }
 391         return map;
 392     }
 393 
 394     static void registerInternalMBeans(MBeanServer mbs) {
 395         // register all internal MBeans if not registered
 396         // No exception is thrown if a MBean with that object name
 397         // already registered
 398         addMBean(mbs, getHotspotClassLoadingMBean(),
 399             HOTSPOT_CLASS_LOADING_MBEAN_NAME);
 400         addMBean(mbs, getHotspotMemoryMBean(),
 401             HOTSPOT_MEMORY_MBEAN_NAME);
 402         addMBean(mbs, getHotspotRuntimeMBean(),
 403             HOTSPOT_RUNTIME_MBEAN_NAME);
 404         addMBean(mbs, getHotspotThreadMBean(),
 405             HOTSPOT_THREAD_MBEAN_NAME);
 406 
 407         // CompilationMBean may not exist
 408         if (getCompilationMXBean() != null) {
 409             addMBean(mbs, getHotspotCompilationMBean(),
 410                 HOTSPOT_COMPILATION_MBEAN_NAME);
 411         }
 412     }
 413 
 414     private static void unregisterMBean(MBeanServer mbs, String mbeanName) {
 415         try {
 416             final ObjectName objName = Util.newObjectName(mbeanName);
 417 
 418             // inner class requires these fields to be final
 419             final MBeanServer mbs0 = mbs;
 420             AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
 421                 public Void run() throws MBeanRegistrationException,
 422                                            RuntimeOperationsException  {
 423                     try {
 424                         mbs0.unregisterMBean(objName);
 425                     } catch (InstanceNotFoundException e) {
 426                         // ignore exception if not found
 427                     }
 428                     return null;
 429                 }
 430             });
 431         } catch (PrivilegedActionException e) {
 432             throw Util.newException(e.getException());
 433         }
 434     }
 435 
 436     static void unregisterInternalMBeans(MBeanServer mbs) {
 437         // unregister all internal MBeans
 438         unregisterMBean(mbs, HOTSPOT_CLASS_LOADING_MBEAN_NAME);
 439         unregisterMBean(mbs, HOTSPOT_MEMORY_MBEAN_NAME);
 440         unregisterMBean(mbs, HOTSPOT_RUNTIME_MBEAN_NAME);
 441         unregisterMBean(mbs, HOTSPOT_THREAD_MBEAN_NAME);
 442 
 443         // CompilationMBean may not exist
 444         if (getCompilationMXBean() != null) {
 445             unregisterMBean(mbs, HOTSPOT_COMPILATION_MBEAN_NAME);
 446         }
 447     }
 448 
 449     static {
 450         AccessController.doPrivileged(
 451             new java.security.PrivilegedAction<Void>() {
 452                 public Void run() {
 453                     System.loadLibrary("management");
 454                     return null;
 455                 }
 456             });
 457         jvm = new VMManagementImpl();
 458     }
 459 
 460     public static boolean isThreadSuspended(int state) {
 461         return ((state & JMM_THREAD_STATE_FLAG_SUSPENDED) != 0);
 462     }
 463 
 464     public static boolean isThreadRunningNative(int state) {
 465         return ((state & JMM_THREAD_STATE_FLAG_NATIVE) != 0);
 466     }
 467 
 468     public static Thread.State toThreadState(int state) {
 469         // suspended and native bits may be set in state
 470         int threadStatus = state & ~JMM_THREAD_STATE_FLAG_MASK;
 471         return sun.misc.VM.toThreadState(threadStatus);
 472     }
 473 
 474     // These values are defined in jmm.h
 475     private static final int JMM_THREAD_STATE_FLAG_MASK = 0xFFF00000;
 476     private static final int JMM_THREAD_STATE_FLAG_SUSPENDED = 0x00100000;
 477     private static final int JMM_THREAD_STATE_FLAG_NATIVE = 0x00400000;
 478 
 479 }