Author SHA1 Message Date
Doug MacEachern ae289d3d41 (SIGAR-134) use UNICODE in EventLog wrapper 2009-02-12 16:37:29 -08:00
Doug MacEachern b64ebca57e s/SVN/SCM/ 2009-02-10 17:38:24 -08:00
Doug MacEachern bc3e8ed6d4 (SIGAR-73) check for 'ocfs' in addition to 'ocfs2' 2009-02-10 13:52:03 -08:00
Doug MacEachern 7ef48da327 dos2unix 2009-02-09 14:21:00 -08:00
Doug MacEachern 7a5288278c dos2unix 2009-02-09 14:15:49 -08:00
Doug MacEachern 2e3c302f4f dos2unix 2009-02-09 13:28:00 -08:00
Doug MacEachern 93afe26132 (SIGAR-138) Recognize zfs as local filesystem type 2009-02-08 18:08:27 -08:00
Doug MacEachern 22dec9316c Merge branch 'jk/pstat_getfile2' 2009-02-06 17:42:39 -08:00
Doug MacEachern 9774d05e20 Merge branch 'jk/pstat_getfile2' 2009-02-06 17:42:33 -08:00
Doug MacEachern bca7314718 .gitignore 2009-02-06 16:14:13 -08:00
Doug MacEachern bf342bc9cf fix git rev-parse 2009-02-06 16:07:21 -08:00
Doug MacEachern 3a9d6b7024 remove invalid assertion 2009-02-06 14:32:02 -08:00
Doug MacEachern 95dcc68c57 no need for libarch in generated sigar_version.c 2009-02-06 13:54:23 -08:00
Doug MacEachern 5d50f402bb fix osx version on 64-bit platforms 2009-02-06 13:54:12 -08:00
Doug MacEachern 5df4c608b4 s/SVN/SCM/ 2009-02-06 13:53:59 -08:00
Doug MacEachern 143e8fb6bd check for git revision 2009-02-06 13:53:47 -08:00
Doug MacEachern e787667e91 cp r157 from http://svn.hyperic.org/projects/hyperic_jni 2009-02-06 13:53:30 -08:00
Doug MacEachern 1cd800ff6e no longer using BCEL 2009-02-06 13:53:02 -08:00
Doug MacEachern 08cfdfef6e update copyright.year 2009-02-06 13:52:47 -08:00
Doug MacEachern a7495637a9 [SIGAR-133] use InputStream.skip (bytes) instead of Reader.skip (chars) in onChange 2009-02-06 13:52:33 -08:00
Doug MacEachern bd2178d0cf [SIGAR-132] Fix possible memory leak in sigar_rpc_ping 2009-02-06 13:46:49 -08:00
Doug MacEachern 6db07f1cba [SIGAR-129] fix possible integer overflow in time_now_millis 2009-02-06 13:46:38 -08:00
Doug MacEachern ede7b6c9de [SIGAR-129] add another sanity check 2009-02-06 13:46:27 -08:00
Doug MacEachern bf61ce78a9 [SIGAR-129] prevent possible wrapping 2009-02-06 13:46:16 -08:00
Doug MacEachern 0175e969e1 [SIGAR-129] prevent possible integer overflow 2009-02-06 13:45:56 -08:00
Doug MacEachern be5f4930a7 handle processes that may have gone away 2009-02-06 13:45:44 -08:00
Doug MacEachern 4c441a3ee2 revert r3669 - requires vc6sp5+vcpp5 on windows 2009-02-06 13:45:26 -08:00
Doug MacEachern 06f4770bf0 bump version 2009-02-06 13:45:11 -08:00
Doug MacEachern 1ccf48ca19 [SIGAR-127] use KERN_ARGMAX for KERN_PROCARGS2 buffer size 2009-02-06 13:44:35 -08:00
Doug MacEachern 4867aeb235 [SIGAR-126] /dev/kmem not usable in aix 6 2009-02-06 13:44:21 -08:00
Doug MacEachern d19ab5ae30 rid "warning: cast from pointer to integer of different size" on 64-bit builds 2009-02-06 13:43:37 -08:00
Doug MacEachern 8e9ab74eee [SIGAR-125] bring back /private/var/vm swap impl for osx 10.3 2009-02-06 13:43:22 -08:00
Doug MacEachern c2114a71e1 [SIGAR-123] do not include global shared text+data region size 2009-02-06 13:42:46 -08:00
Doug MacEachern ec7d726a9d [SIGAR-122] ARG_MAX undefined on glibc 2.8 2009-02-06 13:42:16 -08:00
44 changed files with 5347 additions and 3127 deletions

No files matched your search

+104 -104
View File
@@ -1,104 +1,104 @@
Hyperic FLOSS License Exception Hyperic FLOSS License Exception
The Hyperic Exception for Free/Libre and Open Source The Hyperic Exception for Free/Libre and Open Source
Software-only Applications Using Hyperic SIGAR Libraries (the Software-only Applications Using Hyperic SIGAR Libraries (the
"FLOSS Exception"). "FLOSS Exception").
Version 0.1, September 6, 2008 Version 0.1, September 6, 2008
Exception Intent Exception Intent
We want specified Free/Libre and Open Source Software (``FLOSS'') We want specified Free/Libre and Open Source Software (``FLOSS'')
applications to be able to use specified GPL-licensed Hyperic SIGAR applications to be able to use specified GPL-licensed Hyperic SIGAR
libraries (the ``Program'') despite the fact that not all FLOSS libraries (the ``Program'') despite the fact that not all FLOSS
licenses are compatible with version 2 of the GNU General Public licenses are compatible with version 2 of the GNU General Public
License (the ``GPL''). License (the ``GPL'').
Legal Terms and Conditions Legal Terms and Conditions
As a special exception to the terms and conditions of version 2.0 As a special exception to the terms and conditions of version 2.0
of the GPL: of the GPL:
1. You are free to distribute a Derivative Work that is formed 1. You are free to distribute a Derivative Work that is formed
entirely from the Program and one or more works (each, a entirely from the Program and one or more works (each, a
"FLOSS Work") licensed under one or more of the licenses "FLOSS Work") licensed under one or more of the licenses
listed below in section 1, as long as: listed below in section 1, as long as:
a. You obey the GPL in all respects for the Program and the a. You obey the GPL in all respects for the Program and the
Derivative Work, except for identifiable sections of the Derivative Work, except for identifiable sections of the
Derivative Work which are not derived from the Program, Derivative Work which are not derived from the Program,
and which can reasonably be considered independent and and which can reasonably be considered independent and
separate works in themselves, separate works in themselves,
b. all identifiable sections of the Derivative Work which b. all identifiable sections of the Derivative Work which
are not derived from the Program, and which can are not derived from the Program, and which can
reasonably be considered independent and separate works reasonably be considered independent and separate works
in themselves, in themselves,
i. are distributed subject to one of the FLOSS licenses i. are distributed subject to one of the FLOSS licenses
listed below, and listed below, and
ii. the object code or executable form of those sections ii. the object code or executable form of those sections
are accompanied by the complete corresponding are accompanied by the complete corresponding
machine-readable source code for those sections on machine-readable source code for those sections on
the same medium and under the same FLOSS license as the same medium and under the same FLOSS license as
the corresponding object code or executable forms of the corresponding object code or executable forms of
those sections, and those sections, and
c. any works which are aggregated with the Program or with a c. any works which are aggregated with the Program or with a
Derivative Work on a volume of a storage or distribution Derivative Work on a volume of a storage or distribution
medium in accordance with the GPL, can reasonably be medium in accordance with the GPL, can reasonably be
considered independent and separate works in themselves considered independent and separate works in themselves
which are not derivatives of either the Program, a which are not derivatives of either the Program, a
Derivative Work or a FLOSS Work. Derivative Work or a FLOSS Work.
If the above conditions are not met, then the Program may only If the above conditions are not met, then the Program may only
be copied, modified, distributed or used under the terms and be copied, modified, distributed or used under the terms and
conditions of the GPL or another valid licensing option from conditions of the GPL or another valid licensing option from
Hyperic, Inc. Hyperic, Inc.
2. FLOSS License List 2. FLOSS License List
License name Version(s)/Copyright Date License name Version(s)/Copyright Date
Apache Software License 1.0/1.1/2.0 Apache Software License 1.0/1.1/2.0
Artistic license From Perl 5.8.0 Artistic license From Perl 5.8.0
BSD license "July 22 1999" BSD license "July 22 1999"
Eclipse Public License 1.0 Eclipse Public License 1.0
Mozilla Public License (MPL) 1.0/1.1 Mozilla Public License (MPL) 1.0/1.1
Open Software License 2.0 Open Software License 2.0
PHP License 3.0 PHP License 3.0
Python Software Foundation License 2.1.1 Python Software Foundation License 2.1.1
Due to the many variants of some of the above licenses, we Due to the many variants of some of the above licenses, we
require that any version follow the 2003 version of the Free require that any version follow the 2003 version of the Free
Software Foundation's Free Software Definition Software Foundation's Free Software Definition
(http://www.gnu.org/philosophy/free-sw.html) or version 1.9 of (http://www.gnu.org/philosophy/free-sw.html) or version 1.9 of
the Open Source Definition by the Open Source Initiative the Open Source Definition by the Open Source Initiative
(http://www.opensource.org/docs/definition.php). (http://www.opensource.org/docs/definition.php).
3. Definitions 3. Definitions
a. Terms used, but not defined, herein shall have the a. Terms used, but not defined, herein shall have the
meaning provided in the GPL. meaning provided in the GPL.
b. Derivative Work means a derivative work under copyright b. Derivative Work means a derivative work under copyright
law. law.
4. Applicability: This FLOSS Exception applies to all Programs 4. Applicability: This FLOSS Exception applies to all Programs
that contain a notice placed by Hyperic, Inc. saying that the that contain a notice placed by Hyperic, Inc. saying that the
Program may be distributed under the terms of this FLOSS Program may be distributed under the terms of this FLOSS
Exception. If you create or distribute a work which is a Exception. If you create or distribute a work which is a
Derivative Work of both the Program and any other work Derivative Work of both the Program and any other work
licensed under the GPL, then this FLOSS Exception is not licensed under the GPL, then this FLOSS Exception is not
available for that work; thus, you must remove the FLOSS available for that work; thus, you must remove the FLOSS
Exception notice from that work and comply with the GPL in all Exception notice from that work and comply with the GPL in all
respects, including by retaining all GPL notices. You may respects, including by retaining all GPL notices. You may
choose to redistribute a copy of the Program exclusively under choose to redistribute a copy of the Program exclusively under
the terms of the GPL by removing the FLOSS Exception notice the terms of the GPL by removing the FLOSS Exception notice
from that copy of the Program, provided that the copy has from that copy of the Program, provided that the copy has
never been modified by you or any third party. never been modified by you or any third party.
Appendix A. Qualified Libraries and Packages Appendix A. Qualified Libraries and Packages
The following is a non-exhaustive list of libraries and packages The following is a non-exhaustive list of libraries and packages
which are covered by the FLOSS License Exception. Please note that which are covered by the FLOSS License Exception. Please note that
this appendix is provided merely as an additional service to this appendix is provided merely as an additional service to
specific FLOSS projects wishing to simplify licensing information specific FLOSS projects wishing to simplify licensing information
for their users. Compliance with one of the licenses noted under for their users. Compliance with one of the licenses noted under
the "FLOSS license list" section remains a prerequisite. the "FLOSS license list" section remains a prerequisite.
Package Name Qualifying License and Version Package Name Qualifying License and Version
Apache Portable Runtime (APR) Apache Software License 2.0 Apache Portable Runtime (APR) Apache Software License 2.0
-4
View File
@@ -8,10 +8,6 @@ of the projects listed below for their contributions.
The following components are included without modification: The following components are included without modification:
- BCEL -
Information: http://jakarta.apache.org/bcel/index.html
License: http://www.apache.org/licenses/LICENSE-2.0
- log4j - - log4j -
Information: http://logging.apache.org/ Information: http://logging.apache.org/
License: http://www.apache.org/licenses/LICENSE-2.0 License: http://www.apache.org/licenses/LICENSE-2.0
+2
View File
@@ -0,0 +1,2 @@
build
sigar-bin
+28 -4
View File
@@ -141,7 +141,7 @@
</condition> </condition>
</target> </target>
<target name="scm-revision" if="svn.available"> <target name="svn-revision" if="svn.available">
<exec executable="svnversion" dir="." <exec executable="svnversion" dir="."
outputproperty="sigar.scmrev" outputproperty="sigar.scmrev"
failifexecutionfails="false"> failifexecutionfails="false">
@@ -150,7 +150,31 @@
<echo message="SIGAR svn revision #${sigar.scmrev}"/> <echo message="SIGAR svn revision #${sigar.scmrev}"/>
</target> </target>
<target name="sigar-version" depends="check-svn,scm-revision"> <target name="check-git">
<condition property="git.available">
<and>
<available file="../../.git" type="dir"/>
<available file="git" type="file">
<filepath>
<pathelement path="${env.PATH}"/>
</filepath>
</available>
</and>
</condition>
</target>
<target name="git-revision" if="git.available">
<exec executable="git" dir="."
outputproperty="sigar.scmrev"
failifexecutionfails="false">
<arg value="rev-parse"/>
<arg value="--short"/>
<arg value="HEAD"/>
</exec>
<echo message="SIGAR git revision #${sigar.scmrev}"/>
</target>
<target name="sigar-version" depends="check-svn,svn-revision,check-git,git-revision">
<tstamp> <tstamp>
<format property="BUILD_DATE" pattern="MM/dd/yyyy hh:mm aa"/> <format property="BUILD_DATE" pattern="MM/dd/yyyy hh:mm aa"/>
</tstamp> </tstamp>
@@ -169,7 +193,7 @@
<param name="version.file" <param name="version.file"
value="src/sigar_version.c"/> value="src/sigar_version.c"/>
<param name="version.tofile" <param name="version.tofile"
value="${build}/src/sigar_version_${jni.libarch}.c"/> value="${build}/src/sigar_version.c"/>
</antcall> </antcall>
<antcall target="version-file"> <antcall target="version-file">
@@ -239,7 +263,7 @@
<include name="bindings/java/src/${win32.jni}/*.cpp"/> <include name="bindings/java/src/${win32.jni}/*.cpp"/>
<include name="bindings/java/src/${win32.jni}/*.c"/> <include name="bindings/java/src/${win32.jni}/*.c"/>
<include name="bindings/java/src/${vmware.jni}/*.c"/> <include name="bindings/java/src/${vmware.jni}/*.c"/>
<include name="bindings/java/build/src/sigar_version_${jni.libarch}.c"/> <include name="bindings/java/build/src/sigar_version.c"/>
</patternset> </patternset>
<path id="jni.include.dirs"> <path id="jni.include.dirs">
+522
View File
@@ -0,0 +1,522 @@
<!--
Copyright (C) [2004, 2005, 2006], 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.
-->
<property environment="env"/>
<property name="build" location="build"/>
<property name="jni.bin" location="${build}"/>
<property name="jni.define.name" value="JNI"/>
<property name="jni.source.dir" value="src"/>
<property name="jni.src.java" value="src"/>
<property name="jni.libprefix" value="java"/>
<property name="jni.libversion" value=""/>
<property name="uni.sdk.version" value="4u"/>
<property name="osx.min" value="-mmacosx-version-min=10.3"/>
<property name="cpptasks.jar" location="lib/cpptasks.jar"/>
<taskdef name="cc" classname="net.sf.antcontrib.cpptasks.CCTask">
<classpath location="${cpptasks.jar}"/>
</taskdef>
<target name="jni-init">
<mkdir dir="${build}/classes"/>
<available property="libproc.h" file="/usr/include/libproc.h"/>
<condition property="jni.debug" value="true">
<isset property="jni.dmalloc"/>
</condition>
<condition property="jni.optim" value="true">
<not>
<istrue value="${jni.debug}"/>
</not>
</condition>
<condition property="static.gcc">
<os arch="i386"/><!-- only for x86 solaris -->
</condition>
<condition property="jni.javahome" value="${env.JAVA_HOME}">
<isset property="env.JAVA_HOME"/>
</condition>
<condition property="jni.javahome" value="${java.home}">
<not>
<isset property="jni.javahome"/>
</not>
</condition>
<echo>java.home=${jni.javahome}</echo>
<checksum file="${jni.javahome}/include/jni.h" property="jni.md5"/>
<condition property="linux">
<equals arg1="${os.name}" arg2="Linux"/>
</condition>
<condition property="solaris">
<equals arg1="${os.name}" arg2="SunOS"/>
</condition>
<condition property="win32">
<os family="windows"/>
</condition>
<condition property="hpux">
<equals arg1="${os.name}" arg2="HP-UX"/>
</condition>
<condition property="aix">
<equals arg1="${os.name}" arg2="AIX"/>
</condition>
<condition property="darwin">
<equals arg1="${os.name}" arg2="Mac OS X"/>
</condition>
<condition property="freebsd">
<equals arg1="${os.name}" arg2="FreeBSD"/>
</condition>
<condition property="openbsd">
<equals arg1="${os.name}" arg2="OpenBSD"/>
</condition>
<condition property="netbsd">
<equals arg1="${os.name}" arg2="NetBSD"/>
</condition>
<condition property="osf1">
<equals arg1="${os.name}" arg2="OSF1"/>
</condition>
<condition property="jni.os" value="linux">
<isset property="linux"/>
</condition>
<condition property="jni.os" value="win32">
<isset property="win32"/>
</condition>
<condition property="jni.os" value="solaris">
<isset property="solaris"/>
</condition>
<condition property="jni.os" value="aix">
<isset property="aix"/>
</condition>
<condition property="jni.os" value="hpux">
<isset property="hpux"/>
</condition>
<condition property="jni.os" value="darwin">
<isset property="darwin"/>
</condition>
<condition property="jni.os" value="freebsd">
<isset property="freebsd"/>
</condition>
<condition property="jni.os" value="openbsd">
<isset property="openbsd"/>
</condition>
<condition property="jni.os" value="netbsd">
<isset property="netbsd"/>
</condition>
<!-- darwin and freebsd use the same source files -->
<condition property="jni.src" value="darwin">
<isset property="freebsd"/>
</condition>
<condition property="jni.src" value="darwin">
<isset property="openbsd"/>
</condition>
<condition property="jni.src" value="darwin">
<isset property="netbsd"/>
</condition>
<condition property="jni.os" value="osf1">
<isset property="osf1"/>
</condition>
<condition property="jni.jdk.os" value="${jni.os}">
<and>
<isfalse value="${hpux}"/>
<isfalse value="${osf1}"/>
</and>
</condition>
<condition property="jni.jdk.os" value="hp-ux">
<istrue value="${hpux}"/>
</condition>
<condition property="jni.jdk.os" value="alpha">
<istrue value="${osf1}"/>
</condition>
<condition property="jni.src" value="${jni.os}">
<isfalse value="${jni.src}"/>
</condition>
<echo message="jni.src=${jni.src}, jni.jdk.os=${jni.jdk.os}, ${sun.arch.data.model}-bit"/>
<javac srcdir="${jni.src.java}" destdir="${build}/classes" debug="true"
source="1.4" target="1.4"
includes="org/hyperic/jni/*.java"/>
<taskdef name="libarch" classname="org.hyperic.jni.ArchNameTask">
<classpath location="${build}/classes"/>
</taskdef>
<taskdef name="copydep" classname="org.hyperic.jni.CopyDependsTask">
<classpath location="${build}/classes"/>
</taskdef>
<libarch/>
<property name="jni.project.archname"
value="${project.name}-${jni.libarch}"/>
<condition property="jni.libname"
value="${jni.libprefix}${jni.project.archname}${jni.libversion}">
<isfalse value="${jni.libname}"/>
</condition>
<property name="jni.libname.full"
value="${jni.libpre}${jni.libname}${jni.libext}"/>
<property name="jni.objdir" value="${build}/obj/${jni.libarch}"/>
<condition property="uni.sdk"
value="/Developer/SDKs/MacOSX10.${uni.sdk.version}.sdk">
<istrue value="${darwin}"/>
</condition>
<condition property="jni.cc" value="uni-cc">
<isset property="darwin"/>
</condition>
<property name="jni.cc" value="jni-cc"/>
<condition property="cc.runtime" value="static">
<isset property="win32"/>
</condition>
<condition property="cc.runtime" value="dynamic">
<not>
<isset property="win32"/>
</not>
</condition>
</target>
<target name="jni-lib-copy" if="jni.libarch">
<mkdir dir="${jni.bin}/lib"/>
<copy toDir="${jni.bin}/lib" overwrite="true">
<fileset dir="${jni.objdir}/lib"/>
</copy>
<chmod perm="a+x">
<fileset dir="${jni.bin}/lib">
<include name="*.sl"/>
</fileset>
</chmod>
</target>
<target name="jni-compile" if="jni.libarch">
<antcall target="${jni.cc}" inheritRefs="true"/>
</target>
<!-- run jni-cc twice {ppc,i386}, then feed both to lipo to build a universal binary -->
<target name="uni-cc" if="jni.libarch">
<property name="shlib" value="${jni.objdir}/lib/lib${jni.libname}.dylib"/>
<!-- ppc -->
<echo message="build 'ppc' arch"/>
<antcall target="jni-cc" inheritRefs="true">
<param name="uni.arch" value="ppc"/>
</antcall>
<copy file="${shlib}" tofile="${shlib}.ppc"/>
<!-- i386 -->
<echo message="build 'i386' arch"/>
<delete>
<fileset dir="${jni.objdir}" includes="*.o"/>
</delete>
<antcall target="jni-cc" inheritRefs="true">
<param name="uni.arch" value="i386"/>
</antcall>
<copy file="${shlib}" tofile="${shlib}.i386"/>
<echo message="lipo 'ppc'+'i386'"/>
<exec executable="lipo">
<arg line="-create ${shlib}.ppc ${shlib}.i386 -output ${jni.objdir}/lib/lib${jni.libname}.dylib"/>
</exec>
<delete>
<fileset dir="${jni.objdir}/lib" includes="*.ppc,*.i386"/>
</delete>
</target>
<target name="jni-cc" if="jni.libarch">
<mkdir dir="${jni.objdir}/lib"/>
<echo message="jni libname=${jni.libname}"/>
<cc outtype="shared"
outfile="${jni.objdir}/lib/${jni.libname}"
objdir="${jni.objdir}"
runtime="${cc.runtime}"
relentless="false">
<!-- HPUX -->
<compiler name="hp" if="hpux">
<compilerarg value="+Z"/>
<defineset>
<define name="${jni.define.name}_HPUX"/>
<define name="_HPUX_SOURCE"/>
<define name="_REENTRANT"/>
</defineset>
</compiler>
<linker name="hp" if="hpux">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<syslibset libs="nsl"/>
<syslibset libs="nm"/>
</linker>
<!-- Solaris -->
<compiler name="gcc" if="solaris">
<compilerarg value="-O2" if="jni.optim"/>
<compilerarg value="-g" if="jni.debug"/>
<compilerarg value="-Wall"/>
<compilerarg value="-Werror" if="jni.werror"/>
<compilerarg value="-m64" if="jni.arch64"/>
<defineset>
<define name="${jni.define.name}_SOLARIS"/>
<define name="_REENTRANT"/>
<define name="_POSIX_PTHREAD_SEMANTICS"/>
<define name="DMALLOC" if="jni.dmalloc"/>
</defineset>
</compiler>
<linker name="gcc" if="solaris">
<!-- required for modern gcc to avoid libgcc_s.so dependency -->
<!-- this arg is ignored by older gcc -->
<linkerarg value="-static-libgcc"/>
<linkerarg value="-m64" if="jni.arch64"/>
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<libset if="jni.dmalloc"
dir="${jni.dmalloc}/lib"
libs="dmallocth"/>
</linker>
<!-- Linux -->
<compiler name="gcc" debug="${jni.debug}" if="linux">
<compilerarg value="-O2" if="jni.optim"/>
<compilerarg value="-g" if="jni.debug"/>
<compilerarg value="-Wall"/>
<compilerarg value="-Werror" if="jni.werror"/>
<compilerarg value="-m64" if="jni.usem64"/>
<defineset>
<define name="${jni.define.name}_LINUX"/>
<define name="_REENTRANT"/>
<define name="DMALLOC" if="jni.dmalloc"/>
</defineset>
</compiler>
<linker name="gcc" if="linux">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<libset if="jni.dmalloc"
dir="${jni.dmalloc}/lib"
libs="dmallocth"/>
<linkerarg value="-m64" if="jni.usem64"/>
</linker>
<!-- Darwin -->
<compiler name="gcc" if="darwin">
<compilerarg value="-Wall"/>
<compilerarg value="-Werror" if="jni.werror"/>
<compilerarg value="-m64" if="jni.arch64"/>
<compilerarg value="-O2" if="jni.optim"/>
<compilerarg value="-g" if="jni.debug"/>
<compilerarg value="-isysroot"/>
<compilerarg value="${uni.sdk}"/>
<compilerarg value="-arch"/>
<compilerarg value="${uni.arch}"/>
<compilerarg value="${osx.min}"/>
<sysincludepath location="/Developer/Headers/FlatCarbon"/>
<defineset>
<define name="DARWIN"/>
<define name="DARWIN_HAS_LIBPROC_H" if="libproc.h"/>
</defineset>
</compiler>
<linker name="gcc" if="darwin">
<linkerarg value="-m64" if="jni.arch64"/>
<linkerarg value="-Wl,-syslibroot,${uni.sdk}"/>
<linkerarg value="-arch"/>
<linkerarg value="${uni.arch}"/>
<linkerarg value="${osx.min}"/>
<!-- for Gestalt() -->
<linkerarg value="-framework"/>
<linkerarg value="CoreServices"/>
<linkerarg value="-sectcreate,__TEXT,__info_plist,${jni.info.plist}" if="jni.info.plist"/>
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<syslibset libs="IOKit"/>
</linker>
<!-- Freebsd -->
<compiler name="gcc" if="freebsd">
<compilerarg value="-O2" if="jni.optim"/>
<compilerarg value="-g" if="jni.debug"/>
<compilerarg value="-Wall"/>
<compilerarg value="-Werror" if="jni.werror"/>
<defineset>
<define name="${jni.define.name}_FREEBSD"/>
</defineset>
</compiler>
<linker name="gcc" if="freebsd">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<syslibset libs="kvm"/>
</linker>
<!-- OpenBSD -->
<compiler name="gcc" if="openbsd">
<compilerarg value="-O2" if="jni.optim"/>
<compilerarg value="-g" if="jni.debug"/>
<compilerarg value="-Wall"/>
<!-- <compilerarg value="-Werror" if="jni.werror"/> -->
<defineset>
<define name="${jni.define.name}_OPENBSD"/>
</defineset>
</compiler>
<linker name="gcc" if="openbsd">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<syslibset libs="kvm"/>
</linker>
<!-- NetBSD -->
<compiler name="gcc" if="netbsd">
<compilerarg value="-O2" if="jni.optim"/>
<compilerarg value="-g" if="jni.debug"/>
<compilerarg value="-Wall"/>
<!-- <compilerarg value="-Werror" if="jni.werror"/> -->
<defineset>
<define name="${jni.define.name}_NETBSD"/>
</defineset>
</compiler>
<linker name="gcc" if="netbsd">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<syslibset libs="kvm"/>
</linker>
<!-- AIX -->
<compiler name="xlc_r" if="aix">
<defineset>
<define name="${jni.define.name}_AIX"/>
<define name="_ALL_SOURCE"/>
<define name="_ANSI_C_SOURCE"/>
<define name="_POSIX_SOURCE"/>
</defineset>
</compiler>
<linker name="xlc_r" if="aix">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
</linker>
<!-- WIN32 -->
<linker name="msvc" debug="${jni.debug}" if="win32">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<linkerarg value="/MACHINE:X64" if="jni.arch64"/>
<linkerarg value="${jni.info.res}" if="jni.info.res"/>
<syslibset libs="kernel32,user32,advapi32,ws2_32,netapi32,shell32,pdh,version"/>
</linker>
<compiler name="msvc" debug="${jni.debug}" if="win32">
<defineset>
<define name="WIN32"/>
<define name="_CRT_SECURE_NO_DEPRECATE"/>
<!-- XXX 2008 MSC express/SDK does not include atl headers -->
<define name="SIGAR_NO_ATL" if="jni.noatl"/>
</defineset>
</compiler>
<!-- OSF1 -->
<compiler name="gcc" if="osf1">
<compilerarg value="-Wall"/>
<compilerarg value="-pthread"/>
<defineset>
<define name="${jni.define.name}_OSF1"/>
</defineset>
</compiler>
<linker name="gcc" if="osf1">
<libset if="jni.libset.libs"
dir="${jni.libset.dir}"
libs="${jni.libset.libs}"/>
<syslibset libs="mach"/>
</linker>
<!-- C sources -->
<fileset dir="${jni.source.dir}">
<patternset refid="jni.source.files"/>
</fileset>
<includepath>
<path refid="jni.include.dirs"/>
</includepath>
<sysincludepath location="${jni.javahome}/include"/>
<sysincludepath location="${jni.javahome}/include/${jni.jdk.os}"/>
<sysincludepath location="${jni.dmalloc}/include"
if="jni.dmalloc"/>
</cc>
</target>
<target name="jni-clean">
<delete dir="${jni.objdir}"/>
</target>
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
cpptasks.pat - provides support for HP cc and AIX xlc_r
the classes listed below are copy-n-pastes from existing cpptasks
classes, simply changed program names, flags, etc. the HP classes
were submitted as a patch to ant-contrib-developers on 10/09/2002,
to which there was no response, so have not bothered to submit the aix
patch.
SubsystemEnum patch is for the osf1 javac (aka tru64).
was throwing IllegalAccessError. why clone a final String[] anyhow??
CUtil patch is for jdk 1.3 (StringBuffer.indexOf is 1.4+)
GccLinker patch adds -arch to known flags for building universal binaries
added | derived from
--------------------------
HPCompiler | aCCCompiler
HPLinker | aCCLinker
XlcCompiler | VisualAgeCCompiler
XlcLinker | VisualAgeLinker
cpptasks.pat applies to:
cvs -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/ant-contrib \
co -D"2006/04/28 15:00:00" cpptasks
@@ -0,0 +1,696 @@
Index: src/net/sf/antcontrib/cpptasks/CUtil.java
===================================================================
RCS file: /cvsroot/ant-contrib/cpptasks/src/net/sf/antcontrib/cpptasks/CUtil.java,v
retrieving revision 1.28
diff -u -r1.28 CUtil.java
--- src/net/sf/antcontrib/cpptasks/CUtil.java 17 Mar 2006 16:38:12 -0000 1.28
+++ src/net/sf/antcontrib/cpptasks/CUtil.java 29 Apr 2006 02:35:28 -0000
@@ -438,19 +438,19 @@
StringBuffer buf = new StringBuffer (attrValue);
int quotePos;
- for (quotePos = -1; (quotePos = buf.indexOf("\"", quotePos + 1)) >= 0;) {
+ for (quotePos = -1; (quotePos = buf.toString().indexOf("\"", quotePos + 1)) >= 0;) {
buf.deleteCharAt(quotePos);
buf.insert (quotePos, "&quot;");
quotePos += 5;
}
- for (quotePos = -1; (quotePos = buf.indexOf("<", quotePos + 1)) >= 0;) {
+ for (quotePos = -1; (quotePos = buf.toString().indexOf("<", quotePos + 1)) >= 0;) {
buf.deleteCharAt(quotePos);
buf.insert (quotePos, "&lt;");
quotePos += 3;
}
- for (quotePos = -1; (quotePos = buf.indexOf(">", quotePos + 1)) >= 0;) {
+ for (quotePos = -1; (quotePos = buf.toString().indexOf(">", quotePos + 1)) >= 0;) {
buf.deleteCharAt(quotePos);
buf.insert (quotePos, "&gt;");
quotePos += 3;
Index: src/net/sf/antcontrib/cpptasks/CompilerEnum.java
===================================================================
RCS file: /cvsroot/ant-contrib/cpptasks/src/net/sf/antcontrib/cpptasks/CompilerEnum.java,v
retrieving revision 1.18
diff -u -r1.18 CompilerEnum.java
--- src/net/sf/antcontrib/cpptasks/CompilerEnum.java 8 Jul 2004 22:30:53 -0000 1.18
+++ src/net/sf/antcontrib/cpptasks/CompilerEnum.java 29 Apr 2006 02:35:28 -0000
@@ -25,7 +25,9 @@
import net.sf.antcontrib.cpptasks.devstudio.DevStudioResourceCompiler;
import net.sf.antcontrib.cpptasks.gcc.GccCCompiler;
import net.sf.antcontrib.cpptasks.hp.aCCCompiler;
+import net.sf.antcontrib.cpptasks.hp.HPCompiler;
import net.sf.antcontrib.cpptasks.ibm.VisualAgeCCompiler;
+import net.sf.antcontrib.cpptasks.ibm.XlcCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelLinux32CCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelLinux64CCompiler;
import net.sf.antcontrib.cpptasks.intel.IntelWin32CCompiler;
@@ -205,6 +207,8 @@
new ProcessorEnumValue("armcpp", ADSCCompiler.getArmCpp()),
new ProcessorEnumValue("tcc", ADSCCompiler.getThumbCC()),
new ProcessorEnumValue("tcpp", ADSCCompiler.getThumbCpp()),
+ new ProcessorEnumValue("hp", HPCompiler.getInstance()),
+ new ProcessorEnumValue("xlc_r", XlcCompiler.getInstance()),
// GCC Cross Compilers
new ProcessorEnumValue(
"sparc-sun-solaris2-gcc",
Index: src/net/sf/antcontrib/cpptasks/LinkerEnum.java
===================================================================
RCS file: /cvsroot/ant-contrib/cpptasks/src/net/sf/antcontrib/cpptasks/LinkerEnum.java,v
retrieving revision 1.16
diff -u -r1.16 LinkerEnum.java
--- src/net/sf/antcontrib/cpptasks/LinkerEnum.java 8 Jul 2004 22:30:53 -0000 1.16
+++ src/net/sf/antcontrib/cpptasks/LinkerEnum.java 29 Apr 2006 02:35:28 -0000
@@ -25,7 +25,9 @@
import net.sf.antcontrib.cpptasks.gcc.GppLinker;
import net.sf.antcontrib.cpptasks.gcc.LdLinker;
import net.sf.antcontrib.cpptasks.hp.aCCLinker;
+import net.sf.antcontrib.cpptasks.hp.HPLinker;
import net.sf.antcontrib.cpptasks.ibm.VisualAgeLinker;
+import net.sf.antcontrib.cpptasks.ibm.XlcLinker;
import net.sf.antcontrib.cpptasks.intel.IntelLinux32Linker;
import net.sf.antcontrib.cpptasks.intel.IntelLinux64Linker;
import net.sf.antcontrib.cpptasks.intel.IntelWin32Linker;
@@ -72,6 +74,8 @@
new ProcessorEnumValue("armcpp", ADSLinker.getInstance()),
new ProcessorEnumValue("tcc", ADSLinker.getInstance()),
new ProcessorEnumValue("tcpp", ADSLinker.getInstance()),
+ new ProcessorEnumValue("hp", HPLinker.getInstance()),
+ new ProcessorEnumValue("xlc_r", XlcLinker.getInstance()),
// gcc cross compilers
new ProcessorEnumValue(
"sparc-sun-solaris2-gcc",
Index: src/net/sf/antcontrib/cpptasks/SubsystemEnum.java
===================================================================
RCS file: /cvsroot/ant-contrib/cpptasks/src/net/sf/antcontrib/cpptasks/SubsystemEnum.java,v
retrieving revision 1.7
diff -u -r1.7 SubsystemEnum.java
--- src/net/sf/antcontrib/cpptasks/SubsystemEnum.java 28 Feb 2004 20:04:02 -0000 1.7
+++ src/net/sf/antcontrib/cpptasks/SubsystemEnum.java 29 Apr 2006 02:35:28 -0000
@@ -29,6 +29,6 @@
setValue("gui");
}
public String[] getValues() {
- return (String[]) values.clone();
+ return values;
}
}
Index: src/net/sf/antcontrib/cpptasks/gcc/GccLinker.java
===================================================================
RCS file:
/cvsroot/ant-contrib/cpptasks/src/net/sf/antcontrib/cpptasks/gcc/GccLinker.java,v
retrieving revision 1.32
diff -u -r1.32 GccLinker.java
--- src/net/sf/antcontrib/cpptasks/gcc/GccLinker.java 28 Feb 2004
20:01:15 -0000 1.32
+++ src/net/sf/antcontrib/cpptasks/gcc/GccLinker.java 29 Apr 2006
17:27:50 -0000
@@ -35,7 +35,7 @@
private static String[] linkerOptions = new String[]{"-bundle",
"-dynamiclib", "-nostartfiles", "-nostdlib", "-prebind",
"-s",
"-static", "-shared", "-symbolic", "-Xlinker",
- "--export-all-symbols", "-static-libgcc",};
+ "--export-all-symbols", "-static-libgcc", "-arch"};
private static final GccLinker dllLinker = new GccLinker("gcc",
objFiles,
discardFiles, "lib", ".so", false, new GccLinker("gcc",
objFiles,
discardFiles, "lib", ".so", true, null));
--- /dev/null 2006-04-28 19:36:02.000000000 -0700
+++ src/net/sf/antcontrib/cpptasks/hp/HPCompiler.java 2006-04-28 17:08:22.000000000 -0700
@@ -0,0 +1,161 @@
+/*
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 2001 The Ant-Contrib project. All rights
+ * reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. The end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Ant", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ */
+package net.sf.antcontrib.cpptasks.hp;
+
+import java.io.File;
+import java.util.Vector;
+
+import net.sf.antcontrib.cpptasks.CUtil;
+import net.sf.antcontrib.cpptasks.compiler.LinkType;
+import net.sf.antcontrib.cpptasks.compiler.Linker;
+import net.sf.antcontrib.cpptasks.gcc.GccCompatibleCCompiler;
+import org.apache.tools.ant.types.Environment;
+
+/**
+ * Adapter for the HP compiler
+ *
+ * @author Curt Arnold
+ */
+public final class HPCompiler extends GccCompatibleCCompiler {
+
+ private String identifier;
+ private File[] includePath;
+ private static final HPCompiler instance =
+ new HPCompiler("cc", false, null);
+
+ /**
+ * Private constructor. Use GccCCompiler.getInstance() to get
+ * singleton instance of this class.
+ */
+ private HPCompiler(
+ String command,
+ boolean newEnvironment,
+ Environment env) {
+ super(command, "-help", false, null, newEnvironment, env);
+ }
+
+ public int getMaximumCommandLength() {
+ return Integer.MAX_VALUE;
+ }
+
+ /**
+ * Gets singleton instance of this class
+ */
+ public static HPCompiler getInstance() {
+ return instance;
+ }
+
+ public File[] getEnvironmentIncludePath() {
+ if (includePath == null) {
+ File ccLoc = CUtil.getExecutableLocation("cc");
+ if (ccLoc != null) {
+ File compilerIncludeDir =
+ new File(new File(ccLoc, "../include").getAbsolutePath());
+ if (compilerIncludeDir.exists()) {
+ includePath = new File[2];
+ includePath[0] = compilerIncludeDir;
+ }
+ }
+ if (includePath == null) {
+ includePath = new File[1];
+ }
+ includePath[includePath.length - 1] = new File("/usr/include");
+ }
+ return includePath;
+ }
+
+ public void addImpliedArgs(
+ Vector args,
+ boolean debug,
+ boolean multithreaded,
+ boolean exceptions,
+ LinkType linkType) {
+ args.addElement("-c");
+ if (debug) {
+ args.addElement("-g");
+ }
+ /*
+ if (multithreaded) {
+ args.addElement("-mt");
+ }
+ */
+ if (linkType.isSharedLibrary()) {
+ args.addElement("+z");
+ }
+ }
+
+ public void addWarningSwitch(Vector args, int level) {
+ switch (level) {
+ case 0 :
+ args.addElement("-w");
+ break;
+
+ case 1 :
+ case 2 :
+ args.addElement("+w");
+ break;
+ /*
+ case 3:
+ case 4:
+ case 5:
+ args.addElement("+w2");
+ break;
+ */
+ }
+ }
+
+ public Linker getLinker(LinkType linkType) {
+ return HPLinker.getInstance().getLinker(linkType);
+ }
+}
--- /dev/null 2006-04-28 19:36:02.000000000 -0700
+++ src/net/sf/antcontrib/cpptasks/hp/HPLinker.java 2006-04-28 17:08:22.000000000 -0700
@@ -0,0 +1,153 @@
+/*
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 2001 The Ant-Contrib project. All rights
+ * reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. The end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Ant", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ */
+package net.sf.antcontrib.cpptasks.hp;
+
+import java.io.File;
+import java.util.Vector;
+
+import net.sf.antcontrib.cpptasks.CUtil;
+import net.sf.antcontrib.cpptasks.compiler.LinkType;
+import net.sf.antcontrib.cpptasks.compiler.Linker;
+import net.sf.antcontrib.cpptasks.gcc.AbstractLdLinker;
+
+/**
+ * Adapter for HP linker
+ *
+ * @author Curt Arnold
+ */
+public final class HPLinker extends AbstractLdLinker
+{
+ private static final String[] objFiles = new String[]
+ { ".o", ".a", ".lib", ".dll", ".so", ".sl" };
+ private static final String[] discardFiles = new String[0];
+
+ private static final HPLinker instance =
+ new HPLinker("ld", objFiles, discardFiles, "", "");
+ private static final HPLinker dllLinker =
+ new HPLinker("ld", objFiles, discardFiles, "lib", ".sl");
+ private static final HPLinker arLinker =
+ new HPLinker("ld", objFiles, discardFiles, "", ".a");
+
+ private File[] libDirs;
+
+ private HPLinker(String command, String[] extensions,
+ String[] ignoredExtensions, String outputPrefix,
+ String outputSuffix) {
+ super(command, "-help", extensions, ignoredExtensions,
+ outputPrefix, outputSuffix,false,null);
+ }
+
+ public static HPLinker getInstance() {
+ return instance;
+ }
+
+ /**
+ * Returns library path.
+ *
+ */
+ public File[] getLibraryPath() {
+ if(libDirs == null) {
+ File CCloc = CUtil.getExecutableLocation("ld");
+ if(CCloc != null) {
+ File compilerLib = new File(
+ new File(CCloc, "../lib").getAbsolutePath());
+ if (compilerLib.exists()) {
+ libDirs = new File[2];
+ libDirs[0] = compilerLib;
+ }
+ }
+ if (libDirs == null) {
+ libDirs = new File[1];
+ }
+ }
+ libDirs[libDirs.length-1] = new File("/usr/lib");
+ return libDirs;
+ }
+
+ public void addImpliedArgs(boolean debug, LinkType linkType, Vector args) {
+/* if(linkType.isStaticRuntime()) {
+ args.addElement("-static");
+ }
+*/
+ if(linkType.isSharedLibrary()) {
+ args.addElement("-b");
+ }
+/*
+ if (linkType.isStaticLibrary()) {
+ args.addElement("-Wl,-noshared");
+ }
+*/
+ }
+
+
+ public Linker getLinker(LinkType type) {
+ if(type.isStaticLibrary()) {
+ return arLinker;
+ }
+ if(type.isSharedLibrary()) {
+ return dllLinker;
+ }
+ return instance;
+ }
+
+ public void addIncremental(boolean incremental, Vector args) {
+ /*
+ if (incremental) {
+ args.addElement("-xidlon");
+ } else {
+ args.addElement("-xidloff");
+ }
+ */
+ }
+}
--- /dev/null 2006-04-28 19:36:02.000000000 -0700
+++ src/net/sf/antcontrib/cpptasks/ibm/XlcCompiler.java 2006-04-28 17:08:22.000000000 -0700
@@ -0,0 +1,138 @@
+/*
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 2001 The Ant-Contrib project. All rights
+ * reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. The end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Ant-Contrib project (http://sourceforge.net/projects/ant-contrib)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "Ant-Contrib"
+ * must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Ant-Contrib"
+ * nor may "Ant-Contrib" appear in their names without prior written
+ * permission of the Ant-Contrib project.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE ANT-CONTRIB PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ */
+package net.sf.antcontrib.cpptasks.ibm;
+
+import java.io.File;
+import java.util.Vector;
+
+import net.sf.antcontrib.cpptasks.compiler.LinkType;
+import net.sf.antcontrib.cpptasks.compiler.Linker;
+import net.sf.antcontrib.cpptasks.gcc.GccCompatibleCCompiler;
+import org.apache.tools.ant.types.Environment;
+
+
+/**
+ * Adapter for the IBM(r) Visual Age(tm) C++ compiler for AIX(tm)
+ *
+ * @author Curt Arnold
+ */
+public final class XlcCompiler extends GccCompatibleCCompiler {
+ private String identifier;
+ private File[] includePath;
+ private static final XlcCompiler instance =
+ new XlcCompiler("xlc_r", false, null);
+
+ /**
+ * Private constructor. Use getInstance() to get
+ * singleton instance of this class.
+ */
+ private XlcCompiler(String command, boolean newEnvironment, Environment env) {
+ super(command, "-help", false, null, newEnvironment, env);
+ }
+
+ public int getMaximumCommandLength() {
+ return Integer.MAX_VALUE;
+ }
+
+ /**
+ * Gets singleton instance of this class
+ */
+ public static XlcCompiler getInstance() {
+ return instance;
+ }
+
+ public void addImpliedArgs(
+ Vector args,
+ boolean debug,
+ boolean multithreaded,
+ boolean exceptions,
+ LinkType linkType) {
+ args.addElement("-c");
+ if (debug) {
+ args.addElement("-g");
+ }
+ if (linkType.isSharedLibrary()) {
+ args.addElement("-fpic");
+ args.addElement("-qmkshrobj");
+
+ }
+ }
+
+ public void addWarningSwitch(Vector args, int level) {
+ switch (level) {
+ case 0 :
+ args.addElement("-w");
+ break;
+
+ case 1 :
+ args.addElement("-qflag=s:s");
+ break;
+
+ case 2 :
+ args.addElement("-qflag=e:e");
+ break;
+
+ case 3 :
+ args.addElement("-qflag=w:w");
+ break;
+
+ case 4 :
+ args.addElement("-qflag=i:i");
+ break;
+
+ case 5 :
+ args.addElement("-qhalt=w:w");
+ break;
+ }
+ }
+
+ public Linker getLinker(LinkType linkType) {
+ return VisualAgeLinker.getInstance().getLinker(linkType);
+ }
+}
--- /dev/null 2006-04-28 19:36:02.000000000 -0700
+++ src/net/sf/antcontrib/cpptasks/ibm/XlcLinker.java 2006-04-28 17:08:22.000000000 -0700
@@ -0,0 +1,112 @@
+/*
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 2001 The Ant-Contrib project. All rights
+ * reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. The end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Ant-Contrib project (http://sourceforge.net/projects/ant-contrib)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "Ant-Contrib"
+ * must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact apache@apache.org.
+ *
+ * 5. Products derived from this software may not be called "Ant-Contrib"
+ * nor may "Ant-Contrib" appear in their names without prior written
+ * permission of the Ant-Contrib project.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE ANT-CONTRIB PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ */
+package net.sf.antcontrib.cpptasks.ibm;
+
+import java.util.Vector;
+
+import net.sf.antcontrib.cpptasks.compiler.LinkType;
+import net.sf.antcontrib.cpptasks.compiler.Linker;
+import net.sf.antcontrib.cpptasks.gcc.AbstractLdLinker;
+import net.sf.antcontrib.cpptasks.gcc.GccLibrarian;
+
+/**
+ * Adapter for IBM(r) Visual Age(tm) Linker for AIX(tm)
+ *
+ * @author Curt Arnold
+ */
+public final class XlcLinker extends AbstractLdLinker
+{
+ private static final String[] objFiles = new String[]
+ { ".o", ".a", ".lib",".dll", ".so", ".sl"};
+ private static final String[] discardFiles = new String[]
+ { };
+
+ private static final XlcLinker instance =
+ new XlcLinker("ld", objFiles, discardFiles, "", "");
+ private static final XlcLinker dllLinker =
+ new XlcLinker("ld", objFiles, discardFiles, "lib", ".so");
+
+ private XlcLinker(String command, String[] extensions,
+ String[] ignoredExtensions, String outputPrefix,
+ String outputSuffix) {
+ //
+ // just guessing that -? might display something useful
+ //
+ super(command, "-?", extensions, ignoredExtensions,
+ outputPrefix, outputSuffix,false,null);
+ }
+
+ public static XlcLinker getInstance() {
+ return instance;
+ }
+
+ public void addImpliedArgs(boolean debug, LinkType linkType, Vector args) {
+ if(debug) {
+ //args.addElement("-g");
+ }
+ if(linkType.isSharedLibrary()) {
+ args.addElement("-bdynamic");
+ args.addElement("-G");
+ args.addElement("-bnoentry");
+ args.addElement("-bexpall");
+ args.addElement("-lc_r");
+ }
+ }
+
+
+ public Linker getLinker(LinkType type) {
+ if(type.isStaticLibrary()) {
+ return GccLibrarian.getInstance();
+ }
+ if(type.isSharedLibrary()) {
+ return dllLinker;
+ }
+ return instance;
+ }
+}
@@ -0,0 +1,442 @@
/*
* Copyright (C) [2004, 2005, 2006], 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.jni;
import java.io.File;
import java.util.StringTokenizer;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
public class ArchLoader {
private Object loadLock = new Object();
private boolean loaded = false;
private final static String osName = System.getProperty("os.name");
public final static boolean IS_WIN32 = osName.startsWith("Windows");
public final static boolean IS_AIX = osName.equals("AIX");
public final static boolean IS_HPUX = osName.equals("HP-UX");
public final static boolean IS_SOLARIS = osName.equals("SunOS");
public final static boolean IS_LINUX = osName.equals("Linux");
public final static boolean IS_DARWIN = osName.equals("Mac OS X") || osName.equals("Darwin");
public final static boolean IS_OSF1 = osName.equals("OSF1");
public final static boolean IS_FREEBSD = osName.equals("FreeBSD");
public final static boolean IS_NETWARE = osName.equals("NetWare");
private String packageName;
private String name;
private String resourcePath;
private Class loaderClass;
private String jarName;
private String libName = null;
private File nativeLibrary;
private String version;
public ArchLoader() { }
public ArchLoader(Class loaderClass) {
setLoaderClass(loaderClass); //e.g. Sigar.class
//argh. possible for loaderClass.getPackage()
//to return null depending on ClassLoader
String pname = loaderClass.getName();
int ix = pname.lastIndexOf(".");
pname = pname.substring(0, ix);
setPackageName(pname); //e.g. org.hyperic.sigar
ix = pname.lastIndexOf(".");
setName(pname.substring(ix+1)); //e.g. sigar
setJarName(getName() + ".jar");
setResourcePath(toResName(pname)); //e.g. org.hyperic/sigar
}
public Class getLoaderClass() {
return this.loaderClass;
}
public void setLoaderClass(Class value) {
this.loaderClass = value;
}
public ClassLoader getClassLoader() {
return getLoaderClass().getClassLoader();
}
public String getName() {
return this.name;
}
public void setName(String value) {
this.name = value;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String value) {
this.packageName = value;
}
public String getResourcePath() {
return this.resourcePath;
}
public void setResourcePath(String value) {
this.resourcePath = value;
}
public String getJarName() {
return this.jarName;
}
public void setJarName(String value) {
this.jarName = value;
}
public String getLibName() {
return this.libName;
}
public void setLibName(String value) {
this.libName = value;
}
public String getArchLibName()
throws ArchNotSupportedException {
return getName() + "-" + ArchName.getName();
}
public String getDefaultLibName()
throws ArchNotSupportedException {
return
System.getProperty(getPackageName() + ".libname",
//e.g. javasigar-x86-linux
"java" + getArchLibName());
}
public File getNativeLibrary() {
return this.nativeLibrary;
}
private String toResName(String name) {
StringBuffer sb = new StringBuffer(name);
for (int i=0; i < sb.length(); i++) {
if (sb.charAt(i) == '.') {
sb.setCharAt(i, '/');
}
}
return sb.toString();
}
public static String getLibraryPrefix() {
if (IS_WIN32 || IS_NETWARE) {
return "";
}
return "lib";
}
public static String getLibraryExtension() {
if (IS_WIN32) {
return ".dll";
}
if (IS_NETWARE) {
return ".nlm";
}
if (IS_DARWIN) {
return ".dylib";
}
if (IS_HPUX) {
return ".sl";
}
return ".so";
}
public String getLibraryName()
throws ArchNotSupportedException {
String libName;
if ((libName = getLibName()) == null) {
libName = getDefaultLibName();
setLibName(libName);
}
String prefix = getLibraryPrefix();
String ext = getLibraryExtension();
return prefix + libName + ext;
}
public String getVersionedLibraryName() {
if (this.version == null) {
return null;
}
try {
getLibraryName();
} catch (ArchNotSupportedException e) {
return null;
}
String prefix = getLibraryPrefix();
String ext = getLibraryExtension();
return prefix + this.libName + '-' + this.version + ext;
}
private boolean isJarURL(URL url) {
if (url == null) {
return false;
}
String name = url.getFile();
String jarName = getJarName();
if (name.indexOf(jarName) != -1) {
return true;
}
int ix = jarName.indexOf(".jar");
if (ix != -1) {
//check for a versioned name-x.x.jar
jarName = jarName.substring(0, ix) + "-";
//lastIndex else could match "sigar-bin/"
ix = name.lastIndexOf(jarName);
if (ix != -1) {
jarName = name.substring(ix);
ix = jarName.indexOf(".jar");
if (ix == -1) {
return false;
}
this.version =
jarName.substring(jarName.indexOf('-')+1, ix);
jarName = jarName.substring(0, ix+4);
setJarName(jarName); //for future reference
return true;
}
else {
return false;
}
}
else {
return false;
}
}
public String findJarPath(String libName)
throws ArchLoaderException {
/*
* native libraries should be installed along side
* ${this.name}.jar, try to find where ${this.name}.jar
* is on disk and use that path.
*/
if (getJarName() == null) {
throw new ArchLoaderException("jarName is null");
}
String path = getResourcePath();
ClassLoader loader = getClassLoader();
URL url = loader.getResource(path);
if (!isJarURL(url)) {
url = null;
}
if ((url == null) && (loader instanceof URLClassLoader)) {
URL[] urls = ((URLClassLoader)loader).getURLs();
for (int i=0; i<urls.length; i++) {
if (isJarURL(urls[i])) {
url = urls[i];
break;
}
}
}
if (url == null) {
throw new ArchLoaderException("Unable to find " +
getJarName());
}
path = url.getFile();
if (path.startsWith("file:")) {
path = path.substring(5);
}
File file = new File(path);
String jarName = getJarName();
while ((file != null) &&
!file.getName().startsWith(jarName))
{
file = file.getParentFile();
}
if (libName == null) {
//return path containing ${this.name}.jar
//which may or may not be -x.x.x.x versioned
libName = jarName;
}
if ((file != null) &&
((file = file.getParentFile()) != null))
{
String dir = URLDecoder.decode(file.toString());
if (findNativeLibrary(dir, libName)) {
return dir;
}
}
return null;
}
//java.lang.ClassLoader does not delegate native linking
//to the parent ClassLoader.
//overriding these methods provides a workaround.
protected void systemLoadLibrary(String name) {
System.loadLibrary(name);
}
protected void systemLoad(String name) {
System.load(name);
}
protected boolean containsNativeLibrary(File dir, String name) {
if (name == null) {
return false;
}
File file = new File(dir, name);
if (file.exists()) {
this.nativeLibrary = file;
return true;
}
return false;
}
protected boolean findNativeLibrary(String dir, String name) {
//must be an absolute path; this allows relative to $PWD
File path = new File(dir).getAbsoluteFile();
if (containsNativeLibrary(path, name)) {
return true;
}
else if (containsNativeLibrary(path, getVersionedLibraryName())) {
return true;
}
//try w/o arch name (e.g. "libsigar.so")
return containsNativeLibrary(path,
getLibraryPrefix() +
getName() +
getLibraryExtension());
}
protected boolean findInJavaLibraryPath(String libName) {
String path = System.getProperty("java.library.path", "");
StringTokenizer tok =
new StringTokenizer(path, File.pathSeparator);
while (tok.hasMoreTokens()) {
path = tok.nextToken();
if (findNativeLibrary(path, libName)) {
return true;
}
}
return false;
}
protected void loadLibrary(String path)
throws ArchNotSupportedException,
ArchLoaderException {
try {
String libName = getLibraryName();
if (path == null) {
//e.g. org.hyperic.sigar.path
path = System.getProperty(getPackageName() + ".path");
}
if (path != null) {
if (path.equals("-")) {
return; //assume library is already loaded
}
findJarPath(null); //check for versioned .jar
findNativeLibrary(path, libName);
}
else {
if (findJarPath(libName) == null) {
findInJavaLibraryPath(libName);
}
}
//nativeLibrary set when findJarPath() calls findNativeLibrary()
if (this.nativeLibrary != null) {
systemLoad(this.nativeLibrary.toString());
}
else {
//LD_LIBRARY_PATH must be set for linux and solaris
//SHLIB_PATH must be set for hpux
//PATH must be set for windows
systemLoadLibrary(libName);
}
} catch (RuntimeException e) {
String reason = e.getMessage();
if (reason == null) {
reason = e.getClass().getName();
}
String msg =
"Failed to load " + libName +
": " + reason;
throw new ArchLoaderException(msg);
}
}
public void load()
throws ArchNotSupportedException,
ArchLoaderException {
load(null);
}
public void load(String path)
throws ArchNotSupportedException,
ArchLoaderException {
/*
* System.loadLibrary() is only supposed to load the library
* once per-classloader. but we make extra sure that is the case.
*/
synchronized (this.loadLock) {
if (this.loaded) {
return;
}
loadLibrary(path);
this.loaded = true;
}
}
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) [2004, 2005, 2006], 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.jni;
public class ArchLoaderException extends Exception {
public ArchLoaderException() {
super();
}
public ArchLoaderException(String msg) {
super(msg);
}
}
@@ -0,0 +1,115 @@
/*
* Copyright (C) [2004, 2005, 2006], 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.jni;
/**
* Helper class for naming the jni library with
* platform/arch name for which it is binary compatible.
*/
public class ArchName {
static boolean useDmalloc =
System.getProperty("jni.dmalloc") != null;
public static String getName() throws ArchNotSupportedException {
String name = getArchName();
if (useDmalloc) {
name += "-dmalloc";
}
return name;
}
public static boolean is64() {
return "64".equals(System.getProperty("sun.arch.data.model"));
}
private static String getArchName() throws ArchNotSupportedException {
String name = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
String version = System.getProperty("os.version");
String majorVersion = version.substring(0, 1); //4.x, 5.x, etc.
if (arch.endsWith("86")) {
arch = "x86";
}
if (name.equals("Linux")) {
return arch + "-linux";
}
else if (name.indexOf("Windows") > -1) {
return arch + "-winnt";
}
else if (name.equals("SunOS")) {
if (arch.startsWith("sparcv") && is64()) {
arch = "sparc64";
}
return arch + "-solaris";
}
else if (name.equals("HP-UX")) {
if (arch.startsWith("IA64")) {
arch = "ia64";
}
else {
arch = "pa";
}
if (version.indexOf("11") > -1) {
return arch + "-hpux-11";
}
}
else if (name.equals("AIX")) {
if (majorVersion.equals("6")) {
//v5 binary is compatible with v6
majorVersion = "5";
}
//arch == "ppc" on 32-bit, "ppc64" on 64-bit
return arch + "-aix-" + majorVersion;
}
else if (name.equals("Mac OS X") || name.equals("Darwin")) {
if (is64()) {
return "universal64-macosx";
}
else {
return "universal-macosx";
}
}
else if (name.equals("FreeBSD")) {
//none of the 4,5,6 major versions are binary compatible
return arch + "-freebsd-" + majorVersion;
}
else if (name.equals("OpenBSD")) {
return arch + "-openbsd-" + majorVersion;
}
else if (name.equals("NetBSD")) {
return arch + "-netbsd-" + majorVersion;
}
else if (name.equals("OSF1")) {
return "alpha-osf1-" + majorVersion;
}
else if (name.equals("NetWare")) {
return "x86-netware-" + majorVersion;
}
String desc = arch + "-" + name + "-" + version;
throw new ArchNotSupportedException("platform (" + desc + ") not supported");
}
private ArchName () { }
}
@@ -0,0 +1,76 @@
/*
* Copyright (C) [2004, 2005, 2006], 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.jni;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
public class ArchNameTask extends Task {
public void execute() throws BuildException {
String osArch = System.getProperty("os.arch");
if (getProject().getProperty("jni.dmalloc") != null) {
ArchName.useDmalloc = true;
}
String archName;
try {
archName = ArchName.getName();
} catch (ArchNotSupportedException e) {
//ok: can still compile *.java
System.out.println(e.getMessage());
return;
}
System.out.println(archName);
getProject().setProperty("jni.libarch", archName);
getProject().setProperty("jni.libpre",
ArchLoader.getLibraryPrefix());
getProject().setProperty("jni.libext",
ArchLoader.getLibraryExtension());
String compiler;
if (ArchLoader.IS_WIN32) {
compiler = "msvc";
}
else if (ArchLoader.IS_HPUX) {
compiler = "hp";
}
else if (ArchLoader.IS_AIX) {
compiler = "xlc_r";
}
else {
compiler = "gcc";
getProject().setProperty("jni.compiler.isgcc", "true");
}
getProject().setProperty("jni.compiler", compiler);
if (ArchName.is64()) {
getProject().setProperty("jni.arch64", "true");
if (ArchLoader.IS_LINUX) {
if (!osArch.equals("ia64")) {
getProject().setProperty("jni.usem64", "true");
}
}
}
}
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) [2004, 2005, 2006], 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.jni;
public class ArchNotSupportedException extends Exception {
public ArchNotSupportedException() {
super();
}
public ArchNotSupportedException(String msg) {
super(msg);
}
}
@@ -0,0 +1,69 @@
/*
* Copyright (C) [2004, 2005, 2006], 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.jni;
import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Copy;
public class CopyDependsTask extends Copy {
private File depends;
protected void validateAttributes()
throws BuildException {
super.validateAttributes();
if (this.depends == null) {
throw new BuildException("missing depends attribute");
}
}
public void execute()
throws BuildException {
if (this.destFile.exists()) {
String state;
if (this.depends.lastModified() >
this.destFile.lastModified())
{
this.setOverwrite(true);
state = "out of date";
}
else {
state = "up to date";
}
log(this.destFile +
" " + state + " with " +
this.depends);
}
super.execute();
}
public File getDepends() {
return this.depends;
}
public void setDepends(String depends) {
this.depends = new File(depends);
}
}
+70 -64
View File
@@ -17,13 +17,25 @@
*/ */
#ifdef WIN32 #ifdef WIN32
#define UNICODE
#define _UNICODE
#include "javasigar.h" #include "javasigar.h"
#include "win32bindings.h" #include "win32bindings.h"
#define MAX_MSG_LENGTH 8192 #define MAX_MSG_LENGTH 8192
#define MAX_ERROR_LENGTH 1024 #define MAX_ERROR_LENGTH 1024
#define REG_MSGFILE_ROOT "SYSTEM\\CurrentControlSet\\Services\\EventLog\\" #define REG_MSGFILE_ROOT L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\"
#define FILESEP L";"
#define STRING_SIG "Ljava/lang/String;"
#define UNICODE_SetStringField(field, str) \
id = JENV->GetFieldID(env, cls, field, STRING_SIG); \
value = JENV->NewString(env, (const jchar *)str, wcslen(str)); \
JENV->SetObjectField(env, obj, id, value)
#define ARRLEN(arr) (sizeof(arr) / sizeof(arr[0]))
static void win32_set_pointer(JNIEnv *env, jobject obj, const void *ptr) static void win32_set_pointer(JNIEnv *env, jobject obj, const void *ptr)
{ {
@@ -57,27 +69,32 @@ static HANDLE win32_get_pointer(JNIEnv *env, jobject obj)
return h; return h;
} }
static int get_messagefile_dll(const char *app, char *source, char *dllfile) static int get_messagefile_dll(LPWSTR app, LPWSTR source, LPWSTR dllfile)
{ {
HKEY hk; HKEY hk;
char buf[MAX_MSG_LENGTH]; WCHAR buf[MAX_MSG_LENGTH];
DWORD type, data = sizeof(buf); DWORD type, data = sizeof(buf);
LONG rc; LONG rc;
sprintf(buf, "%s%s\\%s", REG_MSGFILE_ROOT, app, source); wcscpy(buf, REG_MSGFILE_ROOT);
rc = RegOpenKey(HKEY_LOCAL_MACHINE, buf, &hk); wcscat(buf, app);
wcscat(buf, L"\\");
wcscat(buf, source);
rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, buf,
0, KEY_READ, &hk);
if (rc) { if (rc) {
return rc; return rc;
} }
rc = RegQueryValueEx(hk, "EventMessageFile", NULL, &type, rc = RegQueryValueEx(hk, L"EventMessageFile", NULL, &type,
(UCHAR *)buf, &data); (LPBYTE)buf, &data);
if (rc) { if (rc) {
RegCloseKey(hk); RegCloseKey(hk);
return rc; return rc;
} }
strncpy(dllfile, buf, MAX_MSG_LENGTH); wcsncpy(dllfile, buf, MAX_MSG_LENGTH);
dllfile[MAX_MSG_LENGTH-1] = '\0'; dllfile[MAX_MSG_LENGTH-1] = '\0';
RegCloseKey(hk); RegCloseKey(hk);
@@ -85,13 +102,13 @@ static int get_messagefile_dll(const char *app, char *source, char *dllfile)
return ERROR_SUCCESS; return ERROR_SUCCESS;
} }
static int get_formatted_message(EVENTLOGRECORD *pevlr, char *dllfile, static int get_formatted_message(EVENTLOGRECORD *pevlr, LPWSTR dllfile,
char *msg) LPWSTR msg)
{ {
LPVOID msgbuf = NULL; LPVOID msgbuf = NULL;
char msgdll[MAX_MSG_LENGTH]; WCHAR msgdll[MAX_MSG_LENGTH];
char *insert_strs[56], *ptr; LPWSTR insert_strs[56], ptr;
int i, max = sizeof(insert_strs) / sizeof(char *); int i, max = ARRLEN(insert_strs);
const DWORD flags = const DWORD flags =
FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_SYSTEM |
@@ -99,25 +116,20 @@ static int get_formatted_message(EVENTLOGRECORD *pevlr, char *dllfile,
FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ARGUMENT_ARRAY |
FORMAT_MESSAGE_MAX_WIDTH_MASK; FORMAT_MESSAGE_MAX_WIDTH_MASK;
if (!ExpandEnvironmentStrings(dllfile, msgdll, sizeof(msgdll))) { if (!ExpandEnvironmentStrings(dllfile, msgdll, ARRLEN(msgdll))) {
return GetLastError(); return GetLastError();
} }
memset(insert_strs, '\0', sizeof(insert_strs)); memset(insert_strs, '\0', sizeof(insert_strs));
ptr = (char *)((LPBYTE)pevlr + pevlr->StringOffset); ptr = (LPWSTR)((LPBYTE)pevlr + pevlr->StringOffset);
for (i = 0; i < pevlr->NumStrings && i < max; i++) { for (i = 0; i < pevlr->NumStrings && i < max; i++) {
insert_strs[i] = ptr; insert_strs[i] = ptr;
ptr += strlen(ptr) + 1; ptr += wcslen(ptr) + 1;
} }
ptr = msgdll; ptr = wcstok(msgdll, FILESEP);
while (ptr) { while (ptr) {
HINSTANCE hlib; HINSTANCE hlib;
char *delim = strchr(ptr, ';');
if (delim) {
*delim++ = '\0';
}
hlib = LoadLibraryEx(ptr, NULL, hlib = LoadLibraryEx(ptr, NULL,
LOAD_LIBRARY_AS_DATAFILE); LOAD_LIBRARY_AS_DATAFILE);
@@ -126,20 +138,20 @@ static int get_formatted_message(EVENTLOGRECORD *pevlr, char *dllfile,
hlib, hlib,
pevlr->EventID, pevlr->EventID,
MAKELANGID(LANG_NEUTRAL, SUBLANG_ENGLISH_US), MAKELANGID(LANG_NEUTRAL, SUBLANG_ENGLISH_US),
(LPTSTR) &msgbuf, (LPWSTR) &msgbuf,
sizeof(msgbuf), sizeof(msgbuf), //min bytes w/ FORMAT_MESSAGE_ALLOCATE_BUFFER
insert_strs); (va_list *)insert_strs);
FreeLibrary(hlib); FreeLibrary(hlib);
if (msgbuf) { if (msgbuf) {
break; break;
} }
} }
ptr = delim; ptr = wcstok(NULL, FILESEP);
} }
if (msgbuf) { if (msgbuf) {
strncpy(msg, msgbuf, MAX_MSG_LENGTH); wcsncpy(msg, msgbuf, MAX_MSG_LENGTH);
msg[MAX_MSG_LENGTH-1] = '\0'; msg[MAX_MSG_LENGTH-1] = '\0';
LocalFree(msgbuf); LocalFree(msgbuf);
return ERROR_SUCCESS; return ERROR_SUCCESS;
@@ -153,9 +165,9 @@ JNIEXPORT void SIGAR_JNI(win32_EventLog_openlog)
(JNIEnv *env, jobject obj, jstring lpSourceName) (JNIEnv *env, jobject obj, jstring lpSourceName)
{ {
HANDLE h; HANDLE h;
const char *name; LPWSTR name;
name = JENV->GetStringUTFChars(env, lpSourceName, 0); name = (LPWSTR)JENV->GetStringChars(env, lpSourceName, NULL);
h = OpenEventLog(NULL, name); h = OpenEventLog(NULL, name);
if (h == NULL) { if (h == NULL) {
@@ -163,12 +175,12 @@ JNIEXPORT void SIGAR_JNI(win32_EventLog_openlog)
DWORD lastError = GetLastError(); DWORD lastError = GetLastError();
sprintf(buf, "Unable to open event log: %d", lastError); sprintf(buf, "Unable to open event log: %d", lastError);
JENV->ReleaseStringUTFChars(env, lpSourceName, name); JENV->ReleaseStringChars(env, lpSourceName, name);
win32_throw_exception(env, buf); win32_throw_exception(env, buf);
return; return;
} }
JENV->ReleaseStringUTFChars(env, lpSourceName, name); JENV->ReleaseStringChars(env, lpSourceName, name);
/* Save the handle for later use */ /* Save the handle for later use */
win32_set_pointer(env, obj, h); win32_set_pointer(env, obj, h);
@@ -217,16 +229,16 @@ JNIEXPORT jobject SIGAR_JNI(win32_EventLog_readlog)
{ {
EVENTLOGRECORD *pevlr; EVENTLOGRECORD *pevlr;
BYTE buffer[8192]; BYTE buffer[8192];
char dllfile[MAX_MSG_LENGTH]; WCHAR dllfile[MAX_MSG_LENGTH];
char msg[MAX_MSG_LENGTH]; WCHAR msg[MAX_MSG_LENGTH];
DWORD dwRead, dwNeeded; DWORD dwRead, dwNeeded;
LPSTR source, machineName; LPWSTR source, machineName;
HANDLE h; HANDLE h;
BOOL rv; BOOL rv;
jclass cls = WIN32_FIND_CLASS("EventLogRecord"); jclass cls = WIN32_FIND_CLASS("EventLogRecord");
jobject eventObj; /* Actual instance of the EventLogRecord */
jfieldID id; jfieldID id;
const char *name; jstring value;
LPWSTR name;
h = win32_get_pointer(env, obj); h = win32_get_pointer(env, obj);
@@ -254,59 +266,54 @@ JNIEXPORT jobject SIGAR_JNI(win32_EventLog_readlog)
return NULL; return NULL;
} }
eventObj = JENV->AllocObject(env, cls); obj = JENV->AllocObject(env, cls);
id = JENV->GetFieldID(env, cls, "recordNumber", "J"); id = JENV->GetFieldID(env, cls, "recordNumber", "J");
JENV->SetLongField(env, eventObj, id, pevlr->RecordNumber); JENV->SetLongField(env, obj, id, pevlr->RecordNumber);
id = JENV->GetFieldID(env, cls, "timeGenerated", "J"); id = JENV->GetFieldID(env, cls, "timeGenerated", "J");
JENV->SetLongField(env, eventObj, id, pevlr->TimeGenerated); JENV->SetLongField(env, obj, id, pevlr->TimeGenerated);
id = JENV->GetFieldID(env, cls, "timeWritten", "J"); id = JENV->GetFieldID(env, cls, "timeWritten", "J");
JENV->SetLongField(env, eventObj, id, pevlr->TimeWritten); JENV->SetLongField(env, obj, id, pevlr->TimeWritten);
id = JENV->GetFieldID(env, cls, "eventId", "J"); id = JENV->GetFieldID(env, cls, "eventId", "J");
JENV->SetLongField(env, eventObj, id, pevlr->EventID); JENV->SetLongField(env, obj, id, pevlr->EventID);
id = JENV->GetFieldID(env, cls, "eventType", "S"); id = JENV->GetFieldID(env, cls, "eventType", "S");
JENV->SetShortField(env, eventObj, id, pevlr->EventType); JENV->SetShortField(env, obj, id, pevlr->EventType);
/* Extract string data from the end of the structure. Lame. */ /* Extract string data from the end of the structure. Lame. */
id = JENV->GetFieldID(env, cls, "source", "Ljava/lang/String;"); source = (LPWSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD));
source = (LPSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD)); UNICODE_SetStringField("source", source);
SetStringField(env, eventObj, id, source);
name = JENV->GetStringUTFChars(env, jname, 0); name = (LPWSTR)JENV->GetStringChars(env, jname, NULL);
/* Get the formatted message */ /* Get the formatted message */
if ((pevlr->NumStrings > 0) && if ((pevlr->NumStrings > 0) &&
(get_messagefile_dll(name, source, dllfile) == ERROR_SUCCESS) && (get_messagefile_dll(name, source, dllfile) == ERROR_SUCCESS) &&
(get_formatted_message(pevlr, dllfile, msg) == ERROR_SUCCESS)) (get_formatted_message(pevlr, dllfile, msg) == ERROR_SUCCESS))
{ {
id = JENV->GetFieldID(env, cls, "message", UNICODE_SetStringField("message", msg);
"Ljava/lang/String;");
SetStringField(env, eventObj, id, msg);
} }
else if (pevlr->NumStrings > 0) { else if (pevlr->NumStrings > 0) {
char *tmp = (LPSTR)((LPBYTE)pevlr + pevlr->StringOffset); LPWSTR tmp = (LPWSTR)((LPBYTE)pevlr + pevlr->StringOffset);
id = JENV->GetFieldID(env, cls, "message", "Ljava/lang/String;"); UNICODE_SetStringField("message", tmp);
SetStringField(env, eventObj, id, tmp);
} }
JENV->ReleaseStringUTFChars(env, jname, name); JENV->ReleaseStringChars(env, jname, name);
/* Increment up to the machine name. */ /* Increment up to the machine name. */
id = JENV->GetFieldID(env, cls, "computerName", "Ljava/lang/String;"); machineName = (LPWSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD) +
machineName = (LPSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD) + wcslen(source) + 1);
strlen(source) + 1); UNICODE_SetStringField("computerName", machineName);
SetStringField(env, eventObj, id, machineName);
/* Get user id info */ /* Get user id info */
if (pevlr->UserSidLength > 0) { if (pevlr->UserSidLength > 0) {
char name[256]; WCHAR name[256];
char domain[256]; WCHAR domain[256];
DWORD namelen = sizeof(name); DWORD namelen = ARRLEN(name);
DWORD domainlen = sizeof(domain); DWORD domainlen = ARRLEN(domain);
DWORD len; DWORD len;
SID_NAME_USE snu; SID_NAME_USE snu;
PSID sid; PSID sid;
@@ -314,12 +321,11 @@ JNIEXPORT jobject SIGAR_JNI(win32_EventLog_readlog)
sid = (PSID)((LPBYTE)pevlr + pevlr->UserSidOffset); sid = (PSID)((LPBYTE)pevlr + pevlr->UserSidOffset);
if (LookupAccountSid(NULL, sid, name, &namelen, domain, if (LookupAccountSid(NULL, sid, name, &namelen, domain,
&domainlen, &snu)) { &domainlen, &snu)) {
id = JENV->GetFieldID(env, cls, "user", "Ljava/lang/String;"); UNICODE_SetStringField("user", name);
SetStringField(env, eventObj, id, name);
} }
} }
return eventObj; return obj;
} }
JNIEXPORT void SIGAR_JNI(win32_EventLog_waitForChange) JNIEXPORT void SIGAR_JNI(win32_EventLog_waitForChange)
@@ -18,8 +18,10 @@
package org.hyperic.sigar; package org.hyperic.sigar;
import java.io.FileInputStream;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
@@ -54,24 +56,24 @@ public abstract class FileTail extends FileWatcher {
} }
public void onChange(FileInfo info) { public void onChange(FileInfo info) {
InputStream in = null;
Reader reader = null; Reader reader = null;
String name = info.getName(); String name = info.getName();
try { try {
if (this.useSudo) { if (this.useSudo) {
reader = in = new SudoFileInputStream(name);
new InputStreamReader(new SudoFileInputStream(name));
} }
else { else {
reader = new FileReader(name); in = new FileInputStream(name);
} }
long offset = getOffset(info); long offset = getOffset(info);
if (offset > 0) { if (offset > 0) {
reader.skip(offset); in.skip(offset); //use InputStream to skip bytes
} }
reader = new InputStreamReader(in);
tail(info, reader); tail(info, reader);
} catch (IOException e) { } catch (IOException e) {
error(name, e); error(name, e);
@@ -79,6 +81,9 @@ public abstract class FileTail extends FileWatcher {
if (reader != null) { if (reader != null) {
try { reader.close(); } catch (IOException e) { } try { reader.close(); } catch (IOException e) { }
} }
if (in != null) {
try { in.close(); } catch (IOException e) { }
}
} }
} }
@@ -1,81 +1,81 @@
/* /*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.cmd; package org.hyperic.sigar.cmd;
import org.hyperic.sigar.win32.EventLog; import org.hyperic.sigar.win32.EventLog;
import org.hyperic.sigar.win32.EventLogNotification; import org.hyperic.sigar.win32.EventLogNotification;
import org.hyperic.sigar.win32.EventLogRecord; import org.hyperic.sigar.win32.EventLogRecord;
import org.hyperic.sigar.win32.EventLogThread; import org.hyperic.sigar.win32.EventLogThread;
import org.hyperic.sigar.win32.Win32Exception; import org.hyperic.sigar.win32.Win32Exception;
public class EventLogTail { public class EventLogTail {
private static void tail(String name, Tail tail) throws Win32Exception { private static void tail(String name, Tail tail) throws Win32Exception {
EventLog log = new EventLog(); EventLog log = new EventLog();
log.open(name); log.open(name);
int max = log.getNumberOfRecords(); int max = log.getNumberOfRecords();
if (tail.number < max) { if (tail.number < max) {
max = tail.number; max = tail.number;
} }
int last = log.getNewestRecord()+1; int last = log.getNewestRecord()+1;
int first = last - max; int first = last - max;
for (int i=first; i<last; i++) { for (int i=first; i<last; i++) {
EventLogRecord record = log.read(i); EventLogRecord record = log.read(i);
System.out.println(record); System.out.println(record);
} }
log.close(); log.close();
} }
private static class TailNotification implements EventLogNotification { private static class TailNotification implements EventLogNotification {
public void handleNotification(EventLogRecord event) { public void handleNotification(EventLogRecord event) {
System.out.println(event); System.out.println(event);
} }
public boolean matches(EventLogRecord event) { public boolean matches(EventLogRecord event) {
return true; return true;
} }
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Tail tail = new Tail(); Tail tail = new Tail();
tail.parseArgs(args); tail.parseArgs(args);
if (tail.files.size() == 0) { if (tail.files.size() == 0) {
tail.files.add(EventLog.SYSTEM); tail.files.add(EventLog.SYSTEM);
} }
for (int i=0; i<tail.files.size(); i++) { for (int i=0; i<tail.files.size(); i++) {
String name = (String)tail.files.get(i); String name = (String)tail.files.get(i);
tail(name, tail); tail(name, tail);
if (tail.follow) { if (tail.follow) {
TailNotification notifier = new TailNotification(); TailNotification notifier = new TailNotification();
EventLogThread thread = EventLogThread thread =
EventLogThread.getInstance(name); EventLogThread.getInstance(name);
thread.add(notifier); thread.add(notifier);
thread.doStart(); thread.doStart();
} }
} }
if (tail.follow) { if (tail.follow) {
System.in.read(); System.in.read();
} }
} }
} }
@@ -1,100 +1,100 @@
/* /*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.cmd; package org.hyperic.sigar.cmd;
import java.io.File; import java.io.File;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.ProcExe; import org.hyperic.sigar.ProcExe;
import org.hyperic.sigar.win32.Win32; import org.hyperic.sigar.win32.Win32;
import org.hyperic.sigar.win32.FileVersion; import org.hyperic.sigar.win32.FileVersion;
/** /**
* Display process file information. * Display process file information.
*/ */
public class FileVersionInfo extends SigarCommandBase { public class FileVersionInfo extends SigarCommandBase {
public FileVersionInfo(Shell shell) { public FileVersionInfo(Shell shell) {
super(shell); super(shell);
} }
public FileVersionInfo() { public FileVersionInfo() {
super(); super();
} }
protected boolean validateArgs(String[] args) { protected boolean validateArgs(String[] args) {
return args.length >= 1; return args.length >= 1;
} }
public String getUsageShort() { public String getUsageShort() {
return "Display file version info"; return "Display file version info";
} }
public void output(String[] args) throws SigarException { public void output(String[] args) throws SigarException {
for (int i=0; i<args.length; i++) { for (int i=0; i<args.length; i++) {
String exe = args[i]; String exe = args[i];
if (new File(exe).exists()) { if (new File(exe).exists()) {
output(exe); output(exe);
} }
else { else {
long[] pids = this.shell.findPids(exe); long[] pids = this.shell.findPids(exe);
for (int j=0; j<pids.length; j++) { for (int j=0; j<pids.length; j++) {
try { try {
output(sigar.getProcExe(pids[j]).getName()); output(sigar.getProcExe(pids[j]).getName());
} catch (SigarException e) { } catch (SigarException e) {
println(exe + ": " + e.getMessage()); println(exe + ": " + e.getMessage());
} }
} }
} }
} }
} }
private void output(String key, String val) { private void output(String key, String val) {
final int max = 20; final int max = 20;
int len = max - key.length(); int len = max - key.length();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(" ").append(key); sb.append(" ").append(key);
while (len-- > 0) { while (len-- > 0) {
sb.append('.'); sb.append('.');
} }
sb.append(val); sb.append(val);
println(sb.toString()); println(sb.toString());
} }
public void output(String exe) throws SigarException { public void output(String exe) throws SigarException {
FileVersion info = Win32.getFileVersion(exe); FileVersion info = Win32.getFileVersion(exe);
if (info == null) { if (info == null) {
return; return;
} }
println("Version info for file '" + exe + "':"); println("Version info for file '" + exe + "':");
output("FileVersion", info.getFileVersion()); output("FileVersion", info.getFileVersion());
output("ProductVersion", info.getProductVersion()); output("ProductVersion", info.getProductVersion());
for (Iterator it = info.getInfo().entrySet().iterator(); for (Iterator it = info.getInfo().entrySet().iterator();
it.hasNext();) it.hasNext();)
{ {
Map.Entry entry = (Map.Entry)it.next(); Map.Entry entry = (Map.Entry)it.next();
output((String)entry.getKey(), (String)entry.getValue()); output((String)entry.getKey(), (String)entry.getValue());
} }
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
new FileVersionInfo().processCommand(args); new FileVersionInfo().processCommand(args);
} }
} }
@@ -83,7 +83,12 @@ public class Top {
String cpuPerc = "?"; String cpuPerc = "?";
List info = Ps.getInfo(sigar, pid); List info;
try {
info = Ps.getInfo(sigar, pid);
} catch (SigarException e) {
continue; //process may have gone away
}
try { try {
ProcCpu cpu = sigar.getProcCpu(pid); ProcCpu cpu = sigar.getProcCpu(pid);
cpuPerc = CpuPerc.format(cpu.getPercent()); cpuPerc = CpuPerc.format(cpu.getPercent());
@@ -70,7 +70,7 @@ public class Version extends SigarCommandBase {
os.println("Sigar version......." + version); os.println("Sigar version......." + version);
os.println("Build date.........." + build); os.println("Build date.........." + build);
os.println("SVN rev............." + scm); os.println("SCM rev............." + scm);
String host = getHostName(); String host = getHostName();
String fqdn; String fqdn;
Sigar sigar = new Sigar(); Sigar sigar = new Sigar();
@@ -1,268 +1,268 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeList; import javax.management.AttributeList;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean; import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException; import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanRegistration; import javax.management.MBeanRegistration;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.management.ObjectName; 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; 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
* creation of the Sigar proxy instance and provides some convenience methods. * creation of the Sigar proxy instance and provides some convenience methods.
* It also enforces usage of the {@link DynamicMBean} inferface while * It also enforces usage of the {@link DynamicMBean} inferface while
* implementing part of it, and it adds empty implementations for all methods of * implementing part of it, and it adds empty implementations for all methods of
* the {@link MBeanRegistration} interface, allowing subclasses to only * the {@link MBeanRegistration} interface, allowing subclasses to only
* implement subset of them. * implement subset of them.
* *
* @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, MBeanRegistration {
protected static final String MBEAN_ATTR_TYPE = "type"; protected static final String MBEAN_ATTR_TYPE = "type";
protected static final short CACHED_30SEC = 0; protected static final short CACHED_30SEC = 0;
protected static final short CACHED_5SEC = 1; protected static final short CACHED_5SEC = 1;
protected static final short CACHED_500MS = 2; protected static final short CACHED_500MS = 2;
protected static final short CACHELESS = 3; protected static final short CACHELESS = 3;
protected static final short DEFAULT = CACHED_30SEC; protected static final short DEFAULT = CACHED_30SEC;
/** /**
* The Sigar implementation to be used to fetch information from the system. * The Sigar implementation to be used to fetch information from the system.
*/ */
protected final Sigar sigarImpl; 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
* construction. See {@link AbstractMBean#AbstractMBean(Sigar, short)} for * construction. See {@link AbstractMBean#AbstractMBean(Sigar, short)} for
* details. * details.
* *
* @see AbstractMBean#AbstractMBean(Sigar, short) * @see AbstractMBean#AbstractMBean(Sigar, short)
*/ */
protected final SigarProxy sigar; protected final SigarProxy sigar;
/** /**
* The MBean server this MBean is registered to. Set during the MBean's * The MBean server this MBean is registered to. Set during the MBean's
* registration to the MBean server and unset to <code>null</code> when * registration to the MBean server and unset to <code>null</code> when
* the deregistration finished. * the deregistration finished.
* *
* @see #preRegister(MBeanServer, ObjectName) * @see #preRegister(MBeanServer, ObjectName)
* @see #postDeregister() * @see #postDeregister()
*/ */
protected MBeanServer mbeanServer; protected MBeanServer mbeanServer;
/** /**
* <p>Creates a new instance of this class. The Sigar instance is stored (and * <p>Creates a new instance of this class. The Sigar instance is stored (and
* accessible) via the {@link #sigarImpl} member. A second instance is * accessible) via the {@link #sigarImpl} member. A second instance is
* stored within the {@link #sigar} member which is either {@link #sigarImpl} * stored within the {@link #sigar} member which is either {@link #sigarImpl}
* or an instance of {@link SigarProxyCache} with the expiration time set to * or an instance of {@link SigarProxyCache} with the expiration time set to
* whatever the <code>cacheMode</code> parameter specifies.</p> * whatever the <code>cacheMode</code> parameter specifies.</p>
* *
* <p>The following cache modes exist:</p> * <p>The following cache modes exist:</p>
* *
* <table border = "1"> * <table border = "1">
* <tr><td><b>Constant</b></td><td><b>Description</b></td></tr> * <tr><td><b>Constant</b></td><td><b>Description</b></td></tr>
* <tr><td>{@link #CACHELESS}</td><td>No cached instance, {@link #sigar} * <tr><td>{@link #CACHELESS}</td><td>No cached instance, {@link #sigar}
* <code>==</code> {@link #sigarImpl}.</td></tr> * <code>==</code> {@link #sigarImpl}.</td></tr>
* <tr><td>{@link #CACHED_500MS}</td><td>500 millisecond cache, for high * <tr><td>{@link #CACHED_500MS}</td><td>500 millisecond cache, for high
* frequency queries on raw data such as reading out CPU timers each * frequency queries on raw data such as reading out CPU timers each
* second. Avoids reading out multiple data sets when all attributes of * second. Avoids reading out multiple data sets when all attributes of
* an MBean are queried in short sequence.</td></tr> * an MBean are queried in short sequence.</td></tr>
* <tr><td>{@link #CACHED_5SEC}</td><td>5 second cache, for high frequency * <tr><td>{@link #CACHED_5SEC}</td><td>5 second cache, for high frequency
* queries on calculated data such as CPU percentages.</td></tr> * queries on calculated data such as CPU percentages.</td></tr>
* <tr><td>{@link #CACHED_30SEC}</td><td>30 second cache, for normal queries * <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 * or data readouts such as CPU model / vendor. This is the default if
* nothing (<code>0</code>) is specified.</td></tr> * nothing (<code>0</code>) is specified.</td></tr>
* <tr><td>{@link #DEFAULT}</td><td>Same as {@link #CACHED_30SEC}.</td></tr> * <tr><td>{@link #DEFAULT}</td><td>Same as {@link #CACHED_30SEC}.</td></tr>
* </table> * </table>
* *
* <p><b>Note:</b> Only make use of the cacheless or half second mode if you * <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 * know what you are doing. They may have impact on system performance if
* used excessively.</p> * used excessively.</p>
* *
* @param sigar The Sigar impl to use. Must not be <code>null</code> * @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} * @param cacheMode The cache mode to use for {@link #sigar} or {@link #CACHELESS}
* if no separate, cached instance is to be maintained. * if no separate, cached instance is to be maintained.
*/ */
protected AbstractMBean(Sigar sigar, short cacheMode) { protected AbstractMBean(Sigar sigar, short cacheMode) {
// store Sigar // store Sigar
this.sigarImpl = sigar; this.sigarImpl = sigar;
// create a cached instance as well // create a cached instance as well
if (cacheMode == CACHELESS) { if (cacheMode == CACHELESS) {
// no cached version // no cached version
this.sigar = this.sigarImpl; this.sigar = this.sigarImpl;
} else if (cacheMode == CACHED_500MS) { } else if (cacheMode == CACHED_500MS) {
// 500ms cached version (for 1/sec queries) // 500ms cached version (for 1/sec queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 500); this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 500);
} else if (cacheMode == CACHED_5SEC) { } else if (cacheMode == CACHED_5SEC) {
// 5sec cached version (for avg'd queries) // 5sec cached version (for avg'd queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 5000); this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 5000);
} else /* if (cacheMode == CACHED_30SEC) */{ } else /* if (cacheMode == CACHED_30SEC) */{
// 30sec (default) cached version (for info and long term queries) // 30sec (default) cached version (for info and long term queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 30000); this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 30000);
} }
} }
/** /**
* Returns the object name the MBean is registered with within the * Returns the object name the MBean is registered with within the
* MBeanServer. May be <code>null</code> in case the instance is not * MBeanServer. May be <code>null</code> in case the instance is not
* registered to an MBeanServer, but used standalone. * registered to an MBeanServer, but used standalone.
* *
* @return The object name or <code>null</code> if not registered to an * @return The object name or <code>null</code> if not registered to an
* MBeanServer * MBeanServer
*/ */
public abstract String getObjectName(); public abstract String getObjectName();
/** /**
* Returns a runtime exception for the type and SigarException specified. * Returns a runtime exception for the type and SigarException specified.
* *
* @param type * @param type
* The type that was called * The type that was called
* @param e * @param e
* The exception that was raised * The exception that was raised
* @return A runtime exception encapsulating the information specified * @return A runtime exception encapsulating the information specified
*/ */
protected RuntimeException unexpectedError(String type, SigarException e) { protected RuntimeException unexpectedError(String type, SigarException e) {
String msg = "Unexected error in Sigar.get" + type + ": " String msg = "Unexected error in Sigar.get" + type + ": "
+ e.getMessage(); + e.getMessage();
return new IllegalArgumentException(msg); return new IllegalArgumentException(msg);
} }
/** /**
* Loops over all attributes and calls * Loops over all attributes and calls
* {@link DynamicMBean#getAttribute(java.lang.String)} method for each * {@link DynamicMBean#getAttribute(java.lang.String)} method for each
* attribute sequentially. Any exception thrown by those methods are ignored * attribute sequentially. Any exception thrown by those methods are ignored
* and simply cause the attribute not being added to the result. * and simply cause the attribute not being added to the result.
*/ */
public AttributeList getAttributes(String[] attrs) { public AttributeList getAttributes(String[] attrs) {
final AttributeList result = new AttributeList(); final AttributeList result = new AttributeList();
for (int i = 0; i < attrs.length; i++) { for (int i = 0; i < attrs.length; i++) {
try { try {
result.add(new Attribute(attrs[i], getAttribute(attrs[i]))); result.add(new Attribute(attrs[i], getAttribute(attrs[i])));
} catch (AttributeNotFoundException e) { } catch (AttributeNotFoundException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} catch (MBeanException e) { } catch (MBeanException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} catch (ReflectionException e) { } catch (ReflectionException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} }
} }
return result; return result;
} }
/** /**
* Loops over all attributes and calls * Loops over all attributes and calls
* {@link DynamicMBean#setAttribute(Attribute)} for each attribute * {@link DynamicMBean#setAttribute(Attribute)} for each attribute
* sequentially. Any exception thrown by those methods are ignored and * sequentially. Any exception thrown by those methods are ignored and
* simply cause the attribute not being added to the result. * simply cause the attribute not being added to the result.
*/ */
public AttributeList setAttributes(AttributeList attrs) { public AttributeList setAttributes(AttributeList attrs) {
final AttributeList result = new AttributeList(); final AttributeList result = new AttributeList();
for (int i = 0; i < attrs.size(); i++) { for (int i = 0; i < attrs.size(); i++) {
try { try {
final Attribute next = (Attribute) attrs.get(i); final Attribute next = (Attribute) attrs.get(i);
setAttribute(next); setAttribute(next);
result.add(next); result.add(next);
} catch (AttributeNotFoundException e) { } catch (AttributeNotFoundException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} catch (InvalidAttributeValueException e) { } catch (InvalidAttributeValueException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} catch (MBeanException e) { } catch (MBeanException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} catch (ReflectionException e) { } catch (ReflectionException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} }
} }
return result; return result;
} }
// ------- // -------
// Implementation of the MBeanRegistration interface // Implementation of the MBeanRegistration interface
// ------- // -------
/** /**
* <p>Returns <code>new ObjectName(this.getObjectName())</code> to guarantee * <p>Returns <code>new ObjectName(this.getObjectName())</code> to guarantee
* a reliable and reproducable object name.</p> * a reliable and reproducable object name.</p>
* *
* <p><b>Note:</b> Make sure any subclass does a super call to this method, * <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p> * otherwise the implementation might be broken.</p>
* *
* @see MBeanRegistration#preRegister(MBeanServer, ObjectName) * @see MBeanRegistration#preRegister(MBeanServer, ObjectName)
*/ */
public ObjectName preRegister(MBeanServer server, ObjectName name) public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception { throws Exception {
this.mbeanServer = server; this.mbeanServer = server;
return new ObjectName(getObjectName()); return new ObjectName(getObjectName());
} }
/** /**
* Empty implementation, allowing aubclasses to ignore the interface. * Empty implementation, allowing aubclasses to ignore the interface.
* *
* <p><b>Note:</b> Make sure any subclass does a super call to this method, * <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p> * otherwise the implementation might be broken.</p>
* *
* @see MBeanRegistration#postRegister(Boolean) * @see MBeanRegistration#postRegister(Boolean)
*/ */
public void postRegister(Boolean success) { public void postRegister(Boolean success) {
} }
/** /**
* Empty implementation, allowing aubclasses to ignore the interface. * Empty implementation, allowing aubclasses to ignore the interface.
* *
* <p><b>Note:</b> Make sure any subclass does a super call to this method, * <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p> * otherwise the implementation might be broken.</p>
* *
* @see MBeanRegistration#preDeregister() * @see MBeanRegistration#preDeregister()
*/ */
public void preDeregister() throws Exception { public void preDeregister() throws Exception {
} }
/** /**
* Empty implementation, allowing aubclasses to ignore the interface. * Empty implementation, allowing aubclasses to ignore the interface.
* *
* <p><b>Note:</b> Make sure any subclass does a super call to this method, * <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p> * otherwise the implementation might be broken.</p>
* *
* @see MBeanRegistration#postDeregister() * @see MBeanRegistration#postDeregister()
*/ */
public void postDeregister() { public void postDeregister() {
this.mbeanServer = null; this.mbeanServer = null;
} }
} }
@@ -1,334 +1,334 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; import javax.management.MBeanParameterInfo;
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;
/** /**
* Sigar JMX MBean implementation for the <code>Cpu</code> information * Sigar JMX MBean implementation for the <code>Cpu</code> information
* package. Provides an OpenMBean conform implementation. * package. Provides an OpenMBean conform implementation.
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarCpu extends AbstractMBean { public class SigarCpu extends AbstractMBean {
private static final String MBEAN_TYPE = "CpuList"; private static final String MBEAN_TYPE = "CpuList";
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX; private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX;
private static final MBeanAttributeInfo MBEAN_ATTR_IDLE; private static final MBeanAttributeInfo MBEAN_ATTR_IDLE;
private static final MBeanAttributeInfo MBEAN_ATTR_NICE; private static final MBeanAttributeInfo MBEAN_ATTR_NICE;
private static final MBeanAttributeInfo MBEAN_ATTR_SYS; private static final MBeanAttributeInfo MBEAN_ATTR_SYS;
private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL; private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL;
private static final MBeanAttributeInfo MBEAN_ATTR_USER; private static final MBeanAttributeInfo MBEAN_ATTR_USER;
private static final MBeanAttributeInfo MBEAN_ATTR_WAIT; private static final MBeanAttributeInfo MBEAN_ATTR_WAIT;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX; private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR; private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_CPUINDEX; private static MBeanParameterInfo MBEAN_PARAM_CPUINDEX;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR; private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static { static {
MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int", MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int",
"The index of the CPU, typically starting at 0", true, false, "The index of the CPU, typically starting at 0", true, false,
false); false);
MBEAN_ATTR_IDLE = new MBeanAttributeInfo("Idle", "long", MBEAN_ATTR_IDLE = new MBeanAttributeInfo("Idle", "long",
"The idle time of the CPU, in [ms]", true, false, false); "The idle time of the CPU, in [ms]", true, false, false);
MBEAN_ATTR_NICE = new MBeanAttributeInfo("Nice", "long", MBEAN_ATTR_NICE = new MBeanAttributeInfo("Nice", "long",
"The time of the CPU spent on nice priority, in [ms]", true, "The time of the CPU spent on nice priority, in [ms]", true,
false, false); false, false);
MBEAN_ATTR_SYS = new MBeanAttributeInfo("Sys", "long", MBEAN_ATTR_SYS = new MBeanAttributeInfo("Sys", "long",
"The time of the CPU used by the system, in [ms]", true, false, "The time of the CPU used by the system, in [ms]", true, false,
false); false);
MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long", MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long",
"The total time of the CPU, in [ms]", true, false, false); "The total time of the CPU, in [ms]", true, false, false);
MBEAN_ATTR_USER = new MBeanAttributeInfo("User", "long", MBEAN_ATTR_USER = new MBeanAttributeInfo("User", "long",
"The time of the CPU used by user processes, in [ms]", true, "The time of the CPU used by user processes, in [ms]", true,
false, false); false, false);
MBEAN_ATTR_WAIT = new MBeanAttributeInfo("Wait", "long", MBEAN_ATTR_WAIT = new MBeanAttributeInfo("Wait", "long",
"The time the CPU had to wait for data to be loaded, in [ms]", "The time the CPU had to wait for data to be loaded, in [ms]",
true, false, false); true, false, false);
MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int", MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int",
"The index of the CPU to read data for. Must be >= 0 " "The index of the CPU to read data for. Must be >= 0 "
+ "and not exceed the CPU count of the system"); + "and not exceed the CPU count of the system");
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from"); .getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpu.class MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpu.class
.getName(), .getName(),
"Creates a new instance for the CPU index specified, " "Creates a new instance for the CPU index specified, "
+ "using a new Sigar instance to fetch the data. " + "using a new Sigar instance to fetch the data. "
+ "Fails if the CPU index is out of range.", + "Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX }); new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX });
MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo( MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo(
SigarCpu.class.getName(), SigarCpu.class.getName(),
"Creates a new instance for the CPU index specified, " "Creates a new instance for the CPU index specified, "
+ "using the Sigar instance specified to fetch the data. " + "using the Sigar instance specified to fetch the data. "
+ "Fails if the CPU index is out of range.", + "Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR, new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR,
MBEAN_PARAM_CPUINDEX }); MBEAN_PARAM_CPUINDEX });
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarCpu.class.getName(), SigarCpu.class.getName(),
"Sigar CPU MBean. Provides raw timing data for a single " "Sigar CPU MBean. Provides raw timing data for a single "
+ "CPU. The data is cached for 500ms, meaning each request " + "CPU. The data is cached for 500ms, meaning each request "
+ "(and as a result each block request to all parameters) " + "(and as a result each block request to all parameters) "
+ "within half a second is satisfied from the same dataset.", + "within half a second is satisfied from the same dataset.",
new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX, new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX,
MBEAN_ATTR_IDLE, MBEAN_ATTR_NICE, MBEAN_ATTR_SYS, MBEAN_ATTR_IDLE, MBEAN_ATTR_NICE, MBEAN_ATTR_SYS,
MBEAN_ATTR_TOTAL, MBEAN_ATTR_USER, MBEAN_ATTR_WAIT }, MBEAN_ATTR_TOTAL, MBEAN_ATTR_USER, MBEAN_ATTR_WAIT },
new MBeanConstructorInfo[] { MBEAN_CONSTR_CPUINDEX, new MBeanConstructorInfo[] { MBEAN_CONSTR_CPUINDEX,
MBEAN_CONSTR_CPUINDEX_SIGAR }, null, null); MBEAN_CONSTR_CPUINDEX_SIGAR }, null, null);
} }
/** /**
* Index of the CPU processed by the instance. * Index of the CPU processed by the instance.
*/ */
private final int cpuIndex; private final int cpuIndex;
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
private final String objectName; private final String objectName;
/** /**
* Creates a new instance for the CPU index specified, using a new Sigar * Creates a new instance for the CPU index specified, using a new Sigar
* instance to fetch the data. Fails if the CPU index is out of range. * instance to fetch the data. Fails if the CPU index is out of range.
* *
* @param cpuIndex * @param cpuIndex
* The index of the CPU to read data for. Must be <code>&gt;= 0</code> * The index of the CPU to read data for. Must be <code>&gt;= 0</code>
* and not exceed the CPU count of the system. * and not exceed the CPU count of the system.
* *
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If the CPU index is out of range or an unexpected Sigar error * If the CPU index is out of range or an unexpected Sigar error
* occurs. * occurs.
*/ */
public SigarCpu(int cpuIndex) throws IllegalArgumentException { public SigarCpu(int cpuIndex) throws IllegalArgumentException {
this(new Sigar(), cpuIndex); this(new Sigar(), cpuIndex);
} }
/** /**
* Creates a new instance for the CPU index specified, using the Sigar * Creates a new instance for the CPU index specified, using the Sigar
* instance specified to fetch the data. Fails if the CPU index is out of * instance specified to fetch the data. Fails if the CPU index is out of
* range. * range.
* *
* @param sigar * @param sigar
* The Sigar instance to use to fetch data from * The Sigar instance to use to fetch data from
* @param cpuIndex * @param cpuIndex
* The index of the CPU to read data for. Must be * The index of the CPU to read data for. Must be
* <code>&gt;= 0</code> and not exceed the CPU count of the * <code>&gt;= 0</code> and not exceed the CPU count of the
* system. * system.
* *
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If the CPU index is out of range or an unexpected Sigar error * If the CPU index is out of range or an unexpected Sigar error
* occurs * occurs
*/ */
public SigarCpu(Sigar sigar, int cpuIndex) throws IllegalArgumentException { public SigarCpu(Sigar sigar, int cpuIndex) throws IllegalArgumentException {
super(sigar, CACHED_500MS); super(sigar, CACHED_500MS);
// check index // check index
if (cpuIndex < 0) if (cpuIndex < 0)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"CPU index has to be non-negative: " + cpuIndex); "CPU index has to be non-negative: " + cpuIndex);
try { try {
int cpuCount; int cpuCount;
if ((cpuCount = sigar.getCpuList().length) < cpuIndex) if ((cpuCount = sigar.getCpuList().length) < cpuIndex)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"CPU index out of range (found " + cpuCount "CPU index out of range (found " + cpuCount
+ " CPU(s)): " + cpuIndex); + " CPU(s)): " + cpuIndex);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
// all fine // all fine
this.cpuIndex = cpuIndex; this.cpuIndex = cpuIndex;
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=Cpu," + "=Cpu,"
+ MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase() + MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase()
+ MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex; + MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex;
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/** /**
* @return The index of the CPU, typically starting at 0 * @return The index of the CPU, typically starting at 0
*/ */
public int getCpuIndex() { public int getCpuIndex() {
return this.cpuIndex; return this.cpuIndex;
} }
/** /**
* @return The idle time of the CPU, in [ms] * @return The idle time of the CPU, in [ms]
*/ */
public long getIdle() { public long getIdle() {
try { try {
return sigar.getCpuList()[this.cpuIndex].getIdle(); return sigar.getCpuList()[this.cpuIndex].getIdle();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time of the CPU spent on nice priority, in [ms] * @return The time of the CPU spent on nice priority, in [ms]
*/ */
public long getNice() { public long getNice() {
try { try {
return sigar.getCpuList()[this.cpuIndex].getNice(); return sigar.getCpuList()[this.cpuIndex].getNice();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time of the CPU used by the system, in [ms] * @return The time of the CPU used by the system, in [ms]
*/ */
public long getSys() { public long getSys() {
try { try {
return sigar.getCpuList()[this.cpuIndex].getSys(); return sigar.getCpuList()[this.cpuIndex].getSys();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The total time of the CPU, in [ms] * @return The total time of the CPU, in [ms]
*/ */
public long getTotal() { public long getTotal() {
try { try {
return sigar.getCpuList()[this.cpuIndex].getTotal(); return sigar.getCpuList()[this.cpuIndex].getTotal();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time of the CPU used by user processes, in [ms] * @return The time of the CPU used by user processes, in [ms]
*/ */
public long getUser() { public long getUser() {
try { try {
return sigar.getCpuList()[this.cpuIndex].getUser(); return sigar.getCpuList()[this.cpuIndex].getUser();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time the CPU had to wait for data to be loaded, in [ms] * @return The time the CPU had to wait for data to be loaded, in [ms]
*/ */
public long getWait() { public long getWait() {
try { try {
return sigar.getCpuList()[this.cpuIndex].getWait(); return sigar.getCpuList()[this.cpuIndex].getWait();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
// ------- // -------
// Implementation of the DynamicMBean interface // Implementation of the DynamicMBean interface
// ------- // -------
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#getAttribute(String) * @see DynamicMBean#getAttribute(String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException { public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) { if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) {
return new Integer(getCpuIndex()); return new Integer(getCpuIndex());
} else if (MBEAN_ATTR_IDLE.getName().equals(attr)) { } else if (MBEAN_ATTR_IDLE.getName().equals(attr)) {
return new Long(getIdle()); return new Long(getIdle());
} else if (MBEAN_ATTR_NICE.getName().equals(attr)) { } else if (MBEAN_ATTR_NICE.getName().equals(attr)) {
return new Long(getNice()); return new Long(getNice());
} else if (MBEAN_ATTR_SYS.getName().equals(attr)) { } else if (MBEAN_ATTR_SYS.getName().equals(attr)) {
return new Long(getSys()); return new Long(getSys());
} else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) { } else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) {
return new Long(getTotal()); return new Long(getTotal());
} else if (MBEAN_ATTR_USER.getName().equals(attr)) { } else if (MBEAN_ATTR_USER.getName().equals(attr)) {
return new Long(getUser()); return new Long(getUser());
} else if (MBEAN_ATTR_WAIT.getName().equals(attr)) { } else if (MBEAN_ATTR_WAIT.getName().equals(attr)) {
return new Long(getWait()); return new Long(getWait());
} else { } else {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#setAttribute(Attribute) * @see DynamicMBean#setAttribute(Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#invoke(String, Object[], String[]) * @see DynamicMBean#invoke(String, Object[], String[])
*/ */
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException { throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName), throw new ReflectionException(new NoSuchMethodException(actionName),
actionName); actionName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#getMBeanInfo() * @see DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
} }
@@ -1,286 +1,286 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; import javax.management.MBeanParameterInfo;
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;
/** /**
* Sigar JMX MBean implementation for the <code>CpuInfo</code> information * Sigar JMX MBean implementation for the <code>CpuInfo</code> information
* package. Provides an OpenMBean conform implementation. * package. Provides an OpenMBean conform implementation.
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarCpuInfo extends AbstractMBean { public class SigarCpuInfo extends AbstractMBean {
private static final String MBEAN_TYPE = "CpuInfoList"; private static final String MBEAN_TYPE = "CpuInfoList";
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX; private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX;
private static final MBeanAttributeInfo MBEAN_ATTR_CACHESIZE; private static final MBeanAttributeInfo MBEAN_ATTR_CACHESIZE;
private static final MBeanAttributeInfo MBEAN_ATTR_MHZ; private static final MBeanAttributeInfo MBEAN_ATTR_MHZ;
private static final MBeanAttributeInfo MBEAN_ATTR_MODEL; private static final MBeanAttributeInfo MBEAN_ATTR_MODEL;
private static final MBeanAttributeInfo MBEAN_ATTR_VENDOR; private static final MBeanAttributeInfo MBEAN_ATTR_VENDOR;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX; private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR; private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR;
private static final MBeanParameterInfo MBEAN_PARAM_CPUINDEX; private static final MBeanParameterInfo MBEAN_PARAM_CPUINDEX;
private static final MBeanParameterInfo MBEAN_PARAM_SIGAR; private static final MBeanParameterInfo MBEAN_PARAM_SIGAR;
static { static {
MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int", MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int",
"The index of the CPU, typically starting at 0", true, false, "The index of the CPU, typically starting at 0", true, false,
false); false);
MBEAN_ATTR_CACHESIZE = new MBeanAttributeInfo("CacheSize", "long", MBEAN_ATTR_CACHESIZE = new MBeanAttributeInfo("CacheSize", "long",
"The cache size of the CPU, in [byte]", true, false, false); "The cache size of the CPU, in [byte]", true, false, false);
MBEAN_ATTR_MHZ = new MBeanAttributeInfo("Mhz", "int", MBEAN_ATTR_MHZ = new MBeanAttributeInfo("Mhz", "int",
"The clock speed of the CPU, in [MHz]", true, false, false); "The clock speed of the CPU, in [MHz]", true, false, false);
MBEAN_ATTR_MODEL = new MBeanAttributeInfo("Model", "java.lang.String", MBEAN_ATTR_MODEL = new MBeanAttributeInfo("Model", "java.lang.String",
"The CPU model reported", true, false, false); "The CPU model reported", true, false, false);
MBEAN_ATTR_VENDOR = new MBeanAttributeInfo("Vendor", MBEAN_ATTR_VENDOR = new MBeanAttributeInfo("Vendor",
"java.lang.String", "The CPU vendor reported", true, false, "java.lang.String", "The CPU vendor reported", true, false,
false); false);
MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int", MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int",
"The index of the CPU to read data for. Must be >= 0 " "The index of the CPU to read data for. Must be >= 0 "
+ "and not exceed the CPU count of the system"); + "and not exceed the CPU count of the system");
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from"); .getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpuInfo.class MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpuInfo.class
.getName(), .getName(),
"Creates a new instance for the CPU index specified, " "Creates a new instance for the CPU index specified, "
+ "using a new Sigar instance to fetch the data. " + "using a new Sigar instance to fetch the data. "
+ "Fails if the CPU index is out of range.", + "Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX }); new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX });
MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo( MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo(
SigarCpuInfo.class.getName(), SigarCpuInfo.class.getName(),
"Creates a new instance for the CPU index specified, " "Creates a new instance for the CPU index specified, "
+ "using the Sigar instance specified to fetch the data. " + "using the Sigar instance specified to fetch the data. "
+ "Fails if the CPU index is out of range.", + "Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR, new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR,
MBEAN_PARAM_CPUINDEX }); MBEAN_PARAM_CPUINDEX });
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarCpuInfo.class.getName(), SigarCpuInfo.class.getName(),
"Sigar CPU Info MBean, provides overall information for a " "Sigar CPU Info MBean, provides overall information for a "
+ "single CPU. This information only changes if, for example, " + "single CPU. This information only changes if, for example, "
+ "a CPU is reducing its clock frequency or shutting down " + "a CPU is reducing its clock frequency or shutting down "
+ "part of its cache. Subsequent requests are satisfied from " + "part of its cache. Subsequent requests are satisfied from "
+ "within a cache that invalidates after 30 seconds.", + "within a cache that invalidates after 30 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX, new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX,
MBEAN_ATTR_CACHESIZE, MBEAN_ATTR_MHZ, MBEAN_ATTR_MODEL, MBEAN_ATTR_CACHESIZE, MBEAN_ATTR_MHZ, MBEAN_ATTR_MODEL,
MBEAN_ATTR_VENDOR }, new MBeanConstructorInfo[] { MBEAN_ATTR_VENDOR }, new MBeanConstructorInfo[] {
MBEAN_CONSTR_CPUINDEX, MBEAN_CONSTR_CPUINDEX_SIGAR }, MBEAN_CONSTR_CPUINDEX, MBEAN_CONSTR_CPUINDEX_SIGAR },
null, null); null, null);
} }
/** /**
* Index of the CPU processed by the instance. * Index of the CPU processed by the instance.
*/ */
private int cpuIndex; private int cpuIndex;
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
private String objectName; private String objectName;
/** /**
* Creates a new instance for the CPU index specified, using a new Sigar * Creates a new instance for the CPU index specified, using a new Sigar
* instance to fetch the data. Fails if the CPU index is out of range. * instance to fetch the data. Fails if the CPU index is out of range.
* *
* @param cpuIndex The index of the CPU to read data for. Must be * @param cpuIndex The index of the CPU to read data for. Must be
* <code>&gt;= 0</code> and not exceed the CPU count of the system. * <code>&gt;= 0</code> and not exceed the CPU count of the system.
* *
* @throws IllegalArgumentException If the CPU index is out of range or * @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs * an unexpected Sigar error occurs
*/ */
public SigarCpuInfo(int index) throws IllegalArgumentException { public SigarCpuInfo(int index) throws IllegalArgumentException {
this(new Sigar(), index); this(new Sigar(), index);
} }
/** /**
* Creates a new instance for the CPU index specified, using the Sigar * Creates a new instance for the CPU index specified, using the Sigar
* instance specified to fetch the data. Fails if the CPU index is out * instance specified to fetch the data. Fails if the CPU index is out
* of range. * of range.
* *
* @param sigar The Sigar instance to use to fetch data from * @param sigar The Sigar instance to use to fetch data from
* @param cpuIndex The index of the CPU to read data for. Must be * @param cpuIndex The index of the CPU to read data for. Must be
* <code>&gt;= 0</code> and not exceed the CPU count of the system. * <code>&gt;= 0</code> and not exceed the CPU count of the system.
* *
* @throws IllegalArgumentException If the CPU index is out of range or * @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs * an unexpected Sigar error occurs
*/ */
public SigarCpuInfo(Sigar sigar, int index) { public SigarCpuInfo(Sigar sigar, int index) {
super(sigar, DEFAULT); super(sigar, DEFAULT);
// check index // check index
if (index < 0) if (index < 0)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"CPU index has to be non-negative: " + index); "CPU index has to be non-negative: " + index);
try { try {
int cpuCount; int cpuCount;
if ((cpuCount = sigar.getCpuInfoList().length) < index) if ((cpuCount = sigar.getCpuInfoList().length) < index)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"CPU index out of range (found " + cpuCount "CPU index out of range (found " + cpuCount
+ " CPU(s)): " + index); + " CPU(s)): " + index);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
// all fine // all fine
this.cpuIndex = index; this.cpuIndex = index;
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=CpuInfo," + "=CpuInfo,"
+ MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase() + MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase()
+ MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex; + MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex;
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/** /**
* @return The index of the CPU, typically starting at 0 * @return The index of the CPU, typically starting at 0
*/ */
public int getCpuIndex() { public int getCpuIndex() {
return this.cpuIndex; return this.cpuIndex;
} }
/** /**
* @return The cache size of the CPU, in [byte] * @return The cache size of the CPU, in [byte]
*/ */
public long getCacheSize() { public long getCacheSize() {
try { try {
return sigar.getCpuInfoList()[this.cpuIndex].getCacheSize(); return sigar.getCpuInfoList()[this.cpuIndex].getCacheSize();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The clock speed of the CPU, in [MHz] * @return The clock speed of the CPU, in [MHz]
*/ */
public int getMhz() { public int getMhz() {
try { try {
return sigar.getCpuInfoList()[this.cpuIndex].getMhz(); return sigar.getCpuInfoList()[this.cpuIndex].getMhz();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The CPU model reported * @return The CPU model reported
*/ */
public String getModel() { public String getModel() {
try { try {
return sigar.getCpuInfoList()[this.cpuIndex].getModel(); return sigar.getCpuInfoList()[this.cpuIndex].getModel();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The CPU vendor reported * @return The CPU vendor reported
*/ */
public String getVendor() { public String getVendor() {
try { try {
return sigar.getCpuInfoList()[this.cpuIndex].getVendor(); return sigar.getCpuInfoList()[this.cpuIndex].getVendor();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
// ------- // -------
// Implementation of the DynamicMBean interface // Implementation of the DynamicMBean interface
// ------- // -------
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#getAttribute(String) * @see DynamicMBean#getAttribute(String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException { public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_CACHESIZE.getName().equals(attr)) { if (MBEAN_ATTR_CACHESIZE.getName().equals(attr)) {
return new Long(getCacheSize()); return new Long(getCacheSize());
} else if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) { } else if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) {
return new Integer(getCpuIndex()); return new Integer(getCpuIndex());
} else if (MBEAN_ATTR_MHZ.getName().equals(attr)) { } else if (MBEAN_ATTR_MHZ.getName().equals(attr)) {
return new Integer(getMhz()); return new Integer(getMhz());
} else if (MBEAN_ATTR_MODEL.getName().equals(attr)) { } else if (MBEAN_ATTR_MODEL.getName().equals(attr)) {
return getModel(); return getModel();
} else if (MBEAN_ATTR_VENDOR.getName().equals(attr)) { } else if (MBEAN_ATTR_VENDOR.getName().equals(attr)) {
return getVendor(); return getVendor();
} else { } else {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#setAttribute(Attribute) * @see DynamicMBean#setAttribute(Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#invoke(String, Object[], String[]) * @see DynamicMBean#invoke(String, Object[], String[])
*/ */
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException { throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName), throw new ReflectionException(new NoSuchMethodException(actionName),
actionName); actionName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#getMBeanInfo() * @see DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
} }
@@ -1,333 +1,333 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; import javax.management.MBeanParameterInfo;
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;
/** /**
* <p>Sigar JMX MBean implementation for the <code>CpuPerc</code> information * <p>Sigar JMX MBean implementation for the <code>CpuPerc</code> information
* package. Provides an OpenMBean conform implementation.</p> * package. Provides an OpenMBean conform implementation.</p>
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarCpuPerc extends AbstractMBean { public class SigarCpuPerc extends AbstractMBean {
private static final String MBEAN_TYPE = "CpuPercList"; private static final String MBEAN_TYPE = "CpuPercList";
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX; private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX;
private static final MBeanAttributeInfo MBEAN_ATTR_COMBINED; private static final MBeanAttributeInfo MBEAN_ATTR_COMBINED;
private static final MBeanAttributeInfo MBEAN_ATTR_IDLE; private static final MBeanAttributeInfo MBEAN_ATTR_IDLE;
private static final MBeanAttributeInfo MBEAN_ATTR_NICE; private static final MBeanAttributeInfo MBEAN_ATTR_NICE;
private static final MBeanAttributeInfo MBEAN_ATTR_SYS; private static final MBeanAttributeInfo MBEAN_ATTR_SYS;
private static final MBeanAttributeInfo MBEAN_ATTR_USER; private static final MBeanAttributeInfo MBEAN_ATTR_USER;
private static final MBeanAttributeInfo MBEAN_ATTR_WAIT; private static final MBeanAttributeInfo MBEAN_ATTR_WAIT;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX; private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR; private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_CPUINDEX; private static MBeanParameterInfo MBEAN_PARAM_CPUINDEX;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR; private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static { static {
MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int", MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int",
"The index of the CPU, typically starting at 0", true, false, "The index of the CPU, typically starting at 0", true, false,
false); false);
MBEAN_ATTR_COMBINED = new MBeanAttributeInfo("Combined", "double", MBEAN_ATTR_COMBINED = new MBeanAttributeInfo("Combined", "double",
"The total time of the CPU, as a fraction of 1", true, false, "The total time of the CPU, as a fraction of 1", true, false,
false); false);
MBEAN_ATTR_IDLE = new MBeanAttributeInfo("Idle", "double", MBEAN_ATTR_IDLE = new MBeanAttributeInfo("Idle", "double",
"The idle time of the CPU, as a fraction of 1", true, false, "The idle time of the CPU, as a fraction of 1", true, false,
false); false);
MBEAN_ATTR_NICE = new MBeanAttributeInfo( MBEAN_ATTR_NICE = new MBeanAttributeInfo(
"Nice", "Nice",
"double", "double",
"The time of the CPU spent on nice priority, as a fraction of 1", "The time of the CPU spent on nice priority, as a fraction of 1",
true, false, false); true, false, false);
MBEAN_ATTR_SYS = new MBeanAttributeInfo("Sys", "double", MBEAN_ATTR_SYS = new MBeanAttributeInfo("Sys", "double",
"The time of the CPU used by the system, as a fraction of 1", "The time of the CPU used by the system, as a fraction of 1",
true, false, false); true, false, false);
MBEAN_ATTR_USER = new MBeanAttributeInfo( MBEAN_ATTR_USER = new MBeanAttributeInfo(
"User", "User",
"double", "double",
"The time of the CPU used by user processes, as a fraction of 1", "The time of the CPU used by user processes, as a fraction of 1",
true, false, false); true, false, false);
MBEAN_ATTR_WAIT = new MBeanAttributeInfo( MBEAN_ATTR_WAIT = new MBeanAttributeInfo(
"Wait", "Wait",
"double", "double",
"The time the CPU had to wait for data to be loaded, as a fraction of 1", "The time the CPU had to wait for data to be loaded, as a fraction of 1",
true, false, false); true, false, false);
MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int", MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int",
"The index of the CPU to read data for. Must be >= 0 " "The index of the CPU to read data for. Must be >= 0 "
+ "and not exceed the CPU count of the system"); + "and not exceed the CPU count of the system");
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from"); .getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpuPerc.class MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpuPerc.class
.getName(), .getName(),
"Creates a new instance for the CPU index specified, " "Creates a new instance for the CPU index specified, "
+ "using a new Sigar instance to fetch the data. " + "using a new Sigar instance to fetch the data. "
+ "Fails if the CPU index is out of range.", + "Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX }); new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX });
MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo( MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo(
SigarCpuPerc.class.getName(), SigarCpuPerc.class.getName(),
"Creates a new instance for the CPU index specified, " "Creates a new instance for the CPU index specified, "
+ "using the Sigar instance specified to fetch the data. " + "using the Sigar instance specified to fetch the data. "
+ "Fails if the CPU index is out of range.", + "Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR, new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR,
MBEAN_PARAM_CPUINDEX }); MBEAN_PARAM_CPUINDEX });
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarCpuPerc.class.getName(), SigarCpuPerc.class.getName(),
"Sigar CPU MBean. Provides percentage data for a single " "Sigar CPU MBean. Provides percentage data for a single "
+ "CPU, averaged over the timeframe between the last and " + "CPU, averaged over the timeframe between the last and "
+ "the current measurement point. Two measurement points " + "the current measurement point. Two measurement points "
+ "can be as close as 5 seconds, meaning subsequent requests " + "can be as close as 5 seconds, meaning subsequent requests "
+ "for data within 5 seconds after the last executed call " + "for data within 5 seconds after the last executed call "
+ "will be satisfied from cached data.", + "will be satisfied from cached data.",
new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX, new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX,
MBEAN_ATTR_COMBINED, MBEAN_ATTR_IDLE, MBEAN_ATTR_NICE, MBEAN_ATTR_COMBINED, MBEAN_ATTR_IDLE, MBEAN_ATTR_NICE,
MBEAN_ATTR_SYS, MBEAN_ATTR_USER, MBEAN_ATTR_WAIT }, MBEAN_ATTR_SYS, MBEAN_ATTR_USER, MBEAN_ATTR_WAIT },
new MBeanConstructorInfo[] { MBEAN_CONSTR_CPUINDEX, new MBeanConstructorInfo[] { MBEAN_CONSTR_CPUINDEX,
MBEAN_CONSTR_CPUINDEX_SIGAR }, null, null); MBEAN_CONSTR_CPUINDEX_SIGAR }, null, null);
} }
/** /**
* Index of the CPU processed by the instance. * Index of the CPU processed by the instance.
*/ */
private int cpuIndex; private int cpuIndex;
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
private String objectName; private String objectName;
/** /**
* Creates a new instance for the CPU index specified, using a new Sigar * Creates a new instance for the CPU index specified, using a new Sigar
* instance to fetch the data. Fails if the CPU index is out of range. * instance to fetch the data. Fails if the CPU index is out of range.
* *
* @param cpuIndex The index of the CPU to read data for. Must be * @param cpuIndex The index of the CPU to read data for. Must be
* <code>&gt;= 0</code> and not exceed the CPU count of the system. * <code>&gt;= 0</code> and not exceed the CPU count of the system.
* *
* @throws IllegalArgumentException If the CPU index is out of range or * @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs * an unexpected Sigar error occurs
*/ */
public SigarCpuPerc(int index) { public SigarCpuPerc(int index) {
this(new Sigar(), index); this(new Sigar(), index);
} }
/** /**
* Creates a new instance for the CPU index specified, using the Sigar * Creates a new instance for the CPU index specified, using the Sigar
* instance specified to fetch the data. Fails if the CPU index is out * instance specified to fetch the data. Fails if the CPU index is out
* of range. * of range.
* *
* @param sigar The Sigar instance to use to fetch data from * @param sigar The Sigar instance to use to fetch data from
* @param cpuIndex The index of the CPU to read data for. Must be * @param cpuIndex The index of the CPU to read data for. Must be
* <code>&gt;= 0</code> and not exceed the CPU count of the system. * <code>&gt;= 0</code> and not exceed the CPU count of the system.
* *
* @throws IllegalArgumentException If the CPU index is out of range or * @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs * an unexpected Sigar error occurs
*/ */
public SigarCpuPerc(Sigar sigar, int index) { public SigarCpuPerc(Sigar sigar, int index) {
super(sigar, CACHED_5SEC); super(sigar, CACHED_5SEC);
// check index // check index
if (index < 0) if (index < 0)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"CPU index has to be non-negative: " + index); "CPU index has to be non-negative: " + index);
try { try {
int cpuCount; int cpuCount;
if ((cpuCount = sigar.getCpuPercList().length) < index) if ((cpuCount = sigar.getCpuPercList().length) < index)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"CPU index out of range (found " + cpuCount "CPU index out of range (found " + cpuCount
+ " CPU(s)): " + index); + " CPU(s)): " + index);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
// all fine // all fine
this.cpuIndex = index; this.cpuIndex = index;
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=CpuPerc," + "=CpuPerc,"
+ MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase() + MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase()
+ MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex; + MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex;
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/** /**
* @return The index of the CPU, typically starting at 0 * @return The index of the CPU, typically starting at 0
*/ */
public int getCpuIndex() { public int getCpuIndex() {
return this.cpuIndex; return this.cpuIndex;
} }
/** /**
* @return The total time of the CPU, as a fraction of 1 * @return The total time of the CPU, as a fraction of 1
*/ */
public double getCombined() { public double getCombined() {
try { try {
return sigar.getCpuPercList()[this.cpuIndex].getCombined(); return sigar.getCpuPercList()[this.cpuIndex].getCombined();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The idle time of the CPU, as a fraction of 1 * @return The idle time of the CPU, as a fraction of 1
*/ */
public double getIdle() { public double getIdle() {
try { try {
return sigar.getCpuPercList()[this.cpuIndex].getIdle(); return sigar.getCpuPercList()[this.cpuIndex].getIdle();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time of the CPU spent on nice priority, as a fraction of 1 * @return The time of the CPU spent on nice priority, as a fraction of 1
*/ */
public double getNice() { public double getNice() {
try { try {
return sigar.getCpuPercList()[this.cpuIndex].getNice(); return sigar.getCpuPercList()[this.cpuIndex].getNice();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time of the CPU used by the system, as a fraction of 1 * @return The time of the CPU used by the system, as a fraction of 1
*/ */
public double getSys() { public double getSys() {
try { try {
return sigar.getCpuPercList()[this.cpuIndex].getSys(); return sigar.getCpuPercList()[this.cpuIndex].getSys();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time of the CPU used by user processes, as a fraction of 1 * @return The time of the CPU used by user processes, as a fraction of 1
*/ */
public double getUser() { public double getUser() {
try { try {
return sigar.getCpuPercList()[this.cpuIndex].getUser(); return sigar.getCpuPercList()[this.cpuIndex].getUser();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The time the CPU had to wait for data to be loaded, as a fraction of 1 * @return The time the CPU had to wait for data to be loaded, as a fraction of 1
*/ */
public double getWait() { public double getWait() {
try { try {
return sigar.getCpuPercList()[this.cpuIndex].getWait(); return sigar.getCpuPercList()[this.cpuIndex].getWait();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
// ------- // -------
// Implementation of the DynamicMBean interface // Implementation of the DynamicMBean interface
// ------- // -------
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#getAttribute(String) * @see DynamicMBean#getAttribute(String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException { public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_COMBINED.getName().equals(attr)) { if (MBEAN_ATTR_COMBINED.getName().equals(attr)) {
return new Double(getCombined()); return new Double(getCombined());
} else if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) { } else if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) {
return new Integer(getCpuIndex()); return new Integer(getCpuIndex());
} else if (MBEAN_ATTR_IDLE.getName().equals(attr)) { } else if (MBEAN_ATTR_IDLE.getName().equals(attr)) {
return new Double(getIdle()); return new Double(getIdle());
} else if (MBEAN_ATTR_NICE.getName().equals(attr)) { } else if (MBEAN_ATTR_NICE.getName().equals(attr)) {
return new Double(getNice()); return new Double(getNice());
} else if (MBEAN_ATTR_SYS.getName().equals(attr)) { } else if (MBEAN_ATTR_SYS.getName().equals(attr)) {
return new Double(getSys()); return new Double(getSys());
} else if (MBEAN_ATTR_USER.getName().equals(attr)) { } else if (MBEAN_ATTR_USER.getName().equals(attr)) {
return new Double(getUser()); return new Double(getUser());
} else if (MBEAN_ATTR_WAIT.getName().equals(attr)) { } else if (MBEAN_ATTR_WAIT.getName().equals(attr)) {
return new Double(getWait()); return new Double(getWait());
} else { } else {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#setAttribute(Attribute) * @see DynamicMBean#setAttribute(Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#invoke(String, Object[], String[]) * @see DynamicMBean#invoke(String, Object[], String[])
*/ */
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException { throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName), throw new ReflectionException(new NoSuchMethodException(actionName),
actionName); actionName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see DynamicMBean#getMBeanInfo() * @see DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
} }
@@ -1,263 +1,263 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; import javax.management.MBeanParameterInfo;
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.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
/** /**
* Sigar JMX MBean implementation for the <code>LoadAverage</code> information * Sigar JMX MBean implementation for the <code>LoadAverage</code> information
* package. Provides an OpenMBean conform implementation. * package. Provides an OpenMBean conform implementation.
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarLoadAverage extends AbstractMBean { public class SigarLoadAverage extends AbstractMBean {
private static final String MBEAN_TYPE = "LoadAverage"; private static final String MBEAN_TYPE = "LoadAverage";
/** /**
* Returned if {@link Sigar#getLoadAverage()}} is detected to be not * Returned if {@link Sigar#getLoadAverage()}} is detected to be not
* implemented on the platform. * implemented on the platform.
* *
* @see #notImplemented * @see #notImplemented
*/ */
private static final double NOT_IMPLEMENTED_LOAD_VALUE = -1.0d; private static final double NOT_IMPLEMENTED_LOAD_VALUE = -1.0d;
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST1MIN; private static final MBeanAttributeInfo MBEAN_ATTR_LAST1MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST5MIN; private static final MBeanAttributeInfo MBEAN_ATTR_LAST5MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST15MIN; private static final MBeanAttributeInfo MBEAN_ATTR_LAST15MIN;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR; private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR; private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static { static {
MBEAN_ATTR_LAST1MIN = new MBeanAttributeInfo( MBEAN_ATTR_LAST1MIN = new MBeanAttributeInfo(
"LastMinute", "LastMinute",
"double", "double",
"The load average in the last minute, as a fraction of 1, or " "The load average in the last minute, as a fraction of 1, or "
+ "-1.0 if the load cannot be determined on this platform", + "-1.0 if the load cannot be determined on this platform",
true, false, false); true, false, false);
MBEAN_ATTR_LAST5MIN = new MBeanAttributeInfo( MBEAN_ATTR_LAST5MIN = new MBeanAttributeInfo(
"LastFiveMinutes", "LastFiveMinutes",
"double", "double",
"The load average over the last five minutes, as a fraction " "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", + "of 1, or -1.0 if the load cannot be determined on this platform",
true, false, false); true, false, false);
MBEAN_ATTR_LAST15MIN = new MBeanAttributeInfo( MBEAN_ATTR_LAST15MIN = new MBeanAttributeInfo(
"Last15Minutes", "Last15Minutes",
"double", "double",
"The load average over the last 15 minutes, as a fraction of " "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", + "1, or -1.0 if the load cannot be determined on this platform",
true, false, false); true, false, false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from"); .getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo( MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(
SigarLoadAverage.class.getName(), SigarLoadAverage.class.getName(),
"Creates a new instance, using the Sigar instance specified " "Creates a new instance, using the Sigar instance specified "
+ "to fetch the data. Fails if the CPU index is out of range.", + "to fetch the data. Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR }); new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarLoadAverage.class.getName(), SigarLoadAverage.class.getName(),
"Sigar load average MBean. Provides load averages of the " "Sigar load average MBean. Provides load averages of the "
+ "system over the last one, five and 15 minutes. Due to the " + "system over the last one, five and 15 minutes. Due to the "
+ "long term character of that information, the fetch is done " + "long term character of that information, the fetch is done "
+ "using a Sigar proxy cache with a timeout of 30 seconds.", + "using a Sigar proxy cache with a timeout of 30 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_LAST1MIN, new MBeanAttributeInfo[] { MBEAN_ATTR_LAST1MIN,
MBEAN_ATTR_LAST5MIN, MBEAN_ATTR_LAST15MIN }, MBEAN_ATTR_LAST5MIN, MBEAN_ATTR_LAST15MIN },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null); new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
private final String objectName; private final String objectName;
/** /**
* <p>Set <code>true</code> when the load average fetch failed with a * <p>Set <code>true</code> when the load average fetch failed with a
* <code>SigarException</code> that indicates the method is not implemented. * <code>SigarException</code> that indicates the method is not implemented.
* Any subsequent call to this instance will then be answered with * Any subsequent call to this instance will then be answered with
* {@link #NOT_IMPLEMENTED_LOAD_VALUE}. * {@link #NOT_IMPLEMENTED_LOAD_VALUE}.
* </p> * </p>
* *
* <p><b>FIXME</b> : This is a workaround and should be replaced by something * <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 * 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 substring being present within the exception. A proposal was made at
* <a href="http://jira.hyperic.com/browse/SIGAR-52">issue SIGAR-52</a>. * <a href="http://jira.hyperic.com/browse/SIGAR-52">issue SIGAR-52</a>.
* </p> * </p>
*/ */
private boolean notImplemented; private boolean notImplemented;
/** /**
* Creates a new instance, using a new Sigar instance to fetch the data. * Creates a new instance, using a new Sigar instance to fetch the data.
* *
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If an unexpected Sigar error occurs. * If an unexpected Sigar error occurs.
*/ */
public SigarLoadAverage() throws IllegalArgumentException { public SigarLoadAverage() throws IllegalArgumentException {
this(new Sigar()); this(new Sigar());
} }
/** /**
* Creates a new instance, using the Sigar instance specified to fetch the * Creates a new instance, using the Sigar instance specified to fetch the
* data. * data.
* *
* @param sigar * @param sigar
* The Sigar instance to use to fetch data from * The Sigar instance to use to fetch data from
* *
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If an unexpected Sigar error occurs * If an unexpected Sigar error occurs
*/ */
public SigarLoadAverage(Sigar sigar) throws IllegalArgumentException { public SigarLoadAverage(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_30SEC); super(sigar, CACHED_30SEC);
// all fine // all fine
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE; + "=" + MBEAN_TYPE;
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/** /**
* @return The load average in the last minute, as a fraction of 1, or * @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 * <code>-1.0d</code> if the load cannot be determined on this platform
*/ */
public double getLastMinute() { public double getLastMinute() {
try { try {
return sigarImpl.getLoadAverage()[0]; return sigarImpl.getLoadAverage()[0];
} catch (SigarNotImplementedException e) { } catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE; return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The load average over the last five minutes, as a fraction of 1, * @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 * or <code>-1.0d</code> if the load cannot be determined on this
* platform * platform
*/ */
public double getLastFiveMinutes() { public double getLastFiveMinutes() {
try { try {
return sigarImpl.getLoadAverage()[1]; return sigarImpl.getLoadAverage()[1];
} catch (SigarNotImplementedException e) { } catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE; return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The load average over the last 15 minutes, as a fraction of 1, or * @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 * <code>-1.0d</code> if the load cannot be determined on this platform
*/ */
public double getLast15Minutes() { public double getLast15Minutes() {
try { try {
return sigarImpl.getLoadAverage()[2]; return sigarImpl.getLoadAverage()[2];
} catch (SigarNotImplementedException e) { } catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE; return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
// ------- // -------
// Implementation of the DynamicMBean interface // Implementation of the DynamicMBean interface
// ------- // -------
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#getAttribute(String) * @see DynamicMBean#getAttribute(String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException { public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_LAST1MIN.getName().equals(attr)) { if (MBEAN_ATTR_LAST1MIN.getName().equals(attr)) {
return new Double(getLastMinute()); return new Double(getLastMinute());
} else if (MBEAN_ATTR_LAST5MIN.getName().equals(attr)) { } else if (MBEAN_ATTR_LAST5MIN.getName().equals(attr)) {
return new Double(getLastFiveMinutes()); return new Double(getLastFiveMinutes());
} else if (MBEAN_ATTR_LAST15MIN.getName().equals(attr)) { } else if (MBEAN_ATTR_LAST15MIN.getName().equals(attr)) {
return new Double(getLast15Minutes()); return new Double(getLast15Minutes());
} else { } else {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#setAttribute(Attribute) * @see DynamicMBean#setAttribute(Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#invoke(String, Object[], String[]) * @see DynamicMBean#invoke(String, Object[], String[])
*/ */
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException { throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName), throw new ReflectionException(new NoSuchMethodException(actionName),
actionName); actionName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see DynamicMBean#getMBeanInfo() * @see DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
} }
@@ -1,251 +1,251 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; import javax.management.MBeanParameterInfo;
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;
/** /**
* Sigar JMX MBean implementation for the <code>Mem</code> information * Sigar JMX MBean implementation for the <code>Mem</code> information
* package. Provides an OpenMBean conform implementation. * package. Provides an OpenMBean conform implementation.
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarMem extends AbstractMBean { public class SigarMem extends AbstractMBean {
private static final String MBEAN_TYPE = "Mem"; private static final String MBEAN_TYPE = "Mem";
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_ACTUAL_FREE; private static final MBeanAttributeInfo MBEAN_ATTR_ACTUAL_FREE;
private static final MBeanAttributeInfo MBEAN_ATTR_ACTUAL_USED; private static final MBeanAttributeInfo MBEAN_ATTR_ACTUAL_USED;
private static final MBeanAttributeInfo MBEAN_ATTR_FREE; private static final MBeanAttributeInfo MBEAN_ATTR_FREE;
private static final MBeanAttributeInfo MBEAN_ATTR_RAM; private static final MBeanAttributeInfo MBEAN_ATTR_RAM;
private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL; private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL;
private static final MBeanAttributeInfo MBEAN_ATTR_USED; private static final MBeanAttributeInfo MBEAN_ATTR_USED;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR; private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR; private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static { static {
MBEAN_ATTR_ACTUAL_FREE = new MBeanAttributeInfo("ActualFree", "long", MBEAN_ATTR_ACTUAL_FREE = new MBeanAttributeInfo("ActualFree", "long",
"TODO add proper description here", true, false, false); "TODO add proper description here", true, false, false);
MBEAN_ATTR_ACTUAL_USED = new MBeanAttributeInfo("ActualUsed", "long", MBEAN_ATTR_ACTUAL_USED = new MBeanAttributeInfo("ActualUsed", "long",
"TODO add proper description here", true, false, false); "TODO add proper description here", true, false, false);
MBEAN_ATTR_FREE = new MBeanAttributeInfo("Free", "long", MBEAN_ATTR_FREE = new MBeanAttributeInfo("Free", "long",
"TODO add proper description here", true, false, false); "TODO add proper description here", true, false, false);
MBEAN_ATTR_RAM = new MBeanAttributeInfo("Ram", "long", MBEAN_ATTR_RAM = new MBeanAttributeInfo("Ram", "long",
"TODO add proper description here", true, false, false); "TODO add proper description here", true, false, false);
MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long", MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long",
"TODO add proper description here", true, false, false); "TODO add proper description here", true, false, false);
MBEAN_ATTR_USED = new MBeanAttributeInfo("Used", "long", MBEAN_ATTR_USED = new MBeanAttributeInfo("Used", "long",
"TODO add proper description here", true, false, false); "TODO add proper description here", true, false, false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from"); .getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(SigarMem.class.getName(), MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(SigarMem.class.getName(),
"Creates a new instance, using the Sigar instance " "Creates a new instance, using the Sigar instance "
+ "specified to fetch the data.", + "specified to fetch the data.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR }); new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarMem.class.getName(), SigarMem.class.getName(),
"Sigar Memory MBean, provides raw data for the physical " "Sigar Memory MBean, provides raw data for the physical "
+ "memory installed on the system. Uses an internal cache " + "memory installed on the system. Uses an internal cache "
+ "that invalidates within 500ms, allowing for bulk request " + "that invalidates within 500ms, allowing for bulk request "
+ "being satisfied with a single dataset fetch.", + "being satisfied with a single dataset fetch.",
new MBeanAttributeInfo[] { MBEAN_ATTR_ACTUAL_FREE, new MBeanAttributeInfo[] { MBEAN_ATTR_ACTUAL_FREE,
MBEAN_ATTR_ACTUAL_USED, MBEAN_ATTR_FREE, MBEAN_ATTR_ACTUAL_USED, MBEAN_ATTR_FREE,
MBEAN_ATTR_RAM, MBEAN_ATTR_TOTAL, MBEAN_ATTR_USED }, MBEAN_ATTR_RAM, MBEAN_ATTR_TOTAL, MBEAN_ATTR_USED },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null); new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
private final String objectName; private final String objectName;
/** /**
* Creates a new instance, using the Sigar instance specified to fetch the * Creates a new instance, using the Sigar instance specified to fetch the
* data. * data.
* *
* @param sigar * @param sigar
* The Sigar instance to use to fetch data from * The Sigar instance to use to fetch data from
* *
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If an unexpected Sigar error occurs * If an unexpected Sigar error occurs
*/ */
public SigarMem(Sigar sigar) throws IllegalArgumentException { public SigarMem(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_500MS); super(sigar, CACHED_500MS);
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=Memory"; + "=Memory";
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/** /**
* @return The actual amount of free physical memory, in [bytes] * @return The actual amount of free physical memory, in [bytes]
*/ */
public long getActualFree() { public long getActualFree() {
try { try {
return sigar.getMem().getActualFree(); return sigar.getMem().getActualFree();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The actual amount of physical memory used, in [bytes] * @return The actual amount of physical memory used, in [bytes]
*/ */
public long getActualUsed() { public long getActualUsed() {
try { try {
return sigar.getMem().getActualUsed(); return sigar.getMem().getActualUsed();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The amount of free physical memory, in [bytes] * @return The amount of free physical memory, in [bytes]
*/ */
public long getFree() { public long getFree() {
try { try {
return sigar.getMem().getFree(); return sigar.getMem().getFree();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The amount of physical memory, in [bytes] * @return The amount of physical memory, in [bytes]
*/ */
public long getRam() { public long getRam() {
try { try {
return sigar.getMem().getRam(); return sigar.getMem().getRam();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The total amount of physical memory, in [bytes] * @return The total amount of physical memory, in [bytes]
*/ */
public long getTotal() { public long getTotal() {
try { try {
return sigar.getMem().getTotal(); return sigar.getMem().getTotal();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The amount of physical memory in use, in [bytes] * @return The amount of physical memory in use, in [bytes]
*/ */
public long getUsed() { public long getUsed() {
try { try {
return sigar.getMem().getUsed(); return sigar.getMem().getUsed();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
// ------- // -------
// Implementation of the DynamicMBean interface // Implementation of the DynamicMBean interface
// ------- // -------
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see javax.management.DynamicMBean#getAttribute(java.lang.String) * @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException, public Object getAttribute(String attr) throws AttributeNotFoundException,
MBeanException, ReflectionException { MBeanException, ReflectionException {
if (MBEAN_ATTR_ACTUAL_FREE.getName().equals(attr)) { if (MBEAN_ATTR_ACTUAL_FREE.getName().equals(attr)) {
return new Long(getActualFree()); return new Long(getActualFree());
} else if (MBEAN_ATTR_ACTUAL_USED.getName().equals(attr)) { } else if (MBEAN_ATTR_ACTUAL_USED.getName().equals(attr)) {
return new Long(getActualUsed()); return new Long(getActualUsed());
} else if (MBEAN_ATTR_FREE.getName().equals(attr)) { } else if (MBEAN_ATTR_FREE.getName().equals(attr)) {
return new Long(getFree()); return new Long(getFree());
} else if (MBEAN_ATTR_RAM.getName().equals(attr)) { } else if (MBEAN_ATTR_RAM.getName().equals(attr)) {
return new Long(getRam()); return new Long(getRam());
} else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) { } else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) {
return new Long(getTotal()); return new Long(getTotal());
} else if (MBEAN_ATTR_USED.getName().equals(attr)) { } else if (MBEAN_ATTR_USED.getName().equals(attr)) {
return new Long(getUsed()); return new Long(getUsed());
} else { } else {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute) * @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String, * @see javax.management.DynamicMBean#invoke(java.lang.String,
* java.lang.Object[], java.lang.String[]) * java.lang.Object[], java.lang.String[])
*/ */
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException { throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName), throw new ReflectionException(new NoSuchMethodException(actionName),
actionName); actionName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo() * @see javax.management.DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
} }
@@ -1,342 +1,342 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import java.util.ArrayList; import java.util.ArrayList;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; 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;
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;
/** /**
* <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
* Sigar MBeans at a central point. This brings a bunch of advantages with * Sigar MBeans at a central point. This brings a bunch of advantages with
* it:</p> * it:</p>
* *
* <ul> * <ul>
* <li>This class can be instantiated and registered to the MBean server by * <li>This class can be instantiated and registered to the MBean server by
* simply calling {@link MBeanServer#createMBean(String, ObjectName)}, * simply calling {@link MBeanServer#createMBean(String, ObjectName)},
* resulting in the automatic creation of all known default Sigar MBeans such * resulting in the automatic creation of all known default Sigar MBeans such
* as CPU and memory monitoring beans.</li> * as CPU and memory monitoring beans.</li>
* <li>Any Sigar MBean spawned by an instance of this class will use the same * <li>Any Sigar MBean spawned by an instance of this class will use the same
* {@link org.hyperic.sigar.Sigar} instance, saving resources in the * {@link org.hyperic.sigar.Sigar} instance, saving resources in the
* process.</li> * process.</li>
* <li>When this instance is deregistered from the MBean server, it will * <li>When this instance is deregistered from the MBean server, it will
* automatically deregister all instances it created, cleaning up behind * automatically deregister all instances it created, cleaning up behind
* itself.</li> * itself.</li>
* </ul> * </ul>
* *
* <p>So using this class to manage the Sigar MBeans requires one line of code * <p>So using this class to manage the Sigar MBeans requires one line of code
* for creation, registration and MBean spawning, and one line of code to shut * for creation, registration and MBean spawning, and one line of code to shut
* it all down again.</p> * it all down again.</p>
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarRegistry extends AbstractMBean { public class SigarRegistry extends AbstractMBean {
private static final String MBEAN_TYPE = "SigarRegistry"; private static final String MBEAN_TYPE = "SigarRegistry";
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT; private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT;
// private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES; // private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES;
static { static {
MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo( MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo(
SigarRegistry.class.getName(), SigarRegistry.class.getName(),
"Creates a new instance of this class. Will create the Sigar " "Creates a new instance of this class. Will create the Sigar "
+ "instance this class uses when constructing other MBeans", + "instance this class uses when constructing other MBeans",
new MBeanParameterInfo[0]); new MBeanParameterInfo[0]);
// MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses", // MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses",
// "Executes a query returning the process IDs of all processes " + // "Executes a query returning the process IDs of all processes " +
// "found on the system.", // "found on the system.",
// null /* new MBeanParameterInfo[0] */, // null /* new MBeanParameterInfo[0] */,
// String.class.getName(), MBeanOperationInfo.INFO); // String.class.getName(), MBeanOperationInfo.INFO);
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarRegistry.class.getName(), SigarRegistry.class.getName(),
"Sigar MBean registry. Provides a central point for creation " "Sigar MBean registry. Provides a central point for creation "
+ "and destruction of Sigar MBeans. Any Sigar MBean created via " + "and destruction of Sigar MBeans. Any Sigar MBean created via "
+ "this instance will automatically be cleaned up when this " + "this instance will automatically be cleaned up when this "
+ "instance is deregistered from the MBean server.", + "instance is deregistered from the MBean server.",
null /*new MBeanAttributeInfo[0]*/, null /*new MBeanAttributeInfo[0]*/,
new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT }, new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT },
null /*new MBeanOperationInfo[0] */, null /*new MBeanOperationInfo[0] */,
null /*new MBeanNotificationInfo[0]*/); null /*new MBeanNotificationInfo[0]*/);
} }
private final String objectName; private final String objectName;
private final ArrayList managedBeans; private final ArrayList managedBeans;
/** /**
* Creates a new instance of this class. Will create the Sigar instance this * Creates a new instance of this class. Will create the Sigar instance this
* class uses when constructing other MBeans. * class uses when constructing other MBeans.
*/ */
public SigarRegistry() { public SigarRegistry() {
super(new Sigar(), CACHELESS); super(new Sigar(), CACHELESS);
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE; + "=" + MBEAN_TYPE;
this.managedBeans = new ArrayList(); this.managedBeans = new ArrayList();
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see AbstractMBean#getObjectName() * @see AbstractMBean#getObjectName()
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/* public String listProcesses() { /* public String listProcesses() {
try { try {
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
long[] ids = sigar.getProcList(); long[] ids = sigar.getProcList();
StringBuffer procNames = new StringBuffer(); StringBuffer procNames = new StringBuffer();
for (int i = 0; i < ids.length; i++) { for (int i = 0; i < ids.length; i++) {
try { try {
procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n'); procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n');
} catch (SigarException e) { } catch (SigarException e) {
procNames.append(ids[i] + ":" + e.getMessage()).append('\n'); procNames.append(ids[i] + ":" + e.getMessage()).append('\n');
} }
} }
final long end = System.currentTimeMillis(); final long end = System.currentTimeMillis();
procNames.append("-- Took " + (end-start) + "ms"); procNames.append("-- Took " + (end-start) + "ms");
return procNames.toString(); return procNames.toString();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("ProcList", e); throw unexpectedError("ProcList", e);
} }
} }
*/ */
/* (non-Javadoc) /* (non-Javadoc)
* @see javax.management.DynamicMBean#getAttribute(java.lang.String) * @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException { public Object getAttribute(String attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute) * @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String, java.lang.Object[], java.lang.String[]) * @see javax.management.DynamicMBean#invoke(java.lang.String, java.lang.Object[], java.lang.String[])
*/ */
public Object invoke(String action, Object[] params, String[] signatures) public Object invoke(String action, Object[] params, String[] signatures)
throws MBeanException, ReflectionException { throws MBeanException, ReflectionException {
/* if (MBEAN_OPER_LISTPROCESSES.getName().equals(action)) /* if (MBEAN_OPER_LISTPROCESSES.getName().equals(action))
return listProcesses(); return listProcesses();
else */ else */
throw new ReflectionException(new NoSuchMethodException(action), action); throw new ReflectionException(new NoSuchMethodException(action), action);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo() * @see javax.management.DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
// ------- // -------
// Implementation of the MBeanRegistration interface // Implementation of the MBeanRegistration interface
// ------- // -------
/** /**
* Registers the default set of Sigar MBeans. Before doing so, a super call * Registers the default set of Sigar MBeans. Before doing so, a super call
* is made to satisfy {@link AbstractMBean}. * is made to satisfy {@link AbstractMBean}.
* *
* @see AbstractMBean#postRegister(Boolean) * @see AbstractMBean#postRegister(Boolean)
*/ */
public void postRegister(Boolean success) { public void postRegister(Boolean success) {
super.postRegister(success); super.postRegister(success);
if (!success.booleanValue()) if (!success.booleanValue())
return; return;
// get CPUs // get CPUs
registerCpuBeans(); registerCpuBeans();
// get memory // get memory
registerMemoryBeans(); registerMemoryBeans();
// get system // get system
registerSystemBeans(); registerSystemBeans();
} }
/** /**
* Registers MBeans for the Sigar types <code>Cpu</code>, <code>CpuPerc</code> * Registers MBeans for the Sigar types <code>Cpu</code>, <code>CpuPerc</code>
* and <code>CpuInfo</code>. One instance will be registered for each CPU * and <code>CpuInfo</code>. One instance will be registered for each CPU
* (core?) found. * (core?) found.
*/ */
private void registerCpuBeans() { private void registerCpuBeans() {
ObjectInstance nextRegistered = null; ObjectInstance nextRegistered = null;
try { try {
final int cpuCount = sigar.getCpuInfoList().length; final int cpuCount = sigar.getCpuInfoList().length;
for (int i = 0; i < cpuCount; i++) { for (int i = 0; i < cpuCount; i++) {
// add CPU bean // add CPU bean
SigarCpu nextCpu = new SigarCpu(sigarImpl, i); SigarCpu nextCpu = new SigarCpu(sigarImpl, i);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(nextCpu if (!mbeanServer.isRegistered(new ObjectName(nextCpu
.getObjectName()))) .getObjectName())))
nextRegistered = mbeanServer.registerMBean(nextCpu, nextRegistered = mbeanServer.registerMBean(nextCpu,
null); null);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
} }
// add MBean to set of managed beans // add MBean to set of managed beans
if (nextRegistered != null) if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName()); managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null; nextRegistered = null;
// add CPU percentage bean // add CPU percentage bean
SigarCpuPerc nextCpuPerc = new SigarCpuPerc(sigarImpl, i); SigarCpuPerc nextCpuPerc = new SigarCpuPerc(sigarImpl, i);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(nextCpuPerc if (!mbeanServer.isRegistered(new ObjectName(nextCpuPerc
.getObjectName()))) .getObjectName())))
nextRegistered = mbeanServer.registerMBean(nextCpuPerc, nextRegistered = mbeanServer.registerMBean(nextCpuPerc,
null); null);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
} }
// add MBean to set of managed beans // add MBean to set of managed beans
if (nextRegistered != null) if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName()); managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null; nextRegistered = null;
// add CPU info bean // add CPU info bean
SigarCpuInfo nextCpuInfo = new SigarCpuInfo(sigarImpl, i); SigarCpuInfo nextCpuInfo = new SigarCpuInfo(sigarImpl, i);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(nextCpuInfo if (!mbeanServer.isRegistered(new ObjectName(nextCpuInfo
.getObjectName()))) .getObjectName())))
nextRegistered = mbeanServer.registerMBean(nextCpuInfo, nextRegistered = mbeanServer.registerMBean(nextCpuInfo,
null); null);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
} }
// add MBean to set of managed beans // add MBean to set of managed beans
if (nextRegistered != null) if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName()); managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null; nextRegistered = null;
} }
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("CpuInfoList", e); throw unexpectedError("CpuInfoList", e);
} }
} }
/** /**
* Registers MBeans for the Sigar types <code>Mem</code> and <code>Swap</code>. * Registers MBeans for the Sigar types <code>Mem</code> and <code>Swap</code>.
*/ */
private void registerMemoryBeans() { private void registerMemoryBeans() {
ObjectInstance nextRegistered = null; ObjectInstance nextRegistered = null;
// add physical memory bean // add physical memory bean
SigarMem mem = new SigarMem(sigarImpl); SigarMem mem = new SigarMem(sigarImpl);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(mem.getObjectName()))) if (!mbeanServer.isRegistered(new ObjectName(mem.getObjectName())))
nextRegistered = mbeanServer.registerMBean(mem, null); nextRegistered = mbeanServer.registerMBean(mem, null);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
} }
// add MBean to set of managed beans // add MBean to set of managed beans
if (nextRegistered != null) if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName()); managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null; nextRegistered = null;
// add swap memory bean // add swap memory bean
SigarSwap swap = new SigarSwap(sigarImpl); SigarSwap swap = new SigarSwap(sigarImpl);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(swap.getObjectName()))) if (!mbeanServer.isRegistered(new ObjectName(swap.getObjectName())))
nextRegistered = mbeanServer.registerMBean(swap, null); nextRegistered = mbeanServer.registerMBean(swap, null);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
nextRegistered = null; nextRegistered = null;
} }
// add MBean to set of managed beans // add MBean to set of managed beans
if (nextRegistered != null) if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName()); managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null; nextRegistered = null;
} }
/** /**
* Registers MBeans for the Sigar types <code>LoadAverage</code>... * Registers MBeans for the Sigar types <code>LoadAverage</code>...
*/ */
private void registerSystemBeans() { private void registerSystemBeans() {
ObjectInstance nextRegistered = null; ObjectInstance nextRegistered = null;
// add load average bean // add load average bean
SigarLoadAverage loadAvg = new SigarLoadAverage(sigarImpl); SigarLoadAverage loadAvg = new SigarLoadAverage(sigarImpl);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(loadAvg if (!mbeanServer.isRegistered(new ObjectName(loadAvg
.getObjectName()))) .getObjectName())))
nextRegistered = mbeanServer.registerMBean(loadAvg, null); nextRegistered = mbeanServer.registerMBean(loadAvg, null);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
} }
// add MBean to set of managed beans // add MBean to set of managed beans
if (nextRegistered != null) if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName()); managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null; nextRegistered = null;
} }
/** /**
* 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. After doing so, a super call is made to satisfy {@link AbstractMBean}.
* @throws Exception * @throws Exception
* *
* @see AbstractMBean#preDeregister() * @see AbstractMBean#preDeregister()
*/ */
public void preDeregister() throws Exception { public void preDeregister() throws Exception {
// count backwards to remove ONs immediately // count backwards to remove ONs immediately
for (int i = managedBeans.size() - 1; i >= 0; i--) { for (int i = managedBeans.size() - 1; i >= 0; i--) {
ObjectName next = (ObjectName) managedBeans.remove(i); ObjectName next = (ObjectName) managedBeans.remove(i);
if (mbeanServer.isRegistered(next)) { if (mbeanServer.isRegistered(next)) {
try { try {
mbeanServer.unregisterMBean(next); mbeanServer.unregisterMBean(next);
} catch (Exception e) { // ignore } catch (Exception e) { // ignore
} }
} }
} }
// do the super call // do the super call
super.preDeregister(); super.preDeregister();
} }
} }
@@ -1,199 +1,199 @@
/* /*
* Copyright (C) [2004, 2005, 2006, 2007], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006, 2007], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute; import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo; import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo; import javax.management.MBeanParameterInfo;
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;
/** /**
* Sigar JMX MBean implementation for the <code>Swap</code> information * Sigar JMX MBean implementation for the <code>Swap</code> information
* package. Provides an OpenMBean conform implementation. * package. Provides an OpenMBean conform implementation.
* *
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarSwap extends AbstractMBean { public class SigarSwap extends AbstractMBean {
private static final String MBEAN_TYPE = "Swap"; private static final String MBEAN_TYPE = "Swap";
private static final MBeanInfo MBEAN_INFO; private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_FREE; private static final MBeanAttributeInfo MBEAN_ATTR_FREE;
private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL; private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL;
private static final MBeanAttributeInfo MBEAN_ATTR_USED; private static final MBeanAttributeInfo MBEAN_ATTR_USED;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR; private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR; private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static { static {
MBEAN_ATTR_FREE = new MBeanAttributeInfo("Free", "long", MBEAN_ATTR_FREE = new MBeanAttributeInfo("Free", "long",
"The amount of free swap memory, in [bytes]", true, false, "The amount of free swap memory, in [bytes]", true, false,
false); false);
MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long", MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long",
"The total amount of swap memory, in [bytes]", true, false, "The total amount of swap memory, in [bytes]", true, false,
false); false);
MBEAN_ATTR_USED = new MBeanAttributeInfo("Used", "long", MBEAN_ATTR_USED = new MBeanAttributeInfo("Used", "long",
"The amount of swap memory in use, in [bytes]", true, false, "The amount of swap memory in use, in [bytes]", true, false,
false); false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from"); .getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo( MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(
SigarSwap.class.getName(), SigarSwap.class.getName(),
"Creates a new instance, using the Sigar instance " "Creates a new instance, using the Sigar instance "
+ "specified to fetch the data.", + "specified to fetch the data.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR }); new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo( MBEAN_INFO = new MBeanInfo(
SigarSwap.class.getName(), SigarSwap.class.getName(),
"Sigar Swap MBean, provides raw data for the swap memory " "Sigar Swap MBean, provides raw data for the swap memory "
+ "configured on the system. Uses an internal cache that " + "configured on the system. Uses an internal cache that "
+ "invalidates within 5 seconds.", + "invalidates within 5 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_FREE, MBEAN_ATTR_TOTAL, new MBeanAttributeInfo[] { MBEAN_ATTR_FREE, MBEAN_ATTR_TOTAL,
MBEAN_ATTR_USED }, MBEAN_ATTR_USED },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null); new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
private final String objectName; private final String objectName;
/** /**
* Creates a new instance, using the Sigar instance specified to fetch the * Creates a new instance, using the Sigar instance specified to fetch the
* data. * data.
* *
* @param sigar * @param sigar
* The Sigar instance to use to fetch data from * The Sigar instance to use to fetch data from
* *
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If an unexpected Sigar error occurs * If an unexpected Sigar error occurs
*/ */
public SigarSwap(Sigar sigar) throws IllegalArgumentException { public SigarSwap(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_5SEC); super(sigar, CACHED_5SEC);
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=Swap"; + "=Swap";
} }
/** /**
* Object name this instance will give itself when being registered to an * Object name this instance will give itself when being registered to an
* MBeanServer. * MBeanServer.
*/ */
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/** /**
* @return The amount of free swap memory, in [bytes] * @return The amount of free swap memory, in [bytes]
*/ */
public long getFree() { public long getFree() {
try { try {
return sigar.getSwap().getFree(); return sigar.getSwap().getFree();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The total amount of swap memory, in [bytes] * @return The total amount of swap memory, in [bytes]
*/ */
public long getTotal() { public long getTotal() {
try { try {
return sigar.getSwap().getTotal(); return sigar.getSwap().getTotal();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/** /**
* @return The amount of swap memory in use, in [bytes] * @return The amount of swap memory in use, in [bytes]
*/ */
public long getUsed() { public long getUsed() {
try { try {
return sigar.getSwap().getUsed(); return sigar.getSwap().getUsed();
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
// ------- // -------
// Implementation of the DynamicMBean interface // Implementation of the DynamicMBean interface
// ------- // -------
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see javax.management.DynamicMBean#getAttribute(java.lang.String) * @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/ */
public Object getAttribute(String attr) throws AttributeNotFoundException, public Object getAttribute(String attr) throws AttributeNotFoundException,
MBeanException, ReflectionException { MBeanException, ReflectionException {
if (MBEAN_ATTR_FREE.getName().equals(attr)) { if (MBEAN_ATTR_FREE.getName().equals(attr)) {
return new Long(getFree()); return new Long(getFree());
} else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) { } else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) {
return new Long(getTotal()); return new Long(getTotal());
} else if (MBEAN_ATTR_USED.getName().equals(attr)) { } else if (MBEAN_ATTR_USED.getName().equals(attr)) {
return new Long(getUsed()); return new Long(getUsed());
} else { } else {
throw new AttributeNotFoundException(attr); throw new AttributeNotFoundException(attr);
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute) * @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException { public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName()); throw new AttributeNotFoundException(attr.getName());
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String, * @see javax.management.DynamicMBean#invoke(java.lang.String,
* java.lang.Object[], java.lang.String[]) * java.lang.Object[], java.lang.String[])
*/ */
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException { throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName), throw new ReflectionException(new NoSuchMethodException(actionName),
actionName); actionName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo() * @see javax.management.DynamicMBean#getMBeanInfo()
*/ */
public MBeanInfo getMBeanInfo() { public MBeanInfo getMBeanInfo() {
return MBEAN_INFO; return MBEAN_INFO;
} }
} }
@@ -157,9 +157,16 @@ public class TestPTQL extends SigarTestCase {
assertTrue(THIS_PROCESS, assertTrue(THIS_PROCESS,
runQuery(sigar, THIS_PROCESS) == 1); runQuery(sigar, THIS_PROCESS) == 1);
assertTrue(JAVA_PROCESS + " vs. " + OTHER_JAVA_PROCESS, int numProcs = runQuery(sigar, JAVA_PROCESS);
runQuery(sigar, JAVA_PROCESS) != int numOtherProcs = runQuery(sigar, OTHER_JAVA_PROCESS);
runQuery(sigar, OTHER_JAVA_PROCESS)); String msg =
JAVA_PROCESS +
" [" + numProcs + "] vs. [" + numOtherProcs + "] "+
OTHER_JAVA_PROCESS;
//process may have gone away in between runQuery's above.
//assertTrue(msg, numProcs != numOtherProcs);
traceln(msg);
for (int i=0; i<OK_QUERIES.length; i++) { for (int i=0; i<OK_QUERIES.length; i++) {
String qs = OK_QUERIES[i]; String qs = OK_QUERIES[i];
@@ -1,41 +1,41 @@
/* /*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.test; package org.hyperic.sigar.test;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
public class TestSignal extends SigarTestCase { public class TestSignal extends SigarTestCase {
public TestSignal(String name) { public TestSignal(String name) {
super(name); super(name);
} }
public void testCreate() throws Exception { public void testCreate() throws Exception {
String[] signals = { String[] signals = {
"HUP", "INT", "KILL", "QUIT", "HUP", "INT", "KILL", "QUIT",
"TERM", "USR1", "USR2" "TERM", "USR1", "USR2"
}; };
for (int i=0; i<signals.length; i++) { for (int i=0; i<signals.length; i++) {
String sig = signals[i]; String sig = signals[i];
traceln(sig + "=" + Sigar.getSigNum(sig)); traceln(sig + "=" + Sigar.getSigNum(sig));
} }
} }
} }
@@ -1,64 +1,64 @@
/* /*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * Copyright (C) [2004, 2005, 2006], 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
* it under the terms version 2 of the GNU General Public License as * it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed * published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more * PARTICULAR PURPOSE. See the GNU General Public License for more
* details. * details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA. * USA.
*/ */
package org.hyperic.sigar.win32.test; package org.hyperic.sigar.win32.test;
import java.io.File; import java.io.File;
import org.hyperic.sigar.test.SigarTestCase; import org.hyperic.sigar.test.SigarTestCase;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.ProcExe; import org.hyperic.sigar.ProcExe;
import org.hyperic.sigar.win32.Win32; import org.hyperic.sigar.win32.Win32;
import org.hyperic.sigar.win32.FileVersion; import org.hyperic.sigar.win32.FileVersion;
public class TestFileVersion extends SigarTestCase { public class TestFileVersion extends SigarTestCase {
public TestFileVersion(String name) { public TestFileVersion(String name) {
super(name); super(name);
} }
private void printExe(long pid) { private void printExe(long pid) {
traceln("\npid=" + pid); traceln("\npid=" + pid);
String name; String name;
try { try {
name = getSigar().getProcExe(pid).getName(); name = getSigar().getProcExe(pid).getName();
} catch (SigarException e) { } catch (SigarException e) {
return; return;
} }
FileVersion info = Win32.getFileVersion(name); FileVersion info = Win32.getFileVersion(name);
if (info != null) { if (info != null) {
traceln("exe='" + name + "'"); traceln("exe='" + name + "'");
traceln("version=" + info.getProductVersion()); traceln("version=" + info.getProductVersion());
} }
} }
public void testCreate() throws Exception { public void testCreate() throws Exception {
assertTrue(Win32.getFileVersion("DoEsNoTeXist.exe") == null); assertTrue(Win32.getFileVersion("DoEsNoTeXist.exe") == null);
long[] pids = getSigar().getProcList(); long[] pids = getSigar().getProcList();
//go through all just to make sure no crashes //go through all just to make sure no crashes
for (int i=0; i<pids.length; i++) { for (int i=0; i<pids.length; i++) {
printExe(pids[i]); printExe(pids[i]);
} }
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
copyright.year=2004-2008 copyright.year=2004-2009
version.major=1 version.major=1
version.minor=6 version.minor=6
version.maint=1 version.maint=2
version.build=0 version.build=0
+3 -2
View File
@@ -164,8 +164,9 @@ int sigar_os_open(sigar_t **sigar)
if (kmem > 0) { if (kmem > 0) {
if ((status = get_koffsets(*sigar)) != SIGAR_OK) { if ((status = get_koffsets(*sigar)) != SIGAR_OK) {
free(*sigar); /* libperfstat only mode (aix 6) */
return status; close((*sigar)->kmem);
(*sigar)->kmem = -1;
} }
} }
+162 -28
View File
@@ -252,7 +252,7 @@ int sigar_os_open(sigar_t **sigar)
(*sigar)->ncpu = ncpu; (*sigar)->ncpu = ncpu;
(*sigar)->lcpu = -1; (*sigar)->lcpu = -1;
(*sigar)->argmax = 0;
(*sigar)->boot_time = boottime.tv_sec; /* XXX seems off a bit */ (*sigar)->boot_time = boottime.tv_sec; /* XXX seems off a bit */
(*sigar)->pagesize = getpagesize(); (*sigar)->pagesize = getpagesize();
@@ -294,6 +294,25 @@ char *sigar_os_error_string(sigar_t *sigar, int err)
} }
} }
/* ARG_MAX in FreeBSD 6.0 == 262144, which blows up the stack */
#define SIGAR_ARG_MAX 65536
static size_t sigar_argmax_get(sigar_t *sigar)
{
#ifdef KERN_ARGMAX
int mib[] = { CTL_KERN, KERN_ARGMAX };
size_t size = sizeof(sigar->argmax);
if (sigar->argmax != 0) {
return sigar->argmax;
}
if (sysctl(mib, NMIB(mib), &sigar->argmax, &size, NULL, 0) == 0) {
return sigar->argmax;
}
#endif
return SIGAR_ARG_MAX;
}
#if defined(DARWIN) #if defined(DARWIN)
static int sigar_vmstat(sigar_t *sigar, vm_statistics_data_t *vmstat) static int sigar_vmstat(sigar_t *sigar, vm_statistics_data_t *vmstat)
{ {
@@ -536,16 +555,81 @@ static int getswapinfo_sysctl(struct kvm_swap *swap_ary,
#define getswapinfo_sysctl(swap_ary, swap_max) SIGAR_ENOTIMPL #define getswapinfo_sysctl(swap_ary, swap_max) SIGAR_ENOTIMPL
#endif #endif
int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) #define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1)
#ifdef DARWIN
#define VM_DIR "/private/var/vm"
#define SWAPFILE "swapfile"
static int sigar_swap_fs_get(sigar_t *sigar, sigar_swap_t *swap) /* <= 10.3 */
{ {
int status; DIR *dirp;
#if defined(DARWIN) struct dirent *ent;
char swapfile[SSTRLEN(VM_DIR) + SSTRLEN("/") + SSTRLEN(SWAPFILE) + 12];
struct stat swapstat;
struct statfs vmfs;
sigar_uint64_t val, bsize;
swap->used = swap->total = swap->free = 0;
if (!(dirp = opendir(VM_DIR))) {
return errno;
}
/* looking for "swapfile0", "swapfile1", etc. */
while ((ent = readdir(dirp))) {
char *ptr = swapfile;
if ((ent->d_namlen < SSTRLEN(SWAPFILE)+1) || /* n/a, see comment above */
(ent->d_namlen > SSTRLEN(SWAPFILE)+11)) /* ensure no overflow */
{
continue;
}
if (!strnEQ(ent->d_name, SWAPFILE, SSTRLEN(SWAPFILE))) {
continue;
}
/* sprintf(swapfile, "%s/%s", VM_DIR, ent->d_name) */
memcpy(ptr, VM_DIR, SSTRLEN(VM_DIR));
ptr += SSTRLEN(VM_DIR);
*ptr++ = '/';
memcpy(ptr, ent->d_name, ent->d_namlen+1);
if (stat(swapfile, &swapstat) < 0) {
continue;
}
swap->used += swapstat.st_size;
}
closedir(dirp);
if (statfs(VM_DIR, &vmfs) < 0) {
return errno;
}
bsize = vmfs.f_bsize / 512;
val = vmfs.f_bfree;
swap->total = SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) + swap->used;
swap->free = swap->total - swap->used;
return SIGAR_OK;
}
static int sigar_swap_sysctl_get(sigar_t *sigar, sigar_swap_t *swap)
{
#ifdef VM_SWAPUSAGE /* => 10.4 */
struct xsw_usage sw_usage; struct xsw_usage sw_usage;
size_t size = sizeof(sw_usage); size_t size = sizeof(sw_usage);
int mib[] = { CTL_VM, VM_SWAPUSAGE }; int mib[] = { CTL_VM, VM_SWAPUSAGE };
vm_statistics_data_t vmstat;
if (sysctl(mib, NMIB(mib), &sw_usage, &size, NULL, 0) < 0) { if (sysctl(mib, NMIB(mib), &sw_usage, &size, NULL, 0) != 0) {
return errno; return errno;
} }
@@ -553,6 +637,26 @@ int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap)
swap->used = sw_usage.xsu_used; swap->used = sw_usage.xsu_used;
swap->free = sw_usage.xsu_avail; swap->free = sw_usage.xsu_avail;
return SIGAR_OK;
#else
return SIGAR_ENOTIMPL; /* <= 10.3 */
#endif
}
#endif /* DARWIN */
int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap)
{
int status;
#if defined(DARWIN)
vm_statistics_data_t vmstat;
if (sigar_swap_sysctl_get(sigar, swap) != SIGAR_OK) {
status = sigar_swap_fs_get(sigar, swap); /* <= 10.3 */
if (status != SIGAR_OK) {
return status;
}
}
if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) { if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) {
return status; return status;
} }
@@ -895,6 +999,10 @@ static int sigar_get_pinfo(sigar_t *sigar, sigar_pid_t pid)
return SIGAR_OK; return SIGAR_OK;
} }
#ifdef DARWIN
#define GLOBAL_SHARED_SIZE (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE)
#endif
int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_mem_t *procmem) sigar_proc_mem_t *procmem)
{ {
@@ -906,6 +1014,8 @@ int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid,
mach_msg_type_number_t count; mach_msg_type_number_t count;
# ifdef DARWIN_HAS_LIBPROC_H # ifdef DARWIN_HAS_LIBPROC_H
struct proc_taskinfo pti; struct proc_taskinfo pti;
struct proc_regioninfo pri;
if (sigar->libproc) { if (sigar->libproc) {
int sz = int sz =
sigar->proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)); sigar->proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti));
@@ -917,6 +1027,15 @@ int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid,
procmem->minor_faults = SIGAR_FIELD_NOTIMPL; procmem->minor_faults = SIGAR_FIELD_NOTIMPL;
procmem->major_faults = SIGAR_FIELD_NOTIMPL; procmem->major_faults = SIGAR_FIELD_NOTIMPL;
procmem->share = SIGAR_FIELD_NOTIMPL; procmem->share = SIGAR_FIELD_NOTIMPL;
sz = sigar->proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, sizeof(pri));
if (sz == sizeof(pri)) {
if ((pri.pri_share_mode == SM_EMPTY) &&
(procmem->size > GLOBAL_SHARED_SIZE))
{
procmem->size -= GLOBAL_SHARED_SIZE; /* SIGAR-123 */
}
}
return SIGAR_OK; return SIGAR_OK;
} }
} }
@@ -1284,12 +1403,21 @@ int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid,
#if defined(DARWIN) #if defined(DARWIN)
typedef struct { typedef struct {
char buffer[8096], *ptr, *end; char *buf, *ptr, *end;
int count; int count;
} sigar_kern_proc_args_t; } sigar_kern_proc_args_t;
static void sigar_kern_proc_args_destroy(sigar_kern_proc_args_t *kargs)
{
if (kargs->buf) {
free(kargs->buf);
kargs->buf = NULL;
}
}
/* re-usable hack for use by proc_args and proc_env */ /* re-usable hack for use by proc_args and proc_env */
static int sigar_kern_proc_args_get(sigar_pid_t pid, static int sigar_kern_proc_args_get(sigar_t *sigar,
sigar_pid_t pid,
char *exe, char *exe,
sigar_kern_proc_args_t *kargs) sigar_kern_proc_args_t *kargs)
{ {
@@ -1298,21 +1426,23 @@ static int sigar_kern_proc_args_get(sigar_pid_t pid,
* http://darwinsource.opendarwin.org/10.4.1/adv_cmds-79.1/ps.tproj/print.c * http://darwinsource.opendarwin.org/10.4.1/adv_cmds-79.1/ps.tproj/print.c
*/ */
int mib[3], len; int mib[3], len;
size_t size = sizeof(kargs->buffer); size_t size = sigar_argmax_get(sigar);
char *args = kargs->buffer;
kargs->buf = malloc(size);
mib[0] = CTL_KERN; mib[0] = CTL_KERN;
mib[1] = KERN_PROCARGS2; mib[1] = KERN_PROCARGS2;
mib[2] = pid; mib[2] = pid;
if (sysctl(mib, NMIB(mib), args, &size, NULL, 0) < 0) { if (sysctl(mib, NMIB(mib), kargs->buf, &size, NULL, 0) < 0) {
sigar_kern_proc_args_destroy(kargs);
return errno; return errno;
} }
kargs->end = &args[size]; kargs->end = &kargs->buf[size];
memcpy(&kargs->count, args, sizeof(kargs->count)); memcpy(&kargs->count, kargs->buf, sizeof(kargs->count));
kargs->ptr = args + sizeof(kargs->count); kargs->ptr = kargs->buf + sizeof(kargs->count);
len = strlen(kargs->ptr); len = strlen(kargs->ptr);
if (exe) { if (exe) {
@@ -1321,6 +1451,7 @@ static int sigar_kern_proc_args_get(sigar_pid_t pid,
kargs->ptr += len+1; kargs->ptr += len+1;
if (kargs->ptr == kargs->end) { if (kargs->ptr == kargs->end) {
sigar_kern_proc_args_destroy(kargs);
return exe ? SIGAR_OK : ENOENT; return exe ? SIGAR_OK : ENOENT;
} }
@@ -1331,6 +1462,7 @@ static int sigar_kern_proc_args_get(sigar_pid_t pid,
} }
if (kargs->ptr == kargs->end) { if (kargs->ptr == kargs->end) {
sigar_kern_proc_args_destroy(kargs);
return exe ? SIGAR_OK : ENOENT; return exe ? SIGAR_OK : ENOENT;
} }
@@ -1362,9 +1494,6 @@ static int kern_proc_args_skip_argv(sigar_kern_proc_args_t *kargs)
} }
#endif #endif
/* ARG_MAX in FreeBSD 6.0 == 262144, which blows up the stack */
#define SIGAR_ARG_MAX 65536
int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_args_t *procargs) sigar_proc_args_t *procargs)
{ {
@@ -1373,7 +1502,7 @@ int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
sigar_kern_proc_args_t kargs; sigar_kern_proc_args_t kargs;
char *ptr, *end; char *ptr, *end;
status = sigar_kern_proc_args_get(pid, NULL, &kargs); status = sigar_kern_proc_args_get(sigar, pid, NULL, &kargs);
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
return status; return status;
} }
@@ -1409,6 +1538,7 @@ int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
ptr += alen; ptr += alen;
} }
sigar_kern_proc_args_destroy(&kargs);
return SIGAR_OK; return SIGAR_OK;
#elif defined(__FreeBSD__) || defined(__NetBSD__) #elif defined(__FreeBSD__) || defined(__NetBSD__)
char buffer[SIGAR_ARG_MAX+1], *ptr=buffer; char buffer[SIGAR_ARG_MAX+1], *ptr=buffer;
@@ -1487,13 +1617,14 @@ int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid,
sigar_kern_proc_args_t kargs; sigar_kern_proc_args_t kargs;
char *ptr, *end; char *ptr, *end;
status = sigar_kern_proc_args_get(pid, NULL, &kargs); status = sigar_kern_proc_args_get(sigar, pid, NULL, &kargs);
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
return status; return status;
} }
status = kern_proc_args_skip_argv(&kargs); status = kern_proc_args_skip_argv(&kargs);
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
sigar_kern_proc_args_destroy(&kargs);
return status; return status;
} }
@@ -1533,6 +1664,7 @@ int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid,
} }
} }
sigar_kern_proc_args_destroy(&kargs);
return SIGAR_OK; return SIGAR_OK;
#else #else
char **env; char **env;
@@ -1647,7 +1779,7 @@ int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid,
int status; int status;
sigar_kern_proc_args_t kargs; sigar_kern_proc_args_t kargs;
status = sigar_kern_proc_args_get(pid, procexe->name, &kargs); status = sigar_kern_proc_args_get(sigar, pid, procexe->name, &kargs);
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
return status; return status;
} }
@@ -1851,6 +1983,7 @@ int sigar_file_system_list_get(sigar_t *sigar,
fs = malloc(len); fs = malloc(len);
if ((num = sigar_getfsstat(fs, len, MNT_NOWAIT)) < 0) { if ((num = sigar_getfsstat(fs, len, MNT_NOWAIT)) < 0) {
free(fs);
return errno; return errno;
} }
@@ -1894,6 +2027,7 @@ int sigar_file_system_list_get(sigar_t *sigar,
sigar_fs_type_init(fsp); sigar_fs_type_init(fsp);
} }
free(fs);
return SIGAR_OK; return SIGAR_OK;
} }
@@ -1983,8 +2117,6 @@ int sigar_disk_usage_get(sigar_t *sigar, const char *name,
#endif #endif
} }
#define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1)
int sigar_file_system_usage_get(sigar_t *sigar, int sigar_file_system_usage_get(sigar_t *sigar,
const char *dirname, const char *dirname,
sigar_file_system_usage_t *fsusage) sigar_file_system_usage_t *fsusage)
@@ -2315,8 +2447,10 @@ static int sigar_ifmsg_iter(sigar_t *sigar, ifmsg_iter_t *iter)
case IFMSG_ITER_LIST: case IFMSG_ITER_LIST:
SIGAR_NET_IFLIST_GROW(iter->data.iflist); SIGAR_NET_IFLIST_GROW(iter->data.iflist);
/* sdl_data doesn't include a trailing \0, it is only sdl_nlen long */
name = malloc(sdl->sdl_nlen+1); name = malloc(sdl->sdl_nlen+1);
memcpy(name, sdl->sdl_data, sdl->sdl_nlen+1); memcpy(name, sdl->sdl_data, sdl->sdl_nlen);
name[sdl->sdl_nlen] = '\0'; /* add the missing \0 */
iter->data.iflist->data[iter->data.iflist->number++] = name; iter->data.iflist->data[iter->data.iflist->number++] = name;
break; break;
@@ -3113,7 +3247,7 @@ int sigar_os_sys_info_get(sigar_t *sigar,
{ {
#ifdef DARWIN #ifdef DARWIN
char *codename = NULL; char *codename = NULL;
long version, version_major, version_minor, version_fix; SInt32 version, version_major, version_minor, version_fix;
SIGAR_SSTRCPY(sysinfo->name, "MacOSX"); SIGAR_SSTRCPY(sysinfo->name, "MacOSX");
SIGAR_SSTRCPY(sysinfo->vendor_name, "Mac OS X"); SIGAR_SSTRCPY(sysinfo->vendor_name, "Mac OS X");
@@ -3139,13 +3273,13 @@ int sigar_os_sys_info_get(sigar_t *sigar,
snprintf(sysinfo->vendor_version, snprintf(sysinfo->vendor_version,
sizeof(sysinfo->vendor_version), sizeof(sysinfo->vendor_version),
"%ld.%ld", "%d.%d",
version_major, version_minor); (int)version_major, (int)version_minor);
snprintf(sysinfo->version, snprintf(sysinfo->version,
sizeof(sysinfo->version), sizeof(sysinfo->version),
"%s.%ld", "%s.%d",
sysinfo->vendor_version, version_fix); sysinfo->vendor_version, (int)version_fix);
if (version_major == 10) { if (version_major == 10) {
switch (version_minor) { switch (version_minor) {
+1
View File
@@ -60,6 +60,7 @@ struct sigar_t {
sigar_pid_t last_pid; sigar_pid_t last_pid;
bsd_pinfo_t *pinfo; bsd_pinfo_t *pinfo;
int lcpu; int lcpu;
size_t argmax;
#ifdef DARWIN #ifdef DARWIN
mach_port_t mach_port; mach_port_t mach_port;
# ifdef DARWIN_HAS_LIBPROC_H # ifdef DARWIN_HAS_LIBPROC_H
+21
View File
@@ -16,6 +16,10 @@
* USA. * USA.
*/ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "sigar.h" #include "sigar.h"
#include "sigar_private.h" #include "sigar_private.h"
#include "sigar_util.h" #include "sigar_util.h"
@@ -416,7 +420,11 @@ int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid,
{ {
struct pst_status status; struct pst_status status;
int idx, i, n; int idx, i, n;
#ifdef HAVE_STRUCT_PST_FILEINFO2
struct pst_fileinfo2 psf[16];
#else
struct pst_fileinfo psf[16]; struct pst_fileinfo psf[16];
#endif
procfd->total = 0; procfd->total = 0;
@@ -424,6 +432,18 @@ int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid,
return errno; return errno;
} }
/* HPUX 11.31 removed the deprecated pstat_getfile call */
#ifdef HAVE_STRUCT_PST_FILEINFO2
idx = status.pst_idx;
while ((n = pstat_getfile2(psf, sizeof(psf[0]),
sizeof(psf)/sizeof(psf[0]),
idx, pid)) > 0)
{
procfd->total += n;
idx = psf[n-1].psf_fd;
}
#else
/* man pstat_getfile for index splaination */ /* man pstat_getfile for index splaination */
idx = (status.pst_idx << 16) | (0 & 0xffff); idx = (status.pst_idx << 16) | (0 & 0xffff);
@@ -434,6 +454,7 @@ int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid,
procfd->total += n; procfd->total += n;
idx = psf[n-1].psf_idx + 1; idx = psf[n-1].psf_idx + 1;
} }
#endif
if (n == -1) { if (n == -1) {
return errno; return errno;
+6 -1
View File
@@ -882,6 +882,11 @@ int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
return sigar_procfs_args_get(sigar, pid, procargs); return sigar_procfs_args_get(sigar, pid, procargs);
} }
/* glibc 2.8 XXX use sysconf(_SC_ARG_MAX) */
#ifndef ARG_MAX
#define ARG_MAX 131072
#endif
int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_env_t *procenv) sigar_proc_env_t *procenv)
{ {
@@ -1081,7 +1086,7 @@ int sigar_os_fs_type_get(sigar_file_system_t *fsp)
} }
break; break;
case 'o': case 'o':
if (strEQ(type, "ocfs2")) { if (strnEQ(type, "ocfs", 4)) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK; fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
} }
break; break;
+2 -2
View File
@@ -468,12 +468,12 @@ int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist)
/* merge times of logical processors */ /* merge times of logical processors */
ent = sigar_cache_get(chips, chip_id); ent = sigar_cache_get(chips, chip_id);
if (ent->value) { if (ent->value) {
cpu = &cpulist->data[(int)ent->value-1]; cpu = &cpulist->data[(long)ent->value-1];
} }
else { else {
SIGAR_CPU_LIST_GROW(cpulist); SIGAR_CPU_LIST_GROW(cpulist);
cpu = &cpulist->data[cpulist->number++]; cpu = &cpulist->data[cpulist->number++];
ent->value = (void *)(int)cpulist->number; ent->value = (void *)(long)cpulist->number;
SIGAR_ZERO(cpu); SIGAR_ZERO(cpu);
if (is_debug) { if (is_debug) {
+327 -327
View File
@@ -1,327 +1,327 @@
/*++ /*++
Copyright (c) Microsoft Corporation. All rights reserved. Copyright (c) Microsoft Corporation. All rights reserved.
Module Name: Module Name:
iptypes.h iptypes.h
--*/ --*/
#ifndef IP_TYPES_INCLUDED #ifndef IP_TYPES_INCLUDED
#define IP_TYPES_INCLUDED #define IP_TYPES_INCLUDED
#if _MSC_VER > 1000 #if _MSC_VER > 1000
#pragma once #pragma once
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
#pragma warning(push) #pragma warning(push)
#pragma warning(disable:4201) #pragma warning(disable:4201)
#include <time.h> #include <time.h>
// Definitions and structures used by getnetworkparams and getadaptersinfo apis // Definitions and structures used by getnetworkparams and getadaptersinfo apis
#define MAX_ADAPTER_DESCRIPTION_LENGTH 128 // arb. #define MAX_ADAPTER_DESCRIPTION_LENGTH 128 // arb.
#define MAX_ADAPTER_NAME_LENGTH 256 // arb. #define MAX_ADAPTER_NAME_LENGTH 256 // arb.
#define MAX_ADAPTER_ADDRESS_LENGTH 8 // arb. #define MAX_ADAPTER_ADDRESS_LENGTH 8 // arb.
#define DEFAULT_MINIMUM_ENTITIES 32 // arb. #define DEFAULT_MINIMUM_ENTITIES 32 // arb.
#define MAX_HOSTNAME_LEN 128 // arb. #define MAX_HOSTNAME_LEN 128 // arb.
#define MAX_DOMAIN_NAME_LEN 128 // arb. #define MAX_DOMAIN_NAME_LEN 128 // arb.
#define MAX_SCOPE_ID_LEN 256 // arb. #define MAX_SCOPE_ID_LEN 256 // arb.
// //
// types // types
// //
// Node Type // Node Type
#define BROADCAST_NODETYPE 1 #define BROADCAST_NODETYPE 1
#define PEER_TO_PEER_NODETYPE 2 #define PEER_TO_PEER_NODETYPE 2
#define MIXED_NODETYPE 4 #define MIXED_NODETYPE 4
#define HYBRID_NODETYPE 8 #define HYBRID_NODETYPE 8
// //
// IP_ADDRESS_STRING - store an IP address as a dotted decimal string // IP_ADDRESS_STRING - store an IP address as a dotted decimal string
// //
typedef struct { typedef struct {
char String[4 * 4]; char String[4 * 4];
} IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING; } IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING;
// //
// IP_ADDR_STRING - store an IP address with its corresponding subnet mask, // IP_ADDR_STRING - store an IP address with its corresponding subnet mask,
// both as dotted decimal strings // both as dotted decimal strings
// //
typedef struct _IP_ADDR_STRING { typedef struct _IP_ADDR_STRING {
struct _IP_ADDR_STRING* Next; struct _IP_ADDR_STRING* Next;
IP_ADDRESS_STRING IpAddress; IP_ADDRESS_STRING IpAddress;
IP_MASK_STRING IpMask; IP_MASK_STRING IpMask;
DWORD Context; DWORD Context;
} IP_ADDR_STRING, *PIP_ADDR_STRING; } IP_ADDR_STRING, *PIP_ADDR_STRING;
// //
// ADAPTER_INFO - per-adapter information. All IP addresses are stored as // ADAPTER_INFO - per-adapter information. All IP addresses are stored as
// strings // strings
// //
typedef struct _IP_ADAPTER_INFO { typedef struct _IP_ADAPTER_INFO {
struct _IP_ADAPTER_INFO* Next; struct _IP_ADAPTER_INFO* Next;
DWORD ComboIndex; DWORD ComboIndex;
char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4]; char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4]; char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
UINT AddressLength; UINT AddressLength;
BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH]; BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
DWORD Index; DWORD Index;
UINT Type; UINT Type;
UINT DhcpEnabled; UINT DhcpEnabled;
PIP_ADDR_STRING CurrentIpAddress; PIP_ADDR_STRING CurrentIpAddress;
IP_ADDR_STRING IpAddressList; IP_ADDR_STRING IpAddressList;
IP_ADDR_STRING GatewayList; IP_ADDR_STRING GatewayList;
IP_ADDR_STRING DhcpServer; IP_ADDR_STRING DhcpServer;
BOOL HaveWins; BOOL HaveWins;
IP_ADDR_STRING PrimaryWinsServer; IP_ADDR_STRING PrimaryWinsServer;
IP_ADDR_STRING SecondaryWinsServer; IP_ADDR_STRING SecondaryWinsServer;
time_t LeaseObtained; time_t LeaseObtained;
time_t LeaseExpires; time_t LeaseExpires;
} IP_ADAPTER_INFO, *PIP_ADAPTER_INFO; } IP_ADAPTER_INFO, *PIP_ADAPTER_INFO;
#ifdef _WINSOCK2API_ #ifdef _WINSOCK2API_
// //
// The following types require Winsock2. // The following types require Winsock2.
// //
typedef enum { typedef enum {
IpPrefixOriginOther = 0, IpPrefixOriginOther = 0,
IpPrefixOriginManual, IpPrefixOriginManual,
IpPrefixOriginWellKnown, IpPrefixOriginWellKnown,
IpPrefixOriginDhcp, IpPrefixOriginDhcp,
IpPrefixOriginRouterAdvertisement, IpPrefixOriginRouterAdvertisement,
} IP_PREFIX_ORIGIN; } IP_PREFIX_ORIGIN;
typedef enum { typedef enum {
IpSuffixOriginOther = 0, IpSuffixOriginOther = 0,
IpSuffixOriginManual, IpSuffixOriginManual,
IpSuffixOriginWellKnown, IpSuffixOriginWellKnown,
IpSuffixOriginDhcp, IpSuffixOriginDhcp,
IpSuffixOriginLinkLayerAddress, IpSuffixOriginLinkLayerAddress,
IpSuffixOriginRandom, IpSuffixOriginRandom,
} IP_SUFFIX_ORIGIN; } IP_SUFFIX_ORIGIN;
typedef enum { typedef enum {
IpDadStateInvalid = 0, IpDadStateInvalid = 0,
IpDadStateTentative, IpDadStateTentative,
IpDadStateDuplicate, IpDadStateDuplicate,
IpDadStateDeprecated, IpDadStateDeprecated,
IpDadStatePreferred, IpDadStatePreferred,
} IP_DAD_STATE; } IP_DAD_STATE;
typedef struct _IP_ADAPTER_UNICAST_ADDRESS { typedef struct _IP_ADAPTER_UNICAST_ADDRESS {
union { union {
ULONGLONG Alignment; ULONGLONG Alignment;
struct { struct {
ULONG Length; ULONG Length;
DWORD Flags; DWORD Flags;
}; };
}; };
struct _IP_ADAPTER_UNICAST_ADDRESS *Next; struct _IP_ADAPTER_UNICAST_ADDRESS *Next;
SOCKET_ADDRESS Address; SOCKET_ADDRESS Address;
IP_PREFIX_ORIGIN PrefixOrigin; IP_PREFIX_ORIGIN PrefixOrigin;
IP_SUFFIX_ORIGIN SuffixOrigin; IP_SUFFIX_ORIGIN SuffixOrigin;
IP_DAD_STATE DadState; IP_DAD_STATE DadState;
ULONG ValidLifetime; ULONG ValidLifetime;
ULONG PreferredLifetime; ULONG PreferredLifetime;
ULONG LeaseLifetime; ULONG LeaseLifetime;
} IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS; } IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS;
typedef struct _IP_ADAPTER_ANYCAST_ADDRESS { typedef struct _IP_ADAPTER_ANYCAST_ADDRESS {
union { union {
ULONGLONG Alignment; ULONGLONG Alignment;
struct { struct {
ULONG Length; ULONG Length;
DWORD Flags; DWORD Flags;
}; };
}; };
struct _IP_ADAPTER_ANYCAST_ADDRESS *Next; struct _IP_ADAPTER_ANYCAST_ADDRESS *Next;
SOCKET_ADDRESS Address; SOCKET_ADDRESS Address;
} IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS; } IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS;
typedef struct _IP_ADAPTER_MULTICAST_ADDRESS { typedef struct _IP_ADAPTER_MULTICAST_ADDRESS {
union { union {
ULONGLONG Alignment; ULONGLONG Alignment;
struct { struct {
ULONG Length; ULONG Length;
DWORD Flags; DWORD Flags;
}; };
}; };
struct _IP_ADAPTER_MULTICAST_ADDRESS *Next; struct _IP_ADAPTER_MULTICAST_ADDRESS *Next;
SOCKET_ADDRESS Address; SOCKET_ADDRESS Address;
} IP_ADAPTER_MULTICAST_ADDRESS, *PIP_ADAPTER_MULTICAST_ADDRESS; } IP_ADAPTER_MULTICAST_ADDRESS, *PIP_ADAPTER_MULTICAST_ADDRESS;
// //
// Per-address Flags // Per-address Flags
// //
#define IP_ADAPTER_ADDRESS_DNS_ELIGIBLE 0x01 #define IP_ADAPTER_ADDRESS_DNS_ELIGIBLE 0x01
#define IP_ADAPTER_ADDRESS_TRANSIENT 0x02 #define IP_ADAPTER_ADDRESS_TRANSIENT 0x02
typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS { typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS {
union { union {
ULONGLONG Alignment; ULONGLONG Alignment;
struct { struct {
ULONG Length; ULONG Length;
DWORD Reserved; DWORD Reserved;
}; };
}; };
struct _IP_ADAPTER_DNS_SERVER_ADDRESS *Next; struct _IP_ADAPTER_DNS_SERVER_ADDRESS *Next;
SOCKET_ADDRESS Address; SOCKET_ADDRESS Address;
} IP_ADAPTER_DNS_SERVER_ADDRESS, *PIP_ADAPTER_DNS_SERVER_ADDRESS; } IP_ADAPTER_DNS_SERVER_ADDRESS, *PIP_ADAPTER_DNS_SERVER_ADDRESS;
typedef struct _IP_ADAPTER_PREFIX { typedef struct _IP_ADAPTER_PREFIX {
union { union {
ULONGLONG Alignment; ULONGLONG Alignment;
struct { struct {
ULONG Length; ULONG Length;
DWORD Flags; DWORD Flags;
}; };
}; };
struct _IP_ADAPTER_PREFIX *Next; struct _IP_ADAPTER_PREFIX *Next;
SOCKET_ADDRESS Address; SOCKET_ADDRESS Address;
ULONG PrefixLength; ULONG PrefixLength;
} IP_ADAPTER_PREFIX, *PIP_ADAPTER_PREFIX; } IP_ADAPTER_PREFIX, *PIP_ADAPTER_PREFIX;
// //
// Per-adapter Flags // Per-adapter Flags
// //
#define IP_ADAPTER_DDNS_ENABLED 0x01 #define IP_ADAPTER_DDNS_ENABLED 0x01
#define IP_ADAPTER_REGISTER_ADAPTER_SUFFIX 0x02 #define IP_ADAPTER_REGISTER_ADAPTER_SUFFIX 0x02
#define IP_ADAPTER_DHCP_ENABLED 0x04 #define IP_ADAPTER_DHCP_ENABLED 0x04
#define IP_ADAPTER_RECEIVE_ONLY 0x08 #define IP_ADAPTER_RECEIVE_ONLY 0x08
#define IP_ADAPTER_NO_MULTICAST 0x10 #define IP_ADAPTER_NO_MULTICAST 0x10
#define IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG 0x20 #define IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG 0x20
// //
// OperStatus values from RFC 2863 // OperStatus values from RFC 2863
// //
typedef enum { typedef enum {
IfOperStatusUp = 1, IfOperStatusUp = 1,
IfOperStatusDown, IfOperStatusDown,
IfOperStatusTesting, IfOperStatusTesting,
IfOperStatusUnknown, IfOperStatusUnknown,
IfOperStatusDormant, IfOperStatusDormant,
IfOperStatusNotPresent, IfOperStatusNotPresent,
IfOperStatusLowerLayerDown IfOperStatusLowerLayerDown
} IF_OPER_STATUS; } IF_OPER_STATUS;
// //
// Scope levels from RFC 2373 used with ZoneIndices array. // Scope levels from RFC 2373 used with ZoneIndices array.
// //
typedef enum { typedef enum {
ScopeLevelInterface = 1, ScopeLevelInterface = 1,
ScopeLevelLink = 2, ScopeLevelLink = 2,
ScopeLevelSubnet = 3, ScopeLevelSubnet = 3,
ScopeLevelAdmin = 4, ScopeLevelAdmin = 4,
ScopeLevelSite = 5, ScopeLevelSite = 5,
ScopeLevelOrganization = 8, ScopeLevelOrganization = 8,
ScopeLevelGlobal = 14 ScopeLevelGlobal = 14
} SCOPE_LEVEL; } SCOPE_LEVEL;
typedef struct _IP_ADAPTER_ADDRESSES { typedef struct _IP_ADAPTER_ADDRESSES {
union { union {
ULONGLONG Alignment; ULONGLONG Alignment;
struct { struct {
ULONG Length; ULONG Length;
DWORD IfIndex; DWORD IfIndex;
}; };
}; };
struct _IP_ADAPTER_ADDRESSES *Next; struct _IP_ADAPTER_ADDRESSES *Next;
PCHAR AdapterName; PCHAR AdapterName;
PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress; PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress;
PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress; PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress;
PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress; PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress;
PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress; PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress;
PWCHAR DnsSuffix; PWCHAR DnsSuffix;
PWCHAR Description; PWCHAR Description;
PWCHAR FriendlyName; PWCHAR FriendlyName;
BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH]; BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];
DWORD PhysicalAddressLength; DWORD PhysicalAddressLength;
DWORD Flags; DWORD Flags;
DWORD Mtu; DWORD Mtu;
DWORD IfType; DWORD IfType;
IF_OPER_STATUS OperStatus; IF_OPER_STATUS OperStatus;
DWORD Ipv6IfIndex; DWORD Ipv6IfIndex;
DWORD ZoneIndices[16]; DWORD ZoneIndices[16];
PIP_ADAPTER_PREFIX FirstPrefix; PIP_ADAPTER_PREFIX FirstPrefix;
} IP_ADAPTER_ADDRESSES, *PIP_ADAPTER_ADDRESSES; } IP_ADAPTER_ADDRESSES, *PIP_ADAPTER_ADDRESSES;
// //
// Flags used as argument to GetAdaptersAddresses(). // Flags used as argument to GetAdaptersAddresses().
// "SKIP" flags are added when the default is to include the information. // "SKIP" flags are added when the default is to include the information.
// "INCLUDE" flags are added when the default is to skip the information. // "INCLUDE" flags are added when the default is to skip the information.
// //
#define GAA_FLAG_SKIP_UNICAST 0x0001 #define GAA_FLAG_SKIP_UNICAST 0x0001
#define GAA_FLAG_SKIP_ANYCAST 0x0002 #define GAA_FLAG_SKIP_ANYCAST 0x0002
#define GAA_FLAG_SKIP_MULTICAST 0x0004 #define GAA_FLAG_SKIP_MULTICAST 0x0004
#define GAA_FLAG_SKIP_DNS_SERVER 0x0008 #define GAA_FLAG_SKIP_DNS_SERVER 0x0008
#define GAA_FLAG_INCLUDE_PREFIX 0x0010 #define GAA_FLAG_INCLUDE_PREFIX 0x0010
#define GAA_FLAG_SKIP_FRIENDLY_NAME 0x0020 #define GAA_FLAG_SKIP_FRIENDLY_NAME 0x0020
#endif /* _WINSOCK2API_ */ #endif /* _WINSOCK2API_ */
// //
// IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list. // IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list.
// //
typedef struct _IP_PER_ADAPTER_INFO { typedef struct _IP_PER_ADAPTER_INFO {
UINT AutoconfigEnabled; UINT AutoconfigEnabled;
UINT AutoconfigActive; UINT AutoconfigActive;
PIP_ADDR_STRING CurrentDnsServer; PIP_ADDR_STRING CurrentDnsServer;
IP_ADDR_STRING DnsServerList; IP_ADDR_STRING DnsServerList;
} IP_PER_ADAPTER_INFO, *PIP_PER_ADAPTER_INFO; } IP_PER_ADAPTER_INFO, *PIP_PER_ADAPTER_INFO;
// //
// FIXED_INFO - the set of IP-related information which does not depend on DHCP // FIXED_INFO - the set of IP-related information which does not depend on DHCP
// //
typedef struct { typedef struct {
char HostName[MAX_HOSTNAME_LEN + 4] ; char HostName[MAX_HOSTNAME_LEN + 4] ;
char DomainName[MAX_DOMAIN_NAME_LEN + 4]; char DomainName[MAX_DOMAIN_NAME_LEN + 4];
PIP_ADDR_STRING CurrentDnsServer; PIP_ADDR_STRING CurrentDnsServer;
IP_ADDR_STRING DnsServerList; IP_ADDR_STRING DnsServerList;
UINT NodeType; UINT NodeType;
char ScopeId[MAX_SCOPE_ID_LEN + 4]; char ScopeId[MAX_SCOPE_ID_LEN + 4];
UINT EnableRouting; UINT EnableRouting;
UINT EnableProxy; UINT EnableProxy;
UINT EnableDns; UINT EnableDns;
} FIXED_INFO, *PFIXED_INFO; } FIXED_INFO, *PFIXED_INFO;
#ifndef IP_INTERFACE_NAME_INFO_DEFINED #ifndef IP_INTERFACE_NAME_INFO_DEFINED
#define IP_INTERFACE_NAME_INFO_DEFINED #define IP_INTERFACE_NAME_INFO_DEFINED
typedef struct ip_interface_name_info { typedef struct ip_interface_name_info {
ULONG Index; // Interface Index ULONG Index; // Interface Index
ULONG MediaType; // Interface Types - see ipifcons.h ULONG MediaType; // Interface Types - see ipifcons.h
UCHAR ConnectionType; UCHAR ConnectionType;
UCHAR AccessType; UCHAR AccessType;
GUID DeviceGuid; // Device GUID is the guid of the device GUID DeviceGuid; // Device GUID is the guid of the device
// that IP exposes // that IP exposes
GUID InterfaceGuid; // Interface GUID, if not GUID_NULL is the GUID InterfaceGuid; // Interface GUID, if not GUID_NULL is the
// GUID for the interface mapped to the device. // GUID for the interface mapped to the device.
} IP_INTERFACE_NAME_INFO, *PIP_INTERFACE_NAME_INFO; } IP_INTERFACE_NAME_INFO, *PIP_INTERFACE_NAME_INFO;
#endif #endif
#pragma warning(pop) #pragma warning(pop)
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif #endif
+4 -2
View File
@@ -1254,11 +1254,13 @@ SIGAR_DECLARE(int) sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid,
sigar_int64_t sigar_time_now_millis(void) sigar_int64_t sigar_time_now_millis(void)
{ {
SYSTEMTIME st;
FILETIME time; FILETIME time;
GetSystemTimeAsFileTime(&time); GetSystemTime(&st);
SystemTimeToFileTime(&st, &time);
return FILETIME2MSEC(time); return sigar_FileTimeToTime(&time) / 1000;
} }
SIGAR_DECLARE(int) sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, SIGAR_DECLARE(int) sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid,
+14 -1
View File
@@ -111,7 +111,7 @@ SIGAR_DECLARE(int) sigar_proc_cpu_get(sigar_t *sigar, sigar_pid_t pid,
sigar_cache_entry_t *entry; sigar_cache_entry_t *entry;
sigar_proc_cpu_t *prev; sigar_proc_cpu_t *prev;
sigar_uint64_t otime, time_now = sigar_time_now_millis(); sigar_uint64_t otime, time_now = sigar_time_now_millis();
sigar_int64_t time_diff, total_diff; sigar_uint64_t time_diff, total_diff;
int status; int status;
if (!sigar->proc_cpu) { if (!sigar->proc_cpu) {
@@ -148,6 +148,11 @@ SIGAR_DECLARE(int) sigar_proc_cpu_get(sigar_t *sigar, sigar_pid_t pid,
memcpy(prev, proccpu, sizeof(*prev)); memcpy(prev, proccpu, sizeof(*prev));
if (proccpu->total < otime) {
/* XXX this should not happen */
otime = 0;
}
if (otime == 0) { if (otime == 0) {
proccpu->percent = 0.0; proccpu->percent = 0.0;
/* first time called */ /* first time called */
@@ -156,6 +161,9 @@ SIGAR_DECLARE(int) sigar_proc_cpu_get(sigar_t *sigar, sigar_pid_t pid,
total_diff = proccpu->total - otime; total_diff = proccpu->total - otime;
proccpu->percent = total_diff / (double)time_diff; proccpu->percent = total_diff / (double)time_diff;
if (proccpu->percent > 1.0) {
proccpu->percent = 1.0;
}
return SIGAR_OK; return SIGAR_OK;
} }
@@ -439,6 +447,11 @@ static int sigar_common_fs_type_get(sigar_file_system_t *fsp)
fsp->type = SIGAR_FSTYPE_LOCAL_DISK; fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
} }
break; break;
case 'z':
if (strEQ(type, "zfs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
} }
return fsp->type; return fsp->type;
+8 -8
View File
@@ -614,14 +614,14 @@ SIGAR_DECLARE(int) sigar_cpu_perc_calculate(sigar_cpu_t *prev,
double diff_wait, diff_irq, diff_soft_irq, diff_stolen; double diff_wait, diff_irq, diff_soft_irq, diff_stolen;
double diff_total; double diff_total;
diff_user = (sigar_int64_t)(curr->user - prev->user); diff_user = curr->user - prev->user;
diff_sys = (sigar_int64_t)(curr->sys - prev->sys); diff_sys = curr->sys - prev->sys;
diff_nice = (sigar_int64_t)(curr->nice - prev->nice); diff_nice = curr->nice - prev->nice;
diff_idle = (sigar_int64_t)(curr->idle - prev->idle); diff_idle = curr->idle - prev->idle;
diff_wait = (sigar_int64_t)(curr->wait - prev->wait); diff_wait = curr->wait - prev->wait;
diff_irq = (sigar_int64_t)(curr->irq - prev->irq); diff_irq = curr->irq - prev->irq;
diff_soft_irq = (sigar_int64_t)(curr->soft_irq - prev->soft_irq); diff_soft_irq = curr->soft_irq - prev->soft_irq;
diff_stolen = (sigar_int64_t)(curr->stolen - prev->stolen); diff_stolen = curr->stolen - prev->stolen;
diff_user = diff_user < 0 ? 0 : diff_user; diff_user = diff_user < 0 ? 0 : diff_user;
diff_sys = diff_sys < 0 ? 0 : diff_sys; diff_sys = diff_sys < 0 ? 0 : diff_sys;
+1 -5
View File
@@ -824,13 +824,9 @@ SIGAR_DECLARE(int) sigar_rpc_ping(char *host,
rpc_stat = clnt_call(client, NULLPROC, (xdrproc_t)xdr_void, NULL, rpc_stat = clnt_call(client, NULLPROC, (xdrproc_t)xdr_void, NULL,
(xdrproc_t)xdr_void, NULL, timeout); (xdrproc_t)xdr_void, NULL, timeout);
if (rpc_stat != RPC_SUCCESS) {
return rpc_stat;
}
clnt_destroy(client); clnt_destroy(client);
return RPC_SUCCESS; return rpc_stat;
} }
#endif #endif
+1 -1
View File
@@ -8,7 +8,7 @@ static sigar_version_t sigar_version = {
"@@ARCHLIB@@", "@@ARCHLIB@@",
"@@BINNAME@@", "@@BINNAME@@",
"SIGAR-@@VERSION_STRING@@, " "SIGAR-@@VERSION_STRING@@, "
"SVN revision @@SCM_REVISION@@, " "SCM revision @@SCM_REVISION@@, "
"built @@BUILD_DATE@@ as @@ARCHLIB@@", "built @@BUILD_DATE@@ as @@ARCHLIB@@",
@@VERSION_MAJOR@@, @@VERSION_MAJOR@@,
@@VERSION_MINOR@@, @@VERSION_MINOR@@,