5 Commits
Author SHA1 Message Date
unknown 494ed4ed3e Some metrics are missing the '/sec' suffix. This fix first tries to add
the counter without the '/sec' and if fails, try again with it. If the
second call fails, throw an exception.This issue must be addressed at the
java level (and not C code), since the counter names must be translated
before to support i18n native OS locals.
Please also note, the C code (at Pdh.c), tries to do the same, but at
this level we cannot use the translation mechanism the Java level offers,
hence this fix won't handle non-English i18n locals.
2014-09-03 14:26:02 +03:00
root f12b8e32d3 process args and query (ptql) string - support dbcs for windows 2013-11-04 12:07:38 +00:00
root 9c931654d7 (German) support for getting a set of formatted metrics 2013-10-22 07:33:06 +00:00
root 797d8a9edf adding disk io per process and bug fixes 2013-10-09 07:59:48 +00:00
Netta Gavrieli 449de48cea Java - Fixed loading native libraries from paths that contain international characters.
This fixes Hyperic bug https://jira.hyperic.com/browse/HQ-4227
2013-10-06 10:13:21 +00:00
271 changed files with 2775 additions and 29645 deletions

No files matched your search

-43
View File
@@ -1,43 +0,0 @@
pkg
Makefile
Makefile.in
*.o
*.lo
*.la
.deps
.libs
aclocal.m4
autom4te.cache
compile
config.guess
config.log
config.status
config.sub
configure
depcomp
install-sh
libtool
ltmain.sh
missing
src/sigar_version_autoconf.c
examples/cpuinfo
examples/sigar_ps
debian/*.log
debian/stamp-*
debian/tmp
m4/
debian/python-sigar*
debian/python-module-stampdir
debian/*.debhelper
debian/*.substvars
debian/libsigar1/
debian/libsigar1-dev/
debian/libsigar-java-doc/
debian/libsigar-java/
debian/files
config.sub*
config.guess*
bindings/java/${dist}
bindings/python/build
TODO*
check*.rb
-35
View File
@@ -1,35 +0,0 @@
PROJECT(sigar C)
cmake_minimum_required(VERSION 2.6)
INCLUDE(CheckIncludeFiles)
INCLUDE(CheckFunctionExists)
INCLUDE(CheckTypeSize)
INCLUDE(CTest)
INCLUDE(InstallRequiredSystemLibraries)
ENABLE_TESTING()
SET(CPACK_PACKAGE_VERSION_MAJOR "1")
SET(CPACK_PACKAGE_VERSION_MINOR "6")
SET(CPACK_PACKAGE_VERSION_PATCH "2")
SET(CPACK_PACKAGE_VENDOR "Hyperic")
## SET(CPACK_*) before the INCLUDE(CPack)
INCLUDE(CPack)
IF(WIN32)
## make sure we only use the smallest set of
## headers on win32. Otherwise we get clashes
## between winsock2.h and winsock.h
ADD_DEFINITIONS(-DWIN32_LEAN_AND_MEAN)
# force the correct version for the redist manifest
ADD_DEFINITIONS(-D_BIND_TO_CURRENT_MFC_VERSION=1 -D_BIND_TO_CURRENT_CRT_VERSION=1)
# turn off security warnings for system calls
ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS)
ENDIF(WIN32)
ADD_SUBDIRECTORY(src build-src)
ADD_SUBDIRECTORY(tests build-tests)
ADD_SUBDIRECTORY(include build-include)
-5
View File
@@ -1,5 +0,0 @@
SUBDIRS = include src bindings examples tests
EXTRA_DIST=\
CMakeLists.txt \
winbuild.bat
+2
View File
@@ -0,0 +1,2 @@
Visit the SIGAR Wiki for documentation, bugs, support, etc.:
http://sigar.hyperic.com/
-36
View File
@@ -1,36 +0,0 @@
# System Information Gatherer And Reporter.
Fork of hyperic/sigar with some fixes. Support only ruby binding. Part of [Eye gem](https://github.com/kostya/eye).
## Fixed:
### [2.0.9] 28-06-2021
* Fix compilation on FreeBSD 13 [#8](https://github.com/kostya/sigar/issues/10)([commit](https://github.com/kostya/sigar/commit/b78b558fb756a75dc7d6cbf704423be3c7098ae5))
### [2.0.8] 02-10-2020
* Fix compilation on MacOS [#8](https://github.com/kostya/sigar/issues/8)([commit](https://github.com/kostya/sigar/pull/9/commits/ad39547629fa328e115f7d7bc3c7c358247d1961))
### [2.0.6] 18-01-2019
* Fix compilation on FreeBSD 12 [#6](https://github.com/kostya/sigar/issues/6)([commit](https://github.com/kostya/sigar/commit/2bb67fa1bf6f6f0ddc2626cf028bcc0e4a8cb377))
### [2.0.5] 02-12-2018
* Fix compilation with musl libc [#4](https://github.com/kostya/sigar/pull/4)([commit](https://github.com/kostya/sigar/pull/4/commits/cd07923dd2ed34aca353dfd182f2f85c13853fd9))
### [2.0.4] 10-06-2018
* fix compilation with glibc 2.26, major/minor functions [#2](https://github.com/kostya/sigar/issues/2)([commit](https://github.com/kostya/sigar/commit/a2c67588d0f686e0007dadcaf0e4bbb35c0e1e83))
### [2.0.2] 30-05-2018
* Remove obsolete rpc usage (fix compilation fail with glibc 2.27) [#213](https://github.com/kostya/eye/issues/213)([commit](https://github.com/kostya/sigar/commit/a971b9e8e1443fdf236c5ffa199c1994c05fcd4b))
### [2.0.1] 10-04-2018
* FreeBSD: don't use v_cache_min/max [#68](https://github.com/hyperic/sigar/pull/68)([commit](https://github.com/kostya/sigar/commit/800076db97bcacb1ba90805d740b4f9a5a1d3cca))
### [2.0.0] 22-01-2018
* sigfaulted logger, [#28](https://github.com/hyperic/sigar/pull/28)([commit](https://github.com/kostya/sigar/commit/c2a1af))
* bug undefined symbol: sigar_skip_token, [#60](https://github.com/hyperic/sigar/pull/60)([commit](https://github.com/kostya/sigar/commit/dfe8fe))
* bug detection boot_time on linux (now it works like gnu ps, and fix some issues with process start_time) ([commit](https://github.com/kostya/sigar/commit/660259))
## Installation:
$ gem install kostya-sigar
-102
View File
@@ -1,102 +0,0 @@
require 'rubygems'
require 'rubygems/package_task'
require 'rake/testtask'
#so we can: ssh host rake -f $hudson_workspace/sigar/Rakefile
Dir.chdir(File.dirname(__FILE__))
props = {}
File.open("version.properties").each { |line|
next if line =~ /^#/
line.chomp!
line.strip!
next if line.empty?
key,val = line.split('=')
props[key] = val
}
GEM = props['project.name']
MAKE = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make'
spec = Gem::Specification.new do |s|
s.name = GEM
s.version = props['version.major'] + '.' + props['version.minor'] + '.' + props['version.maint']
s.summary = props['project.summary']
s.description = s.summary
s.author = props['project.author']
s.email = props['project.email']
s.homepage = props['project.homepage']
s.platform = Gem::Platform::RUBY
s.extensions = 'bindings/ruby/extconf.rb'
s.files =
%w(LICENSE NOTICE README.md Rakefile version.properties) +
%w(bindings/SigarWrapper.pm bindings/SigarBuild.pm) +
`git ls-files -- bindings/ruby/*.*`.split("\n") +
Dir.glob("include/*.h") +
Dir.glob("src/**/*.[ch]") +
Dir.glob("src/**/*.in")
end
Gem::PackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
end
task :default => :test
def in_ext()
ext = 'bindings/ruby'
Dir.chdir(ext) if File.directory? ext
end
desc 'Build sigar extension'
task :build do
in_ext()
unless File.exists? "Makefile"
unless system("ruby extconf.rb")
STDERR.puts "Failed to configure"
break
end
end
unless system(MAKE)
STDERR.puts 'Failed to ' + MAKE
break
end
end
Rake::TestTask.new do |t|
t.pattern = 'test/*_test.rb'
t.libs << "."
end
task :test => [:build] do
in_ext()
end
desc 'Clean sigar extension'
task :clean do
in_ext()
system(MAKE + ' clean') if File.exists? "Makefile"
end
desc 'Dist Clean sigar extension'
task :distclean do
in_ext()
system(MAKE + ' distclean') if File.exists? "Makefile"
end
desc 'Run sigar examples (test)'
task :examples => [:build] do
in_ext()
Dir["examples/*.rb"].each do |file|
cmd = "ruby -I. #{file}"
print cmd + "\n"
system(cmd)
end
end
desc "create a gemspec file"
task :make_spec do
File.open("#{GEM}.gemspec", "w") do |file|
file.puts spec.to_ruby
end
end
-61
View File
@@ -1,61 +0,0 @@
#!/bin/sh
set -x
rm -f INSTALL NEWS \
&& rm -f -r m4 \
&& rm -f aclocal.m4 \
&& rm -f -r autom4te.cache \
&& rm -f compile \
&& rm -f config.guess \
&& rm -f config.log \
&& rm -f config.status \
&& rm -f config.sub \
&& rm -f configure \
&& rm -f depcomp \
&& rm -f src/config.h \
&& rm -f src/config.h.in \
&& rm -f install-sh \
&& rm -f -r libltdl \
&& rm -f libtool \
&& rm -f ltmain.sh \
&& rm -f Makefile \
&& rm -f Makefile.in \
&& rm -f missing \
&& rm -f src/*.la \
&& rm -f src/*.lo \
&& rm -f src/*.o \
&& rm -f src/sigar_version_autoconf.c \
&& rm -f -r src/.libs \
&& rm -f -r src/.deps \
&& rm -f src/os/Makefile \
&& rm -f src/os/Makefile.in \
&& rm -f src/os/*/Makefile \
&& rm -f src/os/*/Makefile.in \
&& rm -f src/os/*/*.la \
&& rm -f src/os/*/*.lo \
&& rm -f src/os/*/*.o \
&& rm -f -r src/os/*/.libs \
&& rm -f -r src/os/*/.deps \
&& rm -f src/Makefile \
&& rm -f src/Makefile.in \
&& rm -f src/stamp-h1 \
&& rm -f src/stamp-h1.in \
&& rm -f bindings/Makefile \
&& rm -f bindings/Makefile.in \
&& rm -f bindings/lua/Makefile \
&& rm -f bindings/*/Makefile.in \
&& rm -f -r bindings/*/.deps \
&& rm -f include/Makefile \
&& rm -f include/Makefile.in \
&& rm -f -r tests/.deps \
&& rm -f tests/Makefile \
&& rm -f tests/Makefile.in \
&& rm -f examples/Makefile \
&& rm -f examples/Makefile.in \
&& rm -f examples/*.o \
&& rm -f -r examples/.libs \
&& rm -f -r examples/.deps \
&& perl -le 's/\.c$// && unlink && print "rm $_" for <examples/*.c>'
-96
View File
@@ -1,96 +0,0 @@
#!/bin/sh
# Run this to generate all the initial makefiles, etc.
# LIBTOOLIZE=${LIBTOOLIZE:-libtoolize}
LIBTOOLIZE_FLAGS="--copy --force"
# ACLOCAL=${ACLOCAL:-aclocal}
# AUTOHEADER=${AUTOHEADER:-autoheader}
# AUTOMAKE=${AUTOMAKE:-automake}
AUTOMAKE_FLAGS="--add-missing --copy"
# AUTOCONF=${AUTOCONF:-autoconf}
ARGV0=$0
ARGS="$@"
run() {
echo "$ARGV0: running \`$@' $ARGS"
$@ $ARGS
}
## jump out if one of the programs returns 'false'
set -e
## on macosx glibtoolize, others have libtool
if test x$LIBTOOLIZE = x; then
if test \! "x`which glibtoolize 2> /dev/null | grep -v '^no'`" = x; then
LIBTOOLIZE=glibtoolize
elif test \! "x`which libtoolize-1.5 2> /dev/null | grep -v '^no'`" = x; then
LIBTOOLIZE=libtoolize-1.5
elif test \! "x`which libtoolize 2> /dev/null | grep -v '^no'`" = x; then
LIBTOOLIZE=libtoolize
else
echo "libtoolize 1.5.x wasn't found, exiting"; exit 0
fi
fi
## suse has aclocal and aclocal-1.9
if test x$ACLOCAL = x; then
if test \! "x`which aclocal-1.9 2> /dev/null | grep -v '^no'`" = x; then
ACLOCAL=aclocal-1.9
elif test \! "x`which aclocal19 2> /dev/null | grep -v '^no'`" = x; then
ACLOCAL=aclocal19
elif test \! "x`which aclocal 2> /dev/null | grep -v '^no'`" = x; then
ACLOCAL=aclocal
else
echo "automake 1.9.x (aclocal) wasn't found, exiting"; exit 0
fi
fi
if test x$AUTOMAKE = x; then
if test \! "x`which automake-1.9 2> /dev/null | grep -v '^no'`" = x; then
AUTOMAKE=automake-1.9
elif test \! "x`which automake19 2> /dev/null | grep -v '^no'`" = x; then
AUTOMAKE=automake19
elif test \! "x`which automake 2> /dev/null | grep -v '^no'`" = x; then
AUTOMAKE=automake
else
echo "automake 1.9.x wasn't found, exiting"; exit 0
fi
fi
## macosx has autoconf-2.59 and autoconf-2.60
if test x$AUTOCONF = x; then
if test \! "x`which autoconf-2.59 2> /dev/null | grep -v '^no'`" = x; then
AUTOCONF=autoconf-2.59
elif test \! "x`which autoconf259 2> /dev/null | grep -v '^no'`" = x; then
AUTOCONF=autoconf259
elif test \! "x`which autoconf 2> /dev/null | grep -v '^no'`" = x; then
AUTOCONF=autoconf
else
echo "autoconf 2.59+ wasn't found, exiting"; exit 0
fi
fi
if test x$AUTOHEADER = x; then
if test \! "x`which autoheader-2.59 2> /dev/null | grep -v '^no'`" = x; then
AUTOHEADER=autoheader-2.59
elif test \! "x`which autoheader259 2> /dev/null | grep -v '^no'`" = x; then
AUTOHEADER=autoheader259
elif test \! "x`which autoheader 2> /dev/null | grep -v '^no'`" = x; then
AUTOHEADER=autoheader
else
echo "autoconf 2.59+ (autoheader) wasn't found, exiting"; exit 0
fi
fi
run $LIBTOOLIZE $LIBTOOLIZE_FLAGS
run $ACLOCAL $ACLOCAL_FLAGS
# we don't need autoheader as we don't have a config.h
# run $AUTOHEADER
run $AUTOMAKE $AUTOMAKE_FLAGS
run $AUTOCONF
test "$ARGS" = "" && echo "Now type './configure --enable-maintainer-mode ...' and 'make' to compile."
-1
View File
@@ -1 +0,0 @@
SUBDIRS=lua
-301
View File
@@ -1,301 +0,0 @@
#
# Copyright (c) 2009 Hyperic, Inc.
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2009 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package SigarBuild;
use strict;
use Config;
use Exporter;
use File::Basename qw(basename);
use File::Copy qw(copy);
use File::Spec ();
use POSIX ();
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(cppflags ldflags libs os src inline_src version_file resource_file);
sub archname {
my $os = lc $^O;
my $vers = $Config{osvers};
my $arch = $Config{archname};
if ($os =~ /win32/) {
return 'x86-winnt';
}
elsif ($os =~ /linux/) {
if ($arch =~ /_64/) {
return 'amd64-linux';
}
else {
return 'x86-linux';
}
}
elsif ($os =~ /hpux/) {
if ($vers =~ /11\./) {
return 'pa-hpux-11';
}
}
elsif ($os =~ /aix/) {
return 'ppc-aix-5';
}
elsif ($os =~ /solaris/) {
if ($arch =~ /sun4/) {
return 'sparc-solaris';
}
elsif ($arch =~ /.86/) {
return 'x86-solaris';
}
}
elsif ($os =~ /darwin/) {
return 'universal-macosx';
}
elsif ($os =~ /freebsd/) {
if ($arch =~ /.86/) {
if($vers =~ /6\../ ) {
return 'x86-freebsd-6';
}
}
elsif ($arch =~ /amd64/) {
if ($vers =~ /6\../ ) {
return 'amd64-freebsd-6';
}
}
}
return '';
}
sub flags {
my $os = lc $^O;
my $is_win32 = 0;
my (@cppflags, @ldflags, @libs);
if ($os =~ /(win32)/) {
$os = $1;
$is_win32 = 1;
@cppflags = ('-DWIN32', '-D_CRT_SECURE_NO_DEPRECATE');
@libs = qw(kernel32 user32 advapi32 ws2_32 netapi32 shell32 pdh version comsupp wbemuuid);
}
elsif ($os =~ /(linux)/) {
$os = $1;
}
elsif ($os =~ /(hpux)/) {
$os = $1;
@libs = qw(nsl nm);
}
elsif ($os =~ /(aix)/) {
$os = $1;
@libs = qw(odm cfg perfstat);
}
elsif ($os =~ /(solaris)/) {
$os = $1;
@libs = qw(nsl socket kstat);
}
elsif ($os =~ /(darwin)/) {
$os = $1;
@cppflags = ('-DDARWIN');
@ldflags = ('-framework CoreServices', '-framework IOKit');
if (-e "/usr/local/libproc.h") {
push @cppflags, '-DDARWIN_HAS_LIBPROC_H';
}
}
elsif ($os =~ /bsd/) {
$os = 'darwin';
@libs = qw(kvm);
}
push @cppflags,
'-I../../include',
"-I../../src/os/$os";
unless ($is_win32) {
push @cppflags, '-U_FILE_OFFSET_BITS';
}
my(@src) = (<../../src/*.c>, <../../src/os/$os/*.c>, <../../src/os/$os/*.cpp>);
return {
is_win32 => $is_win32,
os => $os,
libs => \@libs,
cppflags => \@cppflags,
ldflags => \@ldflags,
src => \@src,
};
}
#perl -Mlib=.. -MSigarBuild -e cppflags
sub cppflags {
print join ' ', @{ flags()->{cppflags} };
}
sub ldflags {
print join ' ', @{ flags()->{ldflags} };
}
sub libs {
print join ' ', @{ flags()->{libs} };
}
sub os {
print flags()->{os};
}
sub src {
print join ' ', @{ flags()->{src} };
}
sub inline_src {
my $stdout = @_ ? 0 : 1;
my $flags = shift || flags();
my $src = $flags->{src};
my $dir = $flags->{build_dir} || $ARGV[0];
my(@files);
#unlink symlinks incase of nfs shared dir...
for my $file (grep { -l } <*.c>) {
unlink $file;
}
for my $file (@$src) {
my $cf = basename $file;
#sigar.c -> libsigar.c else
#sigar.o and perl Sigar.o clash on case insensitive filesystems
$cf = 'libsigar.c' if $cf eq 'sigar.c';
if ($dir) {
$cf = join '/', $dir, $cf;
$file = File::Spec->rel2abs($file);
}
push @files, $cf;
if ($flags->{is_win32}) {
copy($file, $cf);
}
else {
symlink($file, $cf) unless -e $cf;
}
}
if ($stdout) {
print join ' ', @files;
}
else {
return @files;
}
}
sub scm_revision {
my $rev;
$rev = `git rev-parse --short HEAD`;
if ($rev) {
chomp $rev;
}
else {
$rev = "exported";
}
return $rev;
}
sub build_date {
return POSIX::strftime("%m/%d/%Y %I:%M %p", localtime);
}
sub find_file {
my $file = shift;
for my $dir (qw(../.. .. .)) {
my $pfile = "$dir/$file";
return $pfile if -e $pfile;
}
return $file;
}
sub version_properties {
my $props = {};
my $file = $_[0] || find_file('version.properties');
open my $fh, $file or die "open $file: $!";
while (<$fh>) {
chomp;
my($key,$val) = split '=';
next unless $key and defined $val;
$props->{$key} = $val;
}
close $fh;
$props->{'scm.revision'} = scm_revision();
$props->{'build.date'} = build_date();
$props->{'version'} =
join '.', map $props->{"version.$_"}, qw(major minor maint);
$props->{'version.build'} = $ENV{BUILD_NUMBER} || '0';
$props->{'version.string'} =
join '.', $props->{'version'}, $props->{'version.build'};
return $props;
}
sub resource_file {
my(@args) = @_ ? @_ : @ARGV;
version_file(find_file("src/os/win32/sigar.rc.in"), "sigar.rc", @args);
}
sub version_file {
local $_;
my($source, $dest, %filters);
my(@args) = @_ ? @_ : @ARGV;
for (@args) {
if (/=/) {
my($key,$val) = split '=', $_, 2;
$filters{$key} = $val;
}
else {
if ($source) {
$dest = $_;
}
else {
$source = $_;
}
}
}
unless ($source) {
$dest = 'sigar_version.c';
$source = find_file("src/$dest.in");
}
my $props = version_properties();
while (my($key,$val) = each %$props) {
$key = uc $key;
$key =~ s/\./_/;
$filters{$key} = $val;
}
my $re = join '|', keys %filters;
open my $in, $source or die "open $source: $!";
my $out;
if ($dest) {
open $out, '>', $dest or die "open $dest: $!";
}
else {
$out = \*STDOUT;
}
while (<$in>) {
s/\@\@($re)\@\@/$filters{$1}/go;
print $out $_;
}
close $in;
close $out if $dest;
}
1;
__END__
+79 -251
View File
@@ -1,7 +1,6 @@
# #
# Copyright (c) 2007-2009 Hyperic, Inc. # Copyright (c) 2007-2008 Hyperic, Inc.
# Copyright (c) 2009 SpringSource, Inc. # Copyright (c) 2010 VMware, Inc.
# Copyright (c) 2009-2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -20,6 +19,7 @@
package SigarWrapper; package SigarWrapper;
use strict; use strict;
use Config;
use Cwd; use Cwd;
use Exporter; use Exporter;
use File::Path; use File::Path;
@@ -29,6 +29,57 @@ use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter); @ISA = qw(Exporter);
@EXPORT = qw(generate); @EXPORT = qw(generate);
sub archname {
my $os = lc $^O;
my $vers = $Config{osvers};
my $arch = $Config{archname};
if ($os =~ /win32/) {
return 'x86-winnt';
}
elsif ($os =~ /linux/) {
if ($arch =~ /_64/) {
return 'amd64-linux';
}
else {
return 'x86-linux';
}
}
elsif ($os =~ /hpux/) {
if ($vers =~ /11\./) {
return 'pa-hpux-11';
}
}
elsif ($os =~ /aix/) {
return 'ppc-aix-5';
}
elsif ($os =~ /solaris/) {
if ($arch =~ /sun4/) {
return 'sparc-solaris';
}
elsif ($arch =~ /.86/) {
return 'x86-solaris';
}
}
elsif ($os =~ /darwin/) {
return 'universal-macosx';
}
elsif ($os =~ /freebsd/) {
if($arch =~ /.86/) {
if($vers =~ /6\../ ) {
return 'x86-freebsd-6';
}
}
elsif( $arch =~ /amd64/) {
if($vers =~ /6\../ ) {
return 'amd64-freebsd-6';
}
}
}
return '';
}
my %platforms = ( my %platforms = (
A => "AIX", A => "AIX",
D => "Darwin", D => "Darwin",
@@ -47,7 +98,7 @@ my %has_name_arg = map { $_, 1 } qw(FileSystemUsage DiskUsage
my %proc_no_arg = map { $_, 1 } qw(stat); my %proc_no_arg = map { $_, 1 } qw(stat);
my %get_not_impl = map { $_, 1 } qw(net_address net_route net_connection net_stat cpu_perc my %get_not_impl = map { $_, 1 } qw(net_address net_route net_connection net_stat cpu_perc
arp who cpu_info file_system); #list funcs only who cpu_info file_system); #list funcs only
sub supported_platforms { sub supported_platforms {
my $p = shift; my $p = shift;
@@ -481,44 +532,34 @@ use vars qw(%classes %cmds);
{ {
name => 'vendor', type => 'String', name => 'vendor', type => 'String',
desc => 'CPU vendor id', desc => 'CPU vendor id',
plat => '*' plat => 'AFLHSW'
}, },
{ {
name => 'model', type => 'String', name => 'model', type => 'String',
desc => 'CPU model', desc => 'CPU model',
plat => '*' plat => 'AFLHSW'
}, },
{ {
name => 'mhz', type => 'Int', name => 'mhz', type => 'Int',
desc => 'Current CPU speed', desc => 'CPU speed',
plat => '*' plat => 'AFHLSW'
},
{
name => 'mhz_max', type => 'Int',
desc => 'Maximum CPU speed',
plat => 'DL'
},
{
name => 'mhz_min', type => 'Int',
desc => 'Maximum CPU speed',
plat => 'DL'
}, },
{ {
name => 'cache_size', type => 'Long', name => 'cache_size', type => 'Long',
desc => 'CPU cache size', desc => 'CPU cache size',
plat => 'ADL' plat => 'AL'
}, },
{ {
name => 'total_cores', type => 'Int', name => 'total_cores', type => 'Int',
desc => 'Total CPU cores (logical)', desc => 'Total CPU cores (logical)',
}, },
{ {
name => 'total_sockets', type => 'Int', name => 'total_sockets', type => 'Int',
desc => 'Total CPU sockets (physical)', desc => 'Total CPU sockets (physical)',
}, },
{ {
name => 'cores_per_socket', type => 'Int', name => 'cores_per_socket', type => 'Int',
desc => 'Number of CPU cores per CPU socket', desc => 'Number of CPU cores per CPU socket',
}, },
], ],
Uptime => [ Uptime => [
@@ -674,6 +715,14 @@ use vars qw(%classes %cmds);
], ],
DumpPidCache => [
{
name => 'dummy', type => 'Long',
desc => 'Dummy',
plat => 'LWAHS'
}
],
ProcState => [ ProcState => [
{ {
name => 'state', type => 'Char', name => 'state', type => 'Char',
@@ -1010,11 +1059,6 @@ use vars qw(%classes %cmds);
desc => '', desc => '',
plat => '' plat => ''
}, },
{
name => 'default_gateway_interface', type => 'String',
desc => '',
plat => ''
},
{ {
name => 'host_name', type => 'String', name => 'host_name', type => 'String',
desc => '', desc => '',
@@ -1119,18 +1163,6 @@ use vars qw(%classes %cmds);
desc => '', desc => '',
plat => '*' plat => '*'
}, },
{
name => 'address6', type => 'NetAddress',
desc => '',
},
{
name => 'prefix6_length', type => 'Int',
desc => '',
},
{
name => 'scope6', type => 'Int',
desc => '',
},
{ {
name => 'destination', type => 'NetAddress', name => 'destination', type => 'NetAddress',
desc => '', desc => '',
@@ -1161,11 +1193,6 @@ use vars qw(%classes %cmds);
desc => '', desc => '',
plat => 'DFL' plat => 'DFL'
}, },
{
name => 'tx_queue_len', type => 'Int',
desc => '',
plat => 'L'
},
], ],
NetInterfaceStat => [ NetInterfaceStat => [
{ {
@@ -1466,33 +1493,6 @@ use vars qw(%classes %cmds);
plat => '*' plat => '*'
}, },
], ],
Arp => [
{
name => 'ifname', type => 'String',
desc => '',
plat => '*'
},
{
name => 'hwaddr', type => 'NetAddress',
desc => '',
plat => '*'
},
{
name => 'type', type => 'String',
desc => '',
plat => '*'
},
{
name => 'address', type => 'NetAddress',
desc => '',
plat => '*'
},
{
name => 'flags', type => 'Long',
desc => '',
plat => '*'
},
],
Who => [ Who => [
{ {
name => 'user', type => 'String', name => 'user', type => 'String',
@@ -1697,13 +1697,6 @@ $comment
EOF EOF
} }
sub erl_warning_comment {
my $self = shift;
my $comment = $self->warning_comment;
$comment =~ s/^/% /mg;
"$comment\n";
}
sub generate { sub generate {
my($lang, $dir) = @_ ? @_ : @ARGV; my($lang, $dir) = @_ ? @_ : @ARGV;
@@ -1768,9 +1761,7 @@ sub uptodate {
return 1; return 1;
} }
my(%warning_comment) = my(%warning_comment) = map { $_ => \&c_warning_comment } qw(c h java);
((map { $_ => \&c_warning_comment } qw(c h java)),
(map { $_ => \&erl_warning_comment } qw(erl hrl)));
sub create { sub create {
my($self, $file) = @_; my($self, $file) = @_;
@@ -2172,8 +2163,8 @@ EOF
my $member = $field->{member} || $name; my $member = $field->{member} || $name;
my $desc = $field->{desc} || $name; my $desc = $field->{desc} || $name;
(my $jname = $name) =~ s/_(\w)/\u$1/g; (my $jname = $name) =~ s/_(\w)/\u$1/g;
my $getter = "get\u$jname"; my $getter = "get\u$jname";
$jname = jname($jname); $jname = jname($jname);
my $sig = qq("$field_types{$type}"); my $sig = qq("$field_types{$type}");
my $set = "JENV->Set${type}Field"; my $set = "JENV->Set${type}Field";
my $get = "JENV->Get${type}Field"; my $get = "JENV->Get${type}Field";
@@ -2431,7 +2422,7 @@ sub generate_class {
if ($func->{num_args} == 1) { if ($func->{num_args} == 1) {
my $arg_type; my $arg_type;
if ($func->{is_proc}) { if ($func->{is_proc}) {
$arg_type = 'OBJ2PID'; $arg_type = 'NUM2UINT';
} }
else { else {
$arg_type = 'StringValuePtr'; $arg_type = 'StringValuePtr';
@@ -2445,9 +2436,8 @@ static VALUE $ruby_class;
static VALUE rb_sigar_$cname($proto) static VALUE rb_sigar_$cname($proto)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
$func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL)); $func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL));
if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) { if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) {
@@ -2859,167 +2849,5 @@ sub finish {
$self->SUPER::finish; $self->SUPER::finish;
} }
package SigarWrapper::Erlang;
use vars qw(@ISA);
@ISA = qw(SigarWrapper);
my %field_types = (
Long => "esigar_encode_ulonglong",
Double => "esigar_encode_double",
Int => "esigar_encode_long",
Char => "esigar_encode_char",
String => "esigar_encode_string",
NetAddress => "esigar_encode_netaddr",
);
my $c_file = 'priv/gen/sigar_drv_gen.c';
my $h_file = 'priv/gen/sigar.hrl';
my $g_file = 'priv/gen/sigar_gen.hrl';
sub sources {
return $c_file;
}
sub start {
my $self = shift;
$self->SUPER::start;
$self->{cfh} = $self->create($c_file);
$self->{hfh} = $self->create($h_file);
$self->{gfh} = $self->create($g_file);
}
sub generate_class {
my($self, $func) = @_;
my $cfh = $self->{cfh};
my $cname = $func->{cname};
my $parse_args = "";
my $vars = "";
my $args = 'sigar';
if ($func->{num_args} == 1) {
if ($func->{is_proc}) {
$parse_args = 'pid = esigar_pid_get(sigar, bytes);';
$vars = "long $func->{arg};\n";
}
else {
$parse_args .= 'name = bytes;';
$vars = "char *$func->{arg};\n";
}
$args .= ", $func->{arg}";
}
my $encoder = "esigar_encode_$cname";
my $n = scalar @{ $func->{fields} };
print $cfh <<EOF;
static void $encoder(ei_x_buff *x,
$func->{sigar_type} *$cname)
{
ei_x_encode_list_header(x, $n);
EOF
for my $field (@{ $func->{fields} }) {
my $name = $field->{name};
my $type = $field_types{ $field->{type} };
print $cfh qq{ $type(x, "$name", $cname->$name);\n};
}
print $cfh " ei_x_encode_empty_list(x);\n}\n\n";
print $cfh <<EOF if $func->{has_get};
static int e$func->{sigar_function}(ErlDrvPort port, sigar_t *sigar, char *bytes)
{
int status;
ei_x_buff x;
$func->{sigar_type} $cname;
$vars
$parse_args
ESIGAR_NEW(&x);
if ((status = $func->{sigar_function}($args, &$cname)) == SIGAR_OK) {
ESIGAR_OK(&x);
$encoder(&x, &$cname);
ESIGAR_SEND(port, &x);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
return status;
}
EOF
}
my(@nongens) =
qw{net_interface_list net_route_list net_connection_list
file_system_list cpu_info_list arp_list who_list
loadavg};
sub finish {
my $self = shift;
my $mappings = $self->get_mappings;
my $cfh = $self->{cfh};
my $hfh = $self->{hfh};
my $gfh = $self->{gfh};
my $ncmd = 1;
for my $ngen (@nongens) {
my $cmd = uc $ngen;
print $cfh "#define ESIGAR_$cmd $ncmd\n";
print $hfh "-define($cmd, $ncmd).\n";
$ncmd++;
}
for my $func (@$mappings) {
next unless $func->{has_get};
my $name = $func->{cname};
my $cmd = uc $name;
my $nargs = 1 + $func->{num_args};
print $cfh "#define ESIGAR_$cmd $ncmd\n";
print $hfh "-define($cmd, $ncmd).\n";
print $hfh "-export([$name/$nargs]).\n";
$ncmd++;
}
print $cfh <<EOF;
static int esigar_dispatch(ErlDrvPort port, sigar_t *sigar, int cmd, char *bytes) {
switch (cmd) {
EOF
for my $func (@$mappings) {
next unless $func->{has_get};
my $name = $func->{cname};
my $cmd = uc $name;
my $arg = "";
if ($func->{num_args}) {
$arg = ", Arg";
}
print $gfh <<EOF;
$name({sigar, S}$arg) ->
do_command(S, ?$cmd$arg).
EOF
print $cfh <<EOF
case ESIGAR_$cmd:
return e$func->{sigar_function}(port, sigar, bytes);
EOF
}
print $cfh <<EOF;
default:
esigar_notimpl(port, sigar, cmd);
return SIGAR_ENOTIMPL;
}
}
EOF
$self->SUPER::finish;
}
1; 1;
__END__ __END__
-12
View File
@@ -1,12 +0,0 @@
all:
perl -Mlib=.. -MSigarWrapper -e generate Erlang .
cd src && make
cd c_src && make
shell:
make all
erl -pa ebin
clean:
cd src && make clean
cd c_src && make clean
-40
View File
@@ -1,40 +0,0 @@
## SIGAR driver for Erlang
If you're not already familar with sigar, have a look at the [SIGAR Wiki](http://sigar.hyperic.com).
Also helpful: **../../include/sigar.h**, **../*/examples** and
**../java/src/org/hyperic/sigar/cmd/** to get an idea of what you can do.
### Building
The other bindings/* inline the libsigar sources by default, haven't done that yet for erl.
So, you'll need a libsigar to link against, one of:
Ant build:
cd ../java ; ant
ln -s sigar-bin/lib/libsigar-amd64-linux.so sigar-lib/lib/libsigar.so
Or, download release binary created by the ant build:
curl -o priv/libsigar.so http://svn.hyperic.org/projects/sigar_bin/dist/SIGAR_1_6_2/lib/libsigar-amd64-linux.so
Or, top-level autotools build (WIP):
cd ../.. ; ./autogen.sh && ./configure && make install
Once you have a libsigar in place, just run **make** and have a look at the **examples/**.
Note that the majority of the driver code is generated by **../SigarWrapper.pm** and output to **priv/gen**.
### ToDo/Help Wanted
* Fill out the **examples/** - currently weaksauce in part due to me having just a few hours w/ Erlang
* Build system - doubt the current will work anywhere cept Linux
* EUnit
* Other stuff Erlangers know that I don't
-16
View File
@@ -1,16 +0,0 @@
GCC = gcc
OTP_ROOT = $(shell ./check_otp -root)
EI_ROOT = $(shell ./check_otp -ei)
EI_LIB = $(EI_ROOT)/lib
EI_INC = $(EI_ROOT)/include
SIGAR_LIB = ../../java/sigar-bin/lib
LDFLAGS = -shared -L${EI_LIB} -lei -lpthread -L${SIGAR_LIB} -L../priv -lsigar
SRCS = sigar_drv.c
OUTPUT = ../priv/sigar_drv.so
CFLAGS = -Wall -fPIC -I../../../include -I${OTP_ROOT}/usr/include -I${EI_INC} -o ${OUTPUT}
all:
${GCC} ${SRCS} ${LDFLAGS} ${CFLAGS}
clean:
rm -rf ${OUTPUT} ../priv/gen/*.c ../priv/gen/*.hrl
-17
View File
@@ -1,17 +0,0 @@
#!/bin/bash
#copied from jungerl
if [ "$1" == "-root" -o "$1" == "" ]; then
erl -noinput -eval 'io:format("~s~n", [code:root_dir()]), halt(0).'
fi
if [ "$1" == "-ei" -o "$1" == "" ]; then
erl -noinput -eval \
'case code:lib_dir("erl_interface") of
{error, bad_name} ->
io:format("not found~n", []),
halt(1);
LibDir ->
io:format("~s~n", [LibDir]),
halt(0)
end.'
fi
-439
View File
@@ -1,439 +0,0 @@
/*
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <erl_driver.h>
#include <ei.h>
#include <ctype.h>
#include <string.h>
#include "sigar.h"
#include "sigar_fileinfo.h"
#include "sigar_format.h"
#include "sigar_ptql.h"
typedef struct {
ErlDrvPort port;
sigar_t *sigar;
} sigar_drv_t;
static ErlDrvData start(ErlDrvPort port, char *cmd) {
sigar_drv_t *sd = (sigar_drv_t *)driver_alloc(sizeof(*sd));
int status;
status = sigar_open(&sd->sigar);
if (status != SIGAR_OK) {
sd->sigar = NULL;
driver_failure_posix(port, status);
}
sd->port = port;
return (ErlDrvData)sd;
}
static void stop(ErlDrvData handle) {
sigar_drv_t *driver_data = (sigar_drv_t *)handle;
if (driver_data->sigar) {
sigar_close(driver_data->sigar);
}
}
#ifdef SIGAR_64BIT
#define str2pid(value) strtoull(value, NULL, 10)
#else
#define str2pid(value) strtoul(value, NULL, 10)
#endif
static sigar_pid_t esigar_pid_get(sigar_t *sigar, char *pid)
{
if (isdigit(*pid)) {
return str2pid(pid);
}
else if ((*pid == '$') && (*(pid + 1) == '$')) {
return sigar_pid_get(sigar);
}
else {
/* XXX cache queries */
sigar_ptql_query_t *query;
sigar_ptql_error_t error;
int status =
sigar_ptql_query_create(&query, (char *)pid, &error);
if (status == SIGAR_OK) {
sigar_pid_t qpid;
status = sigar_ptql_query_find_process(sigar, query, &qpid);
sigar_ptql_query_destroy(query);
if (status == SIGAR_OK) {
return qpid;
}
}
}
return 0;
}
static void esigar_to_strlist(ei_x_buff *x,
char **data, unsigned long number)
{
unsigned long i;
ei_x_encode_list_header(x, number);
for (i=0; i<number; i++) {
ei_x_encode_string(x, data[i]);
}
ei_x_encode_empty_list(x);
}
typedef void (*esigar_encoder_func_t)(ei_x_buff *x, void *data);
static void esigar_to_list(ei_x_buff *x,
char *data, unsigned long number, int size,
esigar_encoder_func_t encoder)
{
unsigned long i;
ei_x_encode_list_header(x, number);
for (i=0; i<number; i++, data += size) {
encoder(x, data);
}
ei_x_encode_empty_list(x);
}
#define ESIGAR_NEW(x) \
ei_x_new_with_version(x)
#define ESIGAR_OK(x) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, "ok")
#define ESIGAR_ERROR(x, sigar, status) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, "error"); \
ei_x_encode_string(x, sigar_strerror(sigar, status))
#define ESIGAR_SEND(p, x) \
driver_output(port, (x)->buff, (x)->index); \
ei_x_free(x)
#define esigar_encode_long(x, k, v) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, k); \
ei_x_encode_long(x, v)
#define esigar_encode_ulonglong(x, k, v) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, k); \
ei_x_encode_ulonglong(x, v)
#define esigar_encode_char(x, k, v) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, k); \
ei_x_encode_char(x, v)
#define esigar_encode_string(x, k, v) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, k); \
ei_x_encode_string(x, v)
#define esigar_encode_double(x, k, v) \
ei_x_encode_tuple_header(x, 2); \
ei_x_encode_atom(x, k); \
ei_x_encode_double(x, v)
static void esigar_encode_net_address(ei_x_buff *x, const char *key,
sigar_net_address_t *address)
{
char buf[SIGAR_INET6_ADDRSTRLEN];
sigar_net_address_to_string(NULL, address, buf);
esigar_encode_string(x, key, buf);
}
#define esigar_encode_netaddr(x, k, v) \
esigar_encode_net_address(x, k, &v)
static void esigar_notimpl(ErlDrvPort port, sigar_t *sigar, int cmd)
{
ei_x_buff x;
ESIGAR_NEW(&x);
ESIGAR_ERROR(&x, sigar, SIGAR_ENOTIMPL);
ESIGAR_SEND(port, &x);
}
#include "../priv/gen/sigar_drv_gen.c"
static void esigar_loadavg_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_loadavg_t loadavg;
ESIGAR_NEW(&x);
if ((status = sigar_loadavg_get(sigar, &loadavg)) == SIGAR_OK) {
ESIGAR_OK(&x);
ei_x_encode_list_header(&x, 3);
ei_x_encode_double(&x, loadavg.loadavg[0]);
ei_x_encode_double(&x, loadavg.loadavg[1]);
ei_x_encode_double(&x, loadavg.loadavg[2]);
ei_x_encode_empty_list(&x);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_net_connection_list_get(ErlDrvPort port, sigar_t *sigar,
unsigned int flags)
{
int status;
ei_x_buff x;
sigar_net_connection_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_net_connection_list_get(sigar, &list, flags) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_list(&x,
(char *)&list.data[0], list.number,
sizeof(*list.data),
(esigar_encoder_func_t)esigar_encode_net_connection);
sigar_net_connection_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_net_interface_list_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_net_interface_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_net_interface_list_get(sigar, &list) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_strlist(&x, list.data, list.number);
sigar_net_interface_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_file_system_list_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_file_system_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_file_system_list_get(sigar, &list) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_list(&x,
(char *)&list.data[0], list.number,
sizeof(*list.data),
(esigar_encoder_func_t)esigar_encode_file_system);
sigar_file_system_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_net_route_list_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_net_route_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_net_route_list_get(sigar, &list) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_list(&x,
(char *)&list.data[0], list.number,
sizeof(*list.data),
(esigar_encoder_func_t)esigar_encode_net_route);
sigar_net_route_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_cpu_info_list_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_cpu_info_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_cpu_info_list_get(sigar, &list) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_list(&x,
(char *)&list.data[0], list.number,
sizeof(*list.data),
(esigar_encoder_func_t)esigar_encode_cpu_info);
sigar_cpu_info_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_arp_list_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_arp_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_arp_list_get(sigar, &list) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_list(&x,
(char *)&list.data[0], list.number,
sizeof(*list.data),
(esigar_encoder_func_t)esigar_encode_arp);
sigar_arp_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void esigar_who_list_get(ErlDrvPort port, sigar_t *sigar)
{
int status;
ei_x_buff x;
sigar_who_list_t list;
ei_x_new_with_version(&x);
if ((status = sigar_who_list_get(sigar, &list) == SIGAR_OK)) {
ESIGAR_OK(&x);
esigar_to_list(&x,
(char *)&list.data[0], list.number,
sizeof(*list.data),
(esigar_encoder_func_t)esigar_encode_who);
sigar_who_list_destroy(sigar, &list);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
ESIGAR_SEND(port, &x);
}
static void outputv(ErlDrvData handle, ErlIOVec *ev) {
sigar_drv_t *sd = (sigar_drv_t *)handle;
sigar_t *sigar = sd->sigar;
ErlDrvPort port = sd->port;
ErlDrvBinary *data = ev->binv[1];
int cmd = data->orig_bytes[0];
switch(cmd) {
case ESIGAR_NET_CONNECTION_LIST:
esigar_net_connection_list_get(port, sigar,
data->orig_bytes[1]);
break;
case ESIGAR_NET_INTERFACE_LIST:
esigar_net_interface_list_get(port, sigar);
break;
case ESIGAR_NET_ROUTE_LIST:
esigar_net_route_list_get(port, sigar);
break;
case ESIGAR_FILE_SYSTEM_LIST:
esigar_file_system_list_get(port, sigar);
break;
case ESIGAR_CPU_INFO_LIST:
esigar_cpu_info_list_get(port, sigar);
break;
case ESIGAR_ARP_LIST:
esigar_arp_list_get(port, sigar);
break;
case ESIGAR_WHO_LIST:
esigar_who_list_get(port, sigar);
break;
case ESIGAR_LOADAVG:
esigar_loadavg_get(port, sigar);
break;
default:
esigar_dispatch(port, sigar, cmd, &data->orig_bytes[1]);
break;
}
}
static ErlDrvEntry sigar_driver_entry = {
NULL, /* init */
start, /* startup */
stop, /* shutdown */
NULL, /* output */
NULL, /* ready_input */
NULL, /* ready_output */
"sigar_drv", /* name of the driver */
NULL, /* finish */
NULL, /* handle */
NULL, /* control */
NULL, /* timeout */
outputv, /* outputv */
NULL, /* ready_async */
NULL, /* flush */
NULL, /* call */
NULL, /* event */
ERL_DRV_EXTENDED_MARKER, /* ERL_DRV_EXTENDED_MARKER */
ERL_DRV_EXTENDED_MAJOR_VERSION, /* ERL_DRV_EXTENDED_MAJOR_VERSION */
ERL_DRV_EXTENDED_MAJOR_VERSION, /* ERL_DRV_EXTENDED_MINOR_VERSION */
ERL_DRV_FLAG_USE_PORT_LOCKING /* ERL_DRV_FLAGs */
};
DRIVER_INIT(sigar_driver) {
return &sigar_driver_entry;
}
-1
View File
@@ -1 +0,0 @@
*.beam
-32
View File
@@ -1,32 +0,0 @@
#!/usr/bin/env escript
%%! -pz ebin
%
% Copyright (c) 2010 VMware, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
{ok, List} = sigar:arp_list(S),
lists:map(
fun(Arp) ->
lists:map(
fun(K) ->
io:format("~s\t", [sigar:get_value(K, Arp)]) end,
[address, hwaddr, type, ifname]),
io:format("~n")
end, List),
sigar:stop(S).
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env escript
%
% Copyright (c) 2009 SpringSource, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
{ok, FsList} = sigar:file_system_list(S),
lists:map(
fun(Fs) ->
io:format("~s ~n", [sigar:get_value(dir_name, Fs)]) end,
FsList),
sigar:stop(S).
-40
View File
@@ -1,40 +0,0 @@
#!/usr/bin/env escript
%
% Copyright (c) 2009 SpringSource, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
{ok, Mem} = sigar:mem(S),
io:format("\tTotal\tUsed\tFree~n"),
io:format("Mem: "),
lists:map(
fun(K) ->
io:format("~w\t", [sigar:get_value(K, Mem)/1024]) end,
[total, used, free]),
io:format("~n"),
{ok, Swap} = sigar:swap(S),
io:format("Swap: "),
lists:map(
fun(K) ->
io:format("~w\t", [sigar:get_value(K, Swap)/1024]) end,
[total, used, free]),
io:format("~n"),
io:format("RAM: ~wMB~n", [sigar:get_value(ram, Mem)]),
sigar:stop(S).
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env escript
%
% Copyright (c) 2009 SpringSource, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
{ok, Names} = sigar:net_interface_list(S),
lists:map(
fun(K) ->
{ok, Ifconfig} = sigar:net_interface_config(S, K),
io:format("~s ~s~n", [K, sigar:get_value(address, Ifconfig)]) end,
Names),
sigar:stop(S).
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env escript
%
% Copyright (c) 2009 SpringSource, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
{ok, Mem} = sigar:proc_mem(S, "$$"),
io:format("Size\tResident~n"),
lists:map(
fun(K) ->
io:format("~w\t", [sigar:get_value(K, Mem)/1024]) end,
[size, resident]),
io:format("~n"),
sigar:stop(S).
-34
View File
@@ -1,34 +0,0 @@
#!/usr/bin/env escript
%
% Copyright (c) 2009 SpringSource, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
case sigar:loadavg(S) of
{ok, Avg} ->
lists:map(
fun(A) ->
io:format("~w% ", [A]) end,
Avg);
{error, Err} ->
Err
end,
io:format("~n"),
sigar:stop(S).
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env escript
%
% Copyright (c) 2009 SpringSource, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-include(sigar).
main(_) ->
{ok, S} = sigar:start(),
{ok, List} = sigar:who_list(S),
lists:map(
fun(Who) ->
lists:map(
fun(K) ->
io:format("~s\t", [sigar:get_value(K, Who)]) end,
[user, device, host]),
io:format("~n")
end, List),
sigar:stop(S).
-1
View File
@@ -1 +0,0 @@
*.so
-2
View File
@@ -1,2 +0,0 @@
*.c
*.hrl
-11
View File
@@ -1,11 +0,0 @@
ERLC=erlc
EBIN=../ebin
INCLUDE=../include
EFLAGS=-I ${INCLUDE} -o ${EBIN}
SRCS=`ls *.erl`
all:
${ERLC} ${EFLAGS} ${SRCS}
clean:
rm -rf ${EBIN}/*.beam
-108
View File
@@ -1,108 +0,0 @@
%
% Copyright (c) 2009 SpringSource, Inc.
% Copyright (c) 2010 VMware, Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
-module(sigar).
% generated by SigarWrapper.pm
-include("../priv/gen/sigar.hrl").
-export([start/0, stop/1, get_value/2]).
% handrolled wrappers
-export([loadavg/1,
net_connection_list/2,
net_interface_list/1,
net_route_list/1,
file_system_list/1,
cpu_info_list/1,
arp_list/1,
who_list/1]).
-define(NETCONN_CLIENT, 0x01).
-define(NETCONN_SERVER, 0x02).
-define(SIGAR_NETCONN_TCP, 0x10).
-define(SIGAR_NETCONN_UDP, 0x20).
-define(SIGAR_NETCONN_RAW, 0x40).
-define(SIGAR_NETCONN_UNIX, 0x80).
start() ->
case load_driver() of
ok ->
S = open_port({spawn, 'sigar_drv'}, [binary]),
{ok, {sigar, S}};
{error, Err} ->
Msg = erl_ddll:format_error(Err),
{error, Msg}
end.
% handrolled wrappers
loadavg({sigar, S}) ->
do_command(S, ?LOADAVG).
net_connection_list({sigar, S}, F) ->
do_command(S, ?NET_CONNECTION_LIST, F).
net_interface_list({sigar, S}) ->
do_command(S, ?NET_INTERFACE_LIST).
net_route_list({sigar, S}) ->
do_command(S, ?NET_ROUTE_LIST).
file_system_list({sigar, S}) ->
do_command(S, ?FILE_SYSTEM_LIST).
cpu_info_list({sigar, S}) ->
do_command(S, ?CPU_INFO_LIST).
arp_list({sigar, S}) ->
do_command(S, ?ARP_LIST).
who_list({sigar, S}) ->
do_command(S, ?WHO_LIST).
% generated by SigarWrapper.pm
-include("../priv/gen/sigar_gen.hrl").
% XXX must be a better way
get_value(Key, List) ->
case lists:keysearch(Key,1,List) of
false ->
1;
{ value, {Key, N} } ->
N
end.
stop({sigar, S}) ->
unlink(S),
port_close(S).
load_driver() ->
Dir = filename:join([filename:dirname(code:which(sigar)), "..", "priv"]),
erl_ddll:load(Dir, "sigar_drv").
do_command(S, C) ->
port_command(S, [C]),
receive
{S, {data, Bin}} -> binary_to_term(Bin)
end.
do_command(S, C, A) ->
port_command(S, [C, A]),
receive
{S, {data, Bin}} -> binary_to_term(Bin)
end.
+4 -6
View File
@@ -4,7 +4,7 @@
<project name="Sigar" default="build" basedir="."> <project name="Sigar" default="build" basedir=".">
<property file="../../version.properties"/> <property file="version.properties"/>
<property name="sigar.version" <property name="sigar.version"
value="${version.major}.${version.minor}.${version.maint}"/> value="${version.major}.${version.minor}.${version.maint}"/>
@@ -144,7 +144,7 @@
<antcall target="version-file"> <antcall target="version-file">
<param name="version.file" <param name="version.file"
value="src/org/hyperic/sigar/Version.java"/> value="src/org/hyperic/sigar/SigarVersion.java"/>
</antcall> </antcall>
<antcall target="version-file"> <antcall target="version-file">
@@ -346,11 +346,9 @@
<arg value="version"/> <arg value="version"/>
</java> </java>
<property name="junit.mx" value="-Dcom.sun.management.jmxremote"/>
<junit printsummary="yes" fork="yes" <junit printsummary="yes" fork="yes"
haltonfailure="yes" showoutput="true"> haltonfailure="yes" showoutput="true">
<jvmarg line="${junit.args} ${junit.mx}"/> <jvmarg line="${junit.args}"/>
<classpath refid="alljars"/> <classpath refid="alljars"/>
<formatter type="xml"/> <formatter type="xml"/>
@@ -499,7 +497,6 @@
<copy toDir="${dist.src}"> <copy toDir="${dist.src}">
<fileset dir="../.."> <fileset dir="../..">
<include name="version.properties"/>
<include name="include/*.h"/> <include name="include/*.h"/>
<include name="src/**/*.h"/> <include name="src/**/*.h"/>
<include name="src/**/*.c"/> <include name="src/**/*.c"/>
@@ -512,6 +509,7 @@
<include name="bindings/java/**/*.h"/> <include name="bindings/java/**/*.h"/>
<include name="bindings/java/**/*.pl"/> <include name="bindings/java/**/*.pl"/>
<include name="bindings/java/**/build.xml"/> <include name="bindings/java/**/build.xml"/>
<include name="bindings/java/version.properties"/>
<include name="bindings/java/.classpath"/> <include name="bindings/java/.classpath"/>
<include name="bindings/java/.project"/> <include name="bindings/java/.project"/>
<include name="bindings/java/.sigar_shellrc"/> <include name="bindings/java/.sigar_shellrc"/>
+2
View File
@@ -356,6 +356,8 @@
<compilerarg value="${uni.arch}"/> <compilerarg value="${uni.arch}"/>
<compilerarg value="-mmacosx-version-min=${osx.min}"/> <compilerarg value="-mmacosx-version-min=${osx.min}"/>
<sysincludepath location="/Developer/Headers/FlatCarbon"/>
<defineset> <defineset>
<define name="DARWIN"/> <define name="DARWIN"/>
<define name="DARWIN_HAS_LIBPROC_H" if="libproc.h"/> <define name="DARWIN_HAS_LIBPROC_H" if="libproc.h"/>
@@ -90,12 +90,8 @@ public class ArchNameTask extends Task {
if (ArchLoader.IS_DARWIN) { if (ArchLoader.IS_DARWIN) {
//default to most recent SDK //default to most recent SDK
//MacOSX10.3.9.sdk, MacOSX10.4u.sdk, MacOSX10.5.sdk,etc. //MacOSX10.3.9.sdk, MacOSX10.4u.sdk, MacOSX10.5.sdk,etc.
String sdkRoot = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs"; File[] sdks =
if (new File(sdkRoot).exists() == false) { new File("/Developer/SDKs").listFiles(new FileFilter() {
sdkRoot = "/Developer/SDKs";
}
File[] sdks =
new File(sdkRoot).listFiles(new FileFilter() {
public boolean accept(File file) { public boolean accept(File file) {
String name = file.getName(); String name = file.getName();
return return
@@ -103,7 +99,6 @@ public class ArchNameTask extends Task {
name.endsWith(".sdk"); name.endsWith(".sdk");
} }
}); });
if (sdks != null) { if (sdks != null) {
Arrays.sort(sdks); Arrays.sort(sdks);
String prop = "uni.sdk"; String prop = "uni.sdk";
+30 -47
View File
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2004-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc. * Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -666,6 +665,17 @@ JNIEXPORT jlongArray SIGAR_JNIx(getProcList)
return procarray; return procarray;
} }
jstring getProcArgStr(char *arg, JNIEnv *env) {
jstring s;
#ifdef WIN32
WCHAR warg[3000];
SIGAR_A2W(arg, warg, sizeof(warg));
s = JENV->NewString(env, (const jchar *)warg, wcslen(warg));
#else
s = JENV->NewStringUTF(env, arg);
#endif
return s;
}
JNIEXPORT jobjectArray SIGAR_JNIx(getProcArgs) JNIEXPORT jobjectArray SIGAR_JNIx(getProcArgs)
(JNIEnv *env, jobject sigar_obj, jlong pid) (JNIEnv *env, jobject sigar_obj, jlong pid)
@@ -685,8 +695,9 @@ JNIEXPORT jobjectArray SIGAR_JNIx(getProcArgs)
argsarray = JENV->NewObjectArray(env, procargs.number, stringclass, 0); argsarray = JENV->NewObjectArray(env, procargs.number, stringclass, 0);
SIGAR_CHEX; SIGAR_CHEX;
for (i=0; i<procargs.number; i++) { for (i=0; i<procargs.number; i++) {
jstring s = JENV->NewStringUTF(env, procargs.data[i]);
jstring s = getProcArgStr(procargs.data[i], env);
JENV->SetObjectArrayElement(env, argsarray, i, s); JENV->SetObjectArrayElement(env, argsarray, i, s);
SIGAR_CHEX; SIGAR_CHEX;
} }
@@ -898,13 +909,6 @@ JNIEXPORT jstring SIGAR_JNI(NetFlags_getIfFlagsString)
return JENV->NewStringUTF(env, buf); return JENV->NewStringUTF(env, buf);
} }
JNIEXPORT jstring SIGAR_JNI(NetFlags_getScopeString)
(JNIEnv *env, jclass cls, jint scope)
{
const char *buf = sigar_net_scope_to_string(scope);
return JENV->NewStringUTF(env, buf);
}
JNIEXPORT jobjectArray SIGAR_JNIx(getNetConnectionList) JNIEXPORT jobjectArray SIGAR_JNIx(getNetConnectionList)
(JNIEnv *env, jobject sigar_obj, jint flags) (JNIEnv *env, jobject sigar_obj, jint flags)
{ {
@@ -1068,37 +1072,6 @@ JNIEXPORT jstring SIGAR_JNI(NetConnection_getStateString)
sigar_net_connection_state_get(state)); sigar_net_connection_state_get(state));
} }
JNIEXPORT jobjectArray SIGAR_JNIx(getArpList)
(JNIEnv *env, jobject sigar_obj)
{
int status;
unsigned int i;
sigar_arp_list_t arplist;
jobjectArray arparray;
jclass cls = SIGAR_FIND_CLASS("Arp");
dSIGAR(NULL);
if ((status = sigar_arp_list_get(sigar, &arplist)) != SIGAR_OK) {
sigar_throw_error(env, jsigar, status);
return NULL;
}
JAVA_SIGAR_INIT_FIELDS_ARP(cls);
arparray = JENV->NewObjectArray(env, arplist.number, cls, 0);
for (i=0; i<arplist.number; i++) {
jobject info_obj = JENV->AllocObject(env, cls);
JAVA_SIGAR_SET_FIELDS_ARP(cls, info_obj,
arplist.data[i]);
JENV->SetObjectArrayElement(env, arparray, i, info_obj);
}
sigar_arp_list_destroy(sigar, &arplist);
return arparray;
}
JNIEXPORT jobjectArray SIGAR_JNIx(getWhoList) JNIEXPORT jobjectArray SIGAR_JNIx(getWhoList)
(JNIEnv *env, jobject sigar_obj) (JNIEnv *env, jobject sigar_obj)
{ {
@@ -1335,18 +1308,28 @@ JNIEXPORT jboolean SIGAR_JNI(ptql_SigarProcessQuery_match)
JNIEXPORT void SIGAR_JNI(ptql_SigarProcessQuery_create) JNIEXPORT void SIGAR_JNI(ptql_SigarProcessQuery_create)
(JNIEnv *env, jobject obj, jstring jptql) (JNIEnv *env, jobject obj, jstring jptql)
{ {
int status; int status;
jboolean is_copy; jboolean is_copy;
const char *ptql;
sigar_ptql_query_t *query; sigar_ptql_query_t *query;
sigar_ptql_error_t error; sigar_ptql_error_t error;
#ifdef WIN32
ptql = JENV->GetStringUTFChars(env, jptql, &is_copy); LPCTSTR ptql;
char ptql_ch[3000];
ptql = (LPCTSTR)JENV->GetStringChars(env, jptql, &is_copy);
SIGAR_W2A((LPCWSTR)ptql, ptql_ch, sizeof(ptql_ch));
status = sigar_ptql_query_create(&query, ptql_ch, &error);
if (is_copy) {
JENV->ReleaseStringChars(env, jptql, (const jchar *)ptql);
}
#else
const char *ptql;
ptql = JENV->GetStringUTFChars(env, jptql, &is_copy);
status = sigar_ptql_query_create(&query, (char *)ptql, &error); status = sigar_ptql_query_create(&query, (char *)ptql, &error);
if (is_copy) { if (is_copy) {
JENV->ReleaseStringUTFChars(env, jptql, ptql); JENV->ReleaseStringUTFChars(env, jptql, ptql);
} }
#endif
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
sigar_throw_ptql_malformed(env, error.message); sigar_throw_ptql_malformed(env, error.message);
} }
+29
View File
@@ -172,6 +172,34 @@ JNIEXPORT void SIGAR_JNI(win32_Pdh_pdhRemoveCounter)
} }
} }
JNIEXPORT void SIGAR_JNI(win32_Pdh_pdhCollectQueryDataOverSecond)
(JNIEnv *env, jclass cur, jlong query)
{
HQUERY h_query = (HQUERY)query;
PdhCollectQueryData(h_query);
Sleep(1000);
PdhCollectQueryData(h_query);
}
JNIEXPORT jdouble SIGAR_JNI(win32_Pdh_pdhGetFormattedValue)
(JNIEnv *env, jclass cur, jlong counter)
{
HCOUNTER h_counter = (HCOUNTER)counter;
PDH_STATUS status;
PDH_FMT_COUNTERVALUE fmt_value;
status = PdhGetFormattedCounterValue(h_counter,
PDH_FMT_DOUBLE,
(LPDWORD)NULL,
&fmt_value);
if (status != ERROR_SUCCESS) {
win32_throw_exception(env, get_error_message(status));
return 0;
}
return fmt_value.doubleValue;
}
JNIEXPORT jdouble SIGAR_JNI(win32_Pdh_pdhGetValue) JNIEXPORT jdouble SIGAR_JNI(win32_Pdh_pdhGetValue)
(JNIEnv *env, jclass cur, jlong query, jlong counter, jboolean fmt) (JNIEnv *env, jclass cur, jlong query, jlong counter, jboolean fmt)
{ {
@@ -353,6 +381,7 @@ JNIEXPORT jobjectArray SIGAR_JNI(win32_Pdh_pdhGetInstances)
return array; return array;
} }
JNIEXPORT jobjectArray SIGAR_JNI(win32_Pdh_pdhGetKeys) JNIEXPORT jobjectArray SIGAR_JNI(win32_Pdh_pdhGetKeys)
(JNIEnv *env, jclass cur, jstring cp) (JNIEnv *env, jclass cur, jstring cp)
{ {
@@ -1,52 +0,0 @@
/*
* Copyright (c) 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar;
import java.util.HashMap;
import java.util.Map;
/**
* Object wrapper of double[] Sigar.getLoadAverage() for use in bean patterns (JMX).
*/
public class LoadAverage {
private double[] average;
public LoadAverage(double[] average) {
this.average = average;
}
public double getOneMinute() {
return this.average[0];
}
public double getFiveMinute() {
return this.average[1];
}
public double getFifteenMinute() {
return this.average[2];
}
public Map toMap() {
Map map = new HashMap();
map.put("OneMinute", new Double(getOneMinute()));
map.put("FiveMinute", new Double(getFiveMinute()));
map.put("FifteenMinute", new Double(getFifteenMinute()));
return map;
}
}
@@ -16,6 +16,9 @@
package org.hyperic.sigar; package org.hyperic.sigar;
import java.util.HashMap;
import java.util.Map;
import org.hyperic.sigar.ptql.ProcessFinder; import org.hyperic.sigar.ptql.ProcessFinder;
/** /**
@@ -25,33 +28,64 @@ public class MultiProcCpu extends ProcCpu {
private long pid; private long pid;
private int nproc = 0; private int nproc = 0;
private static Map ptable = new HashMap();
static synchronized MultiProcCpu get(Sigar sigar, String query) static synchronized MultiProcCpu get(Sigar sigar, String query)
throws SigarException { throws SigarException {
MultiProcCpu cpu = new MultiProcCpu(); MultiProcCpu cpu;
cpu.pid = query.hashCode(); //for equals()
cpu = (MultiProcCpu)ptable.get(query);
if (cpu == null) {
cpu = new MultiProcCpu();
cpu.pid = query.hashCode(); //for equals()
ptable.put(query, cpu);
}
long timeNow = System.currentTimeMillis();
double diff = timeNow - cpu.lastTime;
if (diff == 0) {
return cpu; //we were just called within < 1 second ago.
}
cpu.lastTime = timeNow;
long otime = cpu.total;
cpu.total = 0; cpu.total = 0;
cpu.user = 0; cpu.user = 0;
cpu.sys = 0; cpu.sys = 0;
cpu.percent = 0.0D; cpu.nproc = 0;
long[] pids = ProcessFinder.find(sigar, query); long[] pids = ProcessFinder.find(sigar, query);
cpu.nproc = pids.length; cpu.nproc = pids.length;
for (int i=0; i<pids.length; i++) { for (int i=0; i<pids.length; i++) {
ProcTime time;
try { try {
ProcCpu procCpu = sigar.getProcCpu(pids[i]); time = sigar.getProcTime(pids[i]);
cpu.total += procCpu.getTotal();
cpu.user += procCpu.getUser();
cpu.sys += procCpu.getSys();
cpu.percent += procCpu.getPercent();
} catch (SigarException e) { } catch (SigarException e) {
//process may have gone away or EPERM //process may have gone away or EPERM
continue; continue;
} }
cpu.total += time.total;
cpu.user += time.user;
cpu.sys += time.sys;
}
if (otime == 0) {
//XXX could/should pause first time called.
return cpu;
}
cpu.percent = ((cpu.total - otime) / diff);
if (cpu.percent < 0.0) {
//counter wrapped
cpu.percent = (0.0 - cpu.percent);
}
if (cpu.percent >= 1.0) {
cpu.percent = 0.99;
} }
return cpu; return cpu;
@@ -1,7 +1,5 @@
/* /*
* Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -97,16 +95,6 @@ public class NetFlags {
public final static int IFF_SLAVE = 0x1000; public final static int IFF_SLAVE = 0x1000;
/**
* Master of a load balancer
*/
public static final int IFF_MASTER = 0x2000;
/**
* Dialup device with changing addresses
*/
public static final int IFF_DYNAMIC = 0x4000;
public static final int RTF_UP = 0x1; public static final int RTF_UP = 0x1;
public static final int RTF_GATEWAY = 0x2; public static final int RTF_GATEWAY = 0x2;
@@ -167,13 +155,6 @@ public class NetFlags {
*/ */
public static native String getIfFlagsString(long flags); public static native String getIfFlagsString(long flags);
/**
* @param network interface ipv6 address scope.
* @return String representation of ipv6 address scope.
* @see org.hyperic.sigar.NetInterfaceConfig#getScope6
*/
public static native String getScopeString(int scope);
public static boolean isAnyAddress(String address) { public static boolean isAnyAddress(String address) {
return return
(address == null) || (address == null) ||
+9 -21
View File
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2006-2009 Hyperic, Inc. * Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -49,7 +48,7 @@ public class Sigar implements SigarProxy {
* The Sigar java version. * The Sigar java version.
*/ */
public static final String VERSION_STRING = public static final String VERSION_STRING =
Version.VERSION_STRING; SigarVersion.VERSION_STRING;
/** /**
* The Sigar native version. * The Sigar native version.
@@ -60,7 +59,7 @@ public class Sigar implements SigarProxy {
* The scm (svn) revision from which sigar.jar was built. * The scm (svn) revision from which sigar.jar was built.
*/ */
public static final String SCM_REVISION = public static final String SCM_REVISION =
Version.SCM_REVISION; SigarVersion.SCM_REVISION;
/** /**
* The scm (svn) revision from which the sigar native binary was built. * The scm (svn) revision from which the sigar native binary was built.
@@ -71,7 +70,7 @@ public class Sigar implements SigarProxy {
* The date on which sigar.jar was built. * The date on which sigar.jar was built.
*/ */
public static final String BUILD_DATE = public static final String BUILD_DATE =
Version.BUILD_DATE; SigarVersion.BUILD_DATE;
/** /**
* The date on which the sigar native binary was built. * The date on which the sigar native binary was built.
@@ -157,19 +156,15 @@ public class Sigar implements SigarProxy {
} }
private static void loadLibrary() throws SigarException { private static void loadLibrary() throws SigarException {
if (SigarLoader.IS_WIN32 && try {
System.getProperty("os.version").equals("4.0")) if (SigarLoader.IS_WIN32 &&
{ System.getProperty("os.version").equals("4.0"))
try { {
//NT 4.0 only
String lib = String lib =
loader.findJarPath("pdh.dll") + loader.findJarPath("pdh.dll") +
File.separator + "pdh.dll"; File.separator + "pdh.dll";
loader.systemLoad(lib); loader.systemLoad(lib);
} catch (Exception e) {} }
}
try {
loader.load(); loader.load();
} catch (ArchNotSupportedException e) { } catch (ArchNotSupportedException e) {
throw new SigarException(e.getMessage()); throw new SigarException(e.getMessage());
@@ -860,9 +855,6 @@ public class Sigar implements SigarProxy {
return netstat; return netstat;
} }
public native Arp[] getArpList()
throws SigarException;
public native Who[] getWhoList() public native Who[] getWhoList()
throws SigarException; throws SigarException;
@@ -1014,10 +1006,6 @@ public class Sigar implements SigarProxy {
*/ */
public native String getFQDN() throws SigarException; public native String getFQDN() throws SigarException;
public SigarVersion getSigarVersion() {
return new SigarVersion();
}
/** /**
* Enabling logging in the native Sigar code. * Enabling logging in the native Sigar code.
* This method will hook log4j into the Sigar * This method will hook log4j into the Sigar
@@ -94,7 +94,7 @@ public class SigarInvoker {
this.sigarProxy = proxy; this.sigarProxy = proxy;
} }
public void setType(String val) { protected void setType(String val) {
String alias = (String)compatTypes.get(val); String alias = (String)compatTypes.get(val);
if (alias != null) { if (alias != null) {
val = alias; val = alias;
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2006-2007, 2009 Hyperic, Inc. * Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009 SpringSource, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -183,7 +183,5 @@ public interface SigarProxy {
public NetInfo getNetInfo() throws SigarException; public NetInfo getNetInfo() throws SigarException;
public SigarVersion getSigarVersion();
public String getFQDN() throws SigarException; public String getFQDN() throws SigarException;
} }
@@ -1,69 +0,0 @@
/*
* Copyright (c) 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar;
public class SigarVersion {
/**
* @return Version number of the Java sigar.jar library
*/
public String getJarVersion() {
return Sigar.VERSION_STRING;
}
/**
* @return Version number of the native sigar library
*/
public String getNativeVersion() {
return Sigar.NATIVE_VERSION_STRING;
}
/**
* @return Build date of the Java sigar.jar library
*/
public String getJarBuildDate() {
return Sigar.BUILD_DATE;
}
/**
* @return Build date of the native sigar library
*/
public String getNativeBuildDate() {
return Sigar.NATIVE_BUILD_DATE;
}
/**
* @return Source code revision of the Java sigar.jar library
*/
public String getJarSourceRevision() {
return Sigar.SCM_REVISION;
}
/**
* @return Source code revision of the native sigar library
*/
public String getNativeSourceRevision() {
return Sigar.NATIVE_SCM_REVISION;
}
/**
* @return Name of the loaded native sigar library file
*/
public String getNativeLibraryName() {
return SigarLoader.getNativeLibraryName();
}
}
@@ -1,6 +1,6 @@
package org.hyperic.sigar; package org.hyperic.sigar;
class Version { class SigarVersion {
static final String BUILD_DATE = "@@BUILD_DATE@@"; static final String BUILD_DATE = "@@BUILD_DATE@@";
@@ -1,52 +0,0 @@
/*
* Copyright (c) 2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.cmd;
import org.hyperic.sigar.SigarException;
public class Arp extends SigarCommandBase {
public Arp(Shell shell) {
super(shell);
}
public Arp() {
super();
}
public String getUsageShort() {
return "Display system ARP cache";
}
//arp -an
public void output(String[] args) throws SigarException {
org.hyperic.sigar.Arp[] entries = this.sigar.getArpList();
for (int i=0; i<entries.length; i++) {
org.hyperic.sigar.Arp arp = entries[i];
String host = "?"; //XXX
println(host + " " +
"(" + arp.getAddress() + ")" + " at " +
arp.getHwaddr() + " " +
"[" + arp.getType() + "]" + " on " +
arp.getIfname());
}
}
public static void main(String[] args) throws Exception {
new Arp().processCommand(args);
}
}
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2006 Hyperic, Inc. * Copyright (c) 2006 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -116,13 +115,6 @@ public class Ifconfig extends SigarCommandBase {
bcast + bcast +
" Mask:" + ifconfig.getNetmask()); " Mask:" + ifconfig.getNetmask());
if (ifconfig.getPrefix6Length() != 0) {
println("\t" +
"inet6 addr: " + ifconfig.getAddress6() + "/" +
ifconfig.getPrefix6Length() +
" Scope:" + NetFlags.getScopeString(ifconfig.getScope6()));
}
println("\t" + println("\t" +
NetFlags.getIfFlagsString(flags) + NetFlags.getIfFlagsString(flags) +
" MTU:" + ifconfig.getMtu() + " MTU:" + ifconfig.getMtu() +
@@ -1,169 +0,0 @@
/*
* Copyright (c) 2008-2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* 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.sigar.cmd;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.jmx.SigarProcess;
public class Mx extends SigarCommandBase {
private ObjectName registryName;
public Mx(Shell shell) {
super(shell);
}
public Mx() {
super();
}
//java -Dcom.sun.management.jmxremote -jar sigar.jar
public String getUsageShort() {
return "Register MBeans for use via jconsole, etc.";
}
protected boolean validateArgs(String[] args) {
return args.length <= 1;
}
public static MBeanServer getMBeanServer()
throws SigarException {
List servers =
MBeanServerFactory.findMBeanServer(null);
if (servers.size() == 0) {
throw new SigarException("No MBeanServers available");
}
else {
return (MBeanServer)servers.get(0);
}
}
private void register(MBeanServer server) throws SigarException {
if (this.registryName != null) {
return;
}
try {
String name = org.hyperic.sigar.jmx.SigarRegistry.class.getName();
this.registryName = server.createMBean(name, null).getObjectName();
SigarProcess proc = new SigarProcess(this.sigar);
ObjectName pname = new ObjectName(proc.getObjectName());
if (!server.isRegistered(pname)) {
server.registerMBean(proc, pname);
}
} catch (Exception e) {
e.printStackTrace();
throw new SigarException(e.getMessage());
}
}
private void jconsole() {
String pid = String.valueOf(this.sigar.getPid());
String[] argv = { "jconsole", pid };
println("exec(jconsole, " + pid + ")");
try {
Process p = Runtime.getRuntime().exec(argv);
p.waitFor();
println("jconsole exited");
} catch (Exception e) {
println(e.getMessage());
}
}
public void output(String[] args) throws SigarException {
MBeanServer server = getMBeanServer();
register(server);
boolean hasQuery = false;
boolean launchJconsole = false;
String query = "sigar:*";
for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.equals("-jconsole")) {
launchJconsole = true;
}
else {
query = arg;
hasQuery = true;
}
}
try {
Set beans =
server.queryNames(new ObjectName(query), null);
println(beans.size() + " MBeans are registered...");
for (Iterator it=beans.iterator(); it.hasNext();) {
ObjectName name = (ObjectName)it.next();
if (hasQuery) {
MBeanInfo info = server.getMBeanInfo(name);
MBeanAttributeInfo[] attrs = info.getAttributes();
for (int i=0; i<attrs.length; i++) {
String attr = attrs[i].getName();
Object val = server.getAttribute(name, attr);
println(name + ":" + attr + "=" + val);
}
}
else {
println(name.toString());
}
}
} catch (Exception e) {
throw new SigarException(e.getMessage());
}
if (launchJconsole) {
flush();
jconsole();
try { //test unregisterMBean
server.unregisterMBean(this.registryName);
this.registryName = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
new Mx().processCommand(args);
}
}
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2009 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -61,8 +60,7 @@ public class NetInfo extends SigarCommandBase {
info.getDomainName()); info.getDomainName());
println("default gateway......." + println("default gateway......." +
info.getDefaultGateway() + info.getDefaultGateway());
" (" + info.getDefaultGatewayInterface() + ")");
println("primary dns..........." + println("primary dns..........." +
info.getPrimaryDns()); info.getPrimaryDns());
@@ -76,7 +76,6 @@ public class Shell extends ShellBase {
} }
public void registerCommands() throws ShellCommandInitException { public void registerCommands() throws ShellCommandInitException {
registerCommandHandler("arp", new Arp(this));
registerCommandHandler("df", new Df(this)); registerCommandHandler("df", new Df(this));
registerCommandHandler("du", new Du(this)); registerCommandHandler("du", new Du(this));
registerCommandHandler("ls", new Ls(this)); registerCommandHandler("ls", new Ls(this));
@@ -114,10 +113,6 @@ public class Shell extends ShellBase {
registerCommandHandler("test", "org.hyperic.sigar.test.SigarTestRunner"); registerCommandHandler("test", "org.hyperic.sigar.test.SigarTestRunner");
} catch (NoClassDefFoundError e) { } } catch (NoClassDefFoundError e) { }
catch (Exception e) { } catch (Exception e) { }
try {
//requires jre 1.5+ or mx4j
registerCommandHandler("mx", new Mx(this));
} catch (NoClassDefFoundError e) { }
} }
private void registerCommandHandler(String name, String className) throws Exception { private void registerCommandHandler(String name, String className) throws Exception {
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007-2009 Hyperic, Inc. * Copyright (c) 2007, 2009 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,13 +20,17 @@ 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.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanRegistration; import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/** /**
* Base class for all Sigar JMX MBeans. Provides a skeleton which handles * Base class for all Sigar JMX MBeans. Provides a skeleton which handles
@@ -39,10 +43,24 @@ import org.hyperic.sigar.SigarProxy;
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public abstract class AbstractMBean implements DynamicMBean { public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME; protected static final String MBEAN_ATTR_TYPE = "type";
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
protected static final short CACHED_30SEC = 0;
protected static final short CACHED_5SEC = 1;
protected static final short CACHED_500MS = 2;
protected static final short CACHELESS = 3;
protected static final short DEFAULT = CACHED_30SEC;
/**
* The Sigar implementation to be used to fetch information from the system.
*/
protected final Sigar sigarImpl;
/** /**
* The Sigar proxy cache to be used in case the data does not have to be * The Sigar proxy cache to be used in case the data does not have to be
@@ -55,13 +73,69 @@ public abstract class AbstractMBean implements DynamicMBean {
protected final SigarProxy sigar; protected final SigarProxy sigar;
/** /**
* <p>Creates a new instance of this class. The SigarProxy instance is stored (and * The MBean server this MBean is registered to. Set during the MBean's
* accessible) via the {@link #sigar} member. * registration to the MBean server and unset to <code>null</code> when
* the deregistration finished.
* *
* @param sigar The SigarProxy instance to use. Must not be <code>null</code> * @see #preRegister(MBeanServer, ObjectName)
* @see #postDeregister()
*/ */
protected AbstractMBean(SigarProxy sigar) { protected MBeanServer mbeanServer;
this.sigar = sigar;
/**
* <p>Creates a new instance of this class. The Sigar instance is stored (and
* accessible) via the {@link #sigarImpl} member. A second instance is
* stored within the {@link #sigar} member which is either {@link #sigarImpl}
* or an instance of {@link SigarProxyCache} with the expiration time set to
* whatever the <code>cacheMode</code> parameter specifies.</p>
*
* <p>The following cache modes exist:</p>
*
* <table border = "1">
* <tr><td><b>Constant</b></td><td><b>Description</b></td></tr>
* <tr><td>{@link #CACHELESS}</td><td>No cached instance, {@link #sigar}
* <code>==</code> {@link #sigarImpl}.</td></tr>
* <tr><td>{@link #CACHED_500MS}</td><td>500 millisecond cache, for high
* frequency queries on raw data such as reading out CPU timers each
* second. Avoids reading out multiple data sets when all attributes of
* an MBean are queried in short sequence.</td></tr>
* <tr><td>{@link #CACHED_5SEC}</td><td>5 second cache, for high frequency
* queries on calculated data such as CPU percentages.</td></tr>
* <tr><td>{@link #CACHED_30SEC}</td><td>30 second cache, for normal queries
* or data readouts such as CPU model / vendor. This is the default if
* nothing (<code>0</code>) is specified.</td></tr>
* <tr><td>{@link #DEFAULT}</td><td>Same as {@link #CACHED_30SEC}.</td></tr>
* </table>
*
* <p><b>Note:</b> Only make use of the cacheless or half second mode if you
* know what you are doing. They may have impact on system performance if
* used excessively.</p>
*
* @param sigar The Sigar impl to use. Must not be <code>null</code>
* @param cacheMode The cache mode to use for {@link #sigar} or {@link #CACHELESS}
* if no separate, cached instance is to be maintained.
*/
protected AbstractMBean(Sigar sigar, short cacheMode) {
// store Sigar
this.sigarImpl = sigar;
// create a cached instance as well
if (cacheMode == CACHELESS) {
// no cached version
this.sigar = this.sigarImpl;
} else if (cacheMode == CACHED_500MS) {
// 500ms cached version (for 1/sec queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 500);
} else if (cacheMode == CACHED_5SEC) {
// 5sec cached version (for avg'd queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 5000);
} else /* if (cacheMode == CACHED_30SEC) */{
// 30sec (default) cached version (for info and long term queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 30000);
}
} }
/** /**
@@ -126,19 +200,67 @@ public abstract class AbstractMBean implements DynamicMBean {
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) {
// ignore, as we cannot throw this exception
} catch (MBeanException e) {
// ignore, as we cannot throw this exception
} catch (ReflectionException e) {
// ignore, as we cannot throw this exception
} }
} }
return result; return result;
} }
public void setAttribute(Attribute attr) throws AttributeNotFoundException { // -------
throw new AttributeNotFoundException(attr.getName()); // Implementation of the MBeanRegistration interface
// -------
/**
* <p>Returns <code>new ObjectName(this.getObjectName())</code> to guarantee
* a reliable and reproducable object name.</p>
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#preRegister(MBeanServer, ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
this.mbeanServer = server;
return new ObjectName(getObjectName());
} }
public Object invoke(String name, Object[] params, String[] signature) /**
throws ReflectionException { * Empty implementation, allowing aubclasses to ignore the interface.
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#postRegister(Boolean)
*/
public void postRegister(Boolean success) {
}
throw new ReflectionException(new NoSuchMethodException(name), /**
name); * Empty implementation, allowing aubclasses to ignore the interface.
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#preDeregister()
*/
public void preDeregister() throws Exception {
}
/**
* Empty implementation, allowing aubclasses to ignore the interface.
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#postDeregister()
*/
public void postDeregister() {
this.mbeanServer = null;
} }
} }
@@ -1,223 +0,0 @@
/*
* Copyright (c) 2008-2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* 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.sigar.jmx;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.SigarProxy;
public class ReflectedMBean extends AbstractMBean {
private Map methods;
private Map attrs = new HashMap();
private String type;
private String name;
private SigarInvokerJMX invoker;
protected String getType() {
return this.type;
}
void setType(String type) {
this.type = type;
}
//static attributes
void putAttribute(String name, Object val) {
this.attrs.put(name, val);
}
void putAttributes(Map attrs) {
this.attrs.putAll(attrs);
}
void putAttributes(Object obj) {
Method[] methods = obj.getClass().getDeclaredMethods();
for (int i=0; i<methods.length; i++) {
Method method = methods[i];
if (method.getParameterTypes().length != 0) {
continue;
}
String name = method.getName();
if (!name.startsWith("get")) {
continue;
}
name = name.substring(3);
try {
putAttribute(name,
method.invoke(obj, new Object[0]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String getMBeanClassName() {
String type = getType();
final String list = "List";
if (type.endsWith(list)) {
type =
type.substring(0, type.length() - list.length());
}
return "org.hyperic.sigar." + type;
}
private Class getMBeanClass() {
try {
return Class.forName(getMBeanClassName());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected ReflectedMBean(SigarProxy sigar, String type) {
super(sigar);
this.type = type;
this.name =
MBEAN_DOMAIN + ":" +
MBEAN_ATTR_TYPE + "=" + getType();
}
protected ReflectedMBean(SigarProxy sigar, String type, String arg) {
this(sigar, type);
this.name += ",Name=" + encode(arg);
}
private String encode(String arg) {
return arg.replaceAll(":", "%3A");
}
public String getObjectName() {
return this.name;
}
protected SigarInvokerJMX getInvoker() {
if (this.invoker == null) {
this.invoker =
SigarInvokerJMX.getInstance(this.sigar, getObjectName());
this.invoker.setType(getType());
}
return this.invoker;
}
public Object getAttribute(String name)
throws AttributeNotFoundException,
MBeanException, ReflectionException {
Object val = this.attrs.get(name);
if (val != null) {
return val;
}
try {
return getInvoker().invoke(name);
} catch (Exception e) {
e.printStackTrace();
throw new ReflectionException(e);
}
}
private Map getMethods() {
if (this.methods != null) {
return this.methods;
}
this.methods = new LinkedHashMap();
Method[] methods = getMBeanClass().getDeclaredMethods();
for (int i=0; i<methods.length; i++) {
String name = methods[i].getName();
if (!name.startsWith("get")) {
continue;
}
name = name.substring(3);
this.methods.put(name, methods[i]);
}
return this.methods;
}
protected MBeanAttributeInfo[] getAttributeInfo() {
Map methods = getMethods();
MBeanAttributeInfo[] attrs =
new MBeanAttributeInfo[methods.size() + this.attrs.size()];
int i=0;
for (Iterator it=methods.entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
String name = (String)entry.getKey();
Method method = (Method)entry.getValue();
attrs[i++] =
new MBeanAttributeInfo(name,
method.getReturnType().getName(),
name + " MBean",
true, // isReadable
false, // isWritable
false); // isIs
}
for (Iterator it=this.attrs.entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
String name = (String)entry.getKey();
Object obj = entry.getValue();
attrs[i++] =
new MBeanAttributeInfo(name,
obj.getClass().getName(),
name + " MBean",
true, // isReadable
false, // isWritable
false); // isIs
}
return attrs;
}
public MBeanInfo getMBeanInfo() {
MBeanInfo info =
new MBeanInfo(getClass().getName(),
getMBeanClassName(),
getAttributeInfo(),
null, //constructors
null, //operations
null); //notifications
return info;
}
}
@@ -0,0 +1,332 @@
/*
* Copyright (c) 2007, 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Sigar JMX MBean implementation for the <code>Cpu</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarCpu extends AbstractMBean {
private static final String MBEAN_TYPE = "CpuList";
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX;
private static final MBeanAttributeInfo MBEAN_ATTR_IDLE;
private static final MBeanAttributeInfo MBEAN_ATTR_NICE;
private static final MBeanAttributeInfo MBEAN_ATTR_SYS;
private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL;
private static final MBeanAttributeInfo MBEAN_ATTR_USER;
private static final MBeanAttributeInfo MBEAN_ATTR_WAIT;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_CPUINDEX;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int",
"The index of the CPU, typically starting at 0", true, false,
false);
MBEAN_ATTR_IDLE = new MBeanAttributeInfo("Idle", "long",
"The idle time of the CPU, in [ms]", true, false, false);
MBEAN_ATTR_NICE = new MBeanAttributeInfo("Nice", "long",
"The time of the CPU spent on nice priority, in [ms]", true,
false, false);
MBEAN_ATTR_SYS = new MBeanAttributeInfo("Sys", "long",
"The time of the CPU used by the system, in [ms]", true, false,
false);
MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long",
"The total time of the CPU, in [ms]", true, false, false);
MBEAN_ATTR_USER = new MBeanAttributeInfo("User", "long",
"The time of the CPU used by user processes, in [ms]", true,
false, false);
MBEAN_ATTR_WAIT = new MBeanAttributeInfo("Wait", "long",
"The time the CPU had to wait for data to be loaded, in [ms]",
true, false, false);
MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int",
"The index of the CPU to read data for. Must be >= 0 "
+ "and not exceed the CPU count of the system");
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpu.class
.getName(),
"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.",
new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX });
MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo(
SigarCpu.class.getName(),
"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 range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR,
MBEAN_PARAM_CPUINDEX });
MBEAN_INFO = new MBeanInfo(
SigarCpu.class.getName(),
"Sigar CPU MBean. Provides raw timing data for a single "
+ "CPU. The data is cached for 500ms, meaning each request "
+ "(and as a result each block request to all parameters) "
+ "within half a second is satisfied from the same dataset.",
new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX,
MBEAN_ATTR_IDLE, MBEAN_ATTR_NICE, MBEAN_ATTR_SYS,
MBEAN_ATTR_TOTAL, MBEAN_ATTR_USER, MBEAN_ATTR_WAIT },
new MBeanConstructorInfo[] { MBEAN_CONSTR_CPUINDEX,
MBEAN_CONSTR_CPUINDEX_SIGAR }, null, null);
}
/**
* Index of the CPU processed by the instance.
*/
private final int cpuIndex;
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
private final String objectName;
/**
* 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.
*
* @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.
*
* @throws IllegalArgumentException
* If the CPU index is out of range or an unexpected Sigar error
* occurs.
*/
public SigarCpu(int cpuIndex) throws IllegalArgumentException {
this(new Sigar(), cpuIndex);
}
/**
* 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
* range.
*
* @param sigar
* The Sigar instance to use to fetch data from
* @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.
*
* @throws IllegalArgumentException
* If the CPU index is out of range or an unexpected Sigar error
* occurs
*/
public SigarCpu(Sigar sigar, int cpuIndex) throws IllegalArgumentException {
super(sigar, CACHED_500MS);
// check index
if (cpuIndex < 0)
throw new IllegalArgumentException(
"CPU index has to be non-negative: " + cpuIndex);
try {
int cpuCount;
if ((cpuCount = sigar.getCpuList().length) < cpuIndex)
throw new IllegalArgumentException(
"CPU index out of range (found " + cpuCount
+ " CPU(s)): " + cpuIndex);
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
// all fine
this.cpuIndex = cpuIndex;
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=Cpu,"
+ MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase()
+ MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex;
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The index of the CPU, typically starting at 0
*/
public int getCpuIndex() {
return this.cpuIndex;
}
/**
* @return The idle time of the CPU, in [ms]
*/
public long getIdle() {
try {
return sigar.getCpuList()[this.cpuIndex].getIdle();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time of the CPU spent on nice priority, in [ms]
*/
public long getNice() {
try {
return sigar.getCpuList()[this.cpuIndex].getNice();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time of the CPU used by the system, in [ms]
*/
public long getSys() {
try {
return sigar.getCpuList()[this.cpuIndex].getSys();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The total time of the CPU, in [ms]
*/
public long getTotal() {
try {
return sigar.getCpuList()[this.cpuIndex].getTotal();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time of the CPU used by user processes, in [ms]
*/
public long getUser() {
try {
return sigar.getCpuList()[this.cpuIndex].getUser();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time the CPU had to wait for data to be loaded, in [ms]
*/
public long getWait() {
try {
return sigar.getCpuList()[this.cpuIndex].getWait();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) {
return new Integer(getCpuIndex());
} else if (MBEAN_ATTR_IDLE.getName().equals(attr)) {
return new Long(getIdle());
} else if (MBEAN_ATTR_NICE.getName().equals(attr)) {
return new Long(getNice());
} else if (MBEAN_ATTR_SYS.getName().equals(attr)) {
return new Long(getSys());
} else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) {
return new Long(getTotal());
} else if (MBEAN_ATTR_USER.getName().equals(attr)) {
return new Long(getUser());
} else if (MBEAN_ATTR_WAIT.getName().equals(attr)) {
return new Long(getWait());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
}
@@ -0,0 +1,284 @@
/*
* Copyright (c) 2007, 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Sigar JMX MBean implementation for the <code>CpuInfo</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarCpuInfo extends AbstractMBean {
private static final String MBEAN_TYPE = "CpuInfoList";
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX;
private static final MBeanAttributeInfo MBEAN_ATTR_CACHESIZE;
private static final MBeanAttributeInfo MBEAN_ATTR_MHZ;
private static final MBeanAttributeInfo MBEAN_ATTR_MODEL;
private static final MBeanAttributeInfo MBEAN_ATTR_VENDOR;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR;
private static final MBeanParameterInfo MBEAN_PARAM_CPUINDEX;
private static final MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int",
"The index of the CPU, typically starting at 0", true, false,
false);
MBEAN_ATTR_CACHESIZE = new MBeanAttributeInfo("CacheSize", "long",
"The cache size of the CPU, in [byte]", true, false, false);
MBEAN_ATTR_MHZ = new MBeanAttributeInfo("Mhz", "int",
"The clock speed of the CPU, in [MHz]", true, false, false);
MBEAN_ATTR_MODEL = new MBeanAttributeInfo("Model", "java.lang.String",
"The CPU model reported", true, false, false);
MBEAN_ATTR_VENDOR = new MBeanAttributeInfo("Vendor",
"java.lang.String", "The CPU vendor reported", true, false,
false);
MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int",
"The index of the CPU to read data for. Must be >= 0 "
+ "and not exceed the CPU count of the system");
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpuInfo.class
.getName(),
"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.",
new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX });
MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo(
SigarCpuInfo.class.getName(),
"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 range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR,
MBEAN_PARAM_CPUINDEX });
MBEAN_INFO = new MBeanInfo(
SigarCpuInfo.class.getName(),
"Sigar CPU Info MBean, provides overall information for a "
+ "single CPU. This information only changes if, for example, "
+ "a CPU is reducing its clock frequency or shutting down "
+ "part of its cache. Subsequent requests are satisfied from "
+ "within a cache that invalidates after 30 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX,
MBEAN_ATTR_CACHESIZE, MBEAN_ATTR_MHZ, MBEAN_ATTR_MODEL,
MBEAN_ATTR_VENDOR }, new MBeanConstructorInfo[] {
MBEAN_CONSTR_CPUINDEX, MBEAN_CONSTR_CPUINDEX_SIGAR },
null, null);
}
/**
* Index of the CPU processed by the instance.
*/
private int cpuIndex;
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
private String objectName;
/**
* 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.
*
* @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.
*
* @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs
*/
public SigarCpuInfo(int index) throws IllegalArgumentException {
this(new Sigar(), index);
}
/**
* 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 range.
*
* @param sigar The Sigar instance to use to fetch data from
* @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.
*
* @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs
*/
public SigarCpuInfo(Sigar sigar, int index) {
super(sigar, DEFAULT);
// check index
if (index < 0)
throw new IllegalArgumentException(
"CPU index has to be non-negative: " + index);
try {
int cpuCount;
if ((cpuCount = sigar.getCpuInfoList().length) < index)
throw new IllegalArgumentException(
"CPU index out of range (found " + cpuCount
+ " CPU(s)): " + index);
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
// all fine
this.cpuIndex = index;
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=CpuInfo,"
+ MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase()
+ MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex;
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The index of the CPU, typically starting at 0
*/
public int getCpuIndex() {
return this.cpuIndex;
}
/**
* @return The cache size of the CPU, in [byte]
*/
public long getCacheSize() {
try {
return sigar.getCpuInfoList()[this.cpuIndex].getCacheSize();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The clock speed of the CPU, in [MHz]
*/
public int getMhz() {
try {
return sigar.getCpuInfoList()[this.cpuIndex].getMhz();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The CPU model reported
*/
public String getModel() {
try {
return sigar.getCpuInfoList()[this.cpuIndex].getModel();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The CPU vendor reported
*/
public String getVendor() {
try {
return sigar.getCpuInfoList()[this.cpuIndex].getVendor();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_CACHESIZE.getName().equals(attr)) {
return new Long(getCacheSize());
} else if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) {
return new Integer(getCpuIndex());
} else if (MBEAN_ATTR_MHZ.getName().equals(attr)) {
return new Integer(getMhz());
} else if (MBEAN_ATTR_MODEL.getName().equals(attr)) {
return getModel();
} else if (MBEAN_ATTR_VENDOR.getName().equals(attr)) {
return getVendor();
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
}
@@ -0,0 +1,331 @@
/*
* Copyright (c) 2007, 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* <p>Sigar JMX MBean implementation for the <code>CpuPerc</code> information
* package. Provides an OpenMBean conform implementation.</p>
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarCpuPerc extends AbstractMBean {
private static final String MBEAN_TYPE = "CpuPercList";
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_CPUINDEX;
private static final MBeanAttributeInfo MBEAN_ATTR_COMBINED;
private static final MBeanAttributeInfo MBEAN_ATTR_IDLE;
private static final MBeanAttributeInfo MBEAN_ATTR_NICE;
private static final MBeanAttributeInfo MBEAN_ATTR_SYS;
private static final MBeanAttributeInfo MBEAN_ATTR_USER;
private static final MBeanAttributeInfo MBEAN_ATTR_WAIT;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX;
private static final MBeanConstructorInfo MBEAN_CONSTR_CPUINDEX_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_CPUINDEX;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_CPUINDEX = new MBeanAttributeInfo("CpuIndex", "int",
"The index of the CPU, typically starting at 0", true, false,
false);
MBEAN_ATTR_COMBINED = new MBeanAttributeInfo("Combined", "double",
"The total time of the CPU, as a fraction of 1", true, false,
false);
MBEAN_ATTR_IDLE = new MBeanAttributeInfo("Idle", "double",
"The idle time of the CPU, as a fraction of 1", true, false,
false);
MBEAN_ATTR_NICE = new MBeanAttributeInfo(
"Nice",
"double",
"The time of the CPU spent on nice priority, as a fraction of 1",
true, false, false);
MBEAN_ATTR_SYS = new MBeanAttributeInfo("Sys", "double",
"The time of the CPU used by the system, as a fraction of 1",
true, false, false);
MBEAN_ATTR_USER = new MBeanAttributeInfo(
"User",
"double",
"The time of the CPU used by user processes, as a fraction of 1",
true, false, false);
MBEAN_ATTR_WAIT = new MBeanAttributeInfo(
"Wait",
"double",
"The time the CPU had to wait for data to be loaded, as a fraction of 1",
true, false, false);
MBEAN_PARAM_CPUINDEX = new MBeanParameterInfo("cpuIndex", "int",
"The index of the CPU to read data for. Must be >= 0 "
+ "and not exceed the CPU count of the system");
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_CPUINDEX = new MBeanConstructorInfo(SigarCpuPerc.class
.getName(),
"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.",
new MBeanParameterInfo[] { MBEAN_PARAM_CPUINDEX });
MBEAN_CONSTR_CPUINDEX_SIGAR = new MBeanConstructorInfo(
SigarCpuPerc.class.getName(),
"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 range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR,
MBEAN_PARAM_CPUINDEX });
MBEAN_INFO = new MBeanInfo(
SigarCpuPerc.class.getName(),
"Sigar CPU MBean. Provides percentage data for a single "
+ "CPU, averaged over the timeframe between the last and "
+ "the current measurement point. Two measurement points "
+ "can be as close as 5 seconds, meaning subsequent requests "
+ "for data within 5 seconds after the last executed call "
+ "will be satisfied from cached data.",
new MBeanAttributeInfo[] { MBEAN_ATTR_CPUINDEX,
MBEAN_ATTR_COMBINED, MBEAN_ATTR_IDLE, MBEAN_ATTR_NICE,
MBEAN_ATTR_SYS, MBEAN_ATTR_USER, MBEAN_ATTR_WAIT },
new MBeanConstructorInfo[] { MBEAN_CONSTR_CPUINDEX,
MBEAN_CONSTR_CPUINDEX_SIGAR }, null, null);
}
/**
* Index of the CPU processed by the instance.
*/
private int cpuIndex;
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
private String objectName;
/**
* 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.
*
* @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.
*
* @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs
*/
public SigarCpuPerc(int index) {
this(new Sigar(), index);
}
/**
* 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 range.
*
* @param sigar The Sigar instance to use to fetch data from
* @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.
*
* @throws IllegalArgumentException If the CPU index is out of range or
* an unexpected Sigar error occurs
*/
public SigarCpuPerc(Sigar sigar, int index) {
super(sigar, CACHED_5SEC);
// check index
if (index < 0)
throw new IllegalArgumentException(
"CPU index has to be non-negative: " + index);
try {
int cpuCount;
if ((cpuCount = sigar.getCpuPercList().length) < index)
throw new IllegalArgumentException(
"CPU index out of range (found " + cpuCount
+ " CPU(s)): " + index);
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
// all fine
this.cpuIndex = index;
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=CpuPerc,"
+ MBEAN_ATTR_CPUINDEX.getName().substring(0, 1).toLowerCase()
+ MBEAN_ATTR_CPUINDEX.getName().substring(1) + "=" + cpuIndex;
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The index of the CPU, typically starting at 0
*/
public int getCpuIndex() {
return this.cpuIndex;
}
/**
* @return The total time of the CPU, as a fraction of 1
*/
public double getCombined() {
try {
return sigar.getCpuPercList()[this.cpuIndex].getCombined();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The idle time of the CPU, as a fraction of 1
*/
public double getIdle() {
try {
return sigar.getCpuPercList()[this.cpuIndex].getIdle();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time of the CPU spent on nice priority, as a fraction of 1
*/
public double getNice() {
try {
return sigar.getCpuPercList()[this.cpuIndex].getNice();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time of the CPU used by the system, as a fraction of 1
*/
public double getSys() {
try {
return sigar.getCpuPercList()[this.cpuIndex].getSys();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time of the CPU used by user processes, as a fraction of 1
*/
public double getUser() {
try {
return sigar.getCpuPercList()[this.cpuIndex].getUser();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The time the CPU had to wait for data to be loaded, as a fraction of 1
*/
public double getWait() {
try {
return sigar.getCpuPercList()[this.cpuIndex].getWait();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_COMBINED.getName().equals(attr)) {
return new Double(getCombined());
} else if (MBEAN_ATTR_CPUINDEX.getName().equals(attr)) {
return new Integer(getCpuIndex());
} else if (MBEAN_ATTR_IDLE.getName().equals(attr)) {
return new Double(getIdle());
} else if (MBEAN_ATTR_NICE.getName().equals(attr)) {
return new Double(getNice());
} else if (MBEAN_ATTR_SYS.getName().equals(attr)) {
return new Double(getSys());
} else if (MBEAN_ATTR_USER.getName().equals(attr)) {
return new Double(getUser());
} else if (MBEAN_ATTR_WAIT.getName().equals(attr)) {
return new Double(getWait());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2006, 2008-2009 Hyperic, Inc. * Copyright (c) 2006 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,16 +16,13 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import java.lang.reflect.InvocationHandler;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarInvoker; import org.hyperic.sigar.SigarInvoker;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
import org.hyperic.sigar.util.ReferenceMap; import org.hyperic.sigar.util.ReferenceMap;
/** /**
@@ -37,7 +34,6 @@ public class SigarInvokerJMX extends SigarInvoker {
public static final String DOMAIN_NAME = "sigar"; public static final String DOMAIN_NAME = "sigar";
public static final String PROP_TYPE = "Type"; public static final String PROP_TYPE = "Type";
public static final String PROP_NAME = "Name"; //prefer Name (Arg for compat)
public static final String PROP_ARG = "Arg"; public static final String PROP_ARG = "Arg";
private String arg = null; private String arg = null;
@@ -62,10 +58,6 @@ public class SigarInvokerJMX extends SigarInvoker {
SigarInvokerJMX invoker; SigarInvokerJMX invoker;
if (!(proxy instanceof InvocationHandler) && (proxy instanceof Sigar)) {
proxy = SigarProxyCache.newInstance((Sigar)proxy);
}
int ix = name.indexOf(":"); int ix = name.indexOf(":");
if (ix > 0) { if (ix > 0) {
//skip domain name //skip domain name
@@ -90,12 +82,10 @@ public class SigarInvokerJMX extends SigarInvoker {
String key = attr.substring(0, ix); String key = attr.substring(0, ix);
String val = attr.substring(key.length()+1); String val = attr.substring(key.length()+1);
if (key.equalsIgnoreCase(PROP_TYPE)) { if (key.equals(PROP_TYPE)) {
invoker.setType(val); invoker.setType(val);
} }
else if (key.equalsIgnoreCase(PROP_NAME) || else if (key.equals(PROP_ARG)) {
key.equalsIgnoreCase(PROP_ARG))
{
//need to decode value, e.g. Arg=C%3D\ => Arg=C:\ //need to decode value, e.g. Arg=C%3D\ => Arg=C:\
invoker.setArg(decode(val)); invoker.setArg(decode(val));
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007-2009 Hyperic, Inc. * Copyright (c) 2007, 2009 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,38 +16,246 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanException; import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.LoadAverage;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy;
public class SigarLoadAverage extends ReflectedMBean { /**
* Sigar JMX MBean implementation for the <code>LoadAverage</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarLoadAverage extends AbstractMBean {
private static final String MBEAN_TYPE = "LoadAverage"; private static final String MBEAN_TYPE = "LoadAverage";
public SigarLoadAverage(SigarProxy sigar) { /**
super(sigar, MBEAN_TYPE); * Returned if {@link Sigar#getLoadAverage()}} is detected to be not
* implemented on the platform.
*
* @see #notImplemented
*/
private static final double NOT_IMPLEMENTED_LOAD_VALUE = -1.0d;
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST1MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST5MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST15MIN;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_LAST1MIN = new MBeanAttributeInfo(
"LastMinute",
"double",
"The load average in the last minute, as a fraction of 1, or "
+ "-1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_ATTR_LAST5MIN = new MBeanAttributeInfo(
"LastFiveMinutes",
"double",
"The load average over the last five minutes, as a fraction "
+ "of 1, or -1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_ATTR_LAST15MIN = new MBeanAttributeInfo(
"Last15Minutes",
"double",
"The load average over the last 15 minutes, as a fraction of "
+ "1, or -1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(
SigarLoadAverage.class.getName(),
"Creates a new instance, using the Sigar instance specified "
+ "to fetch the data. Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo(
SigarLoadAverage.class.getName(),
"Sigar load average MBean. Provides load averages of the "
+ "system over the last one, five and 15 minutes. Due to the "
+ "long term character of that information, the fetch is done "
+ "using a Sigar proxy cache with a timeout of 30 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_LAST1MIN,
MBEAN_ATTR_LAST5MIN, MBEAN_ATTR_LAST15MIN },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
} }
public Object getAttribute(String name) /**
throws AttributeNotFoundException, * Object name this instance will give itself when being registered to an
MBeanException, ReflectionException { * MBeanServer.
*/
private final String objectName;
/**
* <p>Set <code>true</code> when the load average fetch failed with a
* <code>SigarException</code> that indicates the method is not implemented.
* Any subsequent call to this instance will then be answered with
* {@link #NOT_IMPLEMENTED_LOAD_VALUE}.
* </p>
*
* <p><b>FIXME</b> : This is a workaround and should be replaced by something
* more stable, as the code setting this member <code>true</code> relies on
* a substring being present within the exception. A proposal was made at
* <a href="http://jira.hyperic.com/browse/SIGAR-52">issue SIGAR-52</a>.
* </p>
*/
private boolean notImplemented;
/**
* Creates a new instance, using a new Sigar instance to fetch the data.
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs.
*/
public SigarLoadAverage() throws IllegalArgumentException {
this(new Sigar());
}
/**
* Creates a new instance, using the Sigar instance specified to fetch the
* data.
*
* @param sigar
* The Sigar instance to use to fetch data from
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs
*/
public SigarLoadAverage(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_30SEC);
// all fine
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE;
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The load average in the last minute, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLastMinute() {
try { try {
Object val = return sigarImpl.getLoadAverage()[0];
new LoadAverage(this.sigar.getLoadAverage()).toMap().get(name);
if (val == null) {
throw new AttributeNotFoundException(name);
}
return val;
} catch (SigarNotImplementedException e) { } catch (SigarNotImplementedException e) {
return new Double(Sigar.FIELD_NOTIMPL); return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) { } catch (SigarException e) {
throw new ReflectionException(e); throw unexpectedError(MBEAN_TYPE, e);
} }
} }
/**
* @return The load average over the last five minutes, as a fraction of 1,
* or <code>-1.0d</code> if the load cannot be determined on this
* platform
*/
public double getLastFiveMinutes() {
try {
return sigarImpl.getLoadAverage()[1];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The load average over the last 15 minutes, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLast15Minutes() {
try {
return sigarImpl.getLoadAverage()[2];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_LAST1MIN.getName().equals(attr)) {
return new Double(getLastMinute());
} else if (MBEAN_ATTR_LAST5MIN.getName().equals(attr)) {
return new Double(getLastFiveMinutes());
} else if (MBEAN_ATTR_LAST15MIN.getName().equals(attr)) {
return new Double(getLast15Minutes());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
} }
@@ -0,0 +1,249 @@
/*
* Copyright (c) 2007, 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Sigar JMX MBean implementation for the <code>Mem</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarMem extends AbstractMBean {
private static final String MBEAN_TYPE = "Mem";
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_ACTUAL_FREE;
private static final MBeanAttributeInfo MBEAN_ATTR_ACTUAL_USED;
private static final MBeanAttributeInfo MBEAN_ATTR_FREE;
private static final MBeanAttributeInfo MBEAN_ATTR_RAM;
private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL;
private static final MBeanAttributeInfo MBEAN_ATTR_USED;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_ACTUAL_FREE = new MBeanAttributeInfo("ActualFree", "long",
"TODO add proper description here", true, false, false);
MBEAN_ATTR_ACTUAL_USED = new MBeanAttributeInfo("ActualUsed", "long",
"TODO add proper description here", true, false, false);
MBEAN_ATTR_FREE = new MBeanAttributeInfo("Free", "long",
"TODO add proper description here", true, false, false);
MBEAN_ATTR_RAM = new MBeanAttributeInfo("Ram", "long",
"TODO add proper description here", true, false, false);
MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long",
"TODO add proper description here", true, false, false);
MBEAN_ATTR_USED = new MBeanAttributeInfo("Used", "long",
"TODO add proper description here", true, false, false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(SigarMem.class.getName(),
"Creates a new instance, using the Sigar instance "
+ "specified to fetch the data.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo(
SigarMem.class.getName(),
"Sigar Memory MBean, provides raw data for the physical "
+ "memory installed on the system. Uses an internal cache "
+ "that invalidates within 500ms, allowing for bulk request "
+ "being satisfied with a single dataset fetch.",
new MBeanAttributeInfo[] { MBEAN_ATTR_ACTUAL_FREE,
MBEAN_ATTR_ACTUAL_USED, MBEAN_ATTR_FREE,
MBEAN_ATTR_RAM, MBEAN_ATTR_TOTAL, MBEAN_ATTR_USED },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
private final String objectName;
/**
* Creates a new instance, using the Sigar instance specified to fetch the
* data.
*
* @param sigar
* The Sigar instance to use to fetch data from
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs
*/
public SigarMem(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_500MS);
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=Memory";
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The actual amount of free physical memory, in [bytes]
*/
public long getActualFree() {
try {
return sigar.getMem().getActualFree();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The actual amount of physical memory used, in [bytes]
*/
public long getActualUsed() {
try {
return sigar.getMem().getActualUsed();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The amount of free physical memory, in [bytes]
*/
public long getFree() {
try {
return sigar.getMem().getFree();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The amount of physical memory, in [bytes]
*/
public long getRam() {
try {
return sigar.getMem().getRam();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The total amount of physical memory, in [bytes]
*/
public long getTotal() {
try {
return sigar.getMem().getTotal();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The amount of physical memory in use, in [bytes]
*/
public long getUsed() {
try {
return sigar.getMem().getUsed();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException,
MBeanException, ReflectionException {
if (MBEAN_ATTR_ACTUAL_FREE.getName().equals(attr)) {
return new Long(getActualFree());
} else if (MBEAN_ATTR_ACTUAL_USED.getName().equals(attr)) {
return new Long(getActualUsed());
} else if (MBEAN_ATTR_FREE.getName().equals(attr)) {
return new Long(getFree());
} else if (MBEAN_ATTR_RAM.getName().equals(attr)) {
return new Long(getRam());
} else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) {
return new Long(getTotal());
} else if (MBEAN_ATTR_USED.getName().equals(attr)) {
return new Long(getUsed());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String,
* java.lang.Object[], java.lang.String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2006-2009 Hyperic, Inc. * Copyright (c) 2006-2007 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -77,7 +77,7 @@ public class SigarProcess implements SigarProcessMBean {
} }
} }
private synchronized ProcDiskIO getDiskIO() { private synchronized ProcDiskIO getDiskIO() {
try { try {
return this.sigar.getProcDiskIO(getPid()); return this.sigar.getProcDiskIO(getPid());
@@ -91,22 +91,6 @@ public class SigarProcess implements SigarProcessMBean {
return this.sigar.getProcFd(getPid()); return this.sigar.getProcFd(getPid());
} }
public String getObjectName() throws SigarException {
long pid = getPid();
String name = this.sigar.getProcState(pid).getName().replaceAll(":", "_");
String cls = "unknown";
if (name.startsWith("java")) {
try {
cls = ProcUtil.getJavaMainClass(this.sigar, pid);
} catch (SigarException e) {}
} //else XXX
return
AbstractMBean.MBEAN_DOMAIN + ":" +
AbstractMBean.MBEAN_ATTR_TYPE + "=" + "Process" + "," +
"Name" + "=" + name + "," +
"Class" + "=" + cls + "," +
"Pid" + "=" + pid;
}
public long getPid() { public long getPid() {
if (this.pid < 0) { if (this.pid < 0) {
@@ -158,11 +142,22 @@ public class SigarProcess implements SigarProcessMBean {
} }
public Long getOpenFd() { public Long getOpenFd() {
try { try {
return new Long(getFd().getTotal()); return new Long(getFd().getTotal());
} catch (SigarException e) { } catch (SigarException e) {
return NOTIMPL; return NOTIMPL;
} }
}
public static void main(String args[]) {
SigarProcessMBean proc = new SigarProcess();
System.out.println("MemSize=" + proc.getMemSize());
System.out.println("MemResident=" + proc.getMemResident());
System.out.println("MemShared=" + proc.getMemShare());
System.out.println("MemPageFaults=" + proc.getMemPageFaults());
System.out.println("TimeUser=" + proc.getTimeUser());
System.out.println("TimeSys=" + proc.getTimeSys());
System.out.println("OpenFd=" + proc.getOpenFd());
} }
public Double getBytesReadWriteTotal() { public Double getBytesReadWriteTotal() {
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007-2009 Hyperic, Inc. * Copyright (c) 2007, 2009 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,18 +18,19 @@ package org.hyperic.sigar.jmx;
import java.util.ArrayList; import java.util.ArrayList;
import javax.management.MBeanRegistration; import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.management.ObjectInstance; import javax.management.ObjectInstance;
import javax.management.ObjectName; import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/** /**
* <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke * <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke
@@ -56,173 +57,266 @@ import org.hyperic.sigar.SigarProxyCache;
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarRegistry implements MBeanRegistration, SigarRegistryMBean { public class SigarRegistry extends AbstractMBean {
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
private static final String MBEAN_TYPE = "SigarRegistry"; private static final String MBEAN_TYPE = "SigarRegistry";
private static final int CACHE_EXPIRE = 60 * 1000;
private Sigar sigarImpl; private static final MBeanInfo MBEAN_INFO;
private SigarProxy sigar;
private String objectName;
private ArrayList managedBeans; private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT;
private MBeanServer mbeanServer;
public SigarRegistry() {} // private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES;
public SigarRegistry(SigarProxy sigar) { static {
init(sigar); MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo(
SigarRegistry.class.getName(),
"Creates a new instance of this class. Will create the Sigar "
+ "instance this class uses when constructing other MBeans",
new MBeanParameterInfo[0]);
// MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses",
// "Executes a query returning the process IDs of all processes " +
// "found on the system.",
// null /* new MBeanParameterInfo[0] */,
// String.class.getName(), MBeanOperationInfo.INFO);
MBEAN_INFO = new MBeanInfo(
SigarRegistry.class.getName(),
"Sigar MBean registry. Provides a central point for creation "
+ "and destruction of Sigar MBeans. Any Sigar MBean created via "
+ "this instance will automatically be cleaned up when this "
+ "instance is deregistered from the MBean server.",
null /*new MBeanAttributeInfo[0]*/,
new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT },
null /*new MBeanOperationInfo[0] */,
null /*new MBeanNotificationInfo[0]*/);
} }
private void init(SigarProxy sigar) { private final String objectName;
this.sigar = sigar;
this.objectName = private final ArrayList managedBeans;
MBEAN_DOMAIN + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE;
this.managedBeans = new ArrayList(); /**
* Creates a new instance of this class. Will create the Sigar instance this
* class uses when constructing other MBeans.
*/
public SigarRegistry() {
super(new Sigar(), CACHELESS);
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE;
this.managedBeans = new ArrayList();
} }
/* (non-Javadoc)
* @see AbstractMBean#getObjectName()
*/
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
private void registerMBean(AbstractMBean mbean) { /* public String listProcesses() {
try { try {
ObjectName name = final long start = System.currentTimeMillis();
new ObjectName(mbean.getObjectName()); long[] ids = sigar.getProcList();
if (mbeanServer.isRegistered(name)) { StringBuffer procNames = new StringBuffer();
return; for (int i = 0; i < ids.length; i++) {
try {
procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n');
} catch (SigarException e) {
procNames.append(ids[i] + ":" + e.getMessage()).append('\n');
}
} }
ObjectInstance instance =
this.mbeanServer.registerMBean(mbean, name); final long end = System.currentTimeMillis();
this.managedBeans.add(instance.getObjectName()); procNames.append("-- Took " + (end-start) + "ms");
} catch (Exception e) { return procNames.toString();
e.printStackTrace();
} catch (SigarException e) {
throw unexpectedError("ProcList", e);
} }
} }
*/
/* (non-Javadoc)
* @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr);
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String, java.lang.Object[], java.lang.String[])
*/
public Object invoke(String action, Object[] params, String[] signatures)
throws MBeanException, ReflectionException {
/* if (MBEAN_OPER_LISTPROCESSES.getName().equals(action))
return listProcesses();
else */
throw new ReflectionException(new NoSuchMethodException(action), action);
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
// ------- // -------
// Implementation of the MBeanRegistration interface // Implementation of the MBeanRegistration interface
// ------- // -------
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
//no args constructor support
if (this.sigar == null) {
this.sigarImpl = new Sigar();
init(SigarProxyCache.newInstance(this.sigarImpl, CACHE_EXPIRE));
}
this.mbeanServer = server;
if (name == null) {
return new ObjectName(getObjectName());
}
else {
return name;
}
}
/** /**
* Registers the default set of Sigar MBeans. * Registers the default set of Sigar MBeans. Before doing so, a super call
* is made to satisfy {@link AbstractMBean}.
*
* @see AbstractMBean#postRegister(Boolean)
*/ */
public void postRegister(Boolean success) { public void postRegister(Boolean success) {
ReflectedMBean mbean;
super.postRegister(success);
if (!success.booleanValue()) if (!success.booleanValue())
return; return;
//CPU beans // get CPUs
CpuInfo[] info; registerCpuBeans();
// get memory
registerMemoryBeans();
// get system
registerSystemBeans();
}
/**
* Registers MBeans for the Sigar types <code>Cpu</code>, <code>CpuPerc</code>
* and <code>CpuInfo</code>. One instance will be registered for each CPU
* (core?) found.
*/
private void registerCpuBeans() {
ObjectInstance nextRegistered = null;
try { try {
info = sigar.getCpuInfoList(); final int cpuCount = sigar.getCpuInfoList().length;
} catch (SigarException e) { for (int i = 0; i < cpuCount; i++) {
info = new CpuInfo[0]; //XXX log // add CPU bean
} SigarCpu nextCpu = new SigarCpu(sigarImpl, i);
for (int i=0; i<info.length; i++) {
String idx = String.valueOf(i);
mbean =
new ReflectedMBean(this.sigar, "CpuCore", idx);
mbean.setType("CpuList");
registerMBean(mbean);
mbean =
new ReflectedMBean(this.sigar, "CpuCoreUsage", idx);
mbean.setType("CpuPercList");
registerMBean(mbean);
}
mbean = new ReflectedMBean(this.sigar, "Cpu");
mbean.putAttributes(info[0]);
registerMBean(mbean);
mbean = new ReflectedMBean(this.sigar, "CpuUsage");
mbean.setType("CpuPerc");
registerMBean(mbean);
//FileSystem beans
try {
FileSystem[] fslist = this.sigar.getFileSystemList();
for (int i=0; i<fslist.length; i++) {
FileSystem fs = fslist[i];
if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) {
continue;
}
String name = fs.getDirName();
mbean =
new ReflectedMBean(this.sigar, "FileSystem", name);
mbean.setType(mbean.getType() + "Usage");
mbean.putAttributes(fs);
registerMBean(mbean);
}
} catch (SigarException e) {
//XXX log
}
//NetInterface beans
try {
String[] ifnames = this.sigar.getNetInterfaceList();
for (int i=0; i<ifnames.length; i++) {
String name = ifnames[i];
NetInterfaceConfig ifconfig =
this.sigar.getNetInterfaceConfig(name);
try { try {
this.sigar.getNetInterfaceStat(name); if (!mbeanServer.isRegistered(new ObjectName(nextCpu
} catch (SigarException e) { .getObjectName())))
continue; nextRegistered = mbeanServer.registerMBean(nextCpu,
null);
} catch (Exception e) { // ignore
} }
mbean = // add MBean to set of managed beans
new ReflectedMBean(this.sigar, "NetInterface", name); if (nextRegistered != null)
mbean.setType(mbean.getType() + "Stat"); managedBeans.add(nextRegistered.getObjectName());
mbean.putAttributes(ifconfig); nextRegistered = null;
registerMBean(mbean);
// add CPU percentage bean
SigarCpuPerc nextCpuPerc = new SigarCpuPerc(sigarImpl, i);
try {
if (!mbeanServer.isRegistered(new ObjectName(nextCpuPerc
.getObjectName())))
nextRegistered = mbeanServer.registerMBean(nextCpuPerc,
null);
} catch (Exception e) { // ignore
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
// add CPU info bean
SigarCpuInfo nextCpuInfo = new SigarCpuInfo(sigarImpl, i);
try {
if (!mbeanServer.isRegistered(new ObjectName(nextCpuInfo
.getObjectName())))
nextRegistered = mbeanServer.registerMBean(nextCpuInfo,
null);
} catch (Exception e) { // ignore
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
} }
} catch (SigarException e) { } catch (SigarException e) {
//XXX log throw unexpectedError("CpuInfoList", e);
}
}
/**
* Registers MBeans for the Sigar types <code>Mem</code> and <code>Swap</code>.
*/
private void registerMemoryBeans() {
ObjectInstance nextRegistered = null;
// add physical memory bean
SigarMem mem = new SigarMem(sigarImpl);
try {
if (!mbeanServer.isRegistered(new ObjectName(mem.getObjectName())))
nextRegistered = mbeanServer.registerMBean(mem, null);
} catch (Exception e) { // ignore
} }
//network info bean // add MBean to set of managed beans
mbean = new ReflectedMBean(this.sigar, "NetInfo"); if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
// add swap memory bean
SigarSwap swap = new SigarSwap(sigarImpl);
try { try {
mbean.putAttribute("FQDN", this.sigar.getFQDN()); if (!mbeanServer.isRegistered(new ObjectName(swap.getObjectName())))
} catch (SigarException e) { nextRegistered = mbeanServer.registerMBean(swap, null);
} catch (Exception e) { // ignore
nextRegistered = null;
} }
registerMBean(mbean);
//physical memory bean // add MBean to set of managed beans
registerMBean(new ReflectedMBean(this.sigar, "Mem")); if (nextRegistered != null)
//swap memory bean managedBeans.add(nextRegistered.getObjectName());
registerMBean(new ReflectedMBean(this.sigar, "Swap")); nextRegistered = null;
//load average bean }
registerMBean(new SigarLoadAverage(this.sigar));
//global process stats /**
registerMBean(new ReflectedMBean(this.sigar, "ProcStat")); * Registers MBeans for the Sigar types <code>LoadAverage</code>...
//sigar version */
registerMBean(new ReflectedMBean(this.sigar, "SigarVersion")); private void registerSystemBeans() {
ObjectInstance nextRegistered = null;
// add load average bean
SigarLoadAverage loadAvg = new SigarLoadAverage(sigarImpl);
try {
if (!mbeanServer.isRegistered(new ObjectName(loadAvg
.getObjectName())))
nextRegistered = mbeanServer.registerMBean(loadAvg, null);
} catch (Exception e) { // ignore
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
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. * instance. After doing so, a super call is made to satisfy {@link AbstractMBean}.
* @throws Exception * @throws Exception
* *
* @see AbstractMBean#preDeregister() * @see AbstractMBean#preDeregister()
@@ -239,14 +333,8 @@ public class SigarRegistry implements MBeanRegistration, SigarRegistryMBean {
} }
} }
} }
}
public void postDeregister() { // do the super call
this.mbeanServer = null; super.preDeregister();
if (this.sigarImpl != null) {
this.sigarImpl.close();
this.sigarImpl = null;
this.sigar = null;
}
} }
} }
@@ -1,21 +0,0 @@
/*
* Copyright (c) 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.jmx;
public interface SigarRegistryMBean {
}
@@ -0,0 +1,197 @@
/*
* Copyright (c) 2007, 2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
/**
* Sigar JMX MBean implementation for the <code>Swap</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarSwap extends AbstractMBean {
private static final String MBEAN_TYPE = "Swap";
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_FREE;
private static final MBeanAttributeInfo MBEAN_ATTR_TOTAL;
private static final MBeanAttributeInfo MBEAN_ATTR_USED;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_FREE = new MBeanAttributeInfo("Free", "long",
"The amount of free swap memory, in [bytes]", true, false,
false);
MBEAN_ATTR_TOTAL = new MBeanAttributeInfo("Total", "long",
"The total amount of swap memory, in [bytes]", true, false,
false);
MBEAN_ATTR_USED = new MBeanAttributeInfo("Used", "long",
"The amount of swap memory in use, in [bytes]", true, false,
false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(
SigarSwap.class.getName(),
"Creates a new instance, using the Sigar instance "
+ "specified to fetch the data.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo(
SigarSwap.class.getName(),
"Sigar Swap MBean, provides raw data for the swap memory "
+ "configured on the system. Uses an internal cache that "
+ "invalidates within 5 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_FREE, MBEAN_ATTR_TOTAL,
MBEAN_ATTR_USED },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
private final String objectName;
/**
* Creates a new instance, using the Sigar instance specified to fetch the
* data.
*
* @param sigar
* The Sigar instance to use to fetch data from
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs
*/
public SigarSwap(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_5SEC);
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=Swap";
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The amount of free swap memory, in [bytes]
*/
public long getFree() {
try {
return sigar.getSwap().getFree();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The total amount of swap memory, in [bytes]
*/
public long getTotal() {
try {
return sigar.getSwap().getTotal();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The amount of swap memory in use, in [bytes]
*/
public long getUsed() {
try {
return sigar.getSwap().getUsed();
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException,
MBeanException, ReflectionException {
if (MBEAN_ATTR_FREE.getName().equals(attr)) {
return new Long(getFree());
} else if (MBEAN_ATTR_TOTAL.getName().equals(attr)) {
return new Long(getTotal());
} else if (MBEAN_ATTR_USED.getName().equals(attr)) {
return new Long(getUsed());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String,
* java.lang.Object[], java.lang.String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
}
@@ -1,7 +1,6 @@
/* /*
* Copyright (c) 2006-2008 Hyperic, Inc. * Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +43,6 @@ public class SigarTestRunner extends SigarCommandBase {
private static final Class[] ALL_TESTS = { private static final Class[] ALL_TESTS = {
TestLog.class, TestLog.class,
TestInvoker.class, TestInvoker.class,
TestMx.class,
TestPTQL.class, TestPTQL.class,
TestCpu.class, TestCpu.class,
TestCpuInfo.class, TestCpuInfo.class,
@@ -79,7 +77,6 @@ public class SigarTestRunner extends SigarCommandBase {
TestThreadCpu.class, TestThreadCpu.class,
TestUptime.class, TestUptime.class,
TestVMware.class, TestVMware.class,
TestArp.class,
TestWho.class, TestWho.class,
TestHumidor.class TestHumidor.class
}; };
@@ -1,46 +0,0 @@
/*
* Copyright (c) 2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.test;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.Arp;
public class TestArp extends SigarTestCase {
public TestArp(String name) {
super(name);
}
public void testCreate() throws Exception {
try {
Arp[] entries = getSigar().getArpList();
for (int i=0; i<entries.length; i++) {
Arp arp = entries[i];
assertTrueTrace("Address", arp.getAddress());
assertTrueTrace("Ifname", arp.getIfname());
assertTrueTrace("Hwaddr", arp.getHwaddr());
assertTrueTrace("Type", arp.getType());
traceln("Flags=" + arp.getFlags());
}
} catch (SigarNotImplementedException e) {
return;
} catch (SigarException e) {
return;
}
}
}
@@ -1,97 +0,0 @@
/*
* Copyright (c) 2008-2009 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar.test;
import java.util.Iterator;
import java.util.Set;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.Mx;
import org.hyperic.sigar.jmx.SigarProcess;
import org.hyperic.sigar.jmx.SigarRegistry;
public class TestMx extends SigarTestCase {
public TestMx(String name) {
super(name);
}
public void testRegister() throws Exception {
try {
_testRegister();
} catch (NoClassDefFoundError e) {
//1.4 jre
traceln(e + ", skipping");
}
}
private void _testProcess(MBeanServer server) throws Exception {
long[] pids = getSigar().getProcList();
for (int i=0; i<pids.length; i++) {
SigarProcess proc = new SigarProcess();
proc.setPid(pids[i]);
ObjectName name;
try {
name = new ObjectName(proc.getObjectName());
} catch (SigarException e) {
continue; //process may have gone away
}
if (server.isRegistered(name)) {
continue;
}
server.registerMBean(proc, name);
}
}
private void _testRegister() throws Exception {
MBeanServer server;
try {
server = Mx.getMBeanServer();
} catch (SigarException e) {
traceln(e.getMessage());
return;
}
SigarRegistry rgy = new SigarRegistry(getSigar());
ObjectName name = new ObjectName(rgy.getObjectName());
if (!server.isRegistered(name)) {
server.registerMBean(rgy, name);
}
Set beans =
server.queryNames(new ObjectName("sigar:*"), null);
assertGtZeroTrace("beans.size", beans.size());
for (Iterator it=beans.iterator(); it.hasNext();) {
name = (ObjectName)it.next();
MBeanInfo info = server.getMBeanInfo(name);
MBeanAttributeInfo[] attrs = info.getAttributes();
for (int k = 0; k < attrs.length; k++) {
String attr = attrs[k].getName();
Object o = server.getAttribute(name, attr);
traceln(name + ":" + attr + "=" + o);
}
}
_testProcess(server);
}
}
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2006-2008 Hyperic, Inc. * Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,9 +16,6 @@
package org.hyperic.sigar.test; package org.hyperic.sigar.test;
import java.net.InetAddress;
import java.net.Inet6Address;
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;
@@ -46,14 +42,6 @@ public class TestNetIf extends SigarTestCase {
assertTrueTrace("Address", ifconfig.getAddress()); assertTrueTrace("Address", ifconfig.getAddress());
assertTrueTrace("Netmask", ifconfig.getNetmask()); assertTrueTrace("Netmask", ifconfig.getNetmask());
if (ifconfig.getPrefix6Length() != 0) {
assertTrueTrace("Address6", ifconfig.getAddress6());
InetAddress in6 =
InetAddress.getByName(ifconfig.getAddress6());
assertTrue(in6 instanceof Inet6Address);
traceln("Link=" + in6.isLinkLocalAddress());
}
if (!getStats) { if (!getStats) {
continue; continue;
} }
@@ -20,6 +20,8 @@ package org.hyperic.sigar.win32;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@@ -371,6 +373,60 @@ public class Pdh extends Win32 {
return pdhGetObjects(); return pdhGetObjects();
} }
/**
sigar is compatible with java 1.4 (no generics there)
**/
public Map getFormattedValues(Collection paths) throws Win32Exception {
if (this.hostname != null) {
pdhConnectMachine(this.hostname);
}
Map res = new HashMap();
Map counters = new HashMap();
/*
* no for each loop either
*/
Iterator pathsIt = paths.iterator();
while (pathsIt.hasNext()) {
String path = (String)pathsIt.next();
try {
counters.put(path, new Long(pdhAddCounter(this.query, translate(path))));
} catch ( Win32Exception ex) {
}
}
if (counters.size() > 0) {
try {
pdhCollectQueryDataOverSecond(this.query);
pathsIt = paths.iterator();
while (pathsIt.hasNext()) {
try {
String path = (String)pathsIt.next();
Long c = (Long)counters.get(path);
if (c != null) {
double val = pdhGetFormattedValue(c.longValue());
res.put(path, new Double(val));
}
} catch (Exception ex) {
}
}
} finally {
Iterator countersIt = counters.values().iterator();
while (countersIt.hasNext()) {
try {
Long counter = (Long)countersIt.next();
pdhRemoveCounter(counter.longValue());
} catch (Win32Exception ex) {
}
}
}
}
return res;
}
public static final native int validate(String path); public static final native int validate(String path);
private static final native void pdhConnectMachine(String host) private static final native void pdhConnectMachine(String host)
@@ -401,6 +457,13 @@ public class Pdh extends Win32 {
private static final native int pdhLookupPerfIndex(String name) private static final native int pdhLookupPerfIndex(String name)
throws Win32Exception; throws Win32Exception;
private static final native void pdhCollectQueryDataOverSecond(long query)
throws Win32Exception;
private static final native double pdhGetFormattedValue(long counter)
throws Win32Exception;
/** /**
* Main method for dumping the entire PDH * Main method for dumping the entire PDH
* *
@@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class Service extends Win32 { public class Service extends Win32 {
// Service State // Service State
@@ -387,18 +386,6 @@ public class Service extends Win32 {
public void list(PrintStream out) throws Win32Exception { public void list(PrintStream out) throws Win32Exception {
getConfig().list(out); getConfig().list(out);
out.println("status........[" + getStatusString() + "]"); out.println("status........[" + getStatusString() + "]");
if (getStatus() != SERVICE_RUNNING) {
return;
}
Sigar sigar = new Sigar();
try {
long pid = sigar.getServicePid(getConfig().getName());
out.println("pid...........[" + pid + "]");
} catch (SigarException e) {
} finally {
sigar.close();
}
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@@ -18,7 +18,6 @@ package org.hyperic.sigar.win32.test;
import java.util.List; import java.util.List;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.test.SigarTestCase; import org.hyperic.sigar.test.SigarTestCase;
import org.hyperic.sigar.win32.Service; import org.hyperic.sigar.win32.Service;
@@ -26,7 +25,6 @@ import org.hyperic.sigar.win32.ServiceConfig;
import org.hyperic.sigar.win32.Win32Exception; import org.hyperic.sigar.win32.Win32Exception;
public class TestService extends SigarTestCase { public class TestService extends SigarTestCase {
private static final String EVENTLOG_NAME = "Eventlog";
private static final String TEST_NAME = "MyTestService"; private static final String TEST_NAME = "MyTestService";
private static final String PREFIX = private static final String PREFIX =
@@ -43,7 +41,7 @@ public class TestService extends SigarTestCase {
} }
public void testServiceOpen() throws Exception { public void testServiceOpen() throws Exception {
Service service = new Service(EVENTLOG_NAME); Service service = new Service("Eventlog");
service.getConfig(); service.getConfig();
service.close(); service.close();
@@ -93,31 +91,6 @@ public class TestService extends SigarTestCase {
assertGtZeroTrace("getServiceConfigs", configs.size()); assertGtZeroTrace("getServiceConfigs", configs.size());
} }
private boolean contains(List list, String match) {
match = match.toLowerCase();
for (int i=0; i<list.size(); i++) {
String name = (String)list.get(i);
if (name.toLowerCase().equals(match)) {
return true;
}
}
return false;
}
public void testServicePtql() throws Exception {
Sigar sigar = new Sigar();
try {
long pid = sigar.getServicePid(EVENTLOG_NAME);
String ptql = "Service.Pid.eq=" + pid;
List names = Service.getServiceNames(sigar, ptql);
traceln(ptql + "==" + names);
//different case between XP (Eventlog) and 2008 (EventLog)
assertTrue(contains(names, EVENTLOG_NAME));
} finally {
sigar.close();
}
}
public void testServiceCreateDelete() throws Exception { public void testServiceCreateDelete() throws Exception {
if (!TEST_CREATE) { if (!TEST_CREATE) {
return; return;
+6
View File
@@ -0,0 +1,6 @@
copyright.year=2004-2011
version.major=1
version.minor=6
version.maint=6
version.build=0
-38
View File
@@ -1,38 +0,0 @@
INCLUDES=@INCLUDES@
lib_LTLIBRARIES=
TESTS=
if BUILD_LUA
lib_LTLIBRARIES += sigar.la
sigar_la_SOURCES =\
sigar.c \
sigar-cpu.c \
sigar-disk.c \
sigar-fs.c \
sigar-mem.c \
sigar-netif.c \
sigar-proc.c \
sigar-swap.c \
sigar-sysinfo.c \
sigar-version.c \
sigar-who.c
sigar_la_CPPFLAGS = ${LUA_CFLAGS}
sigar_la_LDFLAGS = $(AM_LDFLAGS) -module -avoid-version
sigar_la_LIBADD = $(top_builddir)/src/libsigar.la
TESTS += \
sigar-test.lua
endif
noinst_HEADERS = lua-sigar.h
TESTS_ENVIRONMENT = \
LUA_PATH="${srcdir}/?.lua" \
LUA_CPATH="${builddir}/.libs/?.so" \
DYLD_LIBRARY_PATH="${top_builddir}/src/.libs/" \
lua
-70
View File
@@ -1,70 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#ifndef __LUA_SIGAR_H__
#define __LUA_SIGAR_H__
#include "sigar.h"
#define LUA_EXPORT_INT(x, y) \
if (x->y == SIGAR_FIELD_NOTIMPL) { \
lua_pushnil(L); \
} else { \
lua_pushnumber(L, x->y); \
} \
lua_setfield(L, -2, #y);
#define LUA_EXPORT_DOUBLE(x, y) \
lua_pushnumber(L, x->y); \
lua_setfield(L, -2, #y);
#define LUA_EXPORT_STR(x, y) \
lua_pushstring(L, x->y); \
lua_setfield(L, -2, #y);
#define LUA_EXPORT_ADDRESS(x, y) \
lua_sigar_push_address(L, &(x->y)); \
lua_setfield(L, -2, #y);
int lua_sigar_cpus_get(lua_State *L);
int lua_sigar_mem_get(lua_State *L);
int lua_sigar_swap_get(lua_State *L);
int lua_sigar_procs_get(lua_State *L);
int lua_sigar_proc_get(lua_State *L);
int lua_sigar_pid_get(lua_State *L);
int lua_sigar_fses_get(lua_State *L);
int lua_sigar_disk_get(lua_State *L);
int lua_sigar_disks_get(lua_State *L);
int lua_sigar_netifs_get(lua_State *L);
int lua_sigar_who_get(lua_State *L);
int lua_sigar_version_get(lua_State *L);
int lua_sigar_sysinfo_get(lua_State *L);
int lua_sigar_push_address(lua_State *L, sigar_net_address_t *addr);
#endif
-183
View File
@@ -1,183 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include "sigar.h"
#include "lua-sigar.h"
typedef struct {
sigar_cpu_list_t data;
sigar_cpu_info_list_t info;
int ref_count;
sigar_t *sigar;
} lua_sigar_cpus_t;
typedef struct {
lua_sigar_cpus_t *cpus;
int ndx;
} lua_sigar_cpu_t;
static int lua_sigar_cpus_free(lua_State *L, lua_sigar_cpus_t *cpus);
static int lua_sigar_cpu_gc(lua_State *L) {
lua_sigar_cpu_t *cpu = (lua_sigar_cpu_t *)luaL_checkudata(L, 1, "sigar_cpu");
lua_sigar_cpus_free(L, cpu->cpus);
return 0;
}
static int lua_sigar_cpu_get_data(lua_State *L) {
lua_sigar_cpu_t *cpu = (lua_sigar_cpu_t *)luaL_checkudata(L, 1, "sigar_cpu");
lua_newtable(L);
#define DATA \
(&(cpu->cpus->data.data[cpu->ndx]))
LUA_EXPORT_INT(DATA, user);
LUA_EXPORT_INT(DATA, sys);
LUA_EXPORT_INT(DATA, idle);
LUA_EXPORT_INT(DATA, nice);
LUA_EXPORT_INT(DATA, wait);
LUA_EXPORT_INT(DATA, irq);
LUA_EXPORT_INT(DATA, soft_irq);
LUA_EXPORT_INT(DATA, stolen);
LUA_EXPORT_INT(DATA, total);
#undef DATA
return 1;
}
static int lua_sigar_cpu_get_info(lua_State *L) {
lua_sigar_cpu_t *cpu = (lua_sigar_cpu_t *)luaL_checkudata(L, 1, "sigar_cpu");
lua_newtable(L);
#define DATA \
(&(cpu->cpus->info.data[cpu->ndx]))
LUA_EXPORT_STR(DATA, vendor);
LUA_EXPORT_STR(DATA, model);
LUA_EXPORT_INT(DATA, mhz);
LUA_EXPORT_INT(DATA, total_sockets);
LUA_EXPORT_INT(DATA, total_cores);
LUA_EXPORT_INT(DATA, cores_per_socket);
LUA_EXPORT_INT(DATA, cache_size);
#undef DATA
return 1;
}
static int lua_sigar_cpus_get_cpu(lua_State *L) {
lua_sigar_cpus_t *cpus = (lua_sigar_cpus_t *)luaL_checkudata(L, 1, "sigar_cpus");
lua_sigar_cpu_t *cpu;
int ndx = luaL_checkint(L, 2);
if (ndx - 1 < 0 ||
ndx - 1 >= cpus->data.number) {
luaL_error(L, ".cpu[%d] out of range: 1..%d", ndx, cpus->data.number);
}
cpu = lua_newuserdata(L, sizeof(lua_sigar_cpu_t));
cpu->cpus = cpus;
cpu->ndx = ndx - 1;
cpus->ref_count++;
if (0 != luaL_newmetatable(L, "sigar_cpu")) {
lua_newtable(L);
lua_pushcfunction(L, lua_sigar_cpu_get_data);
lua_setfield(L, -2, "data");
lua_pushcfunction(L, lua_sigar_cpu_get_info);
lua_setfield(L, -2, "info");
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_cpu_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
static int lua_sigar_cpus_free(lua_State *L, lua_sigar_cpus_t *cpus) {
if (--cpus->ref_count == 0) {
sigar_cpu_list_destroy(cpus->sigar, &(cpus->data));
sigar_cpu_info_list_destroy(cpus->sigar, &(cpus->info));
}
return 0;
}
static int lua_sigar_cpus_gc(lua_State *L) {
lua_sigar_cpus_t *cpus = (lua_sigar_cpus_t *)luaL_checkudata(L, 1, "sigar_cpus");
lua_sigar_cpus_free(L, cpus);
return 0;
}
static int lua_sigar_cpus_len(lua_State *L) {
lua_sigar_cpus_t *cpus = (lua_sigar_cpus_t *)luaL_checkudata(L, 1, "sigar_cpus");
lua_pushinteger(L, cpus->data.number);
return 1;
}
int lua_sigar_cpus_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_cpus_t *cpus;
cpus = lua_newuserdata(L, sizeof(lua_sigar_cpus_t));
cpus->sigar = s;
sigar_cpu_list_get(s, &(cpus->data));
sigar_cpu_info_list_get(s, &(cpus->info));
cpus->ref_count = 1;
if (0 != luaL_newmetatable(L, "sigar_cpus")) {
lua_pushcfunction(L, lua_sigar_cpus_len);
lua_setfield(L, -2, "__len");
lua_pushcfunction(L, lua_sigar_cpus_get_cpu);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_cpus_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
-192
View File
@@ -1,192 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include <stdlib.h>
#include "sigar.h"
#include "lua-sigar.h"
/* disks */
typedef struct {
sigar_file_system_list_t disks;
sigar_t *sigar;
int ref_count;
} lua_sigar_disks_t;
typedef struct {
char *dev_name;
sigar_t *sigar;
} lua_sigar_disk_t;
static int lua_sigar_disks_free(lua_State *L, lua_sigar_disks_t *disks) {
if (--disks->ref_count == 0) {
sigar_file_system_list_destroy(disks->sigar, &(disks->disks));
}
return 0;
}
static int lua_sigar_disks_gc(lua_State *L) {
lua_sigar_disks_t *disks = (lua_sigar_disks_t *)luaL_checkudata(L, 1, "sigar_disks");
lua_sigar_disks_free(L, disks);
return 0;
}
static int lua_sigar_disks_len(lua_State *L) {
lua_sigar_disks_t *disks = (lua_sigar_disks_t *)luaL_checkudata(L, 1, "sigar_disks");
lua_pushinteger(L, disks->disks.number);
return 1;
}
static int lua_sigar_disk_gc(lua_State *L) {
lua_sigar_disk_t *disk = (lua_sigar_disk_t *)luaL_checkudata(L, 1, "sigar_disk");
free(disk->dev_name);
return 0;
}
static int lua_sigar_disk_get_name(lua_State *L) {
lua_sigar_disk_t *disk = (lua_sigar_disk_t *)luaL_checkudata(L, 1, "sigar_disk");
lua_pushstring(L, disk->dev_name);
return 1;
}
static int lua_sigar_disk_get_usage(lua_State *L) {
lua_sigar_disk_t *disk = (lua_sigar_disk_t *)luaL_checkudata(L, 1, "sigar_disk");
sigar_disk_usage_t usage;
int err;
if (SIGAR_OK != (err = sigar_disk_usage_get(disk->sigar, disk->dev_name, &usage))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(usage))
LUA_EXPORT_INT(DATA, reads);
LUA_EXPORT_INT(DATA, writes);
LUA_EXPORT_INT(DATA, read_bytes);
LUA_EXPORT_INT(DATA, write_bytes);
LUA_EXPORT_INT(DATA, rtime);
LUA_EXPORT_INT(DATA, wtime);
LUA_EXPORT_INT(DATA, qtime);
LUA_EXPORT_INT(DATA, time);
LUA_EXPORT_INT(DATA, snaptime);
LUA_EXPORT_DOUBLE(DATA, service_time);
LUA_EXPORT_DOUBLE(DATA, queue);
#undef DATA
return 1;
}
static int lua_sigar_disk_set_metatable(lua_State *L, int ndx) {
if (0 != luaL_newmetatable(L, "sigar_disk")) {
lua_newtable(L);
lua_pushcfunction(L, lua_sigar_disk_get_name);
lua_setfield(L, -2, "name");
lua_pushcfunction(L, lua_sigar_disk_get_usage);
lua_setfield(L, -2, "usage");
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_disk_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, ndx - 1);
return 0;
}
static int lua_sigar_disks_get_disk(lua_State *L) {
lua_sigar_disks_t *disks = (lua_sigar_disks_t *)luaL_checkudata(L, 1, "sigar_disks");
lua_sigar_disk_t *disk;
int ndx = luaL_checkint(L, 2);
if (ndx - 1 < 0 ||
ndx - 1 >= disks->disks.number) {
luaL_error(L, ".disks[%d] out of range: 1..%d", ndx, disks->disks.number);
}
disk = lua_newuserdata(L, sizeof(*disk));
disk->dev_name = strdup(disks->disks.data[ndx - 1].dir_name);
disk->sigar = disks->sigar;
lua_sigar_disk_set_metatable(L, -1);
return 1;
}
int lua_sigar_disk_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_disk_t *disk;
const char *key = luaL_checkstring(L, 2);
disk = lua_newuserdata(L, sizeof(*disk));
disk->dev_name = strdup(key);
disk->sigar = s;
lua_sigar_disk_set_metatable(L, -1);
return 1;
}
int lua_sigar_disks_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_disks_t *disks;
disks = lua_newuserdata(L, sizeof(lua_sigar_disks_t));
disks->sigar = s;
sigar_file_system_list_get(s, &(disks->disks));
disks->ref_count = 1;
if (0 != luaL_newmetatable(L, "sigar_disks")) {
lua_pushcfunction(L, lua_sigar_disks_len);
lua_setfield(L, -2, "__len");
lua_pushcfunction(L, lua_sigar_disks_get_disk);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_disks_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
-186
View File
@@ -1,186 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include "sigar.h"
#include "lua-sigar.h"
/* file-systems */
typedef struct {
sigar_file_system_list_t fses;
sigar_t *sigar;
int ref_count;
} lua_sigar_fses_t;
typedef struct {
lua_sigar_fses_t *fses;
int ndx;
} lua_sigar_fs_t;
static int lua_sigar_fses_free(lua_State *L, lua_sigar_fses_t *fses) {
if (--fses->ref_count == 0) {
sigar_file_system_list_destroy(fses->sigar, &(fses->fses));
}
return 0;
}
static int lua_sigar_fses_gc(lua_State *L) {
lua_sigar_fses_t *fses = (lua_sigar_fses_t *)luaL_checkudata(L, 1, "sigar_fses");
lua_sigar_fses_free(L, fses);
return 0;
}
static int lua_sigar_fses_len(lua_State *L) {
lua_sigar_fses_t *fses = (lua_sigar_fses_t *)luaL_checkudata(L, 1, "sigar_fses");
lua_pushinteger(L, fses->fses.number);
return 1;
}
static int lua_sigar_fs_gc(lua_State *L) {
lua_sigar_fs_t *fs = (lua_sigar_fs_t *)luaL_checkudata(L, 1, "sigar_fs");
lua_sigar_fses_free(L, fs->fses);
return 0;
}
static int lua_sigar_fs_get_info(lua_State *L) {
lua_sigar_fs_t *fs = (lua_sigar_fs_t *)luaL_checkudata(L, 1, "sigar_fs");
lua_newtable(L);
#define DATA \
(&(fs->fses->fses.data[fs->ndx]))
LUA_EXPORT_STR(DATA, dir_name);
LUA_EXPORT_STR(DATA, dev_name);
LUA_EXPORT_STR(DATA, type_name);
LUA_EXPORT_STR(DATA, sys_type_name);
LUA_EXPORT_STR(DATA, options);
#if 0
/* valgrind says: Conditional jump or move depends on uninitialised value
* looks like sigar isn't initializing it */
LUA_EXPORT_INT(DATA, flags);
#endif
#undef DATA
return 1;
}
static int lua_sigar_fs_get_usage(lua_State *L) {
lua_sigar_fs_t *fs = (lua_sigar_fs_t *)luaL_checkudata(L, 1, "sigar_fs");
const char *dir_name = fs->fses->fses.data[fs->ndx].dir_name;
sigar_file_system_usage_t usage;
int err;
if (SIGAR_OK != (err = sigar_file_system_usage_get(fs->fses->sigar, dir_name, &usage))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(usage))
LUA_EXPORT_INT(DATA, total);
LUA_EXPORT_INT(DATA, free);
LUA_EXPORT_INT(DATA, used);
LUA_EXPORT_INT(DATA, avail);
LUA_EXPORT_INT(DATA, files);
LUA_EXPORT_INT(DATA, free_files);
#undef DATA
return 1;
}
static int lua_sigar_fses_get_fs(lua_State *L) {
lua_sigar_fses_t *fses = (lua_sigar_fses_t *)luaL_checkudata(L, 1, "sigar_fses");
lua_sigar_fs_t *fs;
int ndx = luaL_checkint(L, 2);
if (ndx - 1 < 0 ||
ndx - 1 >= fses->fses.number) {
luaL_error(L, ".fses[%d] out of range: 1..%d", ndx, fses->fses.number);
}
fs = lua_newuserdata(L, sizeof(*fs));
fs->ndx = ndx - 1;
fs->fses = fses;
fses->ref_count++;
if (0 != luaL_newmetatable(L, "sigar_fs")) {
lua_newtable(L);
lua_pushcfunction(L, lua_sigar_fs_get_info);
lua_setfield(L, -2, "info");
lua_pushcfunction(L, lua_sigar_fs_get_usage);
lua_setfield(L, -2, "usage");
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_fs_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
int lua_sigar_fses_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_fses_t *fses;
fses = lua_newuserdata(L, sizeof(lua_sigar_fses_t));
fses->sigar = s;
sigar_file_system_list_get(s, &(fses->fses));
fses->ref_count = 1;
if (0 != luaL_newmetatable(L, "sigar_fses")) {
lua_pushcfunction(L, lua_sigar_fses_len);
lua_setfield(L, -2, "__len");
lua_pushcfunction(L, lua_sigar_fses_get_fs);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_fses_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
-62
View File
@@ -1,62 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include "sigar.h"
#include "lua-sigar.h"
int lua_sigar_mem_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
sigar_mem_t mem;
sigar_mem_get(s, &mem);
lua_newtable(L);
#define DATA \
(&(mem))
LUA_EXPORT_INT(DATA, ram);
LUA_EXPORT_INT(DATA, total);
LUA_EXPORT_INT(DATA, used);
LUA_EXPORT_INT(DATA, free);
LUA_EXPORT_INT(DATA, actual_used);
LUA_EXPORT_INT(DATA, actual_free);
LUA_EXPORT_DOUBLE(DATA, used_percent);
LUA_EXPORT_DOUBLE(DATA, free_percent);
#undef DATA
return 1;
}
-206
View File
@@ -1,206 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include "sigar.h"
#include "lua-sigar.h"
/* network interfaces */
typedef struct {
sigar_net_interface_list_t netifs;
sigar_t *sigar;
int ref_count;
} lua_sigar_netifs_t;
typedef struct {
lua_sigar_netifs_t *netifs;
int ndx;
} lua_sigar_netif_t;
static int lua_sigar_netifs_free(lua_State *L, lua_sigar_netifs_t *netifs) {
if (--netifs->ref_count == 0) {
sigar_net_interface_list_destroy(netifs->sigar, &(netifs->netifs));
}
return 0;
}
static int lua_sigar_netifs_gc(lua_State *L) {
lua_sigar_netifs_t *netifs = (lua_sigar_netifs_t *)luaL_checkudata(L, 1, "sigar_netifs");
lua_sigar_netifs_free(L, netifs);
return 0;
}
static int lua_sigar_netifs_len(lua_State *L) {
lua_sigar_netifs_t *netifs = (lua_sigar_netifs_t *)luaL_checkudata(L, 1, "sigar_netifs");
lua_pushinteger(L, netifs->netifs.number);
return 1;
}
static int lua_sigar_netif_gc(lua_State *L) {
lua_sigar_netif_t *netif = (lua_sigar_netif_t *)luaL_checkudata(L, 1, "sigar_netif");
lua_sigar_netifs_free(L, netif->netifs);
return 0;
}
static int lua_sigar_netif_get_info(lua_State *L) {
lua_sigar_netif_t *netif = (lua_sigar_netif_t *)luaL_checkudata(L, 1, "sigar_netif");
int err;
const char *if_name = netif->netifs->netifs.data[netif->ndx];
sigar_net_interface_config_t usage;
if (SIGAR_OK != (err = sigar_net_interface_config_get(netif->netifs->sigar, if_name, &usage))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(usage))
LUA_EXPORT_STR(DATA, name);
LUA_EXPORT_STR(DATA, type);
LUA_EXPORT_ADDRESS(DATA, hwaddr);
LUA_EXPORT_ADDRESS(DATA, address);
LUA_EXPORT_ADDRESS(DATA, destination);
LUA_EXPORT_ADDRESS(DATA, broadcast);
LUA_EXPORT_ADDRESS(DATA, netmask);
LUA_EXPORT_INT(DATA, flags);
LUA_EXPORT_INT(DATA, mtu);
LUA_EXPORT_INT(DATA, metric);
#undef DATA
return 1;
}
static int lua_sigar_netif_get_usage(lua_State *L) {
lua_sigar_netif_t *netif = (lua_sigar_netif_t *)luaL_checkudata(L, 1, "sigar_netif");
int err;
const char *if_name = netif->netifs->netifs.data[netif->ndx];
sigar_net_interface_stat_t usage;
if (SIGAR_OK != (err = sigar_net_interface_stat_get(netif->netifs->sigar, if_name, &usage))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(usage))
LUA_EXPORT_INT(DATA, rx_packets);
LUA_EXPORT_INT(DATA, rx_bytes);
LUA_EXPORT_INT(DATA, rx_errors);
LUA_EXPORT_INT(DATA, rx_overruns);
LUA_EXPORT_INT(DATA, rx_dropped);
LUA_EXPORT_INT(DATA, rx_frame);
LUA_EXPORT_INT(DATA, tx_packets);
LUA_EXPORT_INT(DATA, tx_bytes);
LUA_EXPORT_INT(DATA, tx_errors);
LUA_EXPORT_INT(DATA, tx_overruns);
LUA_EXPORT_INT(DATA, tx_dropped);
LUA_EXPORT_INT(DATA, tx_collisions);
LUA_EXPORT_INT(DATA, tx_carrier);
LUA_EXPORT_INT(DATA, speed);
#undef DATA
return 1;
}
static int lua_sigar_netifs_get_netif(lua_State *L) {
lua_sigar_netifs_t *netifs = (lua_sigar_netifs_t *)luaL_checkudata(L, 1, "sigar_netifs");
lua_sigar_netif_t *netif;
int ndx = luaL_checkint(L, 2);
if (ndx - 1 < 0 ||
ndx - 1 >= netifs->netifs.number) {
luaL_error(L, ".netifs[%d] out of range: 1..%d", ndx, netifs->netifs.number);
}
netif = lua_newuserdata(L, sizeof(*netif));
netif->ndx = ndx - 1;
netif->netifs = netifs;
netifs->ref_count++;
if (0 != luaL_newmetatable(L, "sigar_netif")) {
lua_newtable(L);
lua_pushcfunction(L, lua_sigar_netif_get_info);
lua_setfield(L, -2, "info");
lua_pushcfunction(L, lua_sigar_netif_get_usage);
lua_setfield(L, -2, "usage");
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_netif_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
int lua_sigar_netifs_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_netifs_t *netifs;
netifs = lua_newuserdata(L, sizeof(lua_sigar_netifs_t));
netifs->sigar = s;
sigar_net_interface_list_get(s, &(netifs->netifs));
netifs->ref_count = 1;
if (0 != luaL_newmetatable(L, "sigar_netifs")) {
lua_pushcfunction(L, lua_sigar_netifs_len);
lua_setfield(L, -2, "__len");
lua_pushcfunction(L, lua_sigar_netifs_get_netif);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_netifs_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
-246
View File
@@ -1,246 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include "sigar.h"
#include "lua-sigar.h"
typedef struct {
sigar_proc_list_t procs;
sigar_t *sigar;
} lua_sigar_procs_t;
static int lua_sigar_procs_gc(lua_State *L) {
lua_sigar_procs_t *procs = (lua_sigar_procs_t *)luaL_checkudata(L, 1, "sigar_procs");
sigar_proc_list_destroy(procs->sigar, &(procs->procs));
return 0;
}
static int lua_sigar_procs_len(lua_State *L) {
lua_sigar_procs_t *procs = (lua_sigar_procs_t *)luaL_checkudata(L, 1, "sigar_procs");
lua_pushinteger(L, procs->procs.number);
return 1;
}
static int lua_sigar_procs_get_pid(lua_State *L) {
lua_sigar_procs_t *procs = (lua_sigar_procs_t *)luaL_checkudata(L, 1, "sigar_procs");
int ndx = luaL_checkint(L, 2);
if (ndx - 1 < 0 ||
ndx - 1 >= procs->procs.number) {
luaL_error(L, ".procs[%d] out of range: 1..%d", ndx, procs->procs.number);
}
lua_pushinteger(L, procs->procs.data[ndx - 1]);
return 1;
}
int lua_sigar_procs_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_procs_t *procs;
procs = lua_newuserdata(L, sizeof(lua_sigar_procs_t));
procs->sigar = s;
sigar_proc_list_get(s, &(procs->procs));
if (0 != luaL_newmetatable(L, "sigar_procs")) {
lua_pushcfunction(L, lua_sigar_procs_len);
lua_setfield(L, -2, "__len");
lua_pushcfunction(L, lua_sigar_procs_get_pid);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_procs_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
typedef struct {
sigar_pid_t pid;
sigar_t *sigar;
} lua_sigar_proc_t;
static int lua_sigar_proc_gc(lua_State *L) {
lua_sigar_proc_t *proc = (lua_sigar_proc_t *)luaL_checkudata(L, 1, "sigar_proc");
return 0;
}
static int lua_sigar_proc_get_mem(lua_State *L) {
lua_sigar_proc_t *proc = (lua_sigar_proc_t *)luaL_checkudata(L, 1, "sigar_proc");
sigar_proc_mem_t mem;
int err;
if (SIGAR_OK != (err = sigar_proc_mem_get(proc->sigar, proc->pid, &mem))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(mem))
LUA_EXPORT_INT(DATA, size);
LUA_EXPORT_INT(DATA, resident);
LUA_EXPORT_INT(DATA, share);
LUA_EXPORT_INT(DATA, major_faults);
LUA_EXPORT_INT(DATA, minor_faults);
LUA_EXPORT_INT(DATA, page_faults);
#undef DATA
return 1;
}
static int lua_sigar_proc_get_time(lua_State *L) {
lua_sigar_proc_t *proc = (lua_sigar_proc_t *)luaL_checkudata(L, 1, "sigar_proc");
sigar_proc_time_t t;
int err;
if (SIGAR_OK != (err = sigar_proc_time_get(proc->sigar, proc->pid, &t))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
return 0;
}
lua_newtable(L);
#define DATA \
(&(t))
LUA_EXPORT_INT(DATA, start_time);
LUA_EXPORT_INT(DATA, user);
LUA_EXPORT_INT(DATA, sys);
LUA_EXPORT_INT(DATA, total);
#undef DATA
return 1;
}
static int lua_sigar_proc_get_state(lua_State *L) {
lua_sigar_proc_t *proc = (lua_sigar_proc_t *)luaL_checkudata(L, 1, "sigar_proc");
sigar_proc_state_t state;
int err;
if (SIGAR_OK != (err = sigar_proc_state_get(proc->sigar, proc->pid, &state))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(state))
LUA_EXPORT_STR(DATA, name);
LUA_EXPORT_INT(DATA, ppid);
LUA_EXPORT_INT(DATA, tty);
LUA_EXPORT_INT(DATA, priority);
LUA_EXPORT_INT(DATA, nice);
LUA_EXPORT_INT(DATA, processor);
LUA_EXPORT_INT(DATA, threads);
#undef DATA
return 1;
}
static int lua_sigar_proc_get_exe(lua_State *L) {
lua_sigar_proc_t *proc = (lua_sigar_proc_t *)luaL_checkudata(L, 1, "sigar_proc");
sigar_proc_exe_t t;
int err;
if (SIGAR_OK != (err = sigar_proc_exe_get(proc->sigar, proc->pid, &t))) {
lua_pushnil(L);
lua_pushstring(L, strerror(err));
return 2;
}
lua_newtable(L);
#define DATA \
(&(t))
LUA_EXPORT_STR(DATA, name);
LUA_EXPORT_STR(DATA, cwd);
LUA_EXPORT_STR(DATA, root);
#undef DATA
return 1;
}
int lua_sigar_proc_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
sigar_pid_t pid = luaL_checknumber(L, 2);
lua_sigar_proc_t *proc;
proc = lua_newuserdata(L, sizeof(lua_sigar_proc_t));
proc->sigar = s;
proc->pid = pid;
if (0 != luaL_newmetatable(L, "sigar_proc")) {
lua_newtable(L);
lua_pushcfunction(L, lua_sigar_proc_get_mem);
lua_setfield(L, -2, "mem");
lua_pushcfunction(L, lua_sigar_proc_get_time);
lua_setfield(L, -2, "time");
lua_pushcfunction(L, lua_sigar_proc_get_exe);
lua_setfield(L, -2, "exe");
lua_pushcfunction(L, lua_sigar_proc_get_state);
lua_setfield(L, -2, "state");
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_proc_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
int lua_sigar_pid_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_pushnumber(L, sigar_pid_get(s));
return 1;
}
-59
View File
@@ -1,59 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include "sigar.h"
#include "lua-sigar.h"
int lua_sigar_swap_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
sigar_swap_t swap;
sigar_swap_get(s, &swap);
lua_newtable(L);
#define DATA \
(&(swap))
LUA_EXPORT_INT(DATA, total);
LUA_EXPORT_INT(DATA, used);
LUA_EXPORT_INT(DATA, free);
LUA_EXPORT_INT(DATA, page_in);
LUA_EXPORT_INT(DATA, page_out);
#undef DATA
return 1;
}
-65
View File
@@ -1,65 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include <stdlib.h>
#include "sigar.h"
#include "lua-sigar.h"
int lua_sigar_sysinfo_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
sigar_sys_info_t sysinfo;
sigar_sys_info_get(s, &sysinfo);
lua_newtable(L);
#define DATA \
(&(sysinfo))
LUA_EXPORT_STR(DATA, name);
LUA_EXPORT_STR(DATA, version);
LUA_EXPORT_STR(DATA, arch);
LUA_EXPORT_STR(DATA, machine);
LUA_EXPORT_STR(DATA, description);
LUA_EXPORT_STR(DATA, patch_level);
LUA_EXPORT_STR(DATA, vendor);
LUA_EXPORT_STR(DATA, vendor_version);
LUA_EXPORT_STR(DATA, vendor_name);
LUA_EXPORT_STR(DATA, vendor_code_name);
#undef DATA
return 1;
}
-153
View File
@@ -1,153 +0,0 @@
--[[
-- Copyright (c) 2009, Sun Microsystems Inc.
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification,
-- are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * 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.
-- * Neither the name of Sun Microsystems Inc. nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
--]]
local sigar = assert(require("sigar"))
-- test if the GC is called nicely
local s = assert(sigar.new())
s = nil
function print_table(t)
for k, v in pairs(t) do
print((" %s: %s"):format(k, v))
end
end
local s = sigar.new()
print("-- cpus")
local cpus = s:cpus()
for i = 1, #cpus do
local cpu = cpus[i]
print(i)
print(" info")
local info = cpu:info()
print_table(info)
local data = cpu:data()
print(" data")
print_table(data)
end
print("-- mem")
print_table(s:mem())
print("-- swap")
print_table(s:swap())
print("-- procs")
local procs = s:procs()
for i = 1, #procs do
local pid = procs[i]
local proc = s:proc(pid) -- get the data ... but don't use it
if pid == s:pid() then
print(pid)
print(" mem")
local mem, msg = proc:mem()
if mem then print_table(mem) else print(" -- no mem info: " .. msg) end
print(" time")
local t, msg = proc:time()
if t then print_table(t) else print(" -- no time info: " .. msg) end
print(" state")
local t, msg = proc:state()
if t then print_table(t) else print(" -- no state info: " .. msg) end
print(" exe")
local t, msg = proc:exe()
if t then print_table(t) else print(" -- no exe info: " .. msg) end
end
end
print("-- filesystems")
local fses = s:filesystems()
for i = 1, #fses do
local fs = fses[i]
print(i)
print(" info")
local info = fs:info()
if info then print_table(info) else print(" -- no fs info") end
print(" usage")
local usage = fs:usage()
if usage then print_table(usage) else print(" -- no fs usage") end
end
print("-- disks")
local disks = s:disks()
for i = 1, #disks do
local disk = disks[i]
print(" usage")
local usage, msg = disk:usage()
if usage then print_table(usage) else print(" -- no disk usage: " .. msg) end
end
---
-- try to specify a device that is known, but not listed by the fs-list
local disk = s:disk("/dev/disk1")
if disk then
print(disk:name())
print(" usage")
local usage, msg = disk:usage()
if usage then print_table(usage) else print(" -- no disk usage: " .. msg) end
end
print("-- who")
local who = s:who()
for i = 1, #who do
local w = who[i]
print(" usage")
local usage, msg = w
if usage then print_table(usage) else print(" -- no who usage: " .. msg) end
end
print("-- netifs")
local netifs = s:netifs()
for i = 1, #netifs do
local netif = netifs[i]
print(" info")
local usage, msg = netif:info()
if usage then print_table(usage) else print(" -- no netif info: " .. msg) end
print(" usage")
local usage, msg = netif:usage()
if usage then print_table(usage) else print(" -- no netif usage: " .. msg) end
end
print("-- version")
print_table(s:version())
print("-- sysinfo")
print_table(s:sysinfo())
-65
View File
@@ -1,65 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include <stdlib.h>
#include "sigar.h"
#include "lua-sigar.h"
int lua_sigar_version_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
sigar_version_t *version;
version = sigar_version_get();
lua_newtable(L);
#define DATA \
(version)
LUA_EXPORT_STR(DATA, build_date);
LUA_EXPORT_STR(DATA, scm_revision);
LUA_EXPORT_STR(DATA, version);
LUA_EXPORT_STR(DATA, archname);
LUA_EXPORT_STR(DATA, archlib);
LUA_EXPORT_STR(DATA, binname);
LUA_EXPORT_STR(DATA, description);
LUA_EXPORT_INT(DATA, major);
LUA_EXPORT_INT(DATA, minor);
LUA_EXPORT_INT(DATA, maint);
LUA_EXPORT_INT(DATA, build);
#undef DATA
return 1;
}
-103
View File
@@ -1,103 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include <stdlib.h>
#include "sigar.h"
#include "lua-sigar.h"
typedef struct {
sigar_who_list_t who;
sigar_t *sigar;
} lua_sigar_who_t;
static int lua_sigar_who_gc(lua_State *L) {
lua_sigar_who_t *who = (lua_sigar_who_t *)luaL_checkudata(L, 1, "sigar_who");
sigar_who_list_destroy(who->sigar, &(who->who));
return 0;
}
static int lua_sigar_who_len(lua_State *L) {
lua_sigar_who_t *who = (lua_sigar_who_t *)luaL_checkudata(L, 1, "sigar_who");
lua_pushinteger(L, who->who.number);
return 1;
}
static int lua_sigar_who_get_who(lua_State *L) {
lua_sigar_who_t *who = (lua_sigar_who_t *)luaL_checkudata(L, 1, "sigar_who");
int ndx = luaL_checkint(L, 2);
if (ndx - 1 < 0 ||
ndx - 1 >= who->who.number) {
luaL_error(L, ".who[%d] out of range: 1..%d", ndx, who->who.number);
}
lua_newtable(L);
#define DATA \
(&(who->who.data[ndx - 1]))
LUA_EXPORT_STR(DATA, user);
LUA_EXPORT_STR(DATA, device);
LUA_EXPORT_STR(DATA, host);
LUA_EXPORT_INT(DATA, time);
#undef DATA
return 1;
}
int lua_sigar_who_get(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
lua_sigar_who_t *who;
who = lua_newuserdata(L, sizeof(lua_sigar_who_t));
who->sigar = s;
sigar_who_list_get(s, &(who->who));
if (0 != luaL_newmetatable(L, "sigar_who")) {
lua_pushcfunction(L, lua_sigar_who_len);
lua_setfield(L, -2, "__len");
lua_pushcfunction(L, lua_sigar_who_get_who);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_who_gc);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
-185
View File
@@ -1,185 +0,0 @@
/**
* Copyright (c) 2009, Sun Microsystems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Sun Microsystems Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <string.h>
#include <stdlib.h>
#include "sigar.h"
#include "lua-sigar.h"
/**
* push the converted sigar_net_address_t as string on the stack
*/
int lua_sigar_push_address(lua_State *L, sigar_net_address_t *addr) {
char s[24 + 1]; /* AF_LINK is 2 * 8 + 7 colons = 23
AF_INET6 is 4 * 4 + 3 colons = 17
AF_INET is 4 * 3 + 3 dots = 15
*/
size_t s_have = sizeof(s) - 1;
size_t s_need;
switch (addr->family) {
case SIGAR_AF_UNSPEC:
lua_pushnil(L);
return 1;
case SIGAR_AF_INET:
lua_pushfstring(L, "%d.%d.%d.%d",
(addr->addr.in >> 0) & 0xff,
(addr->addr.in >> 8) & 0xff,
(addr->addr.in >> 16) & 0xff,
(addr->addr.in >> 24) & 0xff);
return 1;
case SIGAR_AF_INET6:
s_need = snprintf(s, s_have, "%4x:%4x:%4x:%4x",
(addr->addr.in6[0]),
(addr->addr.in6[1]),
(addr->addr.in6[2]),
(addr->addr.in6[3]));
if (s_need > s_have) {
/* string is truncated, but written to s */
luaL_error(L, "can't convert INET6 address string, not enough memory: %d need, %d available",
s_need, s_have);
}
lua_pushstring(L, s);
return 1;
case SIGAR_AF_LINK:
s_need = snprintf(s, s_have, "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
addr->addr.mac[0],
addr->addr.mac[1],
addr->addr.mac[2],
addr->addr.mac[3],
addr->addr.mac[4],
addr->addr.mac[5],
addr->addr.mac[6],
addr->addr.mac[7]);
if (s_need > s_have) {
/* string is truncated, but written to s */
luaL_error(L, "can't convert MAC address string, not enough memory: %d need, %d available",
s_need, s_have);
}
lua_pushstring(L, s);
return 1;
}
return 0;
}
static int lua_sigar_free(lua_State *L) {
sigar_t *s = *(sigar_t **)luaL_checkudata(L, 1, "sigar");
sigar_close(s);
return 0;
}
static int lua_sigar_new(lua_State *L) {
sigar_t **_s;
sigar_t *s;
if (SIGAR_OK != sigar_open(&s)) {
luaL_error(L, "sigar_open() failed");
return 0;
}
_s = lua_newuserdata(L, sizeof(sigar_t *));
*_s = s;
if (0 != luaL_newmetatable(L, "sigar")) {
lua_newtable(L);
lua_pushcfunction(L, lua_sigar_cpus_get);
lua_setfield(L, -2, "cpus");
lua_pushcfunction(L, lua_sigar_procs_get);
lua_setfield(L, -2, "procs");
lua_pushcfunction(L, lua_sigar_fses_get);
lua_setfield(L, -2, "filesystems");
lua_pushcfunction(L, lua_sigar_disks_get);
lua_setfield(L, -2, "disks");
lua_pushcfunction(L, lua_sigar_disk_get);
lua_setfield(L, -2, "disk");
lua_pushcfunction(L, lua_sigar_who_get);
lua_setfield(L, -2, "who");
lua_pushcfunction(L, lua_sigar_netifs_get);
lua_setfield(L, -2, "netifs");
lua_pushcfunction(L, lua_sigar_proc_get);
lua_setfield(L, -2, "proc");
lua_pushcfunction(L, lua_sigar_pid_get);
lua_setfield(L, -2, "pid");
lua_pushcfunction(L, lua_sigar_mem_get);
lua_setfield(L, -2, "mem");
lua_pushcfunction(L, lua_sigar_swap_get);
lua_setfield(L, -2, "swap");
lua_pushcfunction(L, lua_sigar_version_get);
lua_setfield(L, -2, "version");
lua_pushcfunction(L, lua_sigar_sysinfo_get);
lua_setfield(L, -2, "sysinfo");
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_sigar_free);
lua_setfield(L, -2, "__gc");
}
lua_setmetatable(L, -2);
return 1;
}
/*
** Assumes the table is on top of the stack.
*/
static void set_info (lua_State *L) {
lua_pushliteral (L, "_COPYRIGHT");
lua_pushliteral (L, "Copyright (c) 2009 Sun Microsystems, Inc.");
lua_settable (L, -3);
lua_pushliteral (L, "_DESCRIPTION");
lua_pushliteral (L, "sigar.*");
lua_settable (L, -3);
lua_pushliteral (L, "_VERSION");
lua_pushliteral (L, "LuaSigar 0.1");
lua_settable (L, -3);
}
static const struct luaL_reg sigarlib[] = {
{"new", lua_sigar_new},
{NULL, NULL}
};
#if defined(_WIN32)
# define LUAEXT_API __declspec(dllexport)
#else
# define LUAEXT_API extern
#endif
LUAEXT_API int luaopen_sigar (lua_State *L) {
luaL_register (L, "sigar", sigarlib);
set_info (L);
return 1;
}
-9
View File
@@ -1,9 +0,0 @@
Makefile
*.bs
*.c
*.cpp
*.o
*.old
Sigar_generated.xs
blib
pm_to_blib
+19 -31
View File
@@ -1,55 +1,43 @@
use ExtUtils::MakeMaker; use ExtUtils::MakeMaker;
use strict;
use Config; use Config;
use File::Basename qw(basename);
use File::Copy qw(copy);
use lib qw(.. lib); use lib qw(.. lib);
use SigarWrapper (); use SigarWrapper ();
use SigarBuild ();
my $gen_xs = 'Sigar_generated.xs';
my(@mm_args);
my(@clean_files) = ($gen_xs);
my $installdir;
if ($ARGV[0]) { if ($ARGV[0]) {
#link against installed libsigar $installdir = $ARGV[0];
my $installdir = $ARGV[0];
@mm_args = (
LIBS => ["-L$installdir/lib -lsigar"],
INC => "-I$installdir/include",
);
} }
else { else {
#all sources in Sigar.so #check binary-dist location and svn source location
my $flags = SigarBuild::flags(); for (qw(../../sigar-bin ../java/sigar-bin)) {
my(@inline_src) = SigarBuild::inline_src($flags); if (-e $_) {
push @clean_files, @inline_src; $installdir = $_;
my(@object) = ('Sigar.o', map { s/cp{0,2}$/o/; $_ } @inline_src); last;
my(@libs) = map { "-l$_" } @{$flags->{libs}}; }
}
@mm_args = (
OBJECT => "@object",
LIBS => ["@libs"],
INC => "@{$flags->{cppflags}}",
dynamic_lib => { OTHERLDFLAGS => "@{$flags->{ldflags}}" },
);
} }
SigarWrapper::generate(Perl => '.'); SigarWrapper::generate(Perl => '.');
my $archname = SigarWrapper::archname();
my $libname = 'sigar';
if ($archname) {
$libname .= '-' . $archname;
}
my $ccname = $Config{ccname}; my $ccname = $Config{ccname};
my $define = { my $define = {
gcc => '-Wall', gcc => '-Wall -Werror',
cc_r => '-qhalt=w', cc_r => '-qhalt=w',
}->{$ccname} || ''; }->{$ccname} || '';
WriteMakefile( WriteMakefile(
'NAME' => 'Sigar', 'NAME' => 'Sigar',
'VERSION_FROM' => 'Sigar.pm', 'VERSION_FROM' => 'Sigar.pm',
'LIBS' => ["-L$installdir/lib -l$libname"],
'INC' => "-I$installdir/include",
'DEFINE' => $define, 'DEFINE' => $define,
'depend' => { 'Sigar.c' => $gen_xs }, 'depend' => { 'Sigar.c' => 'Sigar_generated.xs' },
'realclean' => { FILES => "@clean_files" },
@mm_args,
); );
-27
View File
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2004-2008 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -51,7 +50,6 @@ typedef sigar_disk_usage_t * Sigar__DiskUsage;
typedef sigar_proc_stat_t * Sigar__ProcStat; typedef sigar_proc_stat_t * Sigar__ProcStat;
typedef sigar_net_route_t * Sigar__NetRoute; typedef sigar_net_route_t * Sigar__NetRoute;
typedef sigar_net_interface_stat_t * Sigar__NetInterfaceStat; typedef sigar_net_interface_stat_t * Sigar__NetInterfaceStat;
typedef sigar_arp_t * Sigar__Arp;
typedef sigar_who_t * Sigar__Who; typedef sigar_who_t * Sigar__Who;
typedef sigar_thread_cpu_t * Sigar__ThreadCpu; typedef sigar_thread_cpu_t * Sigar__ThreadCpu;
typedef sigar_resource_limit_t * Sigar__ResourceLimit; typedef sigar_resource_limit_t * Sigar__ResourceLimit;
@@ -509,28 +507,3 @@ net_connection_list(sigar, flags)
OUTPUT: OUTPUT:
RETVAL RETVAL
SV *
arp_list(sigar)
Sigar sigar
PREINIT:
sigar_arp_list_t arp_list;
int status;
CODE:
status = sigar_arp_list_get(sigar, &arp_list);
if (status != SIGAR_OK) {
SIGAR_CROAK(sigar, "arp_list");
}
RETVAL = convert_2svav((char *)&arp_list.data[0],
arp_list.number,
sizeof(*arp_list.data),
"Sigar::Arp");
sigar_arp_list_destroy(sigar, &arp_list);
OUTPUT:
RETVAL
+1 -2
View File
@@ -29,7 +29,6 @@ Sigar::DiskUsage T_PTROBJ
Sigar::ProcStat T_PTROBJ Sigar::ProcStat T_PTROBJ
Sigar::NetRoute T_PTROBJ Sigar::NetRoute T_PTROBJ
Sigar::NetInterfaceStat T_PTROBJ Sigar::NetInterfaceStat T_PTROBJ
Sigar::Arp T_PTROBJ
Sigar::Who T_PTROBJ Sigar::Who T_PTROBJ
Sigar::ThreadCpu T_PTROBJ Sigar::ThreadCpu T_PTROBJ
Sigar::ResourceLimit T_PTROBJ Sigar::ResourceLimit T_PTROBJ
@@ -46,7 +45,7 @@ Sigar::NfsServerV3 T_PTROBJ
OUTPUT OUTPUT
T_NETADDR T_NETADDR
{ {
char addr_str[SIGAR_INET6_ADDRSTRLEN]; char addr_str[INET6_ADDRSTRLEN];
sigar_net_address_to_string(NULL, &$var, addr_str); sigar_net_address_to_string(NULL, &$var, addr_str);
sv_setpv($arg, addr_str); sv_setpv($arg, addr_str);
} }
+1 -447
View File
@@ -1,6 +1,5 @@
/* /*
* Copyright (c) 2007 Hyperic, Inc. * Copyright (c) 2007 Hyperic, Inc.
* Copyright (c) 2010-2011 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,14 +18,13 @@
#include "sigar.h" #include "sigar.h"
#include "sigar_fileinfo.h" #include "sigar_fileinfo.h"
#include "sigar_format.h" #include "sigar_format.h"
#include "sigar_ptql.h"
#define PySigarString_FromNetAddr(a) pysigar_net_address_to_string(&a) #define PySigarString_FromNetAddr(a) pysigar_net_address_to_string(&a)
#define PySigarInt_FromChar(c) PyInt_FromLong((int)c) #define PySigarInt_FromChar(c) PyInt_FromLong((int)c)
#define PySigar_ParsePID \ #define PySigar_ParsePID \
if (pysigar_parse_pid(sigar, args, &pid) != SIGAR_OK) return NULL if (!PyArg_ParseTuple(args, "i", &pid)) return NULL
#define PySigar_ParseName \ #define PySigar_ParseName \
if (!PyArg_ParseTuple(args, "s", &name, &name_len)) return NULL if (!PyArg_ParseTuple(args, "s", &name, &name_len)) return NULL
@@ -69,103 +67,6 @@ static void pysigar_free(PyObject *self)
self->ob_type->tp_free((PyObject *)self); self->ob_type->tp_free((PyObject *)self);
} }
static int pysigar_ptql_re_impl(void *data,
char *haystack, char *needle)
{
PyObject *name = PyString_FromString("sigar");
PyObject *module = PyImport_Import(name);
PyObject *match, *args, *source, *regex, *result;
int matches = 0;
match = PyObject_GetAttrString(module, "string_matches");
source = PyString_FromString(haystack);
regex = PyString_FromString(needle);
args = PyTuple_New(2);
PyTuple_SetItem(args, 0, source); /* steals source reference */
PyTuple_SetItem(args, 1, regex); /* steals regex reference */
result = PyObject_CallObject(match, args);
Py_DECREF(name);
Py_DECREF(module);
Py_DECREF(args);
Py_DECREF(match);
if (result == NULL) {
if (PyErr_Occurred()) {
PyErr_Print();
}
}
else {
matches = (result == Py_True);
Py_DECREF(result);
}
return matches;
}
#define sigar_isdigit(c) \
(isdigit(((unsigned char)(c))))
static int pysigar_parse_pid(sigar_t *sigar, PyObject *args, long *pid)
{
if ((PyTuple_Size(args) >= 1) && PyString_Check(PyTuple_GetItem(args, 0))) {
char *ptql;
int ptql_len;
if (!PyArg_ParseTuple(args, "s#", &ptql, &ptql_len)) {
return !SIGAR_OK;
}
if (sigar_isdigit(*ptql)) {
/* XXX pluck strtoull define from sigar_ptql.c */
PyObject *obj = PyLong_FromString(ptql, &ptql, 10);
*pid = PyLong_AsLong(obj);
Py_DECREF(obj);
return SIGAR_OK;
}
else if ((ptql_len == 2) &&
(*ptql == '$') && (*(ptql + 1) == '$'))
{
*pid = sigar_pid_get(sigar);
return SIGAR_OK;
}
else {
/* XXX cache queries */
sigar_ptql_query_t *query;
sigar_ptql_error_t error;
int status;
status = sigar_ptql_query_create(&query, ptql, &error);
if (status == SIGAR_OK) {
sigar_ptql_re_impl_set(sigar, NULL, pysigar_ptql_re_impl);
status = sigar_ptql_query_find_process(sigar, query, (sigar_pid_t *)pid);
sigar_ptql_re_impl_set(sigar, NULL, NULL);
sigar_ptql_query_destroy(query);
if (status == SIGAR_OK) {
return SIGAR_OK;
}
else {
PySigar_Croak();
}
}
else {
PyErr_SetString(PyExc_ValueError, error.message);
return !SIGAR_OK;
}
}
}
if (PyArg_ParseTuple(args, "i", pid)) {
return SIGAR_OK;
}
else {
return !SIGAR_OK;
}
}
static PyObject *pysigar_net_address_to_string(sigar_net_address_t *address) static PyObject *pysigar_net_address_to_string(sigar_net_address_t *address)
{ {
char addr_str[SIGAR_INET6_ADDRSTRLEN]; char addr_str[SIGAR_INET6_ADDRSTRLEN];
@@ -229,38 +130,6 @@ static PyObject *pysigar_new_strlist(char **data, unsigned long number)
return av; return av;
} }
static PyObject *pysigar_new_doublelist(double *data, unsigned long number)
{
unsigned long i;
PyObject *av;
if (!(av = PyTuple_New(number))) {
return NULL;
}
for (i=0; i<number; i++) {
PyTuple_SET_ITEM(av, i, PyFloat_FromDouble(data[i]));
}
return av;
}
static PyObject *pysigar_new_intlist(int *data, unsigned long number)
{
unsigned long i;
PyObject *av;
if (!(av = PyTuple_New(number))) {
return NULL;
}
for (i=0; i<number; i++) {
PyTuple_SET_ITEM(av, i, PyInt_FromLong(data[i]));
}
return av;
}
static PyObject *pysigar_new_list(char *data, unsigned long number, static PyObject *pysigar_new_list(char *data, unsigned long number,
int size, PyTypeObject *type) int size, PyTypeObject *type)
{ {
@@ -321,296 +190,6 @@ static PyObject *pysigar_net_interface_list(PyObject *self, PyObject *args)
return RETVAL; return RETVAL;
} }
static PyObject *pysigar_net_connection_list(PyObject *self, PyObject *args)
{
int status, flags;
sigar_t *sigar = PySIGAR;
sigar_net_connection_list_t connlist;
PyObject *RETVAL;
if (!PyArg_ParseTuple(args, "i", &flags)) {
return NULL;
}
status = sigar_net_connection_list_get(sigar, &connlist, flags);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_list((char *)&connlist.data[0],
connlist.number,
sizeof(*connlist.data),
&pysigar_PySigarNetConnectionType);
sigar_net_connection_list_destroy(sigar, &connlist);
return RETVAL;
}
static PyObject *pysigar_net_route_list(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_net_route_list_t net_routelist;
PyObject *RETVAL;
status = sigar_net_route_list_get(sigar, &net_routelist);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_list((char *)&net_routelist.data[0],
net_routelist.number,
sizeof(*net_routelist.data),
&pysigar_PySigarNetRouteType);
sigar_net_route_list_destroy(sigar, &net_routelist);
return RETVAL;
}
static PyObject *pysigar_arp_list(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_arp_list_t arplist;
PyObject *RETVAL;
status = sigar_arp_list_get(sigar, &arplist);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_list((char *)&arplist.data[0],
arplist.number,
sizeof(*arplist.data),
&pysigar_PySigarArpType);
sigar_arp_list_destroy(sigar, &arplist);
return RETVAL;
}
static PyObject *pysigar_net_stat(PyObject *self, PyObject *args)
{
int status, flags;
sigar_t *sigar = PySIGAR;
sigar_net_stat_t *RETVAL;
if (!PyArg_ParseTuple(args, "i", &flags)) {
return NULL;
}
RETVAL = malloc(sizeof(*RETVAL));
if ((status = sigar_net_stat_get(sigar, RETVAL, flags)) != SIGAR_OK) {
free(RETVAL);
PySigar_Croak();
return NULL;
}
else {
PyObject *self = PySigar_new(pysigar_PySigarNetStatType);
PySIGAR_OBJ->ptr = RETVAL;
return self;
}
}
static PyObject *pysigar_cpu_list(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_cpu_list_t cpus;
PyObject *RETVAL;
status = sigar_cpu_list_get(sigar, &cpus);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_list((char *)&cpus.data[0],
cpus.number,
sizeof(*cpus.data),
&pysigar_PySigarCpuType);
sigar_cpu_list_destroy(sigar, &cpus);
return RETVAL;
}
static PyObject *pysigar_cpu_info_list(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_cpu_info_list_t cpu_infos;
PyObject *RETVAL;
status = sigar_cpu_info_list_get(sigar, &cpu_infos);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_list((char *)&cpu_infos.data[0],
cpu_infos.number,
sizeof(*cpu_infos.data),
&pysigar_PySigarCpuInfoType);
sigar_cpu_info_list_destroy(sigar, &cpu_infos);
return RETVAL;
}
static PyObject *pysigar_loadavg(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_loadavg_t loadavg;
status = sigar_loadavg_get(sigar, &loadavg);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
return pysigar_new_doublelist(loadavg.loadavg, 3);
}
static PyObject *pysigar_who_list(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_who_list_t wholist;
PyObject *RETVAL;
status = sigar_who_list_get(sigar, &wholist);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_list((char *)&wholist.data[0],
wholist.number,
sizeof(*wholist.data),
&pysigar_PySigarWhoType);
sigar_who_list_destroy(sigar, &wholist);
return RETVAL;
}
static PyObject *pysigar_proc_list(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_proc_list_t list;
PyObject *RETVAL;
if (PyTuple_Size(args) == 0) {
status = sigar_proc_list_get(sigar, &list);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
}
else {
sigar_ptql_query_t *query;
sigar_ptql_error_t error;
char *ptql;
if (!PyArg_ParseTuple(args, "s", &ptql)) {
return NULL;
}
status = sigar_ptql_query_create(&query, ptql, &error);
if (status != SIGAR_OK) {
PyErr_SetString(PyExc_ValueError, error.message);
return NULL;
}
sigar_ptql_re_impl_set(sigar, NULL, pysigar_ptql_re_impl);
status = sigar_ptql_query_find(sigar, query, &list);
sigar_ptql_re_impl_set(sigar, NULL, NULL);
sigar_ptql_query_destroy(query);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
}
RETVAL = pysigar_new_intlist(&list.data[0], list.number);
sigar_proc_list_destroy(sigar, &list);
return RETVAL;
}
static PyObject *pysigar_proc_args(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_proc_args_t proc_args;
long pid;
PyObject *RETVAL;
PySigar_ParsePID;
status = sigar_proc_args_get(sigar, pid, &proc_args);
if (status != SIGAR_OK) {
PySigar_Croak();
return NULL;
}
RETVAL = pysigar_new_strlist(proc_args.data, proc_args.number);
sigar_proc_args_destroy(sigar, &proc_args);
return RETVAL;
}
static int pysigar_env_getall(void *data,
const char *key, int klen,
char *val, int vlen)
{
PyDict_SetItem((PyObject *)data,
PyString_FromStringAndSize(key, klen),
PyString_FromStringAndSize(val, vlen));
return SIGAR_OK;
}
static PyObject *pysigar_proc_env(PyObject *self, PyObject *args)
{
int status;
sigar_t *sigar = PySIGAR;
sigar_proc_env_t procenv;
long pid;
PyObject *RETVAL;
PySigar_ParsePID;
RETVAL = PyDict_New();
procenv.type = SIGAR_PROC_ENV_ALL;
procenv.env_getter = pysigar_env_getall;
procenv.data = RETVAL;
status = sigar_proc_env_get(sigar, pid, &procenv);
if (status != SIGAR_OK) {
PySigar_Croak();
}
return RETVAL;
}
static PyObject *pysigar_format_size(PyObject *self, PyObject *args) static PyObject *pysigar_format_size(PyObject *self, PyObject *args)
{ {
char buffer[56]; char buffer[56];
@@ -627,18 +206,7 @@ static PyObject *pysigar_format_size(PyObject *self, PyObject *args)
static PyMethodDef pysigar_methods[] = { static PyMethodDef pysigar_methods[] = {
{ "close", pysigar_close, METH_NOARGS, NULL }, { "close", pysigar_close, METH_NOARGS, NULL },
{ "net_interface_list", pysigar_net_interface_list, METH_NOARGS, NULL }, { "net_interface_list", pysigar_net_interface_list, METH_NOARGS, NULL },
{ "net_connection_list", pysigar_net_connection_list, METH_VARARGS, NULL },
{ "net_route_list", pysigar_net_route_list, METH_NOARGS, NULL },
{ "file_system_list", pysigar_file_system_list, METH_NOARGS, NULL }, { "file_system_list", pysigar_file_system_list, METH_NOARGS, NULL },
{ "arp_list", pysigar_arp_list, METH_NOARGS, NULL },
{ "net_stat", pysigar_net_stat, METH_VARARGS, NULL },
{ "cpu_list", pysigar_cpu_list, METH_NOARGS, NULL },
{ "cpu_info_list", pysigar_cpu_info_list, METH_NOARGS, NULL },
{ "loadavg", pysigar_loadavg, METH_NOARGS, NULL },
{ "who_list", pysigar_who_list, METH_NOARGS, NULL },
{ "proc_list", pysigar_proc_list, METH_VARARGS, NULL },
{ "proc_args", pysigar_proc_args, METH_VARARGS, NULL },
{ "proc_env", pysigar_proc_env, METH_VARARGS, NULL },
PY_SIGAR_METHODS PY_SIGAR_METHODS
{NULL} {NULL}
}; };
@@ -697,24 +265,10 @@ static PyMethodDef pysigar_module_methods[] = {
#define PY_SIGAR_CONST_STR(name) \ #define PY_SIGAR_CONST_STR(name) \
PyDict_SetItemString(dict, #name, o=PyString_FromString(SIGAR_##name)); Py_DECREF(o) PyDict_SetItemString(dict, #name, o=PyString_FromString(SIGAR_##name)); Py_DECREF(o)
#define PY_SIGAR_DEFINE_CONST_STR(name, value) \
PyDict_SetItemString(dict, name, o=PyString_FromString(value)); Py_DECREF(o)
static void init_pysigar_version(PyObject *dict)
{
PyObject *o;
sigar_version_t *sv = sigar_version_get();
PY_SIGAR_DEFINE_CONST_STR("BUILD_DATE", sv->build_date);
PY_SIGAR_DEFINE_CONST_STR("SCM_REVISION", sv->scm_revision);
PY_SIGAR_DEFINE_CONST_STR("VERSION", sv->version);
}
static void init_pysigar_constants(PyObject *dict) static void init_pysigar_constants(PyObject *dict)
{ {
PyObject *o; PyObject *o;
init_pysigar_version(dict);
PY_SIGAR_CONST_INT(FIELD_NOTIMPL); PY_SIGAR_CONST_INT(FIELD_NOTIMPL);
PY_SIGAR_CONST_INT(IFF_UP); PY_SIGAR_CONST_INT(IFF_UP);
Executable → Regular
+11 -77
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright (c) 2007, 2009 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2009 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -17,82 +16,17 @@
# #
from distutils.core import setup, Extension from distutils.core import setup, Extension
from distutils.util import get_platform
from distutils.sysconfig import get_config_var, get_python_version
from os import system, mkdir, path, popen, rename
import sys
build = 'build' _sigar = Extension(
options = {'perl':'perl'} "_sigar",
deps = [build + '/_sigar_generated.c'] ["_sigar.c"],
include_dirs = ['../java/sigar-bin/include'],
def parse_args(): extra_compile_args = ['-Wall'],
global options libraries=['sigar-universal-macosx'],
args = sys.argv[1:] library_dirs=['../java/sigar-bin/lib'],
for arg in args: extra_link_args=[],
if arg.find("--with-sigar") != -1: define_macros=[],
sys.argv.remove(arg) undef_macros=[])
value = arg.split('=')[1]
options['sigar'] = value
elif arg.find("--with-perl") != -1:
sys.argv.remove(arg)
value = arg.split('=')[1]
options['perl'] = value
def sbuild(cmd):
return popen(options['perl'] + ' -Mlib=.. -MSigarBuild -e ' + cmd).readline()
def sargs(cmd):
res = sbuild(cmd)
if len(res) > 0:
return res.split(' ')
else :
return None
parse_args()
if sys.argv[-1] != 'clean':
if not path.exists(build):
mkdir(build)
system(options['perl'] + ' -Mlib=.. -MSigarWrapper -e generate Python ' + build)
if 'sigar' in options:
sigar = options['sigar']
print "Linking againt libsigar in " + sigar
_sigar = Extension(
"_sigar",
["_sigar.c"],
depends = deps,
include_dirs = [sigar + '/include', build],
extra_compile_args = ['-Wall'],
libraries=['sigar'],
library_dirs=[sigar + '/lib'])
else :
print "Inlining libsigar sources"
src = sargs('inline_src -- ' + build)
src.append('_sigar.c')
version_file = "sigar_version.c"
build_version_file = build + "/" + version_file
libname = "_sigar" + get_config_var("SO")
filters = \
'ARCHNAME=' + get_platform() + '-' + get_python_version() + ' ' + \
'ARCHLIB=' + libname + ' ' + \
'BINNAME=' + libname
system(options['perl'] + ' -Mlib=.. -MSigarBuild -e version_file ' + filters)
rename(version_file, build_version_file)
src.append(build_version_file)
cppflags = sargs('cppflags')
cppflags.append('-Wall')
_sigar = Extension(
"_sigar",
src,
depends = deps,
include_dirs = [build],
extra_compile_args = cppflags,
extra_link_args = sargs('ldflags'),
libraries=sargs('libs'))
setup(name="pysigar", version="0.1", setup(name="pysigar", version="0.1",
py_modules = ['sigar'], py_modules = ['sigar'],
-6
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2011 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -16,8 +15,3 @@
# #
from _sigar import * from _sigar import *
import re
#wrapper for pysigar_ptql_re_impl
def string_matches(source, regex):
return re.compile(regex).match(source) != None
-123
View File
@@ -1,123 +0,0 @@
#!/usr/bin/env python
#
# Copyright (c) 2011 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import unittest
import os
import sys
#prepend PYTHONPATH to find sigar in build/
from distutils.util import get_platform
from distutils.sysconfig import get_python_version
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)) + \
"/../build/lib." + get_platform() + "-" + get_python_version())
import sigar
class SigarTest(unittest.TestCase):
def setUp(self):
self.sigar = sigar.open()
def tearDown(self):
self.sigar.close()
self.sigar = None
def is_type(self, obj, cls):
return obj.__class__.__name__ == cls
def testCpuList(self):
retval = self.sigar.cpu_list()
self.assertTrue(isinstance(retval, tuple))
for cpu in retval:
self.assertTrue(self.is_type(cpu, "Cpu"))
def testCpuInfoList(self):
retval = self.sigar.cpu_info_list()
self.assertTrue(isinstance(retval, tuple))
for cpu in retval:
self.assertTrue(self.is_type(cpu, "CpuInfo"))
def testWhoList(self):
retval = self.sigar.who_list()
self.assertTrue(isinstance(retval, tuple))
for who in retval:
self.assertTrue(self.is_type(who, "Who"))
def testNetRouteList(self):
retval = self.sigar.net_connection_list(0)
self.assertTrue(isinstance(retval, tuple))
for conn in retval:
self.assertTrue(self.is_type(conn, "NetConnection"))
def testNetStat(self):
retval = self.sigar.net_stat(0)
self.assertTrue(self.is_type(retval, "NetStat"))
def testNetRoute(self):
retval = self.sigar.net_route_list()
self.assertTrue(isinstance(retval, tuple))
for route in retval:
self.assertTrue(self.is_type(route, "NetRoute"))
def testProcArgs(self):
retval = self.sigar.proc_args(os.getpid())
self.assertTrue(isinstance(retval, tuple))
self.assertTrue(retval > 1)
for arg in retval:
self.assertTrue(isinstance(arg, str))
self.assertEquals(retval, self.sigar.proc_args(str(os.getpid())))
self.assertEquals(retval, self.sigar.proc_args("$$"))
retval = self.sigar.proc_args("Pid.Pid.eq=" + str(os.getpid()))
self.assertTrue(isinstance(retval, tuple))
def testProcEnv(self):
retval = self.sigar.proc_env(os.getpid())
for k, v in os.environ.items():
self.assertEquals(v, retval[k])
for pid in self.sigar.proc_list("State.Name.eq=python"):
self.sigar.proc_env(pid)
def testProcList(self):
retval = self.sigar.proc_list()
self.assertTrue(isinstance(retval, tuple))
self.assertTrue(len(retval) > 1)
self.assertTrue(os.getpid() in retval)
self.assertTrue(os.getpid() in self.sigar.proc_list("State.Name.eq=python"))
self.assertTrue(os.getpid() in self.sigar.proc_list("State.Name.re=.*ython"))
self.assertFalse(os.getpid() in self.sigar.proc_list("State.Name.eq=ruby"))
try:
self.sigar.proc_list("Invalid.Query.xe=.*ython")
self.assertTrue(False)
except ValueError:
self.assertTrue(True)
def testPtql(self):
try:
self.sigar.proc_args("Invalid.Query.xe=.*ython")
self.assertTrue(False)
except ValueError:
self.assertTrue(True)
def testConstants(self):
self.assertEquals(sigar.IFF_UP, 0x1)
self.assertTrue(len(sigar.VERSION) >= 7)
if __name__ == '__main__':
unittest.main()
-23
View File
@@ -1,23 +0,0 @@
Makefile
rbsigar_generated.rx
mkmf.log
*.o
*.so
*.sl
*.bundle
*.obj
*.def
*.exp
*.lib
*.pdb
*.
*_sigar.c
sigar.c
sigar_*.c
get_mib2.c
kstats.c
procfs.c
peb.c
dlpi.c
*.cpp
rbsigar.so.manifest
-24
View File
@@ -1,24 +0,0 @@
#
# Copyright (c) 2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'sigar'
Sigar.new.arp_list.each do |arp|
host = "?" #XXX
puts host + " " +
"(" + arp.address + ")" + " at " + arp.hwaddr + " " +
"[" + arp.type + "]" + " on " + arp.ifname
end
+2 -5
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2009-2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
sigar = Sigar.new sigar = Sigar.new
@@ -28,8 +27,6 @@ puts num.to_s + " total CPUs.."
infos.each do |info| infos.each do |info|
puts "Vendor........" + info.vendor puts "Vendor........" + info.vendor
puts "Model........." + info.model puts "Model........." + info.model
puts "Current Mhz..." + info.mhz.to_s puts "Mhz..........." + info.mhz.to_s
puts "Maximum Mhz..." + info.mhz_max.to_s
puts "Minimum Mhz..." + info.mhz_min.to_s
puts "Cache size...." + info.cache_size.to_s puts "Cache size...." + info.cache_size.to_s
end end
+8 -13
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007, 2009 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
def format_size(size) def format_size(size)
return Sigar.format_size(size * 1024) return Sigar.format_size(size * 1024)
@@ -28,16 +27,12 @@ puts "Filesystem\tSize\tUsed\tAvail\tUse%\tMounted on\tType\n"
fslist.each do |fs| fslist.each do |fs|
dir_name = fs.dir_name dir_name = fs.dir_name
begin usage = sigar.file_system_usage(dir_name)
usage = sigar.file_system_usage(dir_name)
total = usage.total total = usage.total
used = total - usage.free used = total - usage.free
avail = usage.avail avail = usage.avail
pct = usage.use_percent * 100 pct = usage.use_percent * 100
rescue Exception => e
#e.g. floppy or cdrom drive
used = avail = total = pct = 0;
end
puts fs.dev_name + "\t" + puts fs.dev_name + "\t" +
format_size(total) + "\t" + format_size(total) + "\t" +
+1 -2
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
sigar = Sigar.new sigar = Sigar.new
mem = sigar.mem mem = sigar.mem
+25 -43
View File
@@ -1,7 +1,5 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -16,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
sigar = Sigar.new sigar = Sigar.new
iflist = sigar.net_interface_list iflist = sigar.net_interface_list
@@ -26,10 +24,6 @@ iflist.each do |ifname|
flags = ifconfig.flags flags = ifconfig.flags
encap = ifconfig.type encap = ifconfig.type
if (flags & Sigar::IFF_UP) == 0
next
end
hwaddr = ifconfig.hwaddr hwaddr = ifconfig.hwaddr
if hwaddr == Sigar::NULL_HWADDR if hwaddr == Sigar::NULL_HWADDR
hwaddr = "" hwaddr = ""
@@ -51,51 +45,39 @@ iflist.each do |ifname|
bcast = "" bcast = ""
end end
address = ifconfig.address puts "\t" + "inet addr:" + ifconfig.address +
if address != "0.0.0.0" ptp + bcast + " Mask:" + ifconfig.netmask
puts "\t" + "inet addr:" + address +
ptp + bcast + " Mask:" + ifconfig.netmask
end
if ifconfig.prefix6_length != 0
puts "\t" + "inet6 addr: " + ifconfig.address6 + "/" +
ifconfig.prefix6_length.to_s + " Scope:" + Sigar.net_scope_to_s(ifconfig.scope6)
end
puts "\t" + puts "\t" +
Sigar.net_interface_flags_to_s(flags) + Sigar.net_interface_flags_to_s(flags) +
" MTU:" + ifconfig.mtu.to_s + " MTU:" + ifconfig.mtu.to_s +
" Metric:" + ifconfig.metric.to_s " Metric:" + ifconfig.metric.to_s
if (!ifname.include?(":")) ifstat = sigar.net_interface_stat(ifname)
ifstat = sigar.net_interface_stat(ifname)
puts "\t" +
"RX packets:" + ifstat.rx_packets.to_s +
" errors:" + ifstat.rx_errors.to_s +
" dropped:" + ifstat.rx_dropped.to_s +
" overruns:" + ifstat.rx_overruns.to_s +
" frame:" + ifstat.rx_frame.to_s
puts "\t" + puts "\t" +
"TX packets:" + ifstat.tx_packets.to_s + "RX packets:" + ifstat.rx_packets.to_s +
" errors:" + ifstat.tx_errors.to_s + " errors:" + ifstat.rx_errors.to_s +
" dropped:" + ifstat.tx_dropped.to_s + " dropped:" + ifstat.rx_dropped.to_s +
" overruns:" + ifstat.tx_overruns.to_s + " overruns:" + ifstat.rx_overruns.to_s +
" carrier:" + ifstat.tx_carrier.to_s " frame:" + ifstat.rx_frame.to_s
puts "\t" + "collisions:" + ifstat.tx_collisions.to_s + puts "\t" +
" txqueuelen:" + ifconfig.tx_queue_len.to_s "TX packets:" + ifstat.tx_packets.to_s +
" errors:" + ifstat.tx_errors.to_s +
" dropped:" + ifstat.tx_dropped.to_s +
" overruns:" + ifstat.tx_overruns.to_s +
" carrier:" + ifstat.tx_carrier.to_s
rx_bytes = ifstat.rx_bytes puts "\t" + "collisions:" + ifstat.tx_collisions.to_s
tx_bytes = ifstat.tx_bytes
puts "\t" + rx_bytes = ifstat.rx_bytes
"RX bytes:" + rx_bytes.to_s + tx_bytes = ifstat.tx_bytes
" (" + Sigar.format_size(rx_bytes) + ")" +
" " +
"TX bytes:" + tx_bytes.to_s +
" (" + Sigar.format_size(tx_bytes) + ")" + "\n"
end
puts "\n" print "\t" +
"RX bytes:" + rx_bytes.to_s +
" (" + Sigar.format_size(rx_bytes) + ")" +
" " +
"TX bytes:" + tx_bytes.to_s +
" (" + Sigar.format_size(tx_bytes) + ")" + "\n";
end end
-58
View File
@@ -1,58 +0,0 @@
#
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Example illustrating the use of the optional logger.
require 'sigar'
require 'logger'
sigar = Sigar.new
sigar.log_level = Sigar::LOG_DEBUG
logger = Logger.new(STDERR)
logger.datetime_format = "%H:%M:%S"
# Call something that has DEBUG level logging.
fslist = sigar.file_system_list
# cache data
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
end
puts "Calling file_system_usage() for each filesystem"
puts "\nwith Logger:"
sigar.logger = logger
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
end
puts "\nwith Proc:"
sigar.logger = Proc.new do |level, msg|
puts "Level #{level}: #{msg}"
end
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
end
-31
View File
@@ -1,31 +0,0 @@
#
# Copyright (c) 2009-2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Example illustrating the collecting of network information.
require 'sigar'
sigar = Sigar.new
ninfo = sigar.net_info
puts "Hostname: " + ninfo.host_name
puts "Domain Name: " + ninfo.domain_name
puts "FQDN: " + sigar.fqdn
puts "Default gateway: " + ninfo.default_gateway
puts "Default gateway interface: " + ninfo.default_gateway_interface
puts "Primary DNS: " + ninfo.primary_dns
puts "Secondary DNS: " + ninfo.secondary_dns
+1 -2
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
require 'socket' require 'socket'
#XXX this example is incomplete wrt: #XXX this example is incomplete wrt:
+3 -4
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007, 2009 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
def output(sigar, pid) def output(sigar, pid)
args = sigar.proc_args(pid) args = sigar.proc_args(pid)
@@ -31,5 +30,5 @@ end
sigar = Sigar.new sigar = Sigar.new
ARGV.each do |pid| ARGV.each do |pid|
output(sigar, pid) output(sigar, pid.to_i)
end end
+3 -4
View File
@@ -1,6 +1,5 @@
# #
# Copyright (c) 2007, 2009 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,7 +14,7 @@
# limitations under the License. # limitations under the License.
# #
require 'sigar' require 'rbsigar'
def output(sigar, pid) def output(sigar, pid)
env = sigar.proc_env(pid) env = sigar.proc_env(pid)
@@ -27,5 +26,5 @@ end
sigar = Sigar.new sigar = Sigar.new
ARGV.each do |pid| ARGV.each do |pid|
output(sigar, pid) output(sigar, pid.to_i)
end end
-48
View File
@@ -1,48 +0,0 @@
#
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'sigar'
def flags(flags)
f = ""
if (flags & Sigar::RTF_UP) != 0
f += "U"
end
if (flags & Sigar::RTF_GATEWAY) != 0
f += "G"
end
if (flags & Sigar::RTF_HOST) != 0
f += "H"
end
f
end
def gw(addr)
addr == "0.0.0.0" ? "*" : addr
end
def dest(addr)
addr == "0.0.0.0" ? "default" : addr
end
puts "Kernel IP routing table"
fmt = "%-15s %-15s %-15s %-5s %-6s %-3s %-s\n"
printf fmt, "Destination", "Gateway", "Genmask", "Flags", "Metric", "Ref", "Iface"
Sigar.new.net_route_list.each do |route|
printf fmt, dest(route.destination), gw(route.gateway), route.mask,
flags(route.flags), route.metric.to_s, route.refcnt.to_s, route.ifname
end
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff. Show more