Compare commits

...

504 Commits

Author SHA1 Message Date
bughz 2b713c3dd4 更新 src/os/linux/linux_sigar.c 2024-09-27 17:10:00 +08:00
Konstantin Makarchev af03ded75f 2.0.11 2024-09-10 14:52:40 +03:00
Kostya M 00760eebda
Merge pull request #16 from wollistik/fix_build_issue
Fixing build issue on newer linux and also issues with newer Ruby
2024-09-10 14:49:54 +03:00
Wolfgang Wedelich-John 8b887b2380 Fixing build issue on newer linux and alos issue with newer Ruby 2024-09-10 12:58:09 +02:00
Konstantin Makarchev 9f918d1ae9 2.0.10 2021-10-31 05:29:09 +03:00
Konstantin Makarchev 49a9aeeff5 remove nfsstat methods on osx, because seems it not used, this should fix #11
TODO: return is back, if fix would be finded
2021-10-30 21:02:07 +03:00
Konstantin Makarchev 04754bdf48 fix 2021-06-28 12:24:24 +03:00
Konstantin Makarchev 9691f4bbf7 2.0.9 2021-06-28 12:17:33 +03:00
Konstantin Makarchev b78b558fb7 fixed #10, apply path from https://svnweb.freebsd.org/ports/head/devel/sigar/files/patch-src_os_darwin_darwin__sigar.c?r1=438996&r2=544794 2021-06-28 11:59:40 +03:00
Konstantin Makarchev 01df5b7739 fix readme 2020-10-05 23:32:01 +03:00
Konstantin Makarchev d521805a2d 2.0.8 2020-10-05 23:30:16 +03:00
Konstantin Makarchev 7898cebf27 2.0.7 2020-10-02 18:46:51 +03:00
Kostya M 68ba944840
Merge pull request #9 from yxhuvud/fix-compile-macos
Fix compilation on macos.
2020-10-02 18:42:01 +03:00
Linus Sellberg ad39547629 Fix compilation on macos. 2020-10-02 14:55:03 +02:00
Konstantin Makarchev c5f71e36b7 2.0.6 2019-01-18 09:31:25 +03:00
Konstantin Makarchev ad4ff7f83f fix readme 2019-01-18 09:31:17 +03:00
Konstantin Makarchev 2bb67fa1bf apply freebsd12 compilation patch (#6)
https://svnweb.freebsd.org/ports/head/devel/sigar/files/patch-src_os_darwin_darwin__sigar.c?revision=438996&view=markup
2019-01-18 09:21:16 +03:00
Konstantin Makarchev 4aeac4dfe8 fix doc 2018-12-02 22:39:58 +03:00
Konstantin Makarchev 2c5dd8b674 2.0.5 2018-12-02 22:36:19 +03:00
Kostya M d88f2121b8
Merge pull request #4 from jcoyne/patch-1
Fix compilation with musl libc
2018-12-02 22:33:16 +03:00
Natanael Copa 621764c13d only enable the GNU libc strerror_r on GNU libc
We don't want use the non-standard GNU libc variant of strerror_r on
musl libc, or any libc other than GNU.
2018-11-30 22:34:24 -06:00
Natanael Copa cd07923dd2 fix compilation with musl libc
the HZ define is not exposed by musl libc.
2018-11-30 22:33:49 -06:00
Konstantin Makarchev 0d4fe42927 fix 2018-06-28 22:21:59 +03:00
Konstantin Makarchev 369e5b093e fix 2018-06-28 22:20:17 +03:00
Konstantin Makarchev 9f05d47620 fix doc 2018-06-28 22:19:23 +03:00
Konstantin Makarchev 9b60875c06 fix 2018-06-28 22:17:45 +03:00
Konstantin Makarchev 163745ad5d doc 2018-06-10 07:55:25 +03:00
Konstantin Makarchev 489de8187f add doc 2018-06-10 07:48:51 +03:00
Konstantin Makarchev a2c67588d0 fix compilation with glibc 2.26, major/minor functions, fixed #2
compilation error was:
  linux_sigar.c:1156:22: error: called object ‘major’ is not a function or function pointer
  linux_sigar.c:1157:22: error: called object ‘minor’ is not a function or function pointer
2018-06-10 07:46:09 +03:00
Konstantin Makarchev 2f7284cd4c fix readme 2018-05-30 17:21:34 +03:00
Konstantin Makarchev d07ba63c28 better readme 2018-05-30 16:25:01 +03:00
Konstantin Makarchev 0c11387456 fix building gem 2018-05-30 16:24:06 +03:00
Konstantin Makarchev ced59e8ca6 forget remove from h files 2018-05-30 13:39:28 +03:00
Konstantin Makarchev f46a9baeef update readme and version 2.0.2 2018-05-30 13:33:48 +03:00
Konstantin Makarchev a971b9e8e1 Remove obsolete rpc usage
Fix compilation fail with glibc 2.27.
The latest version of glibc (2.27 at this time)
is compiled without --enable-obsolete-rpc flag.
2018-05-30 13:29:40 +03:00
Konstantin Makarchev 5478eb4be9 update readme 2018-04-10 19:47:33 +03:00
Konstantin Makarchev cc726007b3 add to doc and new version 2018-04-10 19:30:16 +03:00
O_o e9897b25b4
Merge pull request #1 from baughj/master
FreeBSD: don't use v_cache_min/max
2018-04-10 19:24:52 +03:00
Justin Baugh 800076db97 FreeBSD: don't use v_cache_min/max (https://github.com/hyperic/sigar/pull/68) 2018-04-10 09:02:28 -07:00
Konstantin Makarchev 1e23251b5c update readme 2018-01-22 13:08:12 +03:00
Konstantin Makarchev 5cb14da077 update readme 2018-01-22 13:05:46 +03:00
Konstantin Makarchev cd0e5bf315 update readme 2018-01-22 13:02:23 +03:00
Konstantin Makarchev 368efdcd05 update readme 2018-01-22 12:59:44 +03:00
Konstantin Makarchev 5245b8f3e3 update version 2018-01-22 12:51:37 +03:00
Konstantin Makarchev 660259e572 fixed sigar_boot_time_get for linux, to work as gnu ps, this fixed some problems with start_time detection 2018-01-22 12:51:24 +03:00
Konstantin Makarchev dfe8fece17 fix bug undefined symbol: sigar_skip_token, fixed #60 2018-01-22 12:50:15 +03:00
Konstantin Makarchev c2a1af3c25 remove unused sigfaulted logger, fixed #28 2018-01-22 12:48:49 +03:00
ilanuriel ad47dc3b49 Go sources update
With latest changes from Lean Agent
2016-01-04 12:30:16 +02:00
ilanuriel 9158290982 go code
to link with sigar c code
2016-01-04 12:23:11 +02:00
ilanuriel 0f0dbe34ce go bindings
statically build go with sigar using visual studio 2015 IDE
2016-01-04 12:14:32 +02:00
tgoldman 7a6aefc7fb Fix [SIGAR-253]- Remove a space from else if condition 2015-08-17 09:39:01 +03:00
BoazHarel 48ba690dd4 With Tomer.
Optimizing the performance counter queries on win32.

splitted performance counters cache to caches per counter_key.
2015-07-20 11:44:50 +03:00
Boaz 341e288e98 With Tomer.
Optimizing the performance counter queries on win32.

There is now a cache for 1 second to all performance counter data.
2015-07-16 16:11:16 +03:00
tgoldman 0928a780f4 Fix [SIGAR-252] - Add support for discovering Windows 2012 R2 2015-07-01 12:02:42 +03:00
Zvika Idelsberg 706f352e56 removing Override annotations 2015-03-25 04:25:43 -06:00
Zvika Idelsberg 6d4ff51b9c fix bug 1361953(bugzilla)/HQ-4820(jira) - changing the way MultiProcess cpu usage(%) is calculated 2015-03-25 03:40:28 -06:00
Doug MacEachern 236006e02d Bump ruby gem version to 0.7.3
Fixes github issue #49
2014-10-30 14:09:38 -07:00
Doug MacEachern 18c2856f75 nfs.h needs sys/socket.h 2014-10-30 11:00:40 -07:00
David Zhao 13bcf8ae45 Moving sigar includes until after system. Fixes compilation on Xcode 6.1 2014-10-06 16:14:45 -07:00
hananaharonof b89060c481 Merge pull request #46 from hyperic/i18n
Some metrics are missing the '/sec' suffix. This fix first tries to add
2014-09-03 14:12:38 +03:00
unknown 4fcaa226bd 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 13:22:19 +03:00
nira11 189843858e Merge pull request #33 from nettag/master
disk io per process, and a few bug fixes
2013-10-06 02:27:13 -07:00
tgoldman 47f01e0177 [SIGAR-248]- Sigar log monitoring ignores successive lines with same timestamp 2013-09-30 10:53:08 +02:00
nira11 6ed8f3c9b5 c on win compatability poblems 2013-09-15 14:14:42 +00:00
nira11 924c4c7476 removed; 2013-09-15 13:54:49 +00:00
nira11 07b221a253 disk io works using cache - also pid cache cleanup and pid cache dump 2013-09-15 12:00:23 +00:00
nira11 f2ba707d9f sigar hpux - disk io fix 2013-08-27 11:37:22 +00:00
nira11 6508b09304 disk io on aix 2013-08-18 11:45:47 +00:00
nira11 64f32dd125 solaris disk io 2013-08-18 08:24:25 +00:00
nira11 aee1d82fae disk io hpux 2013-08-14 10:20:58 +00:00
root 5a1d5e75f1 show windoes 2012 2013-08-12 09:34:24 +00:00
nettag f15aa84dfe Fixed TestProcDiskIO
Added bytesTotal and some more verification.
2013-08-04 16:41:36 +03:00
nettag 0d91f7d6a4 Added total disk IO metric 2013-08-04 16:19:41 +03:00
nettag b13b8dcbbb Implemented empty sigar_proc_disk_io_get on unsupported systems, to avoid breaking compilation. 2013-07-30 16:22:40 +03:00
Netta Gavrieli 273889f827 Implemented process disk IO metrics on Windows 2013-07-30 06:04:06 -07:00
nettag a62558af50 Added Sigar.getProcDiskIO to Java API on Linux
Returns the total bytes read and written for a process using /proc/pid/io.
2013-07-30 10:37:01 +03:00
Netta Gavrieli ec489fb336 Java - Fixed loading native libraries from paths that contain international characters.
This fixes Hyperic bug https://jira.hyperic.com/browse/HQ-4227
2013-07-30 10:22:50 +03:00
Martin Englund 907fe7a87f Merge pull request #24 from ville-k/master
OSX 10.8 - fix building java bindings
2013-05-08 09:00:57 -07:00
Martin Englund 83fbcbeb4e Merge pull request #11 from EdSchouten/master
Make utmp-handling more standards-compliant.
2013-05-08 08:30:09 -07:00
Ville Kallioniemi a20ec372b7 Fix building java bindings on Mac OSX 10.8
* look for SDKs in their new location inside the
  application bundle of XCode
2012-10-28 14:27:00 -06:00
Doug MacEachern 91aead2fd3 fix gemspec files filter 2012-03-26 16:24:27 -07:00
Doug MacEachern 965051cdcf fix build with XCode 4.3
- avoid use of FlatCarbon headers

- remove sysroot/syslibroot

- fix gemspec files attribute
2012-03-26 15:23:42 -07:00
Ed Schouten 67b476efe0 Make utmp-handling more standards-compliant.
As utmpx is standardized by POSIX, first attempt to access the utmpx
database using the standard getutxent() function. If we don't have
utmpx, fall back to some simple utmp code that accesses the database
manually.

This code has been compile-tested on FreeBSD 8 (utmp), FreeBSD 9 (utmpx)
and Ubuntu Linux 11.10 (utmpx).
2011-12-07 23:57:05 +01:00
Doug MacEachern edf041dc7a Merge branch 'sigar-1.6' 2011-07-18 10:51:02 -07:00
Doug MacEachern b88fb7c0c7 Merge branch 'sigar-1.6' 2011-07-08 13:26:45 -07:00
Ian Eure 4c76ea27c5 Update .gitignore. 2011-07-08 13:03:45 -07:00
Doug MacEachern 44a4062111 update files to clean 2011-07-08 13:03:11 -07:00
Ian Eure 8bd48cc477 Fix stupid build issues. 2011-07-08 12:48:21 -07:00
Doug MacEachern ce23dbeec7 add unit tests 2011-06-28 17:29:26 -07:00
Doug MacEachern 5619873f02 expose sigar_version to Python 2011-06-20 16:53:17 -07:00
Doug MacEachern 73b0850a52 add net_stat Python binding 2011-06-15 15:53:39 -07:00
Doug MacEachern 129062d9cd add net_connection_list Python binding 2011-06-15 15:35:21 -07:00
Doug MacEachern cb1e4f491d add proc_env Python binding 2011-06-15 15:24:03 -07:00
Doug MacEachern de81b90497 add cpu list Python bindings 2011-06-15 14:59:31 -07:00
Doug MacEachern fde00170d7 support ptql query in Python proc_list 2011-06-15 14:47:29 -07:00
Doug MacEachern e0ef7a3616 propagate ptql error message to PyErr 2011-06-15 14:16:14 -07:00
Doug MacEachern 2f8090559e add Python ptql re op impl 2011-06-15 13:55:59 -07:00
Doug MacEachern 1f15289d75 add ptql support for Python 2011-06-15 09:19:04 -07:00
Doug MacEachern 7acf88a0bf add depends 2011-06-15 09:17:43 -07:00
Doug MacEachern fcdf809ef5 add net_route_list Python binding 2011-06-14 10:50:18 -07:00
Doug MacEachern dd8d2355cc add who_list Python binding 2011-06-14 10:49:17 -07:00
Doug MacEachern c1ee0a18b9 add proc_args Python binding 2011-06-14 10:48:30 -07:00
Doug MacEachern 58097d9743 bump copyright.year 2011-04-21 11:38:36 -07:00
Doug MacEachern b44692d8e6 Merge branch 'sigar-1.6' 2011-04-21 11:37:54 -07:00
Doug MacEachern 216a2df541 Merge branch 'sigar-1.6' 2011-04-21 11:36:36 -07:00
Doug MacEachern e09ad13a16 unify DLLMOD_ macros for ms and gnu 2011-04-21 09:58:45 -07:00
Doug MacEachern 59aeadaef2 SIGAR_NETIF_NAME_SHORT=1 env var will use the old eth%d names in sigar_net_interface_list_get 2011-04-12 15:28:01 -07:00
Doug MacEachern 73c3c287f7 use stack buffer instead of heap for sigar_net_interface_name_get 2011-04-12 15:16:58 -07:00
Doug MacEachern 4655d5e3df untabify/style 2011-04-12 15:06:33 -07:00
Doug MacEachern cef810dafb don't use sigar->ifconf_buf in sigar_get_adapters_addresses 2011-04-12 15:03:06 -07:00
Doug MacEachern 240649b925 fixes to compile on MSVC again 2011-04-11 15:04:14 -07:00
Adam Stokes 7041d070f1 - Update list network interfaces win32 variant
Some utilities such as netsh require a friendly name when doing
  any administrative tasks such as stop/start network interfaces.
  Currently sigar list network interfaces as 'ethX, lo, laX'. This
  is fine for read only purposes but in order to make further use
  of the network interfaces on windows we need a friendlyname or at
  least the interface description.
2011-04-11 11:26:33 -07:00
Adam Stokes 8337f13d6c Patch to allow mingw32 compilation 2011-04-11 11:26:32 -07:00
Doug MacEachern 9b8ec6ec5a Merge branch 'sigar-1.6' 2011-04-08 13:03:40 -07:00
Dan Sully adfb6d4d0a Add proc_list to Python bindings. 2011-04-08 10:51:32 -07:00
Dan Sully e0c289a34c Add loadavg to Python bindings. 2011-04-08 10:51:20 -07:00
Doug MacEachern 436ceb351a Merge branch 'sigar-1.6' 2011-04-08 10:49:37 -07:00
Doug MacEachern f2aef38d02 escape colon in process ObjectName 2011-04-08 10:25:05 -07:00
Doug MacEachern 833ca18ecf Merge branch 'sigar-1.6' 2010-09-07 12:41:17 -07:00
Doug MacEachern 78f5683bfc remove dynamic runtime flag on ruby win32 2010-05-28 08:59:09 -07:00
Doug MacEachern 619e639eca fix rescue in file_system_test.rb 2010-05-28 08:58:54 -07:00
Doug MacEachern d20d75908d link in sigar.res on win32 2010-05-28 08:23:32 -07:00
Doug MacEachern 642df76807 add resource_file helper to generate sigar.rc 2010-05-28 08:23:08 -07:00
Doug MacEachern 3598952e93 skip rake cleans unless ruby/Makefile exists 2010-05-20 16:01:46 -07:00
Doug MacEachern 98470f551f adjust ruby load path 2010-05-20 16:01:45 -07:00
Doug MacEachern 282c008aea Merge branch 'sigar-1.6' 2010-05-20 11:48:15 -07:00
Doug MacEachern bee9eb97a2 Merge branch 'sigar-1.6' 2010-05-19 11:36:40 -07:00
Doug MacEachern 6a8f3d3d79 Merge branch 'sigar-1.6' 2010-05-13 10:14:31 -07:00
Doug MacEachern 7a23bd943d Merge branch 'sigar-1.6' 2010-05-13 09:20:37 -07:00
Doug MacEachern c439f0e2b3 Merge branch 'sigar-1.6' 2010-04-28 16:19:34 -07:00
Doug MacEachern 8efd79546e Merge branch 'sigar-1.6' 2010-04-28 15:37:36 -07:00
Doug MacEachern f2b8f76711 Merge branch 'sigar-1.6' 2010-04-28 15:35:19 -07:00
Doug MacEachern 57402b29dc Merge branch 'sigar-1.6' 2010-04-28 15:24:27 -07:00
Doug MacEachern 8016dbe364 GPL v2 license -> Apache 2 license
(grit-generated)
2010-04-28 15:08:39 -07:00
Doug MacEachern 4fe3feb198 Merge branch 'sigar-1.6'
Conflicts:
	bindings/java/src/org/hyperic/sigar/jmx/SigarCpu.java
	bindings/java/src/org/hyperic/sigar/jmx/SigarCpuInfo.java
	bindings/java/src/org/hyperic/sigar/jmx/SigarCpuPerc.java
	bindings/java/src/org/hyperic/sigar/jmx/SigarLoadAverage.java
	bindings/java/src/org/hyperic/sigar/jmx/SigarMem.java
	bindings/java/src/org/hyperic/sigar/jmx/SigarSwap.java
	bindings/ruby/examples/cpu_info.rb
	bindings/ruby/examples/df.rb
	bindings/ruby/examples/free.rb
	bindings/ruby/examples/ifconfig.rb
	bindings/ruby/examples/netstat.rb
	bindings/ruby/examples/pargs.rb
	bindings/ruby/examples/penv.rb
	bindings/ruby/examples/who.rb
2010-04-28 15:03:12 -07:00
Doug MacEachern 37c22746b2 Merge branch 'sigar-1.6' 2010-04-28 11:10:57 -07:00
Doug MacEachern 1f7f641473 Merge branch 'sigar-1.6' 2010-04-27 16:09:48 -07:00
Doug MacEachern 6a806d1724 Merge branch 'sigar-1.6' 2010-04-21 15:44:48 -07:00
Doug MacEachern a8963528fc Merge branch 'sigar-1.6' 2010-04-16 11:01:17 -07:00
Doug MacEachern 21a7b096d5 rm hpux/dlpi.c 2010-04-15 14:20:01 -07:00
Doug MacEachern 4a0dc0cef3 Merge branch 'sigar-1.6' into cleanup
Conflicts:
	bindings/SigarWrapper.pm
	src/os/netware/Makefile.nw
	src/os/netware/netware_sigar.c
	src/os/osf1/osf1_sigar.c
	src/os/stub/stub_sigar.c
2010-04-15 14:14:38 -07:00
Doug MacEachern 1d20d41304 remove hmekstat.h 2010-04-15 11:08:16 -07:00
Doug MacEachern 57176b2a24 Merge branch 'sigar-1.6' 2010-04-15 11:02:32 -07:00
Doug MacEachern 539056d24a Merge branch 'sigar-1.6' 2010-04-15 10:55:35 -07:00
Doug MacEachern 247b90618b Merge branch 'sigar-1.6' 2010-04-14 13:56:17 -07:00
Doug MacEachern a540dc045b Merge branch 'sigar-1.6' 2010-04-14 13:46:36 -07:00
Doug MacEachern 7c94ba7164 Merge branch 'sigar-1.6' 2010-04-09 09:01:27 -07:00
Doug MacEachern d4a917c985 Merge branch 'sigar-1.6' 2010-04-08 13:53:22 -07:00
Doug MacEachern d467da754f Merge branch 'sigar-1.6' 2010-04-08 13:47:27 -07:00
Doug MacEachern cbfdc48167 Merge branch 'sigar-1.6' 2010-04-08 09:41:53 -07:00
Doug MacEachern c431fc185c Merge branch 'sigar-1.6'
Conflicts:
	bindings/java/src/org/hyperic/sigar/cmd/Shell.java
2010-04-07 21:27:57 -07:00
Doug MacEachern 03210ee96f Merge branch 'sigar-1.6' 2010-04-07 13:24:26 -07:00
Doug MacEachern 924f694d7b Merge branch 'sigar-1.6' 2010-04-07 11:12:34 -07:00
Doug MacEachern f14fc92e81 Merge branch 'sigar-1.6' 2010-04-05 16:30:37 -07:00
Doug MacEachern 501adebd39 Merge branch 'sigar-1.6' 2010-04-05 15:52:06 -07:00
Doug MacEachern cf22b7f0a1 Merge branch 'sigar-1.6' 2010-04-04 10:26:06 -07:00
Doug MacEachern ccbd22fad6 Merge branch 'sigar-1.6' 2010-04-03 12:42:53 -07:00
Doug MacEachern f1ddda17c2 Merge branch 'sigar-1.6' 2010-04-02 15:51:06 -07:00
Doug MacEachern aa46186a2d Merge branch 'sigar-1.6' 2010-04-01 17:37:28 -07:00
Doug MacEachern 600d4d5523 Merge branch 'sigar-1.6' 2010-04-01 16:44:31 -07:00
Doug MacEachern 48e01e86e3 Merge branch 'sigar-1.6' 2010-04-01 14:55:02 -07:00
Doug MacEachern bdfd156a63 Merge branch 'sigar-1.6' 2010-04-01 14:49:15 -07:00
Doug MacEachern 3c5fbbe022 (SIGAR-198) fix 64-bit AIX net_route_list impl 2010-04-01 11:23:23 -07:00
Doug MacEachern 6c8e6e6d69 Merge branch 'sigar-1.6' 2010-03-31 10:53:55 -07:00
Doug MacEachern 8a2a8e2f6b Merge branch 'sigar-1.6' 2010-03-30 10:12:56 -08:00
Doug MacEachern e008252b86 Merge branch 'sigar-1.6' 2010-02-09 18:01:44 -08:00
Doug MacEachern 6193cb516f Merge branch 'sigar-1.6' 2010-02-05 14:41:45 -08:00
Doug MacEachern 5e6ec3987e (SIGAR-199) add arp_list Erlang binding 2010-02-01 20:45:49 -08:00
Doug MacEachern 8eb87135e4 (SIGAR-199) arp_list win32 impl 2010-01-27 12:17:26 -08:00
Doug MacEachern 5da26ff5e4 (SIGAR-199) arp_list win32 impl 2010-01-25 18:01:29 -08:00
Doug MacEachern 02959a80a5 (SIGAR-199) arp_list aix impl 2010-01-20 17:34:55 -08:00
Doug MacEachern 0cf7c22d11 remove make_spec task dup 2010-01-19 15:18:41 -08:00
Matthew Kent cc52694c7d (SIGAR-200) Fix undefined symbol in installed ruby binding.
Drop gemspec in favour of generating it on demand from the Rakefile with rake make_spec.
2010-01-19 00:06:53 -08:00
Doug MacEachern 105031e7c1 (SIGAR-199) arp_list hpux impl 2010-01-18 22:48:43 -08:00
Doug MacEachern 353a3e7b07 IFT_BRIDGE undef on darwin 2010-01-18 22:26:42 -08:00
Doug MacEachern 0b23dc0082 IFT_BRIDGE undef on darwin 2010-01-18 22:20:13 -08:00
Doug MacEachern b71d5d67a9 (SIGAR-199) arp_list *bsd/darwin impl 2010-01-18 22:14:45 -08:00
Doug MacEachern 8e77198e0f (SIGAR-199) arp_list solaris impl 2010-01-18 19:09:12 -08:00
Doug MacEachern 3098fca444 (SIGAR-199) add arp_list Python binding 2010-01-18 19:09:12 -08:00
Doug MacEachern 3693661516 (SIGAR-199) add arp_list Perl binding 2010-01-18 19:09:12 -08:00
Doug MacEachern 9777e53988 (SIGAR-199) arp Ruby example 2010-01-18 19:09:12 -08:00
Doug MacEachern 6847888168 (SIGAR-199) add arp_list Ruby binding 2010-01-18 19:09:12 -08:00
Doug MacEachern eec4ba7e97 (SIGAR-199) add arp shell command 2010-01-18 19:09:11 -08:00
Doug MacEachern 34c0007c9a (SIGAR-199) add arp_list test 2010-01-18 19:09:11 -08:00
Doug MacEachern 9847f6a454 (SIGAR-199) arp_list linux impl 2010-01-18 19:09:11 -08:00
Doug MacEachern 9207af5536 (SIGAR-199) add Java ArpList binding 2010-01-18 19:09:11 -08:00
Doug MacEachern e804a1b405 (SIGAR-199) add Arp binding 2010-01-18 19:09:10 -08:00
Doug MacEachern ecd0ad6ab8 (SIGAR-199) stub sigar_arp_list_get impls 2010-01-18 19:09:10 -08:00
Doug MacEachern 6bea72a540 (SIGAR-199) add arp_list_{create,grow,destroy} functions 2010-01-18 19:09:10 -08:00
Doug MacEachern b5cf0dbef4 (SIGAR-199) add arp decls 2010-01-18 19:09:10 -08:00
Doug MacEachern 9c37813c57 Merge branch 'sigar-1.6' 2010-01-18 19:08:57 -08:00
Doug MacEachern 39fef6c396 (SIGAR-198) implement net_route_list on AIX 2010-01-17 23:02:16 -08:00
Doug MacEachern a45a09478f Merge branch 'sigar-1.6' 2010-01-17 22:25:34 -08:00
Doug MacEachern b24274941e fix test target 2010-01-17 19:00:26 -08:00
Doug MacEachern ef0dba2c4c update gemspec 2010-01-17 19:00:26 -08:00
Doug MacEachern 4e995b89f8 changing version to '0.7.x' until the sigar-1.7.0 release 2010-01-17 19:00:26 -08:00
Doug MacEachern fd8274153c s/rbsigar/sigar/g 2010-01-17 19:00:26 -08:00
Doug MacEachern 57513b2d0a use helper 2010-01-17 19:00:26 -08:00
Doug MacEachern 1c049cfd33 start ruby port of java unit tests 2010-01-17 19:00:26 -08:00
Doug MacEachern 1e2f84f631 add FTYPE_* constants 2010-01-17 19:00:26 -08:00
Doug MacEachern b2dd835f79 add loadavg binding 2010-01-17 19:00:26 -08:00
Doug MacEachern f721376fc4 add cpu_list binding 2010-01-17 19:00:26 -08:00
Doug MacEachern 9ca7896ad1 Merge branch 'sigar-1.6' 2010-01-12 10:54:04 -08:00
Doug MacEachern 99ac66307a Merge branch 'sigar-1.6' 2010-01-04 13:50:31 -08:00
Doug MacEachern 3aec8d3886 Merge branch 'sigar-1.6' 2009-12-23 16:18:00 -08:00
Doug MacEachern 1cb651d0e3 add ruby proc_port binding 2009-12-14 16:19:09 -08:00
Doug MacEachern 581143f74c add -D_CRT_SECURE_NO_DEPRECATE if win32 2009-11-18 13:26:52 -08:00
Doug MacEachern 2893440374 commands.getoutput does not work on win32, switch to popen 2009-11-18 13:26:33 -08:00
Doug MacEachern 818de4a64c Merge branch 'sigar-1.6' 2009-11-09 16:47:54 -08:00
Doug MacEachern 7cc2308fc8 Merge branch 'sigar-1.6' 2009-11-09 16:27:46 -08:00
Doug MacEachern f6be3e759e Merge branch 'sigar-1.6' 2009-11-09 16:18:25 -08:00
Doug MacEachern c7dc222b4a Merge branch 'sigar-1.6' 2009-11-05 14:03:16 -08:00
Doug MacEachern c2954ec027 Merge branch 'master' of github.com:hyperic/sigar 2009-11-03 16:23:38 -08:00
Doug MacEachern 1cc9a3e44d Merge branch 'sigar-1.6' 2009-11-03 16:19:16 -08:00
Doug MacEachern 850b00f1a9 (SIGAR-187) implement proc_exe on AIX 2009-11-03 16:17:28 -08:00
Doug MacEachern 7aa28d0ddc Merge branch 'sigar-1.6' 2009-11-03 14:19:28 -08:00
Doug MacEachern cd214a2562 Merge branch 'sigar-1.6' 2009-11-02 16:46:02 -08:00
Doug MacEachern dec7508ed1 Merge branch 'sigar-1.6' 2009-10-23 14:59:07 -07:00
Doug MacEachern b43ead331d Merge branch 'sigar-1.6' 2009-09-30 15:56:44 -07:00
Doug MacEachern e05568c00e more clean 2009-09-17 11:57:21 -07:00
Doug MacEachern 0a9ed4aa00 Merge branch 'sigar-1.6' 2009-09-17 11:48:43 -07:00
Doug MacEachern 623cbee5b5 Merge branch 'sigar-1.6' 2009-09-15 15:22:59 -07:00
Doug MacEachern 52101bd408 Merge branch 'sigar-1.6' 2009-09-15 14:54:00 -07:00
Doug MacEachern e9fcf4b336 Merge branch 'sigar-1.6' 2009-09-10 21:44:26 -07:00
Doug MacEachern d55a1fb20e Merge branch 'sigar-1.6' 2009-09-08 21:50:35 -07:00
Doug MacEachern 84b073e889 Merge branch 'sigar-1.6' 2009-09-04 11:14:49 -07:00
Doug MacEachern b877645615 update autoclean 2009-09-02 16:35:06 -07:00
Doug MacEachern 1676d54123 Merge branch 'sigar-1.6' 2009-09-01 15:39:42 -07:00
Doug MacEachern aa4d8f40a5 Merge commit 'mdkent/SIGAR-180' 2009-08-24 22:19:26 -07:00
Matthew Kent abda75748b Add an example of net_info usage. 2009-08-23 23:26:55 -07:00
Matthew Kent 49bc336919 (SIGAR-180) Expose sigar_fqdn_get in the ruby binding. 2009-08-23 23:24:50 -07:00
Doug MacEachern 499c7c8b0b Merge commit 'emonty/master' 2009-08-23 16:13:14 -07:00
Doug MacEachern 7dca6c58cc update .gitignore 2009-08-23 16:12:54 -07:00
Doug MacEachern bf1543877a Merge branch 'SIGAR-179' 2009-08-23 15:59:14 -07:00
Monty Taylor 4608cde968 Don't try to build lua if we don't ask for it. 2009-08-22 10:23:15 -07:00
Doug MacEachern 713e91d59a Merge commit 'weigon/lua' 2009-08-18 21:22:40 -07:00
Doug MacEachern 43b5297178 Merge commit 'weigon/autotools-and-unittest' 2009-08-18 21:19:52 -07:00
Doug MacEachern a3260dc2fc fix Mac SDK selection 2009-08-18 13:20:17 -07:00
Doug MacEachern 75c2671110 ARPHRD_CISCO not in 2.2 kernel headers 2009-08-15 22:22:54 -07:00
Doug MacEachern ff5aa70493 output NetInfo.getDefaultGatewayInterface 2009-08-15 06:11:02 -07:00
Matthew Kent 7496b795e4 Merge branch 'master' into SIGAR-172 2009-08-13 23:41:53 -07:00
Matthew Kent 4fdcee3635 Tweaking based on feedback: default_interface gets a more appropriate name and
sigar_get_default_gateway now gathers both pieces of information.
2009-08-13 23:38:45 -07:00
Doug MacEachern 085218e3fb add win32 comsupp and wbemuuid libs 2009-08-13 16:35:08 -07:00
Doug MacEachern 245e563857 .cpp -> .o 2009-08-13 16:34:11 -07:00
Doug MacEachern ee15426546 need to use sysctlbyname with hw.cpufrequency_{min,max} 2009-08-13 15:45:03 -07:00
Doug MacEachern 326d6085a2 Merge commit 'mdkent/SIGAR-178' 2009-08-13 15:34:37 -07:00
Doug MacEachern bd93c22d14 Merge commit 'mdkent/SIGAR-174' 2009-08-13 14:51:51 -07:00
Doug MacEachern f69a3c10e5 Merge commit 'mdkent/SIGAR-173' 2009-08-13 14:34:41 -07:00
Jan Kneschke 8470738ff3 applied the configure-lua patch to the lua branch 2009-08-13 20:07:02 +02:00
Jan Kneschke 5d222575ef added lua bindings
added lua bindings for the majority of sigar functions
  look at sigar-test.lua on how to use it
2009-08-13 20:04:50 +02:00
Jan Kneschke b3bfe99aea removed the lua-binding part 2009-08-13 20:00:53 +02:00
Matthew Kent dcddb5f642 Untested stab at cpu mhz min/max support for Darwin. 2009-08-12 23:43:41 -07:00
Matthew Kent 09f3418c1a Add linux collection of cpu min/max.
Make cpu mhz default the current mhz.
2009-08-12 23:43:35 -07:00
Jan Kneschke 99d73258a9 added a few more missing files 2009-08-12 21:25:58 +02:00
Doug MacEachern 5c8d1edbae add IFF_DYNAMIC to NetFlags 2009-08-12 10:13:13 -07:00
Doug MacEachern 22c1b065dd add IFF_MASTER to NetFlags 2009-08-12 10:11:36 -07:00
Doug MacEachern a77d7ef04f IFF_DYNAMIC not defined in linux 2.2 kernel 2009-08-12 10:07:08 -07:00
Doug MacEachern 6f75fc0668 Merge commit 'mdkent/SIGAR-171' 2009-08-12 09:57:00 -07:00
Doug MacEachern 1642acc6b0 Merge branch 'sigar-1.6' 2009-08-12 09:42:39 -07:00
Matthew Kent ea3fcd5b45 Add more interface types from net-tools. 2009-08-10 00:29:23 -07:00
Matthew Kent 83996dda13 Add per interface support for tx_queue_len, Linux only.
Update the ifconfig example output.
2009-08-09 15:20:25 -07:00
Jan Kneschke d65177559d fixed the autotools setup
* fixed compile on all Unixes
  * added unit-tests
  * added cmake to build natively on win32
  * fixed the "make dist" setup to include all os-dirs
2009-08-09 15:35:24 +02:00
Jan Kneschke f88489dc73 added unit-tests
unit-tests for the majority of sigar functions including
  valgrind-leak-check
2009-08-09 15:34:27 +02:00
Matthew Kent d9f37b39a4 Collect the default interface as part of net_info_get. 2009-08-09 02:13:45 -07:00
Matthew Kent cfae297d9b Add IFF_DYNAMIC support for Linux.
Support in the ruby binding.
2009-08-08 14:44:58 -07:00
Doug MacEachern c007175b21 update .gitignore 2009-08-05 17:24:28 -07:00
Doug MacEachern c6e8679079 include src/os/*.cpp 2009-08-05 17:22:08 -07:00
Doug MacEachern 7ccd02ef91 Merge branch 'sigar-1.6' 2009-08-05 17:12:48 -07:00
Doug MacEachern c78c5fe899 Merge commit 'mdkent/SIGAR-170' 2009-08-05 06:57:22 -07:00
Matthew Kent 4e206baa61 Make ruby ifconfig example output a bit closer to net-tools default - only
showing interfaces that are up and suppressing the output of unconfigured ip
addresses.
2009-08-04 23:00:07 -07:00
Matthew Kent 4d19f54b94 Finish support for IFF_SLAVE and add IFF_MASTER.
Support both in ruby binding.
2009-08-04 22:27:13 -07:00
Doug MacEachern 48f9f8cc65 fix solaris 8 compile 2009-08-03 15:26:18 -07:00
Doug MacEachern 0cc4f6e8bb fix ruby win32 compile 2009-08-03 10:12:03 -07:00
Doug MacEachern dc8c9ce0f6 Merge branch 'sigar-1.6' 2009-07-31 14:51:30 -07:00
Doug MacEachern 2ee2b7a154 Merge branch 'sigar-1.6' 2009-07-30 17:48:18 -07:00
Doug MacEachern 2733b90ee8 fix ruby compile on solaris 2009-07-30 11:35:28 -07:00
unknown ba22cc0531 net_interface ipv6 support requires msvc7 or higher 2009-07-30 10:32:42 -07:00
Doug MacEachern e2c74bb616 hpux net_interface_ipv6_config impl 2009-07-30 08:27:06 -07:00
Doug MacEachern e3e45a39fe hpux has inet_ntop 2009-07-30 08:26:34 -07:00
Doug MacEachern e92da5240f aix net_interface_ipv6_config impl 2009-07-29 21:37:31 -07:00
Doug MacEachern f55e619bcd output string version of scope6 2009-07-29 16:08:48 -07:00
Doug MacEachern 6d35ab65b3 output string version of scope6 2009-07-29 16:08:42 -07:00
Doug MacEachern e2bb79ca1c add net_scope_to_string ruby wrapper 2009-07-29 16:08:16 -07:00
Doug MacEachern ffd7609c12 add net_scope_to_string java wrapper 2009-07-29 16:07:52 -07:00
Doug MacEachern 75b83e6cf5 add sigar_net_scope_to_string 2009-07-29 16:07:09 -07:00
Doug MacEachern 64fd05c615 Merge commit 'mdkent/SIGAR-167' 2009-07-29 15:45:21 -07:00
Doug MacEachern a7797c7675 Merge commit 'mdkent/SIGAR-166' 2009-07-29 15:35:27 -07:00
Doug MacEachern 911abd2058 Merge branch 'SIGAR-165' 2009-07-29 15:29:12 -07:00
Doug MacEachern 10051fa8ff win32 net_interface_ipv6_config impl 2009-07-29 15:23:09 -07:00
Doug MacEachern f0b96796e1 win32 sigar_inet_ntop impl 2009-07-29 15:20:38 -07:00
Doug MacEachern 3f1b24b7fc solaris net_interface_ipv6_config impl 2009-07-29 15:14:38 -07:00
Doug MacEachern e90567d94b use new ipv6 macros 2009-07-29 15:14:11 -07:00
Doug MacEachern 54d1ee7cff add some ipv6 related macros 2009-07-29 15:13:25 -07:00
Matthew Kent 807aa955c1 No stats for aliased devices. 2009-07-28 23:18:11 -07:00
Matthew Kent 1347d44c78 Add logging ability to ruby bindings via Logger or Proc.
Heavily inspired by the Java implementation.
2009-07-28 22:54:16 -07:00
Doug MacEachern 1c7020c553 add inet6 addr 2009-07-25 08:13:44 -07:00
Doug MacEachern 0da8e9d95f prefix|scope .= 6 2009-07-25 08:09:53 -07:00
Doug MacEachern 8411da271e darwin/*bsd net_interface_ipv6_config impl 2009-07-25 08:00:24 -07:00
Doug MacEachern 9d50d859bf add IPV6_ADDR constants 2009-07-25 07:39:42 -07:00
Doug MacEachern 6cb7d6b398 test NetInterfaceConfig.getAddress6 2009-07-24 17:56:20 -07:00
Doug MacEachern 7c5e4e3a3b linux net_interface_ipv6_config impl 2009-07-24 17:46:56 -07:00
Doug MacEachern 1b28f2a4e3 add ipv6 fields 2009-07-24 17:38:13 -07:00
Doug MacEachern 380297ea2e add ipv6 fields to NetInterfaceConfig 2009-07-24 17:18:30 -07:00
Doug MacEachern 0e763c13e2 stub net_interface_config ipv6 support 2009-07-24 17:13:19 -07:00
Doug MacEachern 1a9eaa800f Merge branch 'ruby-version-properties' 2009-07-18 22:37:56 -07:00
Doug MacEachern ce06f86292 ruby version of Version.java 2009-07-18 21:56:44 -07:00
Doug MacEachern 5d572585b0 add sigar version constants 2009-07-18 21:56:44 -07:00
Doug MacEachern d1622a808d generate sigar_version.c 2009-07-18 21:56:44 -07:00
Doug MacEachern 3e7254f3f7 filter args in version_file 2009-07-18 21:56:44 -07:00
Doug MacEachern 78150c0d9b whitespace fixes 2009-07-18 21:56:44 -07:00
Doug MacEachern 5320b7bf2a -MSigarBuild -e version_file 2009-07-18 21:56:44 -07:00
Doug MacEachern dc2d72f66b move sub archname to SigarBuild.pm 2009-07-18 21:56:43 -07:00
Doug MacEachern 6f9a8423fb Perl impl of version_file 2009-07-18 21:56:43 -07:00
Doug MacEachern 7c3fb1d10d update version.properties location 2009-07-18 21:56:43 -07:00
Doug MacEachern cff9291fc2 update version.properties location 2009-07-18 21:56:43 -07:00
Doug MacEachern ad961111c7 mv version.properties to top-level 2009-07-18 21:56:43 -07:00
Doug MacEachern 49e769bbd8 Merge branch 'sigar-1.6' 2009-07-18 18:44:26 -07:00
Doug MacEachern ba079dc3c5 Merge branch 'sigar-1.6' 2009-07-17 14:16:53 -07:00
Doug MacEachern 7535a0efc2 Merge branch 'sigar-1.6' 2009-07-16 07:10:13 -07:00
Doug MacEachern f2bc7f088d Merge branch 'sigar-1.6' 2009-07-13 17:57:54 -07:00
Doug MacEachern ea2a8f31a1 Merge branch 'sigar-1.6' 2009-07-13 15:18:45 -07:00
Matthew Kent c7a5d127eb Refresh gemspec.
Signed-off-by: Hyperic <doug.maceachern@hyperic.com>
2009-07-09 21:47:14 +08:00
Doug MacEachern 39352f9290 Merge branch 'sigar-1.6' 2009-07-08 18:02:49 -07:00
Doug MacEachern e0a4d10522 Merge branch 'sigar-1.6' 2009-07-08 17:38:19 -07:00
Doug MacEachern e9c0ec7c87 Merge branch 'sigar-1.6' 2009-07-08 16:27:17 -07:00
Doug MacEachern ba6404560e Merge branch 'sigar-1.6' 2009-07-08 16:02:17 -07:00
Doug MacEachern a9533e619d Merge branch 'sigar-1.6' 2009-07-07 15:36:50 -07:00
Doug MacEachern 930de473be Merge branch 'sigar-1.6' 2009-07-07 15:31:07 -07:00
Doug MacEachern 9769d17c3d Merge branch 'sigar-1.6' 2009-07-03 15:50:17 -07:00
Doug MacEachern 14b916fdb6 Merge branch 'sigar-1.6' 2009-07-02 16:03:52 -07:00
Doug MacEachern a19c5a3454 Merge branch 'sigar-1.6' 2009-07-02 13:58:29 -07:00
Doug MacEachern b47f4b8b1b Merge branch 'sigar-1.6' 2009-07-01 16:28:03 -07:00
Doug MacEachern 6a5b8c00de Merge branch 'sigar-1.6' 2009-07-01 15:06:35 -07:00
Doug MacEachern 4c165819a3 Merge branch 'sigar-1.6'
Conflicts:
	bindings/java/hyperic_jni/src/org/hyperic/jni/ArchNameTask.java
2009-06-30 16:08:50 -07:00
Doug MacEachern 118a3e71fa Ruby example of route cmd 2009-06-29 17:21:03 -07:00
Doug MacEachern 38e2e85132 add RTF constants 2009-06-29 17:20:19 -07:00
Doug MacEachern e81c50eeca Merge branch 'sigar-1.6' 2009-06-17 17:57:39 -07:00
Doug MacEachern 0008c56119 Merge branch 'erlang' 2009-06-14 21:29:29 -07:00
Doug MacEachern 22c0d9e356 experimental erlang driver 2009-06-14 21:29:08 -07:00
Doug MacEachern 0cecd10a4d Merge branch 'sigar-1.6' 2009-06-06 08:38:46 -07:00
Doug MacEachern 715b32f1a6 Merge branch 'sigar-1.6' 2009-06-01 13:30:38 -07:00
Doug MacEachern 099f021675 Merge branch 'sigar-1.6' 2009-05-24 18:19:15 -07:00
Doug MacEachern c3feb6e8d7 fix compile on OpenBSD and older FreeBSD 2009-05-23 07:36:43 -07:00
Doug MacEachern a76768c30f rid -Wall statvfs warning on solaris 8 2009-05-23 07:36:33 -07:00
Doug MacEachern cb7b440c0c Merge branch 'sigar-1.6' 2009-05-22 12:06:04 -07:00
Doug MacEachern 474ccff730 Merge branch 'SIGAR-148' 2009-05-21 16:57:50 -07:00
Doug MacEachern 376409a403 (SIGAR-148) use sigar_statvfs 2009-05-21 14:26:34 -07:00
Doug MacEachern b53121d071 (SIGAR-148) use sigar_statvfs 2009-05-21 14:26:29 -07:00
Doug MacEachern 94b3f884a2 (SIGAR-148) add generic sigar_statvfs built with LFS flags 2009-05-21 14:25:46 -07:00
Doug MacEachern d3ceb14ff7 Merge branch 'master' of git@github.com:hyperic/sigar 2009-05-14 08:37:50 -07:00
Doug MacEachern 1f8db9098a Merge branch 'SIGAR-146' 2009-05-13 17:31:30 -07:00
Doug MacEachern c43b43ae03 fix so SigarPermissionDeniedException is throw on open /dev/kmem EACCES 2009-05-13 16:56:08 -07:00
Doug MacEachern 90b2ade95e add 64-bit compile/link flags for AIX 2009-05-13 16:54:49 -07:00
Doug MacEachern 2643818a45 snapshot @c14dc0f: use '-qversion' for identifier, fixes 64-bit xlc_r compile on AIX 2009-05-13 16:54:13 -07:00
Doug MacEachern f5881726fd test unregisterMBean 2009-04-29 18:08:55 -07:00
Doug MacEachern 806ee088d7 support no arg SigarRegistry constructor 2009-04-29 17:58:39 -07:00
Doug MacEachern 074d20d7b6 switch from Dynamic to Standard MBean 2009-04-29 17:41:46 -07:00
Doug MacEachern 7157234182 extend ReflectedMBean 2009-04-29 16:35:51 -07:00
Doug MacEachern b004072d48 Object wrapper of double[] Sigar.getLoadAverage() for use in bean patterns (JMX) 2009-04-29 16:32:36 -07:00
Doug MacEachern 448b595e30 only SigarRegistry needs to implement MBeanRegistration 2009-04-29 15:16:17 -07:00
Doug MacEachern 25241fcc7a remove generated comments 2009-04-29 15:02:11 -07:00
Doug MacEachern f6e85761d2 SigarProxy must implement InvocationHandler 2009-04-29 14:55:47 -07:00
Doug MacEachern ad8325e616 remove MBeanConstructorInfo 2009-04-29 14:42:42 -07:00
Doug MacEachern b3603f4489 SigarProcess.close only applies to SigarProcess(void) constructor 2009-04-29 14:34:40 -07:00
Doug MacEachern bf361a1732 make SigarProxyCached.invoke synchronized 2009-04-29 13:09:15 -07:00
Doug MacEachern 1c87169bdb leave SigarProxy impl to the caller 2009-04-29 12:58:45 -07:00
Doug MacEachern 0eb3672642 add mx -jconsole option 2009-04-29 12:19:40 -07:00
Doug MacEachern 6ef73dcbcb use SigarVersion bean 2009-04-29 10:56:14 -07:00
Doug MacEachern 0a1a3de69f use SigarVersion bean 2009-04-29 10:53:07 -07:00
Doug MacEachern 96ca3970e1 add SigarVersion getter 2009-04-29 10:51:55 -07:00
Doug MacEachern a84788f1a0 encapsulate version attributes 2009-04-29 10:51:32 -07:00
Doug MacEachern 3e0e08f088 rename SigarVersion -> Version 2009-04-29 10:17:58 -07:00
Doug MacEachern ec3fbe993c remove unused code 2009-04-29 10:04:59 -07:00
Doug MacEachern b9caed4157 getrusage on NetBSD may not return monotonically increasing values for CPU time.
See: http://archives.devshed.com/forums/bsd-93/kern-30115-getrusage-returns-bogus-ru-utime-values-220800.html
2009-04-25 09:52:07 -07:00
Doug MacEachern a95b8a8b60 (SIGAR-130) Use pstat(PSTAT_GETCOMMANDLINE,...) on HP-UX < 11iv2 2009-04-25 07:46:40 -07:00
Doug MacEachern 8e6a2179dd (SIGAR-39) Use kern.cp_times in cpu_list on FreeBSD 7.x+ 2009-04-20 18:39:36 -07:00
Doug MacEachern 2fc550c8fd (SIGAR-130) Use pstat_getcommandline on HP-UX 11iv2+ 2009-04-18 08:57:41 -07:00
Doug MacEachern 0996361ec6 (SIGAR-131) switch to pst_fileinfo2 on all HPUX flavors 2009-04-17 18:31:35 -07:00
Doug MacEachern 19d9e00787 python/setup.py now builds all sigar srcs 2009-04-04 19:15:36 -07:00
Doug MacEachern 7f8bfd8195 support build dir other than '.' 2009-04-04 19:07:32 -07:00
Doug MacEachern 9eade5d21a (SIGAR-141) sigar.jar location is not required to find native library 2009-03-27 15:07:32 -07:00
Doug MacEachern 4333771fc3 fix compile against ruby 1.9 2009-03-25 20:10:19 -07:00
Doug MacEachern eb05ff0760 fix compile against ruby 1.8.4 2009-03-25 14:58:06 -07:00
Doug MacEachern 6819b18af6 dont require pdh.dll on NT 4.0 2009-03-25 14:13:56 -07:00
Doug MacEachern 646fc226ea remove pdh.dll (only used on NT 4.0) 2009-03-25 13:46:24 -07:00
Doug MacEachern 85838c3512 remove msvc_iptypes.h 2009-03-25 13:44:30 -07:00
Doug MacEachern 891f30bf0d (SIGAR-140) interface aliases are valid in sigar_net_interface_config_primary_get 2009-03-25 11:18:04 -07:00
Doug MacEachern f7b590cf27 ruby ptql_re_impl 2009-03-16 20:04:33 -07:00
Doug MacEachern 026d560a09 support optional ptql param in proc_list 2009-03-15 23:20:45 -07:00
Doug MacEachern e6d9239844 add proc_list ruby wrapper 2009-03-15 12:47:08 -07:00
Doug MacEachern 4bd7310f9a add ptql support to proc methods 2009-03-15 12:33:54 -07:00
Doug MacEachern 63141c38b9 rid mac os 10.5 warning: utmp is deprecated 2009-03-14 12:37:29 -07:00
Doug MacEachern 3025c4554f (SIGAR-139) support scripted SIGAR_PROC_NET for testing 2009-03-12 21:30:50 -07:00
Doug MacEachern 1ce9a3209d Merge branch 'master' of git@github.com:hyperic/sigar 2009-03-07 06:40:41 -08:00
Doug MacEachern 634cd53a79 6.1 == Windows 7 2009-03-07 06:40:23 -08:00
Doug MacEachern d34efe0474 10.6 == Snow Leopard 2009-03-07 06:37:36 -08:00
Doug MacEachern 1bd4f0e074 use ArchNameTask to configure darwin sdk 2009-02-25 21:35:54 -08:00
Doug MacEachern 839010d6c9 use SIGAR_INET6_ADDRSTRLEN 2009-02-24 19:47:41 -08:00
Doug MacEachern 24bf84a310 import File::Copy 2009-02-24 19:40:25 -08:00
Doug MacEachern 9935c592f6 avoid sigar.o/Sigar.o clash on case insensitive filesystems 2009-02-24 19:34:56 -08:00
Doug MacEachern 349b7caaf6 use SigarBuild.pm 2009-02-24 19:07:51 -08:00
Doug MacEachern b2a1f5cbd5 sharable build utils 2009-02-24 19:07:32 -08:00
Doug MacEachern 59c7c1d975 ignore perl build files 2009-02-24 19:06:23 -08:00
Doug MacEachern 1320801e04 chdir to sigar root 2009-02-16 18:21:45 -08:00
Doug MacEachern aa605fcde1 make distclean incase of nfs shared dir 2009-02-16 17:53:10 -08:00
Doug MacEachern 36f7289082 fix for ruby 1.8.4 2009-02-16 17:36:53 -08:00
Doug MacEachern f81f9a52ab rake tasks for use from hudson 2009-02-16 13:51:24 -08:00
Doug MacEachern 52c3bb0191 fix for mswin64 2009-02-16 13:50:25 -08:00
Doug MacEachern 5fe0332f66 remove unused requires 2009-02-16 12:42:13 -08:00
Doug MacEachern d99e55c9eb Merge branch 'gem' 2009-02-16 10:51:07 -08:00
Doug MacEachern 60e96f28b7 add ruby gemspec 2009-02-16 10:50:31 -08:00
Doug MacEachern 3d437dc78d catch file_system_usage exceptions 2009-02-15 20:23:45 -08:00
Doug MacEachern 9e2576f7d6 need ftools for File.copy on windows 2009-02-15 20:15:22 -08:00
Doug MacEachern 606940eba2 ruby 1.9 fix fix 2009-02-15 20:09:42 -08:00
Doug MacEachern 9c759f0185 hpux extconf 2009-02-15 19:55:57 -08:00
Doug MacEachern 68525d650c fixes for ruby 1.9 2009-02-15 19:51:40 -08:00
Doug MacEachern 9835ea40c7 dont need ftools 2009-02-15 19:48:22 -08:00
Doug MacEachern 9932201d2e require libperfstat on aix 2009-02-15 19:02:25 -08:00
Doug MacEachern 7a648166f1 add aix libs 2009-02-15 16:08:15 -08:00
Doug MacEachern 7cfb3b0570 ruby/extconf.rb now builds all sigar srcs 2009-02-15 15:21:59 -08:00
Doug MacEachern 696f62a637 mv exp/ http://github.com/dougm/sigar-stuff 2009-02-15 07:01:17 -08:00
Doug MacEachern 27aa0532c5 mv tools/PerfBrowser http://github.com/dougm/csharp-perfbrowser 2009-02-14 11:55:37 -08:00
Doug MacEachern 301ce06deb cpptasks patches moved to http://github.com/dougm/ant-contrib-cpptasks 2009-02-14 07:00:52 -08:00
Doug MacEachern 60c95368e6 Merge branch 'SIGAR-134' 2009-02-12 16:33:42 -08:00
Doug MacEachern 39af88f8c5 (SIGAR-134) use UNICODE in EventLog wrapper 2009-02-12 16:32:36 -08:00
Doug MacEachern f48e3f9c07 s/SVN/SCM/ 2009-02-10 17:37:51 -08:00
Doug MacEachern ae45e2c4f3 (SIGAR-73) check for 'ocfs' in addition to 'ocfs2' 2009-02-10 13:50:08 -08:00
Doug MacEachern 168c14e0ff dos2unix 2009-02-09 14:12:02 -08:00
Doug MacEachern e1f64cfe2d dos2unix 2009-02-09 14:11:16 -08:00
Doug MacEachern d573932902 Merge branch 'sigar-1.6-dos2unix' 2009-02-09 13:57:44 -08:00
Doug MacEachern 8edff557f0 Merge branch 'sigar-1.6'
Conflicts:

	bindings/java/version.properties
2009-02-08 18:15:26 -08:00
Doug MacEachern b55603f2a5 bump version 2009-02-07 04:23:19 -08:00
Doug MacEachern 81a19487a9 Merge branch 'jk/pstat_getfile2' 2009-02-06 17:34:36 -08:00
Jan Kneschke 2d86ebadfb (SIGAR-131) use pstat_getfile2 in sigar_proc_fd_get on HP/UX 11iv2+
Signed-off-by: Doug MacEachern <dougm@hyperic.com>
2009-02-06 17:31:47 -08:00
Jan Kneschke 15bfbfef0e (SIGAR-137) ensure net_interface_list names are null-byte terminated
Signed-off-by: Doug MacEachern <dougm@hyperic.com>
2009-02-06 17:15:36 -08:00
Jan Kneschke b48fd1e62f (SIGAR-136) plug memory leak in sigar_file_system_list_get
Signed-off-by: Doug MacEachern <dougm@hyperic.com>
2009-02-06 17:15:36 -08:00
Doug MacEachern f0ef330989 .gitignore 2009-02-06 16:13:07 -08:00
Doug MacEachern eab907beb1 fix git rev-parse 2009-02-06 15:52:06 -08:00
Doug MacEachern 68559e2d24 remove invalid assertion 2009-01-21 13:43:21 +00:00
Doug MacEachern 8aa5b486e8 no need for libarch in generated sigar_version.c 2009-01-19 19:35:18 +00:00
Doug MacEachern 2b7a46de89 fix osx version on 64-bit platforms 2009-01-18 06:31:36 +00:00
Doug MacEachern 8d63124b47 s/SVN/SCM/ 2009-01-18 04:02:44 +00:00
Doug MacEachern b6f891c926 check for git revision 2009-01-18 04:00:07 +00:00
Doug MacEachern 641f42540b cp r157 from http://svn.hyperic.org/projects/hyperic_jni 2009-01-18 03:08:44 +00:00
Doug MacEachern c98ee1cbc0 no more svn:externals 2009-01-18 03:02:57 +00:00
Doug MacEachern 26a3373352 no longer using BCEL 2009-01-14 05:10:29 +00:00
Doug MacEachern 9a270ec91e update copyright.year 2009-01-13 19:06:23 +00:00
Doug MacEachern 6c390d494a [SIGAR-133] use InputStream.skip (bytes) instead of Reader.skip (chars) in onChange 2009-01-09 05:41:52 +00:00
Doug MacEachern 5a602a0a06 handle case of process going away 2009-01-08 04:41:21 +00:00
Doug MacEachern bb5dc06cba [SIGAR-132] Fix possible memory leak in sigar_rpc_ping 2009-01-06 17:25:15 +00:00
Doug MacEachern 48558541ad [SIGAR-129] fix possible integer overflow in time_now_millis 2008-12-20 16:09:49 +00:00
Doug MacEachern 901c6eeef4 [SIGAR-129] add another sanity check 2008-12-19 23:10:37 +00:00
Doug MacEachern 3c0541888f [SIGAR-129] prevent possible wrapping 2008-12-10 21:51:53 +00:00
Doug MacEachern 8537ee876c check for glibtoolize 2008-11-26 23:40:31 +00:00
Doug MacEachern 7630120869 start an autotools based build 2008-11-26 23:39:18 +00:00
Doug MacEachern d716cef196 mv Makefile Makefile.nw 2008-11-26 23:27:53 +00:00
Doug MacEachern 08ed781e71 start an autotools based build 2008-11-26 23:27:32 +00:00
Doug MacEachern ef907e95b6 [SIGAR-129] prevent possible integer overflow 2008-11-26 02:57:34 +00:00
Doug MacEachern bdd27d6f36 handle processes that may have gone away 2008-11-26 01:08:02 +00:00
Doug MacEachern c00dd5aec9 revert r3669 - requires vc6sp5+vcpp5 on windows 2008-11-25 22:46:58 +00:00
Doug MacEachern c68246e8e1 bump version 2008-11-20 15:41:16 +00:00
Doug MacEachern acefffcde4 add ProcStat MBean 2008-10-23 22:35:27 +00:00
Doug MacEachern 06945a8e31 test SigarProcessMBean 2008-10-18 23:37:21 +00:00
Doug MacEachern 6b46d63201 return NOTIMPL if ProcFd fails 2008-10-18 23:36:30 +00:00
Doug MacEachern 2bc3a6ce2a getObjectName method for SigarProcess 2008-10-18 23:31:03 +00:00
Doug MacEachern 27a8d74436 support pid other than self 2008-10-18 22:41:17 +00:00
Doug MacEachern befbdf13d2 remove main method 2008-10-18 22:34:28 +00:00
Doug MacEachern 0d3be12ac6 [SIGAR-127] use KERN_ARGMAX for KERN_PROCARGS2 buffer size 2008-10-15 02:53:23 +00:00
Doug MacEachern f7098e2c5b [SIGAR-126] /dev/kmem not usable in aix 6 2008-10-14 03:27:02 +00:00
Doug MacEachern ddebab492b allow junit.mx override 2008-10-09 07:08:43 +00:00
Doug MacEachern ed7562c0c7 use SigarInvokerJMX.PROP_TYPE 2008-10-09 06:38:11 +00:00
Doug MacEachern c7b398b53a add query support 2008-10-09 06:36:46 +00:00
Doug MacEachern 63478f28ff add aggregate Cpu mbeans 2008-10-09 06:22:46 +00:00
Doug MacEachern 7985dea967 will be reusing CpuInfo 2008-10-09 06:15:02 +00:00
Doug MacEachern 1c75927eca convert Cpu*List to ReflectedMBeans 2008-10-09 06:13:05 +00:00
Doug MacEachern c409cb469f handle List type MBeanClassName 2008-10-09 06:06:58 +00:00
Doug MacEachern 7ff83f9ba9 use SigarInvokerJMX 2008-10-09 05:55:17 +00:00
Doug MacEachern 14fc064709 prefer Name attribute to Arg 2008-10-09 05:54:35 +00:00
Doug MacEachern f3abf92787 make setType public 2008-10-09 05:53:31 +00:00
Doug MacEachern 8240ca58d4 test getAttribute 2008-10-09 05:53:13 +00:00
Doug MacEachern 9756e558fc print MBean ObjectName 2008-10-09 04:45:36 +00:00
Doug MacEachern 5deb0a0c97 add NetInfo MBean 2008-10-08 14:11:17 +00:00
Doug MacEachern d08a3cf189 rid "warning: cast from pointer to integer of different size" on 64-bit builds 2008-10-08 03:30:44 +00:00
Doug MacEachern dd9dd214bd [SIGAR-125] bring back /private/var/vm swap impl for osx 10.3 2008-10-04 19:43:46 +00:00
Doug MacEachern dd471219c4 catch NoClassDefFoundError on 1.4 jre 2008-10-04 19:06:23 +00:00
Doug MacEachern 29b9d5ada1 add -Dcom.sun.management.jmxremote for TestMx 2008-10-04 18:57:03 +00:00
Doug MacEachern cedc189061 test MBean registration 2008-10-04 16:55:42 +00:00
Doug MacEachern bd94719a4a regigster NetInterface beans 2008-10-04 16:38:24 +00:00
Doug MacEachern 273a7aad96 register FileSystem beans 2008-10-04 01:31:16 +00:00
Doug MacEachern e2616dbac1 support additional static attributes 2008-10-04 00:58:08 +00:00
Doug MacEachern ceec932585 support arguments 2008-10-04 00:29:44 +00:00
Doug MacEachern 6f7b2751f2 renames 2008-10-03 22:56:51 +00:00
Doug MacEachern d7e835fa4f use ReflectedMBean for Swap and Mem 2008-10-03 22:46:40 +00:00
Doug MacEachern 2868942667 generic reflection based MBean impl 2008-10-03 22:45:16 +00:00
Doug MacEachern 857e4f0450 simplify MBean registration 2008-10-03 21:20:17 +00:00
Doug MacEachern e6bb9c7f7e pull invoke and setAttribute methods up to superclass 2008-10-03 20:59:58 +00:00
Doug MacEachern e0b67cf3fa add version attributes 2008-10-03 15:48:56 +00:00
Doug MacEachern 913f1ca5a6 mx cmd for testing MBeans 2008-10-03 01:27:01 +00:00
Doug MacEachern df18aa6bbb [SIGAR-123] do not include global shared text+data region size 2008-09-29 03:22:48 +00:00
Doug MacEachern 062d08d9ce [SIGAR-122] ARG_MAX undefined on glibc 2.8 2008-09-27 15:59:39 +00:00
Doug MacEachern 25522f31c8 different case between XP (Eventlog) and 2008 (EventLog) 2008-09-26 20:36:56 +00:00
Doug MacEachern 2f11286b5f remove unused import 2008-09-26 19:19:26 +00:00
Doug MacEachern eeb3f26ad4 [SIGAR-121] Add Service.Pid PTQL support 2008-09-25 17:54:22 +00:00
Doug MacEachern 80ef448f8c list service pid 2008-09-19 16:09:06 +00:00
279 changed files with 30476 additions and 2782 deletions

43
.gitignore vendored Normal file
View File

@ -0,0 +1,43 @@
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
CMakeLists.txt Normal file
View File

@ -0,0 +1,35 @@
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
Makefile.am Normal file
View File

@ -0,0 +1,5 @@
SUBDIRS = include src bindings examples tests
EXTRA_DIST=\
CMakeLists.txt \
winbuild.bat

2
README
View File

@ -1,2 +0,0 @@
Visit the SIGAR Wiki for documentation, bugs, support, etc.:
http://sigar.hyperic.com/

42
README.md Normal file
View File

@ -0,0 +1,42 @@
# 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.11] 10-09-2024
* Fixing build issue on newer linux and also issues with newer Ruby [#16](https://github.com/kostya/sigar/pull/16)([commit](https://github.com/kostya/sigar/pull/16/commits/8b887b2380c4aadea82402904d9c1131bbb9c521))
### [2.0.10] 31-10-2021
* Fix compilation on MacOS 11.3.1 [#11](https://github.com/kostya/sigar/issues/11)([commit](https://github.com/kostya/sigar/commit/49a9aeeff54e97ac6f41d464c30ff6c8adf4bcf4))
### [2.0.9] 28-06-2021
* Fix compilation on FreeBSD 13 [#10](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
Rakefile Normal file
View File

@ -0,0 +1,102 @@
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.exist? "Makefile"
unless system("ruby extconf.rb")
STDERR.puts "Failed to configure"
next
end
end
unless system(MAKE)
STDERR.puts 'Failed to ' + MAKE
next
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.exist? "Makefile"
end
desc 'Dist Clean sigar extension'
task :distclean do
in_ext()
system(MAKE + ' distclean') if File.exist? "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
autoclean.sh Executable file
View File

@ -0,0 +1,61 @@
#!/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
autogen.sh Executable file
View File

@ -0,0 +1,96 @@
#!/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
bindings/Makefile.am Normal file
View File

@ -0,0 +1 @@
SUBDIRS=lua

301
bindings/SigarBuild.pm Normal file
View File

@ -0,0 +1,301 @@
#
# 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__

View File

@ -1,6 +1,7 @@
#
# Copyright (c) 2007-2008 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# Copyright (c) 2007-2009 Hyperic, Inc.
# Copyright (c) 2009 SpringSource, Inc.
# 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.
@ -19,7 +20,6 @@
package SigarWrapper;
use strict;
use Config;
use Cwd;
use Exporter;
use File::Path;
@ -29,57 +29,6 @@ use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@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 = (
A => "AIX",
D => "Darwin",
@ -94,10 +43,11 @@ my %has_name_arg = map { $_, 1 } qw(FileSystemUsage DiskUsage
FileAttrs DirStat DirUsage
NetInterfaceConfig NetInterfaceStat);
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
who cpu_info file_system); #list funcs only
arp who cpu_info file_system); #list funcs only
sub supported_platforms {
my $p = shift;
@ -531,34 +481,44 @@ use vars qw(%classes %cmds);
{
name => 'vendor', type => 'String',
desc => 'CPU vendor id',
plat => 'AFLHSW'
plat => '*'
},
{
name => 'model', type => 'String',
desc => 'CPU model',
plat => 'AFLHSW'
plat => '*'
},
{
name => 'mhz', type => 'Int',
desc => 'CPU speed',
plat => 'AFHLSW'
desc => 'Current CPU speed',
plat => '*'
},
{
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',
desc => 'CPU cache size',
plat => 'AL'
plat => 'ADL'
},
{
name => 'total_cores', type => 'Int',
desc => 'Total CPU cores (logical)',
name => 'total_cores', type => 'Int',
desc => 'Total CPU cores (logical)',
},
{
name => 'total_sockets', type => 'Int',
desc => 'Total CPU sockets (physical)',
name => 'total_sockets', type => 'Int',
desc => 'Total CPU sockets (physical)',
},
{
name => 'cores_per_socket', type => 'Int',
desc => 'Number of CPU cores per CPU socket',
name => 'cores_per_socket', type => 'Int',
desc => 'Number of CPU cores per CPU socket',
},
],
Uptime => [
@ -568,6 +528,7 @@ use vars qw(%classes %cmds);
plat => '*'
},
],
ProcMem => [
{
name => 'size', type => 'Long',
@ -668,6 +629,51 @@ use vars qw(%classes %cmds);
plat => '*'
},
],
ProcDiskIO => [
{
name => 'bytes_read', type => 'Long',
desc => 'Bytes Read',
plat => 'LW'
},
{
name => 'bytes_written', type => 'Long',
desc => 'Bytes Written',
plat => 'LW'
},
{
name => 'bytes_total', type => 'Long',
desc => 'Bytes Total',
plat => 'LWAHS'
}
],
ProcCumulativeDiskIO => [
{
name => 'bytes_read', type => 'Long',
desc => 'Bytes Read from Start',
plat => 'LW'
},
{
name => 'bytes_written', type => 'Long',
desc => 'Bytes Written from Start',
plat => 'LW'
},
{
name => 'bytes_total', type => 'Long',
desc => 'Bytes Total from Start',
plat => 'LWAHS'
}
],
DumpPidCache => [
{
name => 'dummy', type => 'Long',
desc => 'Dummy',
plat => 'LWAHS'
}
],
ProcState => [
{
name => 'state', type => 'Char',
@ -1004,6 +1010,11 @@ use vars qw(%classes %cmds);
desc => '',
plat => ''
},
{
name => 'default_gateway_interface', type => 'String',
desc => '',
plat => ''
},
{
name => 'host_name', type => 'String',
desc => '',
@ -1108,6 +1119,18 @@ use vars qw(%classes %cmds);
desc => '',
plat => '*'
},
{
name => 'address6', type => 'NetAddress',
desc => '',
},
{
name => 'prefix6_length', type => 'Int',
desc => '',
},
{
name => 'scope6', type => 'Int',
desc => '',
},
{
name => 'destination', type => 'NetAddress',
desc => '',
@ -1138,6 +1161,11 @@ use vars qw(%classes %cmds);
desc => '',
plat => 'DFL'
},
{
name => 'tx_queue_len', type => 'Int',
desc => '',
plat => 'L'
},
],
NetInterfaceStat => [
{
@ -1438,6 +1466,33 @@ use vars qw(%classes %cmds);
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 => [
{
name => 'user', type => 'String',
@ -1642,6 +1697,13 @@ $comment
EOF
}
sub erl_warning_comment {
my $self = shift;
my $comment = $self->warning_comment;
$comment =~ s/^/% /mg;
"$comment\n";
}
sub generate {
my($lang, $dir) = @_ ? @_ : @ARGV;
@ -1706,7 +1768,9 @@ sub uptodate {
return 1;
}
my(%warning_comment) = map { $_ => \&c_warning_comment } qw(c h java);
my(%warning_comment) =
((map { $_ => \&c_warning_comment } qw(c h java)),
(map { $_ => \&erl_warning_comment } qw(erl hrl)));
sub create {
my($self, $file) = @_;
@ -2108,8 +2172,8 @@ EOF
my $member = $field->{member} || $name;
my $desc = $field->{desc} || $name;
(my $jname = $name) =~ s/_(\w)/\u$1/g;
my $getter = "get\u$jname";
$jname = jname($jname);
my $getter = "get\u$jname";
$jname = jname($jname);
my $sig = qq("$field_types{$type}");
my $set = "JENV->Set${type}Field";
my $get = "JENV->Get${type}Field";
@ -2367,7 +2431,7 @@ sub generate_class {
if ($func->{num_args} == 1) {
my $arg_type;
if ($func->{is_proc}) {
$arg_type = 'NUM2UINT';
$arg_type = 'OBJ2PID';
}
else {
$arg_type = 'StringValuePtr';
@ -2381,8 +2445,9 @@ static VALUE $ruby_class;
static VALUE rb_sigar_$cname($proto)
{
SIGAR_GET;
int status;
sigar_t *sigar = rb_sigar_get(obj);
$func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL));
if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) {
@ -2794,5 +2859,167 @@ sub 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;
__END__

12
bindings/erl/Makefile Normal file
View File

@ -0,0 +1,12 @@
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

View File

@ -0,0 +1,40 @@
## 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

View File

@ -0,0 +1,16 @@
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
bindings/erl/c_src/check_otp Executable file
View File

@ -0,0 +1,17 @@
#!/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

View File

@ -0,0 +1,439 @@
/*
* 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
bindings/erl/ebin/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.beam

32
bindings/erl/examples/arp.erl Executable file
View File

@ -0,0 +1,32 @@
#!/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
bindings/erl/examples/df.erl Executable file
View File

@ -0,0 +1,29 @@
#!/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
bindings/erl/examples/free.erl Executable file
View File

@ -0,0 +1,40 @@
#!/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).

View File

@ -0,0 +1,30 @@
#!/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
bindings/erl/examples/ps.erl Executable file
View File

@ -0,0 +1,31 @@
#!/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).

View File

@ -0,0 +1,34 @@
#!/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
bindings/erl/examples/who.erl Executable file
View File

@ -0,0 +1,31 @@
#!/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
bindings/erl/priv/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.so

2
bindings/erl/priv/gen/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.c
*.hrl

11
bindings/erl/src/Makefile Normal file
View File

@ -0,0 +1,11 @@
ERLC=erlc
EBIN=../ebin
INCLUDE=../include
EFLAGS=-I ${INCLUDE} -o ${EBIN}
SRCS=`ls *.erl`
all:
${ERLC} ${EFLAGS} ${SRCS}
clean:
rm -rf ${EBIN}/*.beam

108
bindings/erl/src/sigar.erl Normal file
View File

@ -0,0 +1,108 @@
%
% 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.

View File

@ -4,7 +4,7 @@
<project name="Sigar" default="build" basedir=".">
<property file="version.properties"/>
<property file="../../version.properties"/>
<property name="sigar.version"
value="${version.major}.${version.minor}.${version.maint}"/>
@ -144,7 +144,7 @@
<antcall target="version-file">
<param name="version.file"
value="src/org/hyperic/sigar/SigarVersion.java"/>
value="src/org/hyperic/sigar/Version.java"/>
</antcall>
<antcall target="version-file">
@ -346,9 +346,11 @@
<arg value="version"/>
</java>
<property name="junit.mx" value="-Dcom.sun.management.jmxremote"/>
<junit printsummary="yes" fork="yes"
haltonfailure="yes" showoutput="true">
<jvmarg line="${junit.args}"/>
<jvmarg line="${junit.args} ${junit.mx}"/>
<classpath refid="alljars"/>
<formatter type="xml"/>
@ -497,6 +499,7 @@
<copy toDir="${dist.src}">
<fileset dir="../..">
<include name="version.properties"/>
<include name="include/*.h"/>
<include name="src/**/*.h"/>
<include name="src/**/*.c"/>
@ -509,7 +512,6 @@
<include name="bindings/java/**/*.h"/>
<include name="bindings/java/**/*.pl"/>
<include name="bindings/java/**/build.xml"/>
<include name="bindings/java/version.properties"/>
<include name="bindings/java/.classpath"/>
<include name="bindings/java/.project"/>
<include name="bindings/java/.sigar_shellrc"/>

View File

@ -356,8 +356,6 @@
<compilerarg value="${uni.arch}"/>
<compilerarg value="-mmacosx-version-min=${osx.min}"/>
<sysincludepath location="/Developer/Headers/FlatCarbon"/>
<defineset>
<define name="DARWIN"/>
<define name="DARWIN_HAS_LIBPROC_H" if="libproc.h"/>

View File

@ -17,6 +17,7 @@
package org.hyperic.jni;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.net.URL;
import java.net.URLClassLoader;
@ -315,7 +316,16 @@ public class ArchLoader {
if ((file != null) &&
((file = file.getParentFile()) != null))
{
String dir = URLDecoder.decode(file.toString());
String dir;
try {
// Passing UTF-8 according to the recommendation in the URLDecoder.decode JavaDoc.
dir = URLDecoder.decode(file.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
String msg = "Unsupported encoding in file name: " + file.toString();
ArchLoaderException archLoaderException = new ArchLoaderException(msg);
archLoaderException.initCause(e);
throw archLoaderException;
}
if (findNativeLibrary(dir, libName)) {
return dir;
}

View File

@ -90,8 +90,12 @@ public class ArchNameTask extends Task {
if (ArchLoader.IS_DARWIN) {
//default to most recent SDK
//MacOSX10.3.9.sdk, MacOSX10.4u.sdk, MacOSX10.5.sdk,etc.
File[] sdks =
new File("/Developer/SDKs").listFiles(new FileFilter() {
String sdkRoot = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs";
if (new File(sdkRoot).exists() == false) {
sdkRoot = "/Developer/SDKs";
}
File[] sdks =
new File(sdkRoot).listFiles(new FileFilter() {
public boolean accept(File file) {
String name = file.getName();
return
@ -99,6 +103,7 @@ public class ArchNameTask extends Task {
name.endsWith(".sdk");
}
});
if (sdks != null) {
Arrays.sort(sdks);
String prop = "uni.sdk";

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2004-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@ -897,6 +898,13 @@ JNIEXPORT jstring SIGAR_JNI(NetFlags_getIfFlagsString)
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)
(JNIEnv *env, jobject sigar_obj, jint flags)
{
@ -1060,6 +1068,37 @@ JNIEXPORT jstring SIGAR_JNI(NetConnection_getStateString)
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)
(JNIEnv *env, jobject sigar_obj)
{

View File

@ -292,74 +292,58 @@ public class FileInfo extends FileAttrs implements java.io.Serializable {
}
public String diff(FileInfo info) {
ArrayList changes = new ArrayList();
ArrayList changes = new ArrayList();
if (this.getMtime() != info.getMtime()) {
changes.add(new Diff("Mtime",
formatDate(info.getMtime()),
formatDate(this.getMtime())));
if (this.getMtime() != info.getMtime()) {
changes.add(new Diff("Mtime", formatDate(info.getMtime()),
formatDate(this.getMtime())));
} else if (this.getCtime() != info.getCtime()) {
changes.add(new Diff("Ctime", formatDate(info.getCtime()),
formatDate(this.getCtime())));
}
if (this.getPermissions() != info.getPermissions()) {
changes.add(new Diff("Perms", info.getPermissionsString(), this
.getPermissionsString()));
}
if (this.getType() != info.getType()) {
changes.add(new Diff("Type", info.getTypeString(), this
.getTypeString()));
}
if (this.getUid() != info.getUid()) {
changes.add(new Diff("Uid", info.getUid(), this.getUid()));
}
if (this.getGid() != info.getGid()) {
changes.add(new Diff("Gid", info.getGid(), this.getGid()));
}
if (this.getSize() != info.getSize()) {
changes.add(new Diff("Size", info.getSize(), this.getSize()));
}
if (!OperatingSystem.IS_WIN32) {
if (this.getInode() != info.getInode()) {
changes.add(new Diff("Inode", info.getInode(), this.getInode()));
}
if (this.getDevice() != info.getDevice()) {
changes.add(new Diff("Device", info.getDevice(), this
.getDevice()));
}
if (this.getNlink() != info.getNlink()) {
changes.add(new Diff("Nlink", info.getNlink(), this.getNlink()));
}
}
else if (this.getCtime() != info.getCtime()) {
changes.add(new Diff("Ctime",
formatDate(info.getCtime()),
formatDate(this.getCtime())));
}
else {
//no point in checking the rest if all times are the same.
//or should we include atime in the diff?
/* if changes were not detected then return empty String */
if (changes.isEmpty()){
return "";
}
if (this.getPermissions() != info.getPermissions()) {
changes.add(new Diff("Perms",
info.getPermissionsString(),
this.getPermissionsString()));
}
if (this.getType() != info.getType()) {
changes.add(new Diff("Type",
info.getTypeString(),
this.getTypeString()));
}
if (this.getUid() != info.getUid()) {
changes.add(new Diff("Uid",
info.getUid(),
this.getUid()));
}
if (this.getGid() != info.getGid()) {
changes.add(new Diff("Gid",
info.getGid(),
this.getGid()));
}
if (this.getSize() != info.getSize()) {
changes.add(new Diff("Size",
info.getSize(),
this.getSize()));
}
if (!OperatingSystem.IS_WIN32) {
if (this.getInode() != info.getInode()) {
changes.add(new Diff("Inode",
info.getInode(),
this.getInode()));
}
if (this.getDevice() != info.getDevice()) {
changes.add(new Diff("Device",
info.getDevice(),
this.getDevice()));
}
if (this.getNlink() != info.getNlink()) {
changes.add(new Diff("Nlink",
info.getNlink(),
this.getNlink()));
}
}
StringBuffer sb = format(changes);
if (this.dirStatEnabled) {
sb.append(diff(info.stat));
@ -389,7 +373,9 @@ public class FileInfo extends FileAttrs implements java.io.Serializable {
stat();
return this.mtime != oldInfo.mtime;
boolean isModified = isModified(this.oldInfo);
return isModified;
}
public boolean changed()
@ -455,4 +441,49 @@ public class FileInfo extends FileAttrs implements java.io.Serializable {
return fetchInfo(sigar, name, false);
}
private boolean isModified(FileInfo info){
/* Check modified time */
if (this.getMtime() != info.getMtime()) {
return true;
} else if (this.getCtime() != info.getCtime()) {
return true;
}
if (this.getPermissions() != info.getPermissions()) {
return true;
}
if (this.getType() != info.getType()) {
return true;
}
if (this.getUid() != info.getUid()) {
return true;
}
if (this.getGid() != info.getGid()) {
return true;
}
if (this.getSize() != info.getSize()) {
return true;
}
if (!OperatingSystem.IS_WIN32) {
if (this.getInode() != info.getInode()) {
return true;
}
if (this.getDevice() != info.getDevice()) {
return true;
}
if (this.getNlink() != info.getNlink()) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,52 @@
/*
* 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;
}
}

View File

@ -16,9 +16,6 @@
package org.hyperic.sigar;
import java.util.HashMap;
import java.util.Map;
import org.hyperic.sigar.ptql.ProcessFinder;
/**
@ -28,64 +25,33 @@ public class MultiProcCpu extends ProcCpu {
private long pid;
private int nproc = 0;
private static Map ptable = new HashMap();
static synchronized MultiProcCpu get(Sigar sigar, String query)
throws SigarException {
throws SigarException {
MultiProcCpu cpu;
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;
MultiProcCpu cpu = new MultiProcCpu();
cpu.pid = query.hashCode(); //for equals()
cpu.total = 0;
cpu.user = 0;
cpu.sys = 0;
cpu.nproc = 0;
cpu.percent = 0.0D;
long[] pids = ProcessFinder.find(sigar, query);
cpu.nproc = pids.length;
for (int i=0; i<pids.length; i++) {
ProcTime time;
try {
time = sigar.getProcTime(pids[i]);
ProcCpu procCpu = sigar.getProcCpu(pids[i]);
cpu.total += procCpu.getTotal();
cpu.user += procCpu.getUser();
cpu.sys += procCpu.getSys();
cpu.percent += procCpu.getPercent();
} catch (SigarException e) {
//process may have gone away or EPERM
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;

View File

@ -1,5 +1,7 @@
/*
* 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");
* you may not use this file except in compliance with the License.
@ -95,6 +97,16 @@ public class NetFlags {
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_GATEWAY = 0x2;
@ -155,6 +167,13 @@ public class NetFlags {
*/
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) {
return
(address == null) ||

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2006-2009 Hyperic, 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.
@ -41,12 +42,14 @@ public class Sigar implements SigarProxy {
private static String loadError = null;
public static final long FIELD_NOTIMPL = -1;
public static final int PID_PROC_CPU_CACHE = 1;
public static final int PID_PROC_IO_CACHE = 2;
/**
* The Sigar java version.
*/
public static final String VERSION_STRING =
SigarVersion.VERSION_STRING;
Version.VERSION_STRING;
/**
* The Sigar native version.
@ -57,7 +60,7 @@ public class Sigar implements SigarProxy {
* The scm (svn) revision from which sigar.jar was built.
*/
public static final String SCM_REVISION =
SigarVersion.SCM_REVISION;
Version.SCM_REVISION;
/**
* The scm (svn) revision from which the sigar native binary was built.
@ -68,7 +71,7 @@ public class Sigar implements SigarProxy {
* The date on which sigar.jar was built.
*/
public static final String BUILD_DATE =
SigarVersion.BUILD_DATE;
Version.BUILD_DATE;
/**
* The date on which the sigar native binary was built.
@ -154,15 +157,19 @@ public class Sigar implements SigarProxy {
}
private static void loadLibrary() throws SigarException {
try {
if (SigarLoader.IS_WIN32 &&
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 =
loader.findJarPath("pdh.dll") +
File.separator + "pdh.dll";
loader.systemLoad(lib);
}
} catch (Exception e) {}
}
try {
loader.load();
} catch (ArchNotSupportedException e) {
throw new SigarException(e.getMessage());
@ -435,7 +442,7 @@ public class Sigar implements SigarProxy {
return this.processFinder.findSingleProcess(pid);
}
}
/**
* Get process memory info.
* @param pid The process id.
@ -633,6 +640,57 @@ public class Sigar implements SigarProxy {
Integer.parseInt(port));
}
/**
* Get process disk IO info.
* @param pid THe process id.
* @exception SigarException on failure.
*/
public ProcDiskIO getProcDiskIO(long pid) throws SigarException {
try {
return ProcDiskIO.fetch(this, pid);
} catch (UnsatisfiedLinkError linkErrorException) {
// We want to handle exceptions gracefully even if the linked
// shared library is older and isn't compiled with the ProcDiskIO APIs.
// The downside of this is that we throw SigarNotImplemented exception
// also when the shared library can't be loaded.
SigarException sigarException = new SigarNotImplementedException();
sigarException.initCause(linkErrorException);
throw sigarException;
}
}
public ProcDiskIO getProcDiskIO(String pid) throws SigarException {
return getProcDiskIO(convertPid(pid));
}
/**
* Get process cumulative disk IO info.
* @param pid THe process id.
* @exception SigarException on failure.
*/
public ProcCumulativeDiskIO getProcCumulativeDiskIO(long pid) throws SigarException {
try {
return ProcCumulativeDiskIO.fetch(this, pid);
} catch (UnsatisfiedLinkError linkErrorException) {
// We want to handle exceptions gracefully even if the linked
// shared library is older and isn't compiled with the ProcDiskIO APIs.
// The downside of this is that we throw SigarNotImplemented exception
// also when the shared library can't be loaded.
SigarException sigarException = new SigarNotImplementedException();
sigarException.initCause(linkErrorException);
throw sigarException;
}
}
public ProcCumulativeDiskIO getProcCumulativeDiskIO(String pid) throws SigarException {
return getProcCumulativeDiskIO(convertPid(pid));
}
public DumpPidCache dumpPidCache() throws SigarException {
return DumpPidCache.fetch(this);
}
/**
* Get the cumulative cpu time for the calling thread.
*/
@ -802,6 +860,9 @@ public class Sigar implements SigarProxy {
return netstat;
}
public native Arp[] getArpList()
throws SigarException;
public native Who[] getWhoList()
throws SigarException;
@ -953,6 +1014,10 @@ public class Sigar implements SigarProxy {
*/
public native String getFQDN() throws SigarException;
public SigarVersion getSigarVersion() {
return new SigarVersion();
}
/**
* Enabling logging in the native Sigar code.
* This method will hook log4j into the Sigar

View File

@ -94,7 +94,7 @@ public class SigarInvoker {
this.sigarProxy = proxy;
}
protected void setType(String val) {
public void setType(String val) {
String alias = (String)compatTypes.get(val);
if (alias != null) {
val = alias;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2006-2007, 2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@ -106,6 +106,16 @@ public interface SigarProxy {
public long getProcPort(String protocol, String port) throws SigarException;
public ProcDiskIO getProcDiskIO(long pid) throws SigarException;
public ProcDiskIO getProcDiskIO(String pid) throws SigarException;
public ProcCumulativeDiskIO getProcCumulativeDiskIO(long pid) throws SigarException;
public ProcCumulativeDiskIO getProcCumulativeDiskIO(String pid) throws SigarException;
public DumpPidCache dumpPidCache() throws SigarException;
public FileSystem[] getFileSystemList() throws SigarException;
public FileSystemMap getFileSystemMap() throws SigarException;
@ -173,5 +183,7 @@ public interface SigarProxy {
public NetInfo getNetInfo() throws SigarException;
public SigarVersion getSigarVersion();
public String getFQDN() throws SigarException;
}

View File

@ -0,0 +1,69 @@
/*
* 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();
}
}

View File

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

View File

@ -0,0 +1,52 @@
/*
* 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);
}
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2006 Hyperic, Inc.
* 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.
@ -115,6 +116,13 @@ public class Ifconfig extends SigarCommandBase {
bcast +
" Mask:" + ifconfig.getNetmask());
if (ifconfig.getPrefix6Length() != 0) {
println("\t" +
"inet6 addr: " + ifconfig.getAddress6() + "/" +
ifconfig.getPrefix6Length() +
" Scope:" + NetFlags.getScopeString(ifconfig.getScope6()));
}
println("\t" +
NetFlags.getIfFlagsString(flags) +
" MTU:" + ifconfig.getMtu() +

View File

@ -0,0 +1,169 @@
/*
* 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);
}
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2006-2007 Hyperic, 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.
@ -60,7 +61,8 @@ public class NetInfo extends SigarCommandBase {
info.getDomainName());
println("default gateway......." +
info.getDefaultGateway());
info.getDefaultGateway() +
" (" + info.getDefaultGatewayInterface() + ")");
println("primary dns..........." +
info.getPrimaryDns());

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2006-2007 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.cmd;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarPermissionDeniedException;
/**
* Display all pid cache information.
*/
public class PidCacheInfo extends SigarCommandBase {
public PidCacheInfo(Shell shell) {
super(shell);
}
public PidCacheInfo() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getUsageShort() {
return "Display cache info for CPU cache and for IO cache";
}
public boolean isPidCompleter() {
return false;
}
public void output(String[] args) throws SigarException {
sigar.dumpPidCache();
}
}

View File

@ -100,6 +100,14 @@ public class ProcInfo extends SigarCommandBase {
try {
println("credname=" + sigar.getProcCredName(pid));
} catch (SigarException e) {}
try {
println("diskio=" + sigar.getProcDiskIO(pid));
} catch (SigarException e) {}
try {
println("cumulative diskio=" + sigar.getProcCumulativeDiskIO(pid));
} catch (SigarException e) {}
}
public static void main(String[] args) throws Exception {

View File

@ -76,6 +76,7 @@ public class Shell extends ShellBase {
}
public void registerCommands() throws ShellCommandInitException {
registerCommandHandler("arp", new Arp(this));
registerCommandHandler("df", new Df(this));
registerCommandHandler("du", new Du(this));
registerCommandHandler("ls", new Ls(this));
@ -102,6 +103,8 @@ public class Shell extends ShellBase {
registerCommandHandler("time", new Time(this));
registerCommandHandler("ulimit", new Ulimit(this));
registerCommandHandler("who", new Who(this));
registerCommandHandler("pid_cache_info", new PidCacheInfo(this));
if (SigarLoader.IS_WIN32) {
registerCommandHandler("service", new Win32Service(this));
registerCommandHandler("fversion", new FileVersionInfo(this));
@ -111,6 +114,10 @@ public class Shell extends ShellBase {
registerCommandHandler("test", "org.hyperic.sigar.test.SigarTestRunner");
} catch (NoClassDefFoundError 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 {

View File

@ -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");
* you may not use this file except in compliance with the License.
@ -20,17 +20,13 @@ import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/**
* Base class for all Sigar JMX MBeans. Provides a skeleton which handles
@ -43,24 +39,10 @@ import org.hyperic.sigar.SigarProxyCache;
* @author Bjoern Martin
* @since 1.5
*/
public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
public abstract class AbstractMBean implements DynamicMBean {
protected static final String MBEAN_ATTR_TYPE = "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;
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
/**
* The Sigar proxy cache to be used in case the data does not have to be
@ -73,69 +55,13 @@ public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
protected final SigarProxy sigar;
/**
* The MBean server this MBean is registered to. Set during the MBean's
* registration to the MBean server and unset to <code>null</code> when
* the deregistration finished.
* <p>Creates a new instance of this class. The SigarProxy instance is stored (and
* accessible) via the {@link #sigar} member.
*
* @see #preRegister(MBeanServer, ObjectName)
* @see #postDeregister()
* @param sigar The SigarProxy instance to use. Must not be <code>null</code>
*/
protected MBeanServer mbeanServer;
/**
* <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);
}
protected AbstractMBean(SigarProxy sigar) {
this.sigar = sigar;
}
/**
@ -200,67 +126,19 @@ public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
result.add(next);
} catch (AttributeNotFoundException e) {
// 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;
}
// -------
// 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 void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/**
* 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) {
}
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#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;
throw new ReflectionException(new NoSuchMethodException(name),
name);
}
}

View File

@ -0,0 +1,223 @@
/*
* 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;
}
}

View File

@ -1,332 +0,0 @@
/*
* 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;
}
}

View File

@ -1,284 +0,0 @@
/*
* 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;
}
}

View File

@ -1,331 +0,0 @@
/*
* 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;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2006 Hyperic, Inc.
* Copyright (c) 2006, 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.
@ -16,13 +16,16 @@
package org.hyperic.sigar.jmx;
import java.lang.reflect.InvocationHandler;
import java.util.Map;
import java.util.StringTokenizer;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarInvoker;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
import org.hyperic.sigar.util.ReferenceMap;
/**
@ -34,6 +37,7 @@ public class SigarInvokerJMX extends SigarInvoker {
public static final String DOMAIN_NAME = "sigar";
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";
private String arg = null;
@ -58,6 +62,10 @@ public class SigarInvokerJMX extends SigarInvoker {
SigarInvokerJMX invoker;
if (!(proxy instanceof InvocationHandler) && (proxy instanceof Sigar)) {
proxy = SigarProxyCache.newInstance((Sigar)proxy);
}
int ix = name.indexOf(":");
if (ix > 0) {
//skip domain name
@ -82,10 +90,12 @@ public class SigarInvokerJMX extends SigarInvoker {
String key = attr.substring(0, ix);
String val = attr.substring(key.length()+1);
if (key.equals(PROP_TYPE)) {
if (key.equalsIgnoreCase(PROP_TYPE)) {
invoker.setType(val);
}
else if (key.equals(PROP_ARG)) {
else if (key.equalsIgnoreCase(PROP_NAME) ||
key.equalsIgnoreCase(PROP_ARG))
{
//need to decode value, e.g. Arg=C%3D\ => Arg=C:\
invoker.setArg(decode(val));
}

View File

@ -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");
* you may not use this file except in compliance with the License.
@ -16,246 +16,38 @@
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.MBeanException;
import javax.management.ReflectionException;
import org.hyperic.sigar.LoadAverage;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy;
/**
* 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 {
public class SigarLoadAverage extends ReflectedMBean {
private static final String MBEAN_TYPE = "LoadAverage";
/**
* 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 SigarLoadAverage(SigarProxy sigar) {
super(sigar, MBEAN_TYPE);
}
/**
* Object name this instance will give itself when being registered to an
* 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() {
public Object getAttribute(String name)
throws AttributeNotFoundException,
MBeanException, ReflectionException {
try {
return sigarImpl.getLoadAverage()[0];
Object val =
new LoadAverage(this.sigar.getLoadAverage()).toMap().get(name);
if (val == null) {
throw new AttributeNotFoundException(name);
}
return val;
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
return new Double(Sigar.FIELD_NOTIMPL);
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
throw new ReflectionException(e);
}
}
/**
* @return The load average over the last five minutes, as a fraction of 1,
* or <code>-1.0d</code> if the load cannot be determined on this
* platform
*/
public double getLastFiveMinutes() {
try {
return sigarImpl.getLoadAverage()[1];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The load average over the last 15 minutes, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLast15Minutes() {
try {
return sigarImpl.getLoadAverage()[2];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_LAST1MIN.getName().equals(attr)) {
return new Double(getLastMinute());
} else if (MBEAN_ATTR_LAST5MIN.getName().equals(attr)) {
return new Double(getLastFiveMinutes());
} else if (MBEAN_ATTR_LAST15MIN.getName().equals(attr)) {
return new Double(getLast15Minutes());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
}

View File

@ -1,249 +0,0 @@
/*
* 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;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2006-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.
@ -19,6 +19,8 @@ package org.hyperic.sigar.jmx;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcFd;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.ProcDiskIO;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
@ -31,20 +33,24 @@ import org.hyperic.sigar.SigarProxyCache;
public class SigarProcess implements SigarProcessMBean {
private static final Long NOTIMPL = new Long(Sigar.FIELD_NOTIMPL);
private Sigar sigarImpl;
private SigarProxy sigar;
private long pid = -1;
public SigarProcess() {
this(new Sigar());
}
public SigarProcess(Sigar sigar) {
this.sigarImpl = sigar;
this.sigarImpl = new Sigar();
this.sigar = SigarProxyCache.newInstance(sigarImpl);
}
public SigarProcess(SigarProxy sigar) {
this.sigar = sigar;
}
public void close() {
this.sigarImpl.close();
if (this.sigarImpl != null) {
this.sigarImpl.close();
}
}
private RuntimeException unexpectedError(String type,
@ -57,8 +63,7 @@ public class SigarProcess implements SigarProcessMBean {
private synchronized ProcMem getMem() {
try {
long pid = this.sigar.getPid();
return this.sigar.getProcMem(pid);
return this.sigar.getProcMem(getPid());
} catch (SigarException e) {
throw unexpectedError("Mem", e);
}
@ -66,22 +71,56 @@ public class SigarProcess implements SigarProcessMBean {
private synchronized ProcCpu getCpu() {
try {
long pid = this.sigar.getPid();
return this.sigar.getProcCpu(pid);
return this.sigar.getProcCpu(getPid());
} catch (SigarException e) {
throw unexpectedError("Cpu", e);
}
}
private synchronized ProcFd getFd() {
try {
long pid = this.sigar.getPid();
return this.sigar.getProcFd(pid);
private synchronized ProcDiskIO getDiskIO() {
try {
return this.sigar.getProcDiskIO(getPid());
} catch (SigarException e) {
throw unexpectedError("Fd", e);
}
throw unexpectedError("DiskIO", e);
}
}
private synchronized ProcFd getFd() throws SigarException {
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() {
if (this.pid < 0) {
return this.sigar.getPid();
}
else {
return this.pid;
}
}
public void setPid(long pid) {
this.pid = pid;
}
public Long getMemSize() {
return new Long(getMem().getSize());
}
@ -119,17 +158,15 @@ public class SigarProcess implements SigarProcessMBean {
}
public Long getOpenFd() {
return new Long(getFd().getTotal());
try {
return new Long(getFd().getTotal());
} catch (SigarException e) {
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() {
return new Double(getDiskIO().getBytesTotal());
}
}

View File

@ -44,4 +44,6 @@ public interface SigarProcessMBean {
public Double getCpuUsage();
public Long getOpenFd();
public Double getBytesReadWriteTotal();
}

View File

@ -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");
* you may not use this file except in compliance with the License.
@ -18,19 +18,18 @@ package org.hyperic.sigar.jmx;
import java.util.ArrayList;
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.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
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.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
@ -57,266 +56,173 @@ import org.hyperic.sigar.SigarException;
* @author Bjoern Martin
* @since 1.5
*/
public class SigarRegistry extends AbstractMBean {
public class SigarRegistry implements MBeanRegistration, SigarRegistryMBean {
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
private static final String MBEAN_TYPE = "SigarRegistry";
private static final int CACHE_EXPIRE = 60 * 1000;
private static final MBeanInfo MBEAN_INFO;
private Sigar sigarImpl;
private SigarProxy sigar;
private String objectName;
private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT;
private ArrayList managedBeans;
private MBeanServer mbeanServer;
// private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES;
public SigarRegistry() {}
static {
MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo(
SigarRegistry.class.getName(),
"Creates a new instance of this class. Will create the Sigar "
+ "instance this class uses when constructing other MBeans",
new MBeanParameterInfo[0]);
// MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses",
// "Executes a query returning the process IDs of all processes " +
// "found on the system.",
// null /* new MBeanParameterInfo[0] */,
// String.class.getName(), MBeanOperationInfo.INFO);
MBEAN_INFO = new MBeanInfo(
SigarRegistry.class.getName(),
"Sigar MBean registry. Provides a central point for creation "
+ "and destruction of Sigar MBeans. Any Sigar MBean created via "
+ "this instance will automatically be cleaned up when this "
+ "instance is deregistered from the MBean server.",
null /*new MBeanAttributeInfo[0]*/,
new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT },
null /*new MBeanOperationInfo[0] */,
null /*new MBeanNotificationInfo[0]*/);
public SigarRegistry(SigarProxy sigar) {
init(sigar);
}
private final String objectName;
private final ArrayList managedBeans;
/**
* 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();
private void init(SigarProxy sigar) {
this.sigar = sigar;
this.objectName =
MBEAN_DOMAIN + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE;
this.managedBeans = new ArrayList();
}
/* (non-Javadoc)
* @see AbstractMBean#getObjectName()
*/
public String getObjectName() {
return this.objectName;
}
/* public String listProcesses() {
private void registerMBean(AbstractMBean mbean) {
try {
final long start = System.currentTimeMillis();
long[] ids = sigar.getProcList();
StringBuffer procNames = new StringBuffer();
for (int i = 0; i < ids.length; i++) {
try {
procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n');
} catch (SigarException e) {
procNames.append(ids[i] + ":" + e.getMessage()).append('\n');
}
ObjectName name =
new ObjectName(mbean.getObjectName());
if (mbeanServer.isRegistered(name)) {
return;
}
final long end = System.currentTimeMillis();
procNames.append("-- Took " + (end-start) + "ms");
return procNames.toString();
} catch (SigarException e) {
throw unexpectedError("ProcList", e);
ObjectInstance instance =
this.mbeanServer.registerMBean(mbean, name);
this.managedBeans.add(instance.getObjectName());
} catch (Exception e) {
e.printStackTrace();
}
}
*/
/* (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
// -------
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
//no args constructor support
if (this.sigar == null) {
this.sigarImpl = new Sigar();
init(SigarProxyCache.newInstance(this.sigarImpl, CACHE_EXPIRE));
}
this.mbeanServer = server;
if (name == null) {
return new ObjectName(getObjectName());
}
else {
return name;
}
}
/**
* Registers the default set of Sigar MBeans. Before doing so, a super call
* is made to satisfy {@link AbstractMBean}.
*
* @see AbstractMBean#postRegister(Boolean)
* Registers the default set of Sigar MBeans.
*/
public void postRegister(Boolean success) {
super.postRegister(success);
ReflectedMBean mbean;
if (!success.booleanValue())
return;
// get CPUs
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;
//CPU beans
CpuInfo[] info;
try {
final int cpuCount = sigar.getCpuInfoList().length;
for (int i = 0; i < cpuCount; i++) {
// add CPU bean
SigarCpu nextCpu = new SigarCpu(sigarImpl, i);
try {
if (!mbeanServer.isRegistered(new ObjectName(nextCpu
.getObjectName())))
nextRegistered = mbeanServer.registerMBean(nextCpu,
null);
} catch (Exception e) { // ignore
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
// 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;
}
info = sigar.getCpuInfoList();
} catch (SigarException e) {
throw unexpectedError("CpuInfoList", e);
info = new CpuInfo[0]; //XXX log
}
}
/**
* Registers MBeans for the Sigar types <code>Mem</code> and <code>Swap</code>.
*/
private void registerMemoryBeans() {
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);
}
ObjectInstance nextRegistered = null;
mbean = new ReflectedMBean(this.sigar, "Cpu");
mbean.putAttributes(info[0]);
registerMBean(mbean);
// add physical memory bean
SigarMem mem = new SigarMem(sigarImpl);
mbean = new ReflectedMBean(this.sigar, "CpuUsage");
mbean.setType("CpuPerc");
registerMBean(mbean);
//FileSystem beans
try {
if (!mbeanServer.isRegistered(new ObjectName(mem.getObjectName())))
nextRegistered = mbeanServer.registerMBean(mem, null);
} catch (Exception e) { // ignore
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
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
// add swap memory bean
SigarSwap swap = new SigarSwap(sigarImpl);
//NetInterface beans
try {
if (!mbeanServer.isRegistered(new ObjectName(swap.getObjectName())))
nextRegistered = mbeanServer.registerMBean(swap, null);
} catch (Exception e) { // ignore
nextRegistered = null;
String[] ifnames = this.sigar.getNetInterfaceList();
for (int i=0; i<ifnames.length; i++) {
String name = ifnames[i];
NetInterfaceConfig ifconfig =
this.sigar.getNetInterfaceConfig(name);
try {
this.sigar.getNetInterfaceStat(name);
} catch (SigarException e) {
continue;
}
mbean =
new ReflectedMBean(this.sigar, "NetInterface", name);
mbean.setType(mbean.getType() + "Stat");
mbean.putAttributes(ifconfig);
registerMBean(mbean);
}
} catch (SigarException e) {
//XXX log
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
}
/**
* Registers MBeans for the Sigar types <code>LoadAverage</code>...
*/
private void registerSystemBeans() {
ObjectInstance nextRegistered = null;
// add load average bean
SigarLoadAverage loadAvg = new SigarLoadAverage(sigarImpl);
//network info bean
mbean = new ReflectedMBean(this.sigar, "NetInfo");
try {
if (!mbeanServer.isRegistered(new ObjectName(loadAvg
.getObjectName())))
nextRegistered = mbeanServer.registerMBean(loadAvg, null);
} catch (Exception e) { // ignore
mbean.putAttribute("FQDN", this.sigar.getFQDN());
} catch (SigarException e) {
}
// add MBean to set of managed beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
registerMBean(mbean);
//physical memory bean
registerMBean(new ReflectedMBean(this.sigar, "Mem"));
//swap memory bean
registerMBean(new ReflectedMBean(this.sigar, "Swap"));
//load average bean
registerMBean(new SigarLoadAverage(this.sigar));
//global process stats
registerMBean(new ReflectedMBean(this.sigar, "ProcStat"));
//sigar version
registerMBean(new ReflectedMBean(this.sigar, "SigarVersion"));
}
/**
* Deregisters all Sigar MBeans that were created and registered using this
* instance. After doing so, a super call is made to satisfy {@link AbstractMBean}.
* instance.
* @throws Exception
*
* @see AbstractMBean#preDeregister()
@ -333,8 +239,14 @@ public class SigarRegistry extends AbstractMBean {
}
}
}
}
// do the super call
super.preDeregister();
public void postDeregister() {
this.mbeanServer = null;
if (this.sigarImpl != null) {
this.sigarImpl.close();
this.sigarImpl = null;
this.sigar = null;
}
}
}

View File

@ -0,0 +1,21 @@
/*
* 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 {
}

View File

@ -1,197 +0,0 @@
/*
* 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;
}
}

View File

@ -1,6 +1,7 @@
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
* 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.
@ -43,6 +44,7 @@ public class SigarTestRunner extends SigarCommandBase {
private static final Class[] ALL_TESTS = {
TestLog.class,
TestInvoker.class,
TestMx.class,
TestPTQL.class,
TestCpu.class,
TestCpuInfo.class,
@ -77,6 +79,7 @@ public class SigarTestRunner extends SigarCommandBase {
TestThreadCpu.class,
TestUptime.class,
TestVMware.class,
TestArp.class,
TestWho.class,
TestHumidor.class
};

View File

@ -0,0 +1,46 @@
/*
* 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;
}
}
}

View File

@ -133,11 +133,11 @@ public class TestFileInfo extends SigarTestCase {
tmp.deleteOnExit();
traceln("TMP=" + file);
try {
// try {
//stat() mtime is in seconds, this happens to quick to detect change.
Thread.sleep(1000 * 1);
} catch (InterruptedException e) {
}
//Thread.sleep(1000 * 1);
// } catch (InterruptedException e) {
// }
try {
FileInfo info = sigar.getFileInfo(file);

View File

@ -0,0 +1,97 @@
/*
* 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);
}
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2006-2008 Hyperic, Inc.
* 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.
@ -16,6 +17,9 @@
package org.hyperic.sigar.test;
import java.net.InetAddress;
import java.net.Inet6Address;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
@ -42,6 +46,14 @@ public class TestNetIf extends SigarTestCase {
assertTrueTrace("Address", ifconfig.getAddress());
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) {
continue;
}

View File

@ -0,0 +1,57 @@
package org.hyperic.sigar.test;
import org.hyperic.sigar.ProcDiskIO;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class TestProcDiskIO extends SigarTestCase {
public TestProcDiskIO(String name) {
super(name);
}
private void traceDiskIO(Sigar sigar, long pid) throws Exception {
ProcDiskIO procDiskIO;
try {
procDiskIO = sigar.getProcDiskIO(pid);
} catch (SigarException e) {
traceln("pid " + pid + ": " + e.getMessage());
// throw e;
return;
}
long bytesRead = procDiskIO.getBytesRead();
long bytesWritten = procDiskIO.getBytesWritten();
long bytesTotal = procDiskIO.getBytesTotal();
traceln("Pid=" + pid);
traceln("Bytes Read=" + Sigar.formatSize(bytesRead));
traceln("Bytes Written=" + Sigar.formatSize(bytesWritten));
traceln("Bytes Total=" + Sigar.formatSize(bytesTotal));
if (bytesRead != -1 && bytesWritten != -1 && bytesTotal != -1) {
assertTrue("Bytes total should equal bytesRead + bytesWritten",
(bytesTotal == bytesRead + bytesWritten));
}
}
public void testCreate() throws Exception {
Sigar sigar = getSigar();
boolean caughtException = false;
try {
sigar.getProcDiskIO(getInvalidPid());
} catch (SigarException e) {
caughtException = true;
}
assertTrue("Test on invalid PID should have thrown an exception.", caughtException);
long[] pids = sigar.getProcList();
for (int i=0; i<pids.length; i++) {
traceDiskIO(sigar, pids[i]);
}
}
}

View File

@ -284,6 +284,24 @@ public class Pdh extends Win32 {
return trans.toString();
}
private long addPdhCounter(String path, boolean format) throws Win32Exception {
long counter;
/*
* Some metrics are missing the '/sec' suffix. This flow,
* first tries to add the counter without the '/sec' and
* if fails, try again with it. If the seconds 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.
*/
try {
counter = pdhAddCounter(this.query, translate(path));
} catch (Win32Exception e) {
counter = pdhAddCounter(this.query, translate(path + "/sec"));
}
return counter;
}
private double getValue(String path, boolean format)
throws Win32Exception {
@ -291,8 +309,8 @@ public class Pdh extends Win32 {
pdhConnectMachine(this.hostname);
}
long counter =
pdhAddCounter(this.query, translate(path));
long counter = addPdhCounter(path, format);
try {
return pdhGetValue(this.query, counter, format);
} finally {

View File

@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.List;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class Service extends Win32 {
// Service State
@ -386,6 +387,18 @@ public class Service extends Win32 {
public void list(PrintStream out) throws Win32Exception {
getConfig().list(out);
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 {

View File

@ -18,6 +18,7 @@ package org.hyperic.sigar.win32.test;
import java.util.List;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.test.SigarTestCase;
import org.hyperic.sigar.win32.Service;
@ -25,6 +26,7 @@ import org.hyperic.sigar.win32.ServiceConfig;
import org.hyperic.sigar.win32.Win32Exception;
public class TestService extends SigarTestCase {
private static final String EVENTLOG_NAME = "Eventlog";
private static final String TEST_NAME = "MyTestService";
private static final String PREFIX =
@ -41,7 +43,7 @@ public class TestService extends SigarTestCase {
}
public void testServiceOpen() throws Exception {
Service service = new Service("Eventlog");
Service service = new Service(EVENTLOG_NAME);
service.getConfig();
service.close();
@ -91,6 +93,31 @@ public class TestService extends SigarTestCase {
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 {
if (!TEST_CREATE) {
return;

View File

@ -1,6 +0,0 @@
copyright.year=2004-2011
version.major=1
version.minor=6
version.maint=6
version.build=0

38
bindings/lua/Makefile.am Normal file
View File

@ -0,0 +1,38 @@
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
bindings/lua/lua-sigar.h Normal file
View File

@ -0,0 +1,70 @@
/**
* 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
bindings/lua/sigar-cpu.c Normal file
View File

@ -0,0 +1,183 @@
/**
* 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
bindings/lua/sigar-disk.c Normal file
View File

@ -0,0 +1,192 @@
/**
* 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
bindings/lua/sigar-fs.c Normal file
View File

@ -0,0 +1,186 @@
/**
* 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
bindings/lua/sigar-mem.c Normal file
View File

@ -0,0 +1,62 @@
/**
* 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
bindings/lua/sigar-netif.c Normal file
View File

@ -0,0 +1,206 @@
/**
* 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
bindings/lua/sigar-proc.c Normal file
View File

@ -0,0 +1,246 @@
/**
* 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
bindings/lua/sigar-swap.c Normal file
View File

@ -0,0 +1,59 @@
/**
* 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;
}

View File

@ -0,0 +1,65 @@
/**
* 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
bindings/lua/sigar-test.lua Normal file
View File

@ -0,0 +1,153 @@
--[[
-- 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())

View File

@ -0,0 +1,65 @@
/**
* 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
bindings/lua/sigar-who.c Normal file
View File

@ -0,0 +1,103 @@
/**
* 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
bindings/lua/sigar.c Normal file
View File

@ -0,0 +1,185 @@
/**
* 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
bindings/perl/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
Makefile
*.bs
*.c
*.cpp
*.o
*.old
Sigar_generated.xs
blib
pm_to_blib

View File

@ -1,43 +1,55 @@
use ExtUtils::MakeMaker;
use strict;
use Config;
use File::Basename qw(basename);
use File::Copy qw(copy);
use lib qw(.. lib);
use SigarWrapper ();
use SigarBuild ();
my $gen_xs = 'Sigar_generated.xs';
my(@mm_args);
my(@clean_files) = ($gen_xs);
my $installdir;
if ($ARGV[0]) {
$installdir = $ARGV[0];
#link against installed libsigar
my $installdir = $ARGV[0];
@mm_args = (
LIBS => ["-L$installdir/lib -lsigar"],
INC => "-I$installdir/include",
);
}
else {
#check binary-dist location and svn source location
for (qw(../../sigar-bin ../java/sigar-bin)) {
if (-e $_) {
$installdir = $_;
last;
}
}
#all sources in Sigar.so
my $flags = SigarBuild::flags();
my(@inline_src) = SigarBuild::inline_src($flags);
push @clean_files, @inline_src;
my(@object) = ('Sigar.o', map { s/cp{0,2}$/o/; $_ } @inline_src);
my(@libs) = map { "-l$_" } @{$flags->{libs}};
@mm_args = (
OBJECT => "@object",
LIBS => ["@libs"],
INC => "@{$flags->{cppflags}}",
dynamic_lib => { OTHERLDFLAGS => "@{$flags->{ldflags}}" },
);
}
SigarWrapper::generate(Perl => '.');
my $archname = SigarWrapper::archname();
my $libname = 'sigar';
if ($archname) {
$libname .= '-' . $archname;
}
my $ccname = $Config{ccname};
my $define = {
gcc => '-Wall -Werror',
gcc => '-Wall',
cc_r => '-qhalt=w',
}->{$ccname} || '';
WriteMakefile(
'NAME' => 'Sigar',
'VERSION_FROM' => 'Sigar.pm',
'LIBS' => ["-L$installdir/lib -l$libname"],
'INC' => "-I$installdir/include",
'DEFINE' => $define,
'depend' => { 'Sigar.c' => 'Sigar_generated.xs' },
'depend' => { 'Sigar.c' => $gen_xs },
'realclean' => { FILES => "@clean_files" },
@mm_args,
);

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2004-2008 Hyperic, 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.
@ -50,6 +51,7 @@ typedef sigar_disk_usage_t * Sigar__DiskUsage;
typedef sigar_proc_stat_t * Sigar__ProcStat;
typedef sigar_net_route_t * Sigar__NetRoute;
typedef sigar_net_interface_stat_t * Sigar__NetInterfaceStat;
typedef sigar_arp_t * Sigar__Arp;
typedef sigar_who_t * Sigar__Who;
typedef sigar_thread_cpu_t * Sigar__ThreadCpu;
typedef sigar_resource_limit_t * Sigar__ResourceLimit;
@ -507,3 +509,28 @@ net_connection_list(sigar, flags)
OUTPUT:
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

View File

@ -29,6 +29,7 @@ Sigar::DiskUsage T_PTROBJ
Sigar::ProcStat T_PTROBJ
Sigar::NetRoute T_PTROBJ
Sigar::NetInterfaceStat T_PTROBJ
Sigar::Arp T_PTROBJ
Sigar::Who T_PTROBJ
Sigar::ThreadCpu T_PTROBJ
Sigar::ResourceLimit T_PTROBJ
@ -45,7 +46,7 @@ Sigar::NfsServerV3 T_PTROBJ
OUTPUT
T_NETADDR
{
char addr_str[INET6_ADDRSTRLEN];
char addr_str[SIGAR_INET6_ADDRSTRLEN];
sigar_net_address_to_string(NULL, &$var, addr_str);
sv_setpv($arg, addr_str);
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2007 Hyperic, Inc.
* Copyright (c) 2010-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.
@ -18,13 +19,14 @@
#include "sigar.h"
#include "sigar_fileinfo.h"
#include "sigar_format.h"
#include "sigar_ptql.h"
#define PySigarString_FromNetAddr(a) pysigar_net_address_to_string(&a)
#define PySigarInt_FromChar(c) PyInt_FromLong((int)c)
#define PySigar_ParsePID \
if (!PyArg_ParseTuple(args, "i", &pid)) return NULL
if (pysigar_parse_pid(sigar, args, &pid) != SIGAR_OK) return NULL
#define PySigar_ParseName \
if (!PyArg_ParseTuple(args, "s", &name, &name_len)) return NULL
@ -67,6 +69,103 @@ static void pysigar_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)
{
char addr_str[SIGAR_INET6_ADDRSTRLEN];
@ -130,6 +229,38 @@ static PyObject *pysigar_new_strlist(char **data, unsigned long number)
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,
int size, PyTypeObject *type)
{
@ -190,6 +321,296 @@ static PyObject *pysigar_net_interface_list(PyObject *self, PyObject *args)
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)
{
char buffer[56];
@ -206,7 +627,18 @@ static PyObject *pysigar_format_size(PyObject *self, PyObject *args)
static PyMethodDef pysigar_methods[] = {
{ "close", pysigar_close, 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 },
{ "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
{NULL}
};
@ -265,10 +697,24 @@ static PyMethodDef pysigar_module_methods[] = {
#define PY_SIGAR_CONST_STR(name) \
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)
{
PyObject *o;
init_pysigar_version(dict);
PY_SIGAR_CONST_INT(FIELD_NOTIMPL);
PY_SIGAR_CONST_INT(IFF_UP);

88
bindings/python/setup.py Normal file → Executable file
View File

@ -1,6 +1,7 @@
#!/usr/bin/env python
#
# Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2007, 2009 Hyperic, 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.
@ -16,17 +17,82 @@
#
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
_sigar = Extension(
"_sigar",
["_sigar.c"],
include_dirs = ['../java/sigar-bin/include'],
extra_compile_args = ['-Wall'],
libraries=['sigar-universal-macosx'],
library_dirs=['../java/sigar-bin/lib'],
extra_link_args=[],
define_macros=[],
undef_macros=[])
build = 'build'
options = {'perl':'perl'}
deps = [build + '/_sigar_generated.c']
def parse_args():
global options
args = sys.argv[1:]
for arg in args:
if arg.find("--with-sigar") != -1:
sys.argv.remove(arg)
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",
py_modules = ['sigar'],

View File

@ -1,5 +1,6 @@
#
# Copyright (c) 2007 Hyperic, Inc.
# 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.
@ -15,3 +16,8 @@
#
from _sigar import *
import re
#wrapper for pysigar_ptql_re_impl
def string_matches(source, regex):
return re.compile(regex).match(source) != None

View File

@ -0,0 +1,123 @@
#!/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
bindings/ruby/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
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

View File

@ -0,0 +1,24 @@
#
# 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

View File

@ -1,5 +1,6 @@
#
# Copyright (c) 2007 Hyperic, Inc.
# 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.
@ -14,7 +15,7 @@
# limitations under the License.
#
require 'rbsigar'
require 'sigar'
sigar = Sigar.new
@ -27,6 +28,8 @@ puts num.to_s + " total CPUs.."
infos.each do |info|
puts "Vendor........" + info.vendor
puts "Model........." + info.model
puts "Mhz..........." + info.mhz.to_s
puts "Current 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
end

View File

@ -1,5 +1,6 @@
#
# Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2007, 2009 Hyperic, 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.
@ -14,7 +15,7 @@
# limitations under the License.
#
require 'rbsigar'
require 'sigar'
def format_size(size)
return Sigar.format_size(size * 1024)
@ -27,12 +28,16 @@ puts "Filesystem\tSize\tUsed\tAvail\tUse%\tMounted on\tType\n"
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
total = usage.total
used = total - usage.free
avail = usage.avail
pct = usage.use_percent * 100
begin
usage = sigar.file_system_usage(dir_name)
total = usage.total
used = total - usage.free
avail = usage.avail
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" +
format_size(total) + "\t" +

View File

@ -1,5 +1,6 @@
#
# Copyright (c) 2007 Hyperic, 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.
@ -14,7 +15,7 @@
# limitations under the License.
#
require 'rbsigar'
require 'sigar'
sigar = Sigar.new
mem = sigar.mem

View File

@ -1,5 +1,7 @@
#
# 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");
# you may not use this file except in compliance with the License.
@ -14,7 +16,7 @@
# limitations under the License.
#
require 'rbsigar'
require 'sigar'
sigar = Sigar.new
iflist = sigar.net_interface_list
@ -24,6 +26,10 @@ iflist.each do |ifname|
flags = ifconfig.flags
encap = ifconfig.type
if (flags & Sigar::IFF_UP) == 0
next
end
hwaddr = ifconfig.hwaddr
if hwaddr == Sigar::NULL_HWADDR
hwaddr = ""
@ -45,39 +51,51 @@ iflist.each do |ifname|
bcast = ""
end
puts "\t" + "inet addr:" + ifconfig.address +
ptp + bcast + " Mask:" + ifconfig.netmask
address = ifconfig.address
if address != "0.0.0.0"
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" +
Sigar.net_interface_flags_to_s(flags) +
" MTU:" + ifconfig.mtu.to_s +
" Metric:" + ifconfig.metric.to_s
ifstat = sigar.net_interface_stat(ifname)
if (!ifname.include?(":"))
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" +
"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" +
"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
puts "\t" +
"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
puts "\t" + "collisions:" + ifstat.tx_collisions.to_s +
" txqueuelen:" + ifconfig.tx_queue_len.to_s
puts "\t" + "collisions:" + ifstat.tx_collisions.to_s
rx_bytes = ifstat.rx_bytes
tx_bytes = ifstat.tx_bytes
rx_bytes = ifstat.rx_bytes
tx_bytes = ifstat.tx_bytes
puts "\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
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";
puts "\n"
end

Some files were not shown because too many files have changed in this diff Show More