001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.metrics2.util;
019
020import java.lang.management.ManagementFactory;
021import java.util.regex.Matcher;
022import java.util.regex.Pattern;
023
024import javax.management.InstanceAlreadyExistsException;
025import javax.management.MBeanServer;
026import javax.management.ObjectName;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.apache.hadoop.classification.InterfaceAudience;
031import org.apache.hadoop.classification.InterfaceStability;
032import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
033
034/**
035 * This util class provides a method to register an MBean using
036 * our standard naming convention as described in the doc
037 *  for {link {@link #register(String, String, Object)}
038 */
039@InterfaceAudience.Public
040@InterfaceStability.Stable
041public class MBeans {
042  private static final Log LOG = LogFactory.getLog(MBeans.class);
043  private static final String DOMAIN_PREFIX = "Hadoop:";
044  private static final String SERVICE_PREFIX = "service=";
045  private static final String NAME_PREFIX = "name=";
046
047  private static final Pattern MBEAN_NAME_PATTERN = Pattern.compile(
048      "^" + DOMAIN_PREFIX + SERVICE_PREFIX + "([^,]+)," +
049      NAME_PREFIX + "(.+)$");
050
051  /**
052   * Register the MBean using our standard MBeanName format
053   * "hadoop:service=<serviceName>,name=<nameName>"
054   * Where the <serviceName> and <nameName> are the supplied parameters
055   *
056   * @param serviceName
057   * @param nameName
058   * @param theMbean - the MBean to register
059   * @return the named used to register the MBean
060   */
061  static public ObjectName register(String serviceName, String nameName,
062                                    Object theMbean) {
063    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
064    ObjectName name = getMBeanName(serviceName, nameName);
065    try {
066      mbs.registerMBean(theMbean, name);
067      LOG.debug("Registered "+ name);
068      return name;
069    } catch (InstanceAlreadyExistsException iaee) {
070      if (LOG.isTraceEnabled()) {
071        LOG.trace("Failed to register MBean \""+ name + "\"", iaee);
072      } else {
073        LOG.warn("Failed to register MBean \""+ name
074            + "\": Instance already exists.");
075      }
076    } catch (Exception e) {
077      LOG.warn("Failed to register MBean \""+ name + "\"", e);
078    }
079    return null;
080  }
081
082  public static String getMbeanNameService(final ObjectName objectName) {
083    Matcher matcher = MBEAN_NAME_PATTERN.matcher(objectName.toString());
084    if (matcher.matches()) {
085      return matcher.group(1);
086    } else {
087      throw new IllegalArgumentException(
088          objectName + " is not a valid Hadoop mbean");
089    }
090  }
091
092  public static String getMbeanNameName(final ObjectName objectName) {
093    Matcher matcher = MBEAN_NAME_PATTERN.matcher(objectName.toString());
094    if (matcher.matches()) {
095      return matcher.group(2);
096    } else {
097      throw new IllegalArgumentException(
098          objectName + " is not a valid Hadoop mbean");
099    }
100  }
101
102  static public void unregister(ObjectName mbeanName) {
103    LOG.debug("Unregistering "+ mbeanName);
104    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
105    if (mbeanName == null) {
106      LOG.debug("Stacktrace: ", new Throwable());
107      return;
108    }
109    try {
110      mbs.unregisterMBean(mbeanName);
111    } catch (Exception e) {
112      LOG.warn("Error unregistering "+ mbeanName, e);
113    }
114    DefaultMetricsSystem.removeMBeanName(mbeanName);
115  }
116
117  static private ObjectName getMBeanName(String serviceName, String nameName) {
118    String nameStr = DOMAIN_PREFIX + SERVICE_PREFIX + serviceName + "," +
119        NAME_PREFIX + nameName;
120    try {
121      return DefaultMetricsSystem.newMBeanName(nameStr);
122    } catch (Exception e) {
123      LOG.warn("Error creating MBean object name: "+ nameStr, e);
124      return null;
125    }
126  }
127}