Merge branch 'master' of git@github.com:hyperic/sigar

This commit is contained in:
Doug MacEachern 2009-05-14 08:37:50 -07:00
commit d3ceb14ff7
17 changed files with 304 additions and 539 deletions

View File

@ -184,7 +184,7 @@
<antcall target="version-file"> <antcall target="version-file">
<param name="version.file" <param name="version.file"
value="src/org/hyperic/sigar/SigarVersion.java"/> value="src/org/hyperic/sigar/Version.java"/>
</antcall> </antcall>
<antcall target="version-file"> <antcall target="version-file">

View File

@ -0,0 +1,54 @@
/*
* Copyright (C) [2004-2009], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar;
import java.util.HashMap;
import java.util.Map;
/**
* Object wrapper of double[] Sigar.getLoadAverage() for use in bean patterns (JMX).
*/
public class LoadAverage {
private double[] average;
public LoadAverage(double[] average) {
this.average = average;
}
public double getOneMinute() {
return this.average[0];
}
public double getFiveMinute() {
return this.average[1];
}
public double getFifteenMinute() {
return this.average[2];
}
public Map toMap() {
Map map = new HashMap();
map.put("OneMinute", new Double(getOneMinute()));
map.put("FiveMinute", new Double(getFiveMinute()));
map.put("FifteenMinute", new Double(getFifteenMinute()));
return map;
}
}

View File

@ -48,7 +48,7 @@ public class Sigar implements SigarProxy {
* The Sigar java version. * The Sigar java version.
*/ */
public static final String VERSION_STRING = public static final String VERSION_STRING =
SigarVersion.VERSION_STRING; Version.VERSION_STRING;
/** /**
* The Sigar native version. * The Sigar native version.
@ -59,7 +59,7 @@ public class Sigar implements SigarProxy {
* The scm (svn) revision from which sigar.jar was built. * The scm (svn) revision from which sigar.jar was built.
*/ */
public static final String SCM_REVISION = public static final String SCM_REVISION =
SigarVersion.SCM_REVISION; Version.SCM_REVISION;
/** /**
* The scm (svn) revision from which the sigar native binary was built. * The scm (svn) revision from which the sigar native binary was built.
@ -70,7 +70,7 @@ public class Sigar implements SigarProxy {
* The date on which sigar.jar was built. * The date on which sigar.jar was built.
*/ */
public static final String BUILD_DATE = public static final String BUILD_DATE =
SigarVersion.BUILD_DATE; Version.BUILD_DATE;
/** /**
* The date on which the sigar native binary was built. * The date on which the sigar native binary was built.
@ -959,6 +959,10 @@ public class Sigar implements SigarProxy {
*/ */
public native String getFQDN() throws SigarException; public native String getFQDN() throws SigarException;
public SigarVersion getSigarVersion() {
return new SigarVersion();
}
/** /**
* Enabling logging in the native Sigar code. * Enabling logging in the native Sigar code.
* This method will hook log4j into the Sigar * This method will hook log4j into the Sigar

View File

@ -172,5 +172,7 @@ public interface SigarProxy {
public NetInfo getNetInfo() throws SigarException; public NetInfo getNetInfo() throws SigarException;
public SigarVersion getSigarVersion();
public String getFQDN() throws SigarException; public String getFQDN() throws SigarException;
} }

View File

@ -123,7 +123,7 @@ public class SigarProxyCache
* The java.lang.reflect.InvocationHandler used by the Proxy. * The java.lang.reflect.InvocationHandler used by the Proxy.
* This method handles caching of all Sigar type objects. * This method handles caching of all Sigar type objects.
*/ */
public Object invoke(Object proxy, Method method, Object[] args) public synchronized Object invoke(Object proxy, Method method, Object[] args)
throws SigarException, SigarNotImplementedException { throws SigarException, SigarNotImplementedException {
SigarCacheObject cacheVal = null; SigarCacheObject cacheVal = null;

View File

@ -0,0 +1,53 @@
package org.hyperic.sigar;
public class SigarVersion {
/**
* @return Version number of the Java sigar.jar library
*/
public String getJarVersion() {
return Sigar.VERSION_STRING;
}
/**
* @return Version number of the native sigar library
*/
public String getNativeVersion() {
return Sigar.NATIVE_VERSION_STRING;
}
/**
* @return Build date of the Java sigar.jar library
*/
public String getJarBuildDate() {
return Sigar.BUILD_DATE;
}
/**
* @return Build date of the native sigar library
*/
public String getNativeBuildDate() {
return Sigar.NATIVE_BUILD_DATE;
}
/**
* @return Source code revision of the Java sigar.jar library
*/
public String getJarSourceRevision() {
return Sigar.SCM_REVISION;
}
/**
* @return Source code revision of the native sigar library
*/
public String getNativeSourceRevision() {
return Sigar.NATIVE_SCM_REVISION;
}
/**
* @return Name of the loaded native sigar library file
*/
public String getNativeLibraryName() {
return SigarLoader.getNativeLibraryName();
}
}

View File

@ -1,6 +1,6 @@
package org.hyperic.sigar; package org.hyperic.sigar;
class SigarVersion { class Version {
static final String BUILD_DATE = "@@BUILD_DATE@@"; static final String BUILD_DATE = "@@BUILD_DATE@@";

View File

@ -29,11 +29,10 @@ import javax.management.ObjectName;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.jmx.SigarProcess; import org.hyperic.sigar.jmx.SigarProcess;
import org.hyperic.sigar.jmx.SigarRegistry;
public class Mx extends SigarCommandBase { public class Mx extends SigarCommandBase {
private boolean isRegistered; private ObjectName registryName;
public Mx(Shell shell) { public Mx(Shell shell) {
super(shell); super(shell);
@ -65,32 +64,56 @@ public class Mx extends SigarCommandBase {
} }
private void register(MBeanServer server) throws SigarException { private void register(MBeanServer server) throws SigarException {
if (isRegistered) { if (this.registryName != null) {
return; return;
} }
SigarRegistry registry = new SigarRegistry();
try { try {
server.registerMBean(registry, null); String name = org.hyperic.sigar.jmx.SigarRegistry.class.getName();
SigarProcess proc = new SigarProcess(); this.registryName = server.createMBean(name, null).getObjectName();
server.registerMBean(proc, new ObjectName(proc.getObjectName())); SigarProcess proc = new SigarProcess(this.sigar);
isRegistered = true; ObjectName pname = new ObjectName(proc.getObjectName());
if (!server.isRegistered(pname)) {
server.registerMBean(proc, pname);
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
throw new SigarException(e.getMessage()); throw new SigarException(e.getMessage());
} }
} }
private void jconsole() {
String pid = String.valueOf(this.sigar.getPid());
String[] argv = { "jconsole", pid };
println("exec(jconsole, " + pid + ")");
try {
Process p = Runtime.getRuntime().exec(argv);
p.waitFor();
println("jconsole exited");
} catch (Exception e) {
println(e.getMessage());
}
}
public void output(String[] args) throws SigarException { public void output(String[] args) throws SigarException {
MBeanServer server = getMBeanServer(); MBeanServer server = getMBeanServer();
register(server); register(server);
boolean hasQuery = args.length != 0; boolean hasQuery = false;
try { boolean launchJconsole = false;
String query; String query = "sigar:*";
if (hasQuery) {
query = args[0]; for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.equals("-jconsole")) {
launchJconsole = true;
} }
else { else {
query = "sigar:*"; query = arg;
hasQuery = true;
} }
}
try {
Set beans = Set beans =
server.queryNames(new ObjectName(query), null); server.queryNames(new ObjectName(query), null);
println(beans.size() + " MBeans are registered..."); println(beans.size() + " MBeans are registered...");
@ -112,6 +135,16 @@ public class Mx extends SigarCommandBase {
} catch (Exception e) { } catch (Exception e) {
throw new SigarException(e.getMessage()); throw new SigarException(e.getMessage());
} }
if (launchJconsole) {
flush();
jconsole();
try { //test unregisterMBean
server.unregisterMBean(this.registryName);
this.registryName = null;
} catch (Exception e) {
e.printStackTrace();
}
}
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {

View File

@ -24,14 +24,11 @@ import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean; import javax.management.DynamicMBean;
import javax.management.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanRegistration; import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/** /**
* Base class for all Sigar JMX MBeans. Provides a skeleton which handles * Base class for all Sigar JMX MBeans. Provides a skeleton which handles
@ -44,26 +41,11 @@ import org.hyperic.sigar.SigarProxyCache;
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration { public abstract class AbstractMBean implements DynamicMBean {
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME; public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE; public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
protected static final short CACHED_30SEC = 0;
protected static final short CACHED_5SEC = 1;
protected static final short CACHED_500MS = 2;
protected static final short CACHELESS = 3;
protected static final short DEFAULT = CACHED_30SEC;
/**
* The Sigar implementation to be used to fetch information from the system.
*/
protected final Sigar sigarImpl;
/** /**
* The Sigar proxy cache to be used in case the data does not have to be * The Sigar proxy cache to be used in case the data does not have to be
* fetched during each call. The cache timeout is decided during * fetched during each call. The cache timeout is decided during
@ -75,69 +57,13 @@ public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
protected final SigarProxy sigar; protected final SigarProxy sigar;
/** /**
* The MBean server this MBean is registered to. Set during the MBean's * <p>Creates a new instance of this class. The SigarProxy instance is stored (and
* registration to the MBean server and unset to <code>null</code> when * accessible) via the {@link #sigar} member.
* the deregistration finished.
* *
* @see #preRegister(MBeanServer, ObjectName) * @param sigar The SigarProxy instance to use. Must not be <code>null</code>
* @see #postDeregister()
*/ */
protected MBeanServer mbeanServer; protected AbstractMBean(SigarProxy sigar) {
this.sigar = sigar;
/**
* <p>Creates a new instance of this class. The Sigar instance is stored (and
* accessible) via the {@link #sigarImpl} member. A second instance is
* stored within the {@link #sigar} member which is either {@link #sigarImpl}
* or an instance of {@link SigarProxyCache} with the expiration time set to
* whatever the <code>cacheMode</code> parameter specifies.</p>
*
* <p>The following cache modes exist:</p>
*
* <table border = "1">
* <tr><td><b>Constant</b></td><td><b>Description</b></td></tr>
* <tr><td>{@link #CACHELESS}</td><td>No cached instance, {@link #sigar}
* <code>==</code> {@link #sigarImpl}.</td></tr>
* <tr><td>{@link #CACHED_500MS}</td><td>500 millisecond cache, for high
* frequency queries on raw data such as reading out CPU timers each
* second. Avoids reading out multiple data sets when all attributes of
* an MBean are queried in short sequence.</td></tr>
* <tr><td>{@link #CACHED_5SEC}</td><td>5 second cache, for high frequency
* queries on calculated data such as CPU percentages.</td></tr>
* <tr><td>{@link #CACHED_30SEC}</td><td>30 second cache, for normal queries
* or data readouts such as CPU model / vendor. This is the default if
* nothing (<code>0</code>) is specified.</td></tr>
* <tr><td>{@link #DEFAULT}</td><td>Same as {@link #CACHED_30SEC}.</td></tr>
* </table>
*
* <p><b>Note:</b> Only make use of the cacheless or half second mode if you
* know what you are doing. They may have impact on system performance if
* used excessively.</p>
*
* @param sigar The Sigar impl to use. Must not be <code>null</code>
* @param cacheMode The cache mode to use for {@link #sigar} or {@link #CACHELESS}
* if no separate, cached instance is to be maintained.
*/
protected AbstractMBean(Sigar sigar, short cacheMode) {
// store Sigar
this.sigarImpl = sigar;
// create a cached instance as well
if (cacheMode == CACHELESS) {
// no cached version
this.sigar = this.sigarImpl;
} else if (cacheMode == CACHED_500MS) {
// 500ms cached version (for 1/sec queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 500);
} else if (cacheMode == CACHED_5SEC) {
// 5sec cached version (for avg'd queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 5000);
} else /* if (cacheMode == CACHED_30SEC) */{
// 30sec (default) cached version (for info and long term queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 30000);
}
} }
/** /**
@ -207,59 +133,6 @@ public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
return result; return result;
} }
// -------
// Implementation of the MBeanRegistration interface
// -------
/**
* <p>Returns <code>new ObjectName(this.getObjectName())</code> to guarantee
* a reliable and reproducable object name.</p>
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#preRegister(MBeanServer, ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
this.mbeanServer = server;
return new ObjectName(getObjectName());
}
/**
* Empty implementation, allowing subclasses to ignore the interface.
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#postRegister(Boolean)
*/
public void postRegister(Boolean success) {
}
/**
* Empty implementation, allowing subclasses to ignore the interface.
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#preDeregister()
*/
public void preDeregister() throws Exception {
}
/**
* Empty implementation, allowing subclasses to ignore the interface.
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#postDeregister()
*/
public void postDeregister() {
this.mbeanServer = null;
}
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }

View File

@ -29,7 +29,7 @@ import javax.management.MBeanException;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarProxy;
public class ReflectedMBean extends AbstractMBean { public class ReflectedMBean extends AbstractMBean {
@ -96,15 +96,15 @@ public class ReflectedMBean extends AbstractMBean {
} }
} }
protected ReflectedMBean(Sigar sigar, String type) { protected ReflectedMBean(SigarProxy sigar, String type) {
super(sigar, CACHED_5SEC); super(sigar);
this.type = type; this.type = type;
this.name = this.name =
MBEAN_DOMAIN + ":" + MBEAN_DOMAIN + ":" +
MBEAN_ATTR_TYPE + "=" + getType(); MBEAN_ATTR_TYPE + "=" + getType();
} }
protected ReflectedMBean(Sigar sigar, String type, String arg) { protected ReflectedMBean(SigarProxy sigar, String type, String arg) {
this(sigar, type); this(sigar, type);
this.name += ",Name=" + encode(arg); this.name += ",Name=" + encode(arg);
} }

View File

@ -18,13 +18,16 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import java.lang.reflect.InvocationHandler;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarInvoker; import org.hyperic.sigar.SigarInvoker;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
import org.hyperic.sigar.util.ReferenceMap; import org.hyperic.sigar.util.ReferenceMap;
/** /**
@ -61,6 +64,10 @@ public class SigarInvokerJMX extends SigarInvoker {
SigarInvokerJMX invoker; SigarInvokerJMX invoker;
if (!(proxy instanceof InvocationHandler) && (proxy instanceof Sigar)) {
proxy = SigarProxyCache.newInstance((Sigar)proxy);
}
int ix = name.indexOf(":"); int ix = name.indexOf(":");
if (ix > 0) { if (ix > 0) {
//skip domain name //skip domain name

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004-2009], Hyperic, Inc.
* This file is part of SIGAR. * This file is part of SIGAR.
* *
* SIGAR is free software; you can redistribute it and/or modify * SIGAR is free software; you can redistribute it and/or modify
@ -18,246 +18,38 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanException;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.LoadAverage;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy;
/** public class SigarLoadAverage extends ReflectedMBean {
* Sigar JMX MBean implementation for the <code>LoadAverage</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarLoadAverage extends AbstractMBean {
private static final String MBEAN_TYPE = "LoadAverage"; private static final String MBEAN_TYPE = "LoadAverage";
/** public SigarLoadAverage(SigarProxy sigar) {
* Returned if {@link Sigar#getLoadAverage()}} is detected to be not super(sigar, MBEAN_TYPE);
* implemented on the platform.
*
* @see #notImplemented
*/
private static final double NOT_IMPLEMENTED_LOAD_VALUE = -1.0d;
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST1MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST5MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST15MIN;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_LAST1MIN = new MBeanAttributeInfo(
"LastMinute",
"double",
"The load average in the last minute, as a fraction of 1, or "
+ "-1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_ATTR_LAST5MIN = new MBeanAttributeInfo(
"LastFiveMinutes",
"double",
"The load average over the last five minutes, as a fraction "
+ "of 1, or -1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_ATTR_LAST15MIN = new MBeanAttributeInfo(
"Last15Minutes",
"double",
"The load average over the last 15 minutes, as a fraction of "
+ "1, or -1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(
SigarLoadAverage.class.getName(),
"Creates a new instance, using the Sigar instance specified "
+ "to fetch the data. Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo(
SigarLoadAverage.class.getName(),
"Sigar load average MBean. Provides load averages of the "
+ "system over the last one, five and 15 minutes. Due to the "
+ "long term character of that information, the fetch is done "
+ "using a Sigar proxy cache with a timeout of 30 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_LAST1MIN,
MBEAN_ATTR_LAST5MIN, MBEAN_ATTR_LAST15MIN },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
} }
/** public Object getAttribute(String name)
* Object name this instance will give itself when being registered to an throws AttributeNotFoundException,
* MBeanServer. MBeanException, ReflectionException {
*/
private final String objectName;
/**
* <p>Set <code>true</code> when the load average fetch failed with a
* <code>SigarException</code> that indicates the method is not implemented.
* Any subsequent call to this instance will then be answered with
* {@link #NOT_IMPLEMENTED_LOAD_VALUE}.
* </p>
*
* <p><b>FIXME</b> : This is a workaround and should be replaced by something
* more stable, as the code setting this member <code>true</code> relies on
* a substring being present within the exception. A proposal was made at
* <a href="http://jira.hyperic.com/browse/SIGAR-52">issue SIGAR-52</a>.
* </p>
*/
private boolean notImplemented;
/**
* Creates a new instance, using a new Sigar instance to fetch the data.
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs.
*/
public SigarLoadAverage() throws IllegalArgumentException {
this(new Sigar());
}
/**
* Creates a new instance, using the Sigar instance specified to fetch the
* data.
*
* @param sigar
* The Sigar instance to use to fetch data from
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs
*/
public SigarLoadAverage(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_30SEC);
// all fine
this.objectName = MBEAN_DOMAIN + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE;
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The load average in the last minute, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLastMinute() {
try { try {
return sigarImpl.getLoadAverage()[0]; Object val =
new LoadAverage(this.sigar.getLoadAverage()).toMap().get(name);
if (val == null) {
throw new AttributeNotFoundException(name);
}
return val;
} catch (SigarNotImplementedException e) { } catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE; return new Double(Sigar.FIELD_NOTIMPL);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw new ReflectionException(e);
} }
} }
/**
* @return The load average over the last five minutes, as a fraction of 1,
* or <code>-1.0d</code> if the load cannot be determined on this
* platform
*/
public double getLastFiveMinutes() {
try {
return sigarImpl.getLoadAverage()[1];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The load average over the last 15 minutes, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLast15Minutes() {
try {
return sigarImpl.getLoadAverage()[2];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_LAST1MIN.getName().equals(attr)) {
return new Double(getLastMinute());
} else if (MBEAN_ATTR_LAST5MIN.getName().equals(attr)) {
return new Double(getLastFiveMinutes());
} else if (MBEAN_ATTR_LAST15MIN.getName().equals(attr)) {
return new Double(getLast15Minutes());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
} }

View File

@ -40,16 +40,18 @@ public class SigarProcess implements SigarProcessMBean {
private long pid = -1; private long pid = -1;
public SigarProcess() { public SigarProcess() {
this(new Sigar()); this.sigarImpl = new Sigar();
}
public SigarProcess(Sigar sigar) {
this.sigarImpl = sigar;
this.sigar = SigarProxyCache.newInstance(sigarImpl); this.sigar = SigarProxyCache.newInstance(sigarImpl);
} }
public SigarProcess(SigarProxy sigar) {
this.sigar = sigar;
}
public void close() { public void close() {
this.sigarImpl.close(); if (this.sigarImpl != null) {
this.sigarImpl.close();
}
} }
private RuntimeException unexpectedError(String type, private RuntimeException unexpectedError(String type,

View File

@ -19,15 +19,8 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.management.AttributeNotFoundException; import javax.management.MBeanRegistration;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.management.ObjectInstance; import javax.management.ObjectInstance;
import javax.management.ObjectName; import javax.management.ObjectName;
@ -37,7 +30,8 @@ import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarLoader; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/** /**
* <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke * <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke
@ -64,131 +58,37 @@ import org.hyperic.sigar.SigarLoader;
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarRegistry extends AbstractMBean { public class SigarRegistry implements MBeanRegistration, SigarRegistryMBean {
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
private static final String MBEAN_TYPE = "SigarRegistry"; private static final String MBEAN_TYPE = "SigarRegistry";
private static final int CACHE_EXPIRE = 60 * 1000;
private static final Map VERSION_ATTRS = new LinkedHashMap(); private Sigar sigarImpl;
private SigarProxy sigar;
private String objectName;
private static final MBeanInfo MBEAN_INFO; private ArrayList managedBeans;
private MBeanServer mbeanServer;
private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT; public SigarRegistry() {}
// private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES; public SigarRegistry(SigarProxy sigar) {
init(sigar);
static {
MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo(
SigarRegistry.class.getName(),
"Creates a new instance of this class. Will create the Sigar "
+ "instance this class uses when constructing other MBeans",
new MBeanParameterInfo[0]);
// MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses",
// "Executes a query returning the process IDs of all processes " +
// "found on the system.",
// null /* new MBeanParameterInfo[0] */,
// String.class.getName(), MBeanOperationInfo.INFO);
MBEAN_INFO = new MBeanInfo(
SigarRegistry.class.getName(),
"Sigar MBean registry. Provides a central point for creation "
+ "and destruction of Sigar MBeans. Any Sigar MBean created via "
+ "this instance will automatically be cleaned up when this "
+ "instance is deregistered from the MBean server.",
getAttributeInfo(),
new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT },
null /*new MBeanOperationInfo[0] */,
null /*new MBeanNotificationInfo[0]*/);
} }
private final String objectName; private void init(SigarProxy sigar) {
this.sigar = sigar;
private final ArrayList managedBeans; this.objectName =
MBEAN_DOMAIN + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE;
private static MBeanAttributeInfo[] getAttributeInfo() {
VERSION_ATTRS.put("JarVersion", Sigar.VERSION_STRING);
VERSION_ATTRS.put("NativeVersion", Sigar.NATIVE_VERSION_STRING);
VERSION_ATTRS.put("JarBuildDate", Sigar.BUILD_DATE);
VERSION_ATTRS.put("NativeBuildDate", Sigar.NATIVE_BUILD_DATE);
VERSION_ATTRS.put("JarSourceRevision", Sigar.SCM_REVISION);
VERSION_ATTRS.put("NativeSourceRevision", Sigar.NATIVE_SCM_REVISION);
VERSION_ATTRS.put("NativeLibraryName", SigarLoader.getNativeLibraryName());
MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[VERSION_ATTRS.size()];
int i=0;
for (Iterator it=VERSION_ATTRS.entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
String name = (String)entry.getKey();
attrs[i++] =
new MBeanAttributeInfo(name,
entry.getValue().getClass().getName(),
name,
true, // isReadable
false, // isWritable
false); // isIs
}
return attrs;
}
/**
* Creates a new instance of this class. Will create the Sigar instance this
* class uses when constructing other MBeans.
*/
public SigarRegistry() {
super(new Sigar(), CACHELESS);
this.objectName = MBEAN_DOMAIN + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE;
this.managedBeans = new ArrayList(); this.managedBeans = new ArrayList();
} }
/* (non-Javadoc)
* @see AbstractMBean#getObjectName()
*/
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/* public String listProcesses() {
try {
final long start = System.currentTimeMillis();
long[] ids = sigar.getProcList();
StringBuffer procNames = new StringBuffer();
for (int i = 0; i < ids.length; i++) {
try {
procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n');
} catch (SigarException e) {
procNames.append(ids[i] + ":" + e.getMessage()).append('\n');
}
}
final long end = System.currentTimeMillis();
procNames.append("-- Took " + (end-start) + "ms");
return procNames.toString();
} catch (SigarException e) {
throw unexpectedError("ProcList", e);
}
}
*/
/* (non-Javadoc)
* @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
Object obj = VERSION_ATTRS.get(attr);
if (obj == null) {
throw new AttributeNotFoundException(attr);
}
return obj;
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
private void registerMBean(AbstractMBean mbean) { private void registerMBean(AbstractMBean mbean) {
try { try {
ObjectName name = ObjectName name =
@ -207,18 +107,30 @@ public class SigarRegistry extends AbstractMBean {
// ------- // -------
// Implementation of the MBeanRegistration interface // Implementation of the MBeanRegistration interface
// ------- // -------
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
//no args constructor support
if (this.sigar == null) {
this.sigarImpl = new Sigar();
init(SigarProxyCache.newInstance(this.sigarImpl, CACHE_EXPIRE));
}
this.mbeanServer = server;
if (name == null) {
return new ObjectName(getObjectName());
}
else {
return name;
}
}
/** /**
* Registers the default set of Sigar MBeans. Before doing so, a super call * Registers the default set of Sigar MBeans.
* is made to satisfy {@link AbstractMBean}.
*
* @see AbstractMBean#postRegister(Boolean)
*/ */
public void postRegister(Boolean success) { public void postRegister(Boolean success) {
ReflectedMBean mbean; ReflectedMBean mbean;
super.postRegister(success);
if (!success.booleanValue()) if (!success.booleanValue())
return; return;
@ -227,32 +139,32 @@ public class SigarRegistry extends AbstractMBean {
try { try {
info = sigar.getCpuInfoList(); info = sigar.getCpuInfoList();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("CpuInfoList", e); info = new CpuInfo[0]; //XXX log
} }
for (int i=0; i<info.length; i++) { for (int i=0; i<info.length; i++) {
String idx = String.valueOf(i); String idx = String.valueOf(i);
mbean = mbean =
new ReflectedMBean(sigarImpl, "CpuCore", idx); new ReflectedMBean(this.sigar, "CpuCore", idx);
mbean.setType("CpuList"); mbean.setType("CpuList");
registerMBean(mbean); registerMBean(mbean);
mbean = mbean =
new ReflectedMBean(sigarImpl, "CpuCoreUsage", idx); new ReflectedMBean(this.sigar, "CpuCoreUsage", idx);
mbean.setType("CpuPercList"); mbean.setType("CpuPercList");
registerMBean(mbean); registerMBean(mbean);
} }
mbean = new ReflectedMBean(sigarImpl, "Cpu"); mbean = new ReflectedMBean(this.sigar, "Cpu");
mbean.putAttributes(info[0]); mbean.putAttributes(info[0]);
registerMBean(mbean); registerMBean(mbean);
mbean = new ReflectedMBean(sigarImpl, "CpuUsage"); mbean = new ReflectedMBean(this.sigar, "CpuUsage");
mbean.setType("CpuPerc"); mbean.setType("CpuPerc");
registerMBean(mbean); registerMBean(mbean);
//FileSystem beans //FileSystem beans
try { try {
FileSystem[] fslist = sigarImpl.getFileSystemList(); FileSystem[] fslist = this.sigar.getFileSystemList();
for (int i=0; i<fslist.length; i++) { for (int i=0; i<fslist.length; i++) {
FileSystem fs = fslist[i]; FileSystem fs = fslist[i];
if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) { if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) {
@ -260,57 +172,59 @@ public class SigarRegistry extends AbstractMBean {
} }
String name = fs.getDirName(); String name = fs.getDirName();
mbean = mbean =
new ReflectedMBean(sigarImpl, "FileSystem", name); new ReflectedMBean(this.sigar, "FileSystem", name);
mbean.setType(mbean.getType() + "Usage"); mbean.setType(mbean.getType() + "Usage");
mbean.putAttributes(fs); mbean.putAttributes(fs);
registerMBean(mbean); registerMBean(mbean);
} }
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("FileSystemList", e); //XXX log
} }
//NetInterface beans //NetInterface beans
try { try {
String[] ifnames = sigarImpl.getNetInterfaceList(); String[] ifnames = this.sigar.getNetInterfaceList();
for (int i=0; i<ifnames.length; i++) { for (int i=0; i<ifnames.length; i++) {
String name = ifnames[i]; String name = ifnames[i];
NetInterfaceConfig ifconfig = NetInterfaceConfig ifconfig =
this.sigar.getNetInterfaceConfig(name); this.sigar.getNetInterfaceConfig(name);
try { try {
sigarImpl.getNetInterfaceStat(name); this.sigar.getNetInterfaceStat(name);
} catch (SigarException e) { } catch (SigarException e) {
continue; continue;
} }
mbean = mbean =
new ReflectedMBean(sigarImpl, "NetInterface", name); new ReflectedMBean(this.sigar, "NetInterface", name);
mbean.setType(mbean.getType() + "Stat"); mbean.setType(mbean.getType() + "Stat");
mbean.putAttributes(ifconfig); mbean.putAttributes(ifconfig);
registerMBean(mbean); registerMBean(mbean);
} }
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("NetInterfaceList", e); //XXX log
} }
//network info bean //network info bean
mbean = new ReflectedMBean(sigarImpl, "NetInfo"); mbean = new ReflectedMBean(this.sigar, "NetInfo");
try { try {
mbean.putAttribute("FQDN", sigarImpl.getFQDN()); mbean.putAttribute("FQDN", this.sigar.getFQDN());
} catch (SigarException e) { } catch (SigarException e) {
} }
registerMBean(mbean); registerMBean(mbean);
//physical memory bean //physical memory bean
registerMBean(new ReflectedMBean(sigarImpl, "Mem")); registerMBean(new ReflectedMBean(this.sigar, "Mem"));
//swap memory bean //swap memory bean
registerMBean(new ReflectedMBean(sigarImpl, "Swap")); registerMBean(new ReflectedMBean(this.sigar, "Swap"));
//load average bean //load average bean
registerMBean(new SigarLoadAverage(sigarImpl)); registerMBean(new SigarLoadAverage(this.sigar));
//global process stats //global process stats
registerMBean(new ReflectedMBean(sigarImpl, "ProcStat")); registerMBean(new ReflectedMBean(this.sigar, "ProcStat"));
//sigar version
registerMBean(new ReflectedMBean(this.sigar, "SigarVersion"));
} }
/** /**
* Deregisters all Sigar MBeans that were created and registered using this * Deregisters all Sigar MBeans that were created and registered using this
* instance. After doing so, a super call is made to satisfy {@link AbstractMBean}. * instance.
* @throws Exception * @throws Exception
* *
* @see AbstractMBean#preDeregister() * @see AbstractMBean#preDeregister()
@ -327,8 +241,14 @@ public class SigarRegistry extends AbstractMBean {
} }
} }
} }
}
// do the super call public void postDeregister() {
super.preDeregister(); this.mbeanServer = null;
if (this.sigarImpl != null) {
this.sigarImpl.close();
this.sigarImpl = null;
this.sigar = null;
}
} }
} }

View File

@ -0,0 +1,23 @@
/*
* Copyright (C) [2004-2009], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar.jmx;
public interface SigarRegistryMBean {
}

View File

@ -73,10 +73,10 @@ public class TestMx extends SigarTestCase {
return; return;
} }
SigarRegistry rgy = new SigarRegistry(); SigarRegistry rgy = new SigarRegistry(getSigar());
ObjectName name = new ObjectName(rgy.getObjectName()); ObjectName name = new ObjectName(rgy.getObjectName());
if (!server.isRegistered(name)) { if (!server.isRegistered(name)) {
server.registerMBean(new SigarRegistry(), name); server.registerMBean(rgy, name);
} }
Set beans = Set beans =
server.queryNames(new ObjectName("sigar:*"), null); server.queryNames(new ObjectName("sigar:*"), null);

View File

@ -1905,7 +1905,7 @@ int sigar_thread_cpu_get(sigar_t *sigar,
sigar_uint64_t id, sigar_uint64_t id,
sigar_thread_cpu_t *cpu) sigar_thread_cpu_t *cpu)
{ {
#ifdef DARWIN #if defined(DARWIN)
mach_port_t self = mach_thread_self(); mach_port_t self = mach_thread_self();
thread_basic_info_data_t info; thread_basic_info_data_t info;
mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
@ -1922,6 +1922,8 @@ int sigar_thread_cpu_get(sigar_t *sigar,
cpu->user = tval2nsec(info.user_time); cpu->user = tval2nsec(info.user_time);
cpu->sys = tval2nsec(info.system_time); cpu->sys = tval2nsec(info.system_time);
cpu->total = cpu->user + cpu->sys; cpu->total = cpu->user + cpu->sys;
#elif defined(__NetBSD__)
return SIGAR_ENOTIMPL; /* http://tinyurl.com/chbvln */
#else #else
/* XXX this is not per-thread, it is for the whole-process. /* XXX this is not per-thread, it is for the whole-process.
* just want to use for the shell time command at the moment. * just want to use for the shell time command at the moment.