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    if (name != null) {
066      try {
067        mbs.registerMBean(theMbean, name);
068        LOG.debug("Registered " + name);
069        return name;
070      } catch (InstanceAlreadyExistsException iaee) {
071        if (LOG.isTraceEnabled()) {
072          LOG.trace("Failed to register MBean \"" + name + "\"", iaee);
073        } else {
074          LOG.warn("Failed to register MBean \"" + name
075              + "\": Instance already exists.");
076        }
077      } catch (Exception e) {
078        LOG.warn("Failed to register MBean \"" + name + "\"", e);
079      }
080    }
081    return null;
082  }
083
084  public static String getMbeanNameService(final ObjectName objectName) {
085    Matcher matcher = MBEAN_NAME_PATTERN.matcher(objectName.toString());
086    if (matcher.matches()) {
087      return matcher.group(1);
088    } else {
089      throw new IllegalArgumentException(
090          objectName + " is not a valid Hadoop mbean");
091    }
092  }
093
094  public static String getMbeanNameName(final ObjectName objectName) {
095    Matcher matcher = MBEAN_NAME_PATTERN.matcher(objectName.toString());
096    if (matcher.matches()) {
097      return matcher.group(2);
098    } else {
099      throw new IllegalArgumentException(
100          objectName + " is not a valid Hadoop mbean");
101    }
102  }
103
104  static public void unregister(ObjectName mbeanName) {
105    LOG.debug("Unregistering "+ mbeanName);
106    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
107    if (mbeanName == null) {
108      LOG.debug("Stacktrace: ", new Throwable());
109      return;
110    }
111    try {
112      mbs.unregisterMBean(mbeanName);
113    } catch (Exception e) {
114      LOG.warn("Error unregistering "+ mbeanName, e);
115    }
116    DefaultMetricsSystem.removeMBeanName(mbeanName);
117  }
118
119  static private ObjectName getMBeanName(String serviceName, String nameName) {
120    String nameStr = DOMAIN_PREFIX + SERVICE_PREFIX + serviceName + "," +
121        NAME_PREFIX + nameName;
122    try {
123      return DefaultMetricsSystem.newMBeanName(nameStr);
124    } catch (Exception e) {
125      LOG.warn("Error creating MBean object name: "+ nameStr, e);
126      return null;
127    }
128  }
129}