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 
  26 package sun.management;
  27 
  28 import com.sun.management.DiagnosticCommandMBean;
  29 import java.lang.reflect.Constructor;
  30 import java.lang.reflect.InvocationTargetException;
  31 import java.security.Permission;
  32 import java.util.*;
  33 import javax.management.*;
  34 
  35 /**
  36  * Implementation class for the diagnostic commands subsystem.
  37  *
  38  * @since 8
  39  */
  40 class DiagnosticCommandImpl extends NotificationEmitterSupport
  41     implements DiagnosticCommandMBean {
  42 
  43     private final VMManagement jvm;
  44     private volatile Map<String, Wrapper> wrappers = null;
  45     private static final String strClassName = "".getClass().getName();
  46     private static final String strArrayClassName = String[].class.getName();
  47     private final boolean isSupported;
  48 
  49     @Override
  50     public Object getAttribute(String attribute) throws AttributeNotFoundException,
  51         MBeanException, ReflectionException {
  52         throw new AttributeNotFoundException(attribute);
  53     }
  54 
  55     @Override
  56     public void setAttribute(Attribute attribute) throws AttributeNotFoundException,
  57         InvalidAttributeValueException, MBeanException, ReflectionException {
  58         throw new AttributeNotFoundException(attribute.getName());
  59     }
  60 
  61     @Override
  62     public AttributeList getAttributes(String[] attributes) {
  63         throw new UnsupportedOperationException("Not supported.");
  64     }
  65 
  66     @Override
  67     public AttributeList setAttributes(AttributeList attributes) {
  68         throw new UnsupportedOperationException("Not supported.");
  69     }
  70 
  71     private class Wrapper {
  72 
  73         String name;
  74         String cmd;
  75         DiagnosticCommandInfo info;
  76         Permission permission;
  77 
  78         Wrapper(String name, String cmd, DiagnosticCommandInfo info)
  79                 throws InstantiationException {
  80             this.name = name;
  81             this.cmd = cmd;
  82             this.info = info;
  83             this.permission = null;
  84             if (info.getPermissionClass() != null) {
  85                 try {
  86                     Class c = Class.forName(info.getPermissionClass());
  87                     if (info.getPermissionAction() == null) {
  88                         try {
  89                             Constructor constructor = c.getConstructor(String.class);
  90                             permission = (Permission) constructor.newInstance(info.getPermissionName());
  91 
  92                         } catch (InstantiationException | IllegalAccessException
  93                                 | IllegalArgumentException | InvocationTargetException
  94                                 | NoSuchMethodException | SecurityException ex) { }
  95                     }
  96                     if (permission == null) {
  97                         try {
  98                             Constructor constructor = c.getConstructor(String.class, String.class);
  99                             permission = (Permission) constructor.newInstance(
 100                                     info.getPermissionName(),
 101                                     info.getPermissionAction());
 102                         } catch (InstantiationException | IllegalAccessException
 103                                 | IllegalArgumentException | InvocationTargetException
 104                                 | NoSuchMethodException | SecurityException ex) { }
 105                     }
 106                 } catch (ClassNotFoundException ex) { }
 107                 if (permission == null) {
 108                     throw new InstantiationException("Unable to instantiate required permission");
 109                 }
 110             }
 111         }
 112 
 113         public String execute(String[] args) {
 114             if (permission != null) {
 115                 SecurityManager sm = System.getSecurityManager();
 116                 if (sm != null) {
 117                     sm.checkPermission(permission);
 118                 }
 119             }
 120             if(args == null) {
 121                 return executeDiagnosticCommand(cmd);
 122             } else {
 123                 StringBuilder sb = new StringBuilder();
 124                 sb.append(cmd);
 125                 for(int i=0; i<args.length; i++) {
 126                     if(args[i] == null) {
 127                         throw new IllegalArgumentException("Invalid null argument");
 128                     }
 129                     sb.append(" ");
 130                     sb.append(args[i]);
 131                 }
 132                 return executeDiagnosticCommand(sb.toString());
 133             }
 134         }
 135     }
 136 
 137     DiagnosticCommandImpl(VMManagement jvm) {
 138         this.jvm = jvm;
 139         isSupported = jvm.isRemoteDiagnosticCommandsSupported();
 140     }
 141 
 142     private static class OperationInfoComparator implements Comparator<MBeanOperationInfo> {
 143         @Override
 144         public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) {
 145             return o1.getName().compareTo(o2.getName());
 146         }
 147     }
 148 
 149     @Override
 150     public MBeanInfo getMBeanInfo() {
 151         SortedSet<MBeanOperationInfo> operations = new TreeSet<>(new OperationInfoComparator());
 152         Map<String, Wrapper> wrappersmap;
 153         if (!isSupported) {
 154             wrappersmap = (Map<String, Wrapper>) Collections.EMPTY_MAP;
 155         } else {
 156             try {
 157                 String[] command = getDiagnosticCommands();
 158                 DiagnosticCommandInfo[] info = getDiagnosticCommandInfo(command);
 159                 MBeanParameterInfo stringArgInfo[] = new MBeanParameterInfo[]{
 160                     new MBeanParameterInfo("arguments", strArrayClassName,
 161                     "Array of Diagnostic Commands Arguments and Options")
 162                 };
 163                 wrappersmap = new HashMap<>();
 164                 for (int i = 0; i < command.length; i++) {
 165                     String name = transform(command[i]);
 166                     try {
 167                         Wrapper w = new Wrapper(name, command[i], info[i]);
 168                         wrappersmap.put(name, w);
 169                         operations.add(new MBeanOperationInfo(
 170                                 w.name,
 171                                 w.info.getDescription(),
 172                                 (w.info.getArgumentsInfo() == null
 173                                     || w.info.getArgumentsInfo().isEmpty())
 174                                     ? null : stringArgInfo,
 175                                 strClassName,
 176                                 MBeanOperationInfo.ACTION_INFO,
 177                                 commandDescriptor(w)));
 178                     } catch (InstantiationException ex) {
 179                         // If for some reasons the creation of a diagnostic command
 180                         // wrappers fails, the diagnostic command is just ignored
 181                         // and won't appear in the DynamicMBean
 182                     }
 183                 }
 184             } catch (IllegalArgumentException | UnsupportedOperationException e) {
 185                 wrappersmap = (Map<String, Wrapper>) Collections.EMPTY_MAP;
 186             }
 187         }
 188         wrappers =  Collections.unmodifiableMap(wrappersmap);
 189         HashMap<String, Object> map = new HashMap<>();
 190         map.put("immutableInfo", "false");
 191         map.put("interfaceClassName","com.sun.management.DiagnosticCommandMBean");
 192         map.put("mxbean", "false");
 193         Descriptor desc = new ImmutableDescriptor(map);
 194         return new MBeanInfo(
 195                 this.getClass().getName(),
 196                 "Diagnostic Commands",
 197                 null, // attributes
 198                 null, // constructors
 199                 operations.toArray(new MBeanOperationInfo[operations.size()]), // operations
 200                 getNotificationInfo(), // notifications
 201                 desc);
 202     }
 203 
 204     @Override
 205     public Object invoke(String actionName, Object[] params, String[] signature)
 206             throws MBeanException, ReflectionException {
 207         if (!isSupported) {
 208             throw new UnsupportedOperationException();
 209         }
 210         if (wrappers == null) {
 211             getMBeanInfo();
 212         }
 213         Wrapper w = wrappers.get(actionName);
 214         if (w != null) {
 215             if (w.info.getArgumentsInfo().isEmpty()
 216                     && (params == null || params.length == 0)
 217                     && (signature == null || signature.length == 0)) {
 218                 return w.execute(null);
 219             } else if((params != null && params.length == 1)
 220                     && (signature != null && signature.length == 1
 221                     && signature[0] != null
 222                     && signature[0].compareTo(strArrayClassName) == 0)) {
 223                 return w.execute((String[]) params[0]);
 224             }
 225         }
 226         throw new ReflectionException(new NoSuchMethodException(actionName));
 227     }
 228 
 229     private static String transform(String name) {
 230         StringBuilder sb = new StringBuilder();
 231         boolean toLower = true;
 232         boolean toUpper = false;
 233         for (int i = 0; i < name.length(); i++) {
 234             char c = name.charAt(i);
 235             if (c == '.' || c == '_') {
 236                 toLower = false;
 237                 toUpper = true;
 238             } else {
 239                 if (toUpper) {
 240                     toUpper = false;
 241                     sb.append(Character.toUpperCase(c));
 242                 } else if(toLower) {
 243                     sb.append(Character.toLowerCase(c));
 244                 } else {
 245                     sb.append(c);
 246                 }
 247             }
 248         }
 249         return sb.toString();
 250     }
 251 
 252     private Descriptor commandDescriptor(Wrapper w) throws IllegalArgumentException {
 253         HashMap<String, Object> map = new HashMap<>();
 254         map.put("dcmd.name", w.info.getName());
 255         map.put("dcmd.description", w.info.getDescription());
 256         map.put("dcmd.vmImpact", w.info.getImpact());
 257         map.put("dcmd.permissionClass", w.info.getPermissionClass());
 258         map.put("dcmd.permissionName", w.info.getPermissionName());
 259         map.put("dcmd.permissionAction", w.info.getPermissionAction());
 260         map.put("dcmd.enabled", w.info.isEnabled());
 261         StringBuilder sb = new StringBuilder();
 262         sb.append("help ");
 263         sb.append(w.info.getName());
 264         map.put("dcmd.help", executeDiagnosticCommand(sb.toString()));
 265         if (w.info.getArgumentsInfo() != null && !w.info.getArgumentsInfo().isEmpty()) {
 266             HashMap<String, Object> allargmap = new HashMap<>();
 267             for (DiagnosticCommandArgumentInfo arginfo : w.info.getArgumentsInfo()) {
 268                 HashMap<String, Object> argmap = new HashMap<>();
 269                 argmap.put("dcmd.arg.name", arginfo.getName());
 270                 argmap.put("dcmd.arg.type", arginfo.getType());
 271                 argmap.put("dcmd.arg.description", arginfo.getDescription());
 272                 argmap.put("dcmd.arg.isMandatory", arginfo.isMandatory());
 273                 argmap.put("dcmd.arg.isMultiple", arginfo.isMultiple());
 274                 boolean isOption = arginfo.isOption();
 275                 argmap.put("dcmd.arg.isOption", isOption);
 276                 if(!isOption) {
 277                     argmap.put("dcmd.arg.position", arginfo.getPosition());
 278                 } else {
 279                     argmap.put("dcmd.arg.position", -1);
 280                 }
 281                 allargmap.put(arginfo.getName(), new ImmutableDescriptor(argmap));
 282             }
 283             map.put("dcmd.arguments", new ImmutableDescriptor(allargmap));
 284         }
 285         return new ImmutableDescriptor(map);
 286     }
 287 
 288     private final static String notifName =
 289         "javax.management.Notification";
 290 
 291     private final static String[] diagFramNotifTypes = {
 292         "jmx.mbean.info.changed"
 293     };
 294 
 295     private MBeanNotificationInfo[] notifInfo = null;
 296 
 297     @Override
 298     public MBeanNotificationInfo[] getNotificationInfo() {
 299         synchronized (this) {
 300             if (notifInfo == null) {
 301                  notifInfo = new MBeanNotificationInfo[1];
 302                  notifInfo[0] =
 303                          new MBeanNotificationInfo(diagFramNotifTypes,
 304                                                    notifName,
 305                                                    "Diagnostic Framework Notification");
 306             }
 307         }
 308         return notifInfo;
 309     }
 310 
 311     private static long seqNumber = 0;
 312     private static long getNextSeqNumber() {
 313         return ++seqNumber;
 314     }
 315 
 316     private void createDiagnosticFrameworkNotification() {
 317 
 318         if (!hasListeners()) {
 319             return;
 320         }
 321         ObjectName on = null;
 322         try {
 323             on = ObjectName.getInstance(ManagementFactoryHelper.HOTSPOT_DIAGNOSTIC_COMMAND_MBEAN_NAME);
 324         } catch (MalformedObjectNameException e) { }
 325         Notification notif = new Notification("jmx.mbean.info.changed",
 326                                               on,
 327                                               getNextSeqNumber());
 328         notif.setUserData(getMBeanInfo());
 329         sendNotification(notif);
 330     }
 331 
 332     @Override
 333     public synchronized void addNotificationListener(NotificationListener listener,
 334             NotificationFilter filter,
 335             Object handback) {
 336         boolean before = hasListeners();
 337         super.addNotificationListener(listener, filter, handback);
 338         boolean after = hasListeners();
 339         if (!before && after) {
 340             setNotificationEnabled(true);
 341         }
 342     }
 343 
 344     @Override
 345     public synchronized void removeNotificationListener(NotificationListener listener)
 346             throws ListenerNotFoundException {
 347         boolean before = hasListeners();
 348         super.removeNotificationListener(listener);
 349         boolean after = hasListeners();
 350         if (before && !after) {
 351             setNotificationEnabled(false);
 352         }
 353     }
 354 
 355     @Override
 356     public synchronized void removeNotificationListener(NotificationListener listener,
 357             NotificationFilter filter,
 358             Object handback)
 359             throws ListenerNotFoundException {
 360         boolean before = hasListeners();
 361         super.removeNotificationListener(listener, filter, handback);
 362         boolean after = hasListeners();
 363         if (before && !after) {
 364             setNotificationEnabled(false);
 365         }
 366     }
 367 
 368     private native void setNotificationEnabled(boolean enabled);
 369     private native String[] getDiagnosticCommands();
 370     private native DiagnosticCommandInfo[] getDiagnosticCommandInfo(String[] commands);
 371     private native String executeDiagnosticCommand(String command);
 372 
 373 }