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