Author SHA1 Message Date
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
150 changed files with 9179 additions and 2202 deletions

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
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
+35
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
View File
@@ -0,0 +1,5 @@
SUBDIRS = include src bindings examples tests
EXTRA_DIST=\
CMakeLists.txt \
winbuild.bat
+105
View File
@@ -0,0 +1,105 @@
require 'rubygems'
require 'rake/gempackagetask'
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']
# '0.7.x' until the sigar-1.7.0 release
s.version = '0' + '.' + props['version.minor'] + '.' + '0'
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.has_rdoc = false
s.extensions = 'bindings/ruby/extconf.rb'
s.files =
%w(COPYING EXCEPTIONS README Rakefile version.properties) +
%w(bindings/SigarWrapper.pm bindings/SigarBuild.pm) +
Dir.glob("bindings/ruby/**/*") +
Dir.glob("include/*.h") +
Dir.glob("src/**/*.[ch]") +
Dir.glob("src/**/*.in")
end
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
end
task :default => :test
def in_ext()
ext = 'bindings/ruby'
Dir.chdir(ext) if File.directory? ext
end
desc 'Build sigar extension'
task :build do
in_ext()
unless File.exists? "Makefile"
unless system("ruby extconf.rb")
STDERR.puts "Failed to configure"
break
end
end
unless system(MAKE)
STDERR.puts 'Failed to ' + MAKE
break
end
end
Rake::TestTask.new do |t|
t.pattern = 'test/*_test.rb'
t.libs << "."
end
task :test => [:build] do
in_ext()
end
desc 'Clean sigar extension'
task :clean do
in_ext()
system(MAKE + ' clean') if File.exists? "Makefile"
end
desc 'Dist Clean sigar extension'
task :distclean do
in_ext()
system(MAKE + ' distclean') if File.exists? "Makefile"
end
desc 'Run sigar examples (test)'
task :examples => [:build] do
in_ext()
Dir["examples/*.rb"].each do |file|
cmd = "ruby -I. #{file}"
print cmd + "\n"
system(cmd)
end
end
desc "create a gemspec file"
task :make_spec do
File.open("#{GEM}.gemspec", "w") do |file|
file.puts spec.to_ruby
end
end
Executable
+60
View File
@@ -0,0 +1,60 @@
#!/bin/sh
set -x
rm -f INSTALL NEWS AUTHORS \
&& 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>'
Executable
+96
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
View File
@@ -0,0 +1 @@
SUBDIRS=lua
+310
View File
@@ -0,0 +1,310 @@
#
# 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);
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;
my(@sdks) = reverse sort </Developer/SDKs/MacOSX10.*.sdk>;
my $sdk;
if (@sdks == 0) {
die
"Xcode Developer Tools not installed\n".
"Download from http://developer.apple.com/technology/xcode.html";
}
else {
#print "Available SDKs...\n(*) " . join("\n ", @sdks) . "\n";
$sdk = $sdks[0];
}
@cppflags = ('-DDARWIN',
"-I/Developer/Headers/FlatCarbon -isysroot $sdk");
@ldflags = ("-Wl,-syslibroot,$sdk",
'-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 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__
+243 -63
View File
@@ -1,6 +1,7 @@
# #
# Copyright (c) 2007-2008 Hyperic, Inc. # Copyright (c) 2007-2009 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc. # Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2009-2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -19,7 +20,6 @@
package SigarWrapper; package SigarWrapper;
use strict; use strict;
use Config;
use Cwd; use Cwd;
use Exporter; use Exporter;
use File::Path; use File::Path;
@@ -29,57 +29,6 @@ use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter); @ISA = qw(Exporter);
@EXPORT = qw(generate); @EXPORT = qw(generate);
sub archname {
my $os = lc $^O;
my $vers = $Config{osvers};
my $arch = $Config{archname};
if ($os =~ /win32/) {
return 'x86-winnt';
}
elsif ($os =~ /linux/) {
if ($arch =~ /_64/) {
return 'amd64-linux';
}
else {
return 'x86-linux';
}
}
elsif ($os =~ /hpux/) {
if ($vers =~ /11\./) {
return 'pa-hpux-11';
}
}
elsif ($os =~ /aix/) {
return 'ppc-aix-5';
}
elsif ($os =~ /solaris/) {
if ($arch =~ /sun4/) {
return 'sparc-solaris';
}
elsif ($arch =~ /.86/) {
return 'x86-solaris';
}
}
elsif ($os =~ /darwin/) {
return 'universal-macosx';
}
elsif ($os =~ /freebsd/) {
if($arch =~ /.86/) {
if($vers =~ /6\../ ) {
return 'x86-freebsd-6';
}
}
elsif( $arch =~ /amd64/) {
if($vers =~ /6\../ ) {
return 'amd64-freebsd-6';
}
}
}
return '';
}
my %platforms = ( my %platforms = (
A => "AIX", A => "AIX",
D => "Darwin", D => "Darwin",
@@ -97,7 +46,7 @@ my %has_name_arg = map { $_, 1 } qw(FileSystemUsage DiskUsage
my %proc_no_arg = map { $_, 1 } qw(stat); my %proc_no_arg = map { $_, 1 } qw(stat);
my %get_not_impl = map { $_, 1 } qw(net_address net_route net_connection net_stat cpu_perc my %get_not_impl = map { $_, 1 } qw(net_address net_route net_connection net_stat cpu_perc
who cpu_info file_system); #list funcs only arp who cpu_info file_system); #list funcs only
sub supported_platforms { sub supported_platforms {
my $p = shift; my $p = shift;
@@ -531,22 +480,32 @@ use vars qw(%classes %cmds);
{ {
name => 'vendor', type => 'String', name => 'vendor', type => 'String',
desc => 'CPU vendor id', desc => 'CPU vendor id',
plat => 'AFLHSW' plat => '*'
}, },
{ {
name => 'model', type => 'String', name => 'model', type => 'String',
desc => 'CPU model', desc => 'CPU model',
plat => 'AFLHSW' plat => '*'
}, },
{ {
name => 'mhz', type => 'Int', name => 'mhz', type => 'Int',
desc => 'CPU speed', desc => 'Current CPU speed',
plat => 'AFHLSW' 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', name => 'cache_size', type => 'Long',
desc => 'CPU cache size', desc => 'CPU cache size',
plat => 'AL' plat => 'ADL'
}, },
{ {
name => 'total_cores', type => 'Int', name => 'total_cores', type => 'Int',
@@ -1004,6 +963,11 @@ use vars qw(%classes %cmds);
desc => '', desc => '',
plat => '' plat => ''
}, },
{
name => 'default_gateway_interface', type => 'String',
desc => '',
plat => ''
},
{ {
name => 'host_name', type => 'String', name => 'host_name', type => 'String',
desc => '', desc => '',
@@ -1108,6 +1072,18 @@ use vars qw(%classes %cmds);
desc => '', desc => '',
plat => '*' plat => '*'
}, },
{
name => 'address6', type => 'NetAddress',
desc => '',
},
{
name => 'prefix6_length', type => 'Int',
desc => '',
},
{
name => 'scope6', type => 'Int',
desc => '',
},
{ {
name => 'destination', type => 'NetAddress', name => 'destination', type => 'NetAddress',
desc => '', desc => '',
@@ -1138,6 +1114,11 @@ use vars qw(%classes %cmds);
desc => '', desc => '',
plat => 'DFL' plat => 'DFL'
}, },
{
name => 'tx_queue_len', type => 'Int',
desc => '',
plat => 'L'
},
], ],
NetInterfaceStat => [ NetInterfaceStat => [
{ {
@@ -1438,6 +1419,33 @@ use vars qw(%classes %cmds);
plat => '*' plat => '*'
}, },
], ],
Arp => [
{
name => 'ifname', type => 'String',
desc => '',
plat => '*'
},
{
name => 'hwaddr', type => 'NetAddress',
desc => '',
plat => '*'
},
{
name => 'type', type => 'String',
desc => '',
plat => '*'
},
{
name => 'address', type => 'NetAddress',
desc => '',
plat => '*'
},
{
name => 'flags', type => 'Long',
desc => '',
plat => '*'
},
],
Who => [ Who => [
{ {
name => 'user', type => 'String', name => 'user', type => 'String',
@@ -1642,6 +1650,13 @@ $comment
EOF EOF
} }
sub erl_warning_comment {
my $self = shift;
my $comment = $self->warning_comment;
$comment =~ s/^/% /mg;
"$comment\n";
}
sub generate { sub generate {
my($lang, $dir) = @_ ? @_ : @ARGV; my($lang, $dir) = @_ ? @_ : @ARGV;
@@ -1706,7 +1721,9 @@ sub uptodate {
return 1; 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 { sub create {
my($self, $file) = @_; my($self, $file) = @_;
@@ -2367,7 +2384,7 @@ sub generate_class {
if ($func->{num_args} == 1) { if ($func->{num_args} == 1) {
my $arg_type; my $arg_type;
if ($func->{is_proc}) { if ($func->{is_proc}) {
$arg_type = 'NUM2UINT'; $arg_type = 'OBJ2PID';
} }
else { else {
$arg_type = 'StringValuePtr'; $arg_type = 'StringValuePtr';
@@ -2381,8 +2398,9 @@ static VALUE $ruby_class;
static VALUE rb_sigar_$cname($proto) static VALUE rb_sigar_$cname($proto)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
$func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL)); $func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL));
if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) { if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) {
@@ -2794,5 +2812,167 @@ sub finish {
$self->SUPER::finish; $self->SUPER::finish;
} }
package SigarWrapper::Erlang;
use vars qw(@ISA);
@ISA = qw(SigarWrapper);
my %field_types = (
Long => "esigar_encode_ulonglong",
Double => "esigar_encode_double",
Int => "esigar_encode_long",
Char => "esigar_encode_char",
String => "esigar_encode_string",
NetAddress => "esigar_encode_netaddr",
);
my $c_file = 'priv/gen/sigar_drv_gen.c';
my $h_file = 'priv/gen/sigar.hrl';
my $g_file = 'priv/gen/sigar_gen.hrl';
sub sources {
return $c_file;
}
sub start {
my $self = shift;
$self->SUPER::start;
$self->{cfh} = $self->create($c_file);
$self->{hfh} = $self->create($h_file);
$self->{gfh} = $self->create($g_file);
}
sub generate_class {
my($self, $func) = @_;
my $cfh = $self->{cfh};
my $cname = $func->{cname};
my $parse_args = "";
my $vars = "";
my $args = 'sigar';
if ($func->{num_args} == 1) {
if ($func->{is_proc}) {
$parse_args = 'pid = esigar_pid_get(sigar, bytes);';
$vars = "long $func->{arg};\n";
}
else {
$parse_args .= 'name = bytes;';
$vars = "char *$func->{arg};\n";
}
$args .= ", $func->{arg}";
}
my $encoder = "esigar_encode_$cname";
my $n = scalar @{ $func->{fields} };
print $cfh <<EOF;
static void $encoder(ei_x_buff *x,
$func->{sigar_type} *$cname)
{
ei_x_encode_list_header(x, $n);
EOF
for my $field (@{ $func->{fields} }) {
my $name = $field->{name};
my $type = $field_types{ $field->{type} };
print $cfh qq{ $type(x, "$name", $cname->$name);\n};
}
print $cfh " ei_x_encode_empty_list(x);\n}\n\n";
print $cfh <<EOF if $func->{has_get};
static int e$func->{sigar_function}(ErlDrvPort port, sigar_t *sigar, char *bytes)
{
int status;
ei_x_buff x;
$func->{sigar_type} $cname;
$vars
$parse_args
ESIGAR_NEW(&x);
if ((status = $func->{sigar_function}($args, &$cname)) == SIGAR_OK) {
ESIGAR_OK(&x);
$encoder(&x, &$cname);
ESIGAR_SEND(port, &x);
}
else {
ESIGAR_ERROR(&x, sigar, status);
}
return status;
}
EOF
}
my(@nongens) =
qw{net_interface_list net_route_list net_connection_list
file_system_list cpu_info_list arp_list who_list
loadavg};
sub finish {
my $self = shift;
my $mappings = $self->get_mappings;
my $cfh = $self->{cfh};
my $hfh = $self->{hfh};
my $gfh = $self->{gfh};
my $ncmd = 1;
for my $ngen (@nongens) {
my $cmd = uc $ngen;
print $cfh "#define ESIGAR_$cmd $ncmd\n";
print $hfh "-define($cmd, $ncmd).\n";
$ncmd++;
}
for my $func (@$mappings) {
next unless $func->{has_get};
my $name = $func->{cname};
my $cmd = uc $name;
my $nargs = 1 + $func->{num_args};
print $cfh "#define ESIGAR_$cmd $ncmd\n";
print $hfh "-define($cmd, $ncmd).\n";
print $hfh "-export([$name/$nargs]).\n";
$ncmd++;
}
print $cfh <<EOF;
static int esigar_dispatch(ErlDrvPort port, sigar_t *sigar, int cmd, char *bytes) {
switch (cmd) {
EOF
for my $func (@$mappings) {
next unless $func->{has_get};
my $name = $func->{cname};
my $cmd = uc $name;
my $arg = "";
if ($func->{num_args}) {
$arg = ", Arg";
}
print $gfh <<EOF;
$name({sigar, S}$arg) ->
do_command(S, ?$cmd$arg).
EOF
print $cfh <<EOF
case ESIGAR_$cmd:
return e$func->{sigar_function}(port, sigar, bytes);
EOF
}
print $cfh <<EOF;
default:
esigar_notimpl(port, sigar, cmd);
return SIGAR_ENOTIMPL;
}
}
EOF
$self->SUPER::finish;
}
1; 1;
__END__ __END__
+12
View File
@@ -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
+40
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
+16
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
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
+439
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
View File
@@ -0,0 +1 @@
*.beam
+32
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
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
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).
+30
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
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).
+34
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
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
View File
@@ -0,0 +1 @@
*.so
+2
View File
@@ -0,0 +1,2 @@
*.c
*.hrl
+11
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
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.
+6 -4
View File
@@ -4,7 +4,7 @@
<project name="Sigar" default="build" basedir="."> <project name="Sigar" default="build" basedir=".">
<property file="version.properties"/> <property file="../../version.properties"/>
<property name="sigar.version" <property name="sigar.version"
value="${version.major}.${version.minor}.${version.maint}"/> value="${version.major}.${version.minor}.${version.maint}"/>
@@ -144,7 +144,7 @@
<antcall target="version-file"> <antcall target="version-file">
<param name="version.file" <param name="version.file"
value="src/org/hyperic/sigar/SigarVersion.java"/> value="src/org/hyperic/sigar/Version.java"/>
</antcall> </antcall>
<antcall target="version-file"> <antcall target="version-file">
@@ -346,9 +346,11 @@
<arg value="version"/> <arg value="version"/>
</java> </java>
<property name="junit.mx" value="-Dcom.sun.management.jmxremote"/>
<junit printsummary="yes" fork="yes" <junit printsummary="yes" fork="yes"
haltonfailure="yes" showoutput="true"> haltonfailure="yes" showoutput="true">
<jvmarg line="${junit.args}"/> <jvmarg line="${junit.args} ${junit.mx}"/>
<classpath refid="alljars"/> <classpath refid="alljars"/>
<formatter type="xml"/> <formatter type="xml"/>
@@ -497,6 +499,7 @@
<copy toDir="${dist.src}"> <copy toDir="${dist.src}">
<fileset dir="../.."> <fileset dir="../..">
<include name="version.properties"/>
<include name="include/*.h"/> <include name="include/*.h"/>
<include name="src/**/*.h"/> <include name="src/**/*.h"/>
<include name="src/**/*.c"/> <include name="src/**/*.c"/>
@@ -508,7 +511,6 @@
<include name="bindings/java/**/*.h"/> <include name="bindings/java/**/*.h"/>
<include name="bindings/java/**/*.pl"/> <include name="bindings/java/**/*.pl"/>
<include name="bindings/java/**/build.xml"/> <include name="bindings/java/**/build.xml"/>
<include name="bindings/java/version.properties"/>
<include name="bindings/java/.classpath"/> <include name="bindings/java/.classpath"/>
<include name="bindings/java/.project"/> <include name="bindings/java/.project"/>
<include name="bindings/java/.sigar_shellrc"/> <include name="bindings/java/.sigar_shellrc"/>
+39
View File
@@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2004-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc. * Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -897,6 +898,13 @@ JNIEXPORT jstring SIGAR_JNI(NetFlags_getIfFlagsString)
return JENV->NewStringUTF(env, buf); return JENV->NewStringUTF(env, buf);
} }
JNIEXPORT jstring SIGAR_JNI(NetFlags_getScopeString)
(JNIEnv *env, jclass cls, jint scope)
{
const char *buf = sigar_net_scope_to_string(scope);
return JENV->NewStringUTF(env, buf);
}
JNIEXPORT jobjectArray SIGAR_JNIx(getNetConnectionList) JNIEXPORT jobjectArray SIGAR_JNIx(getNetConnectionList)
(JNIEnv *env, jobject sigar_obj, jint flags) (JNIEnv *env, jobject sigar_obj, jint flags)
{ {
@@ -1060,6 +1068,37 @@ JNIEXPORT jstring SIGAR_JNI(NetConnection_getStateString)
sigar_net_connection_state_get(state)); sigar_net_connection_state_get(state));
} }
JNIEXPORT jobjectArray SIGAR_JNIx(getArpList)
(JNIEnv *env, jobject sigar_obj)
{
int status;
unsigned int i;
sigar_arp_list_t arplist;
jobjectArray arparray;
jclass cls = SIGAR_FIND_CLASS("Arp");
dSIGAR(NULL);
if ((status = sigar_arp_list_get(sigar, &arplist)) != SIGAR_OK) {
sigar_throw_error(env, jsigar, status);
return NULL;
}
JAVA_SIGAR_INIT_FIELDS_ARP(cls);
arparray = JENV->NewObjectArray(env, arplist.number, cls, 0);
for (i=0; i<arplist.number; i++) {
jobject info_obj = JENV->AllocObject(env, cls);
JAVA_SIGAR_SET_FIELDS_ARP(cls, info_obj,
arplist.data[i]);
JENV->SetObjectArrayElement(env, arparray, i, info_obj);
}
sigar_arp_list_destroy(sigar, &arplist);
return arparray;
}
JNIEXPORT jobjectArray SIGAR_JNIx(getWhoList) JNIEXPORT jobjectArray SIGAR_JNIx(getWhoList)
(JNIEnv *env, jobject sigar_obj) (JNIEnv *env, jobject sigar_obj)
{ {
@@ -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;
}
}
@@ -1,5 +1,7 @@
/* /*
* Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -95,6 +97,16 @@ public class NetFlags {
public final static int IFF_SLAVE = 0x1000; public final static int IFF_SLAVE = 0x1000;
/**
* Master of a load balancer
*/
public static final int IFF_MASTER = 0x2000;
/**
* Dialup device with changing addresses
*/
public static final int IFF_DYNAMIC = 0x4000;
public static final int RTF_UP = 0x1; public static final int RTF_UP = 0x1;
public static final int RTF_GATEWAY = 0x2; public static final int RTF_GATEWAY = 0x2;
@@ -155,6 +167,13 @@ public class NetFlags {
*/ */
public static native String getIfFlagsString(long flags); public static native String getIfFlagsString(long flags);
/**
* @param network interface ipv6 address scope.
* @return String representation of ipv6 address scope.
* @see org.hyperic.sigar.NetInterfaceConfig#getScope6
*/
public static native String getScopeString(int scope);
public static boolean isAnyAddress(String address) { public static boolean isAnyAddress(String address) {
return return
(address == null) || (address == null) ||
+17 -5
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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -46,7 +47,7 @@ public class Sigar implements SigarProxy {
* The Sigar java version. * The Sigar java version.
*/ */
public static final String VERSION_STRING = public static final String VERSION_STRING =
SigarVersion.VERSION_STRING; Version.VERSION_STRING;
/** /**
* The Sigar native version. * The Sigar native version.
@@ -57,7 +58,7 @@ public class Sigar implements SigarProxy {
* The scm (svn) revision from which sigar.jar was built. * The scm (svn) revision from which sigar.jar was built.
*/ */
public static final String SCM_REVISION = public static final String SCM_REVISION =
SigarVersion.SCM_REVISION; Version.SCM_REVISION;
/** /**
* The scm (svn) revision from which the sigar native binary was built. * The scm (svn) revision from which the sigar native binary was built.
@@ -68,7 +69,7 @@ public class Sigar implements SigarProxy {
* The date on which sigar.jar was built. * The date on which sigar.jar was built.
*/ */
public static final String BUILD_DATE = public static final String BUILD_DATE =
SigarVersion.BUILD_DATE; Version.BUILD_DATE;
/** /**
* The date on which the sigar native binary was built. * The date on which the sigar native binary was built.
@@ -154,15 +155,19 @@ public class Sigar implements SigarProxy {
} }
private static void loadLibrary() throws SigarException { private static void loadLibrary() throws SigarException {
try {
if (SigarLoader.IS_WIN32 && if (SigarLoader.IS_WIN32 &&
System.getProperty("os.version").equals("4.0")) System.getProperty("os.version").equals("4.0"))
{ {
try {
//NT 4.0 only
String lib = String lib =
loader.findJarPath("pdh.dll") + loader.findJarPath("pdh.dll") +
File.separator + "pdh.dll"; File.separator + "pdh.dll";
loader.systemLoad(lib); loader.systemLoad(lib);
} catch (Exception e) {}
} }
try {
loader.load(); loader.load();
} catch (ArchNotSupportedException e) { } catch (ArchNotSupportedException e) {
throw new SigarException(e.getMessage()); throw new SigarException(e.getMessage());
@@ -802,6 +807,9 @@ public class Sigar implements SigarProxy {
return netstat; return netstat;
} }
public native Arp[] getArpList()
throws SigarException;
public native Who[] getWhoList() public native Who[] getWhoList()
throws SigarException; throws SigarException;
@@ -953,6 +961,10 @@ public class Sigar implements SigarProxy {
*/ */
public native String getFQDN() throws SigarException; public native String getFQDN() throws SigarException;
public SigarVersion getSigarVersion() {
return new SigarVersion();
}
/** /**
* Enabling logging in the native Sigar code. * Enabling logging in the native Sigar code.
* This method will hook log4j into the Sigar * This method will hook log4j into the Sigar
@@ -94,7 +94,7 @@ public class SigarInvoker {
this.sigarProxy = proxy; this.sigarProxy = proxy;
} }
protected void setType(String val) { public void setType(String val) {
String alias = (String)compatTypes.get(val); String alias = (String)compatTypes.get(val);
if (alias != null) { if (alias != null) {
val = alias; val = alias;
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2006-2007, 2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009 SpringSource, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -173,5 +173,7 @@ public interface SigarProxy {
public NetInfo getNetInfo() throws SigarException; public NetInfo getNetInfo() throws SigarException;
public SigarVersion getSigarVersion();
public String getFQDN() throws SigarException; public String getFQDN() throws SigarException;
} }
@@ -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();
}
}
@@ -1,6 +1,6 @@
package org.hyperic.sigar; package org.hyperic.sigar;
class SigarVersion { class Version {
static final String BUILD_DATE = "@@BUILD_DATE@@"; static final String BUILD_DATE = "@@BUILD_DATE@@";
@@ -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);
}
}
@@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2006 Hyperic, Inc. * Copyright (c) 2006 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -115,6 +116,13 @@ public class Ifconfig extends SigarCommandBase {
bcast + bcast +
" Mask:" + ifconfig.getNetmask()); " Mask:" + ifconfig.getNetmask());
if (ifconfig.getPrefix6Length() != 0) {
println("\t" +
"inet6 addr: " + ifconfig.getAddress6() + "/" +
ifconfig.getPrefix6Length() +
" Scope:" + NetFlags.getScopeString(ifconfig.getScope6()));
}
println("\t" + println("\t" +
NetFlags.getIfFlagsString(flags) + NetFlags.getIfFlagsString(flags) +
" MTU:" + ifconfig.getMtu() + " MTU:" + ifconfig.getMtu() +
@@ -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);
}
}
@@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2006-2007 Hyperic, Inc.
* Copyright (c) 2009 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -60,7 +61,8 @@ public class NetInfo extends SigarCommandBase {
info.getDomainName()); info.getDomainName());
println("default gateway......." + println("default gateway......." +
info.getDefaultGateway()); info.getDefaultGateway() +
" (" + info.getDefaultGatewayInterface() + ")");
println("primary dns..........." + println("primary dns..........." +
info.getPrimaryDns()); info.getPrimaryDns());
@@ -76,6 +76,7 @@ public class Shell extends ShellBase {
} }
public void registerCommands() throws ShellCommandInitException { public void registerCommands() throws ShellCommandInitException {
registerCommandHandler("arp", new Arp(this));
registerCommandHandler("df", new Df(this)); registerCommandHandler("df", new Df(this));
registerCommandHandler("du", new Du(this)); registerCommandHandler("du", new Du(this));
registerCommandHandler("ls", new Ls(this)); registerCommandHandler("ls", new Ls(this));
@@ -111,6 +112,10 @@ public class Shell extends ShellBase {
registerCommandHandler("test", "org.hyperic.sigar.test.SigarTestRunner"); registerCommandHandler("test", "org.hyperic.sigar.test.SigarTestRunner");
} catch (NoClassDefFoundError e) { } } catch (NoClassDefFoundError e) { }
catch (Exception e) { } catch (Exception e) { }
try {
//requires jre 1.5+ or mx4j
registerCommandHandler("mx", new Mx(this));
} catch (NoClassDefFoundError e) { }
} }
private void registerCommandHandler(String name, String className) throws Exception { private void registerCommandHandler(String name, String className) throws Exception {
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007, 2009 Hyperic, Inc. * Copyright (c) 2007-2009 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,17 +20,13 @@ import javax.management.Attribute;
import javax.management.AttributeList; import javax.management.AttributeList;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean; import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException; import javax.management.MBeanException;
import javax.management.MBeanRegistration; import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/** /**
* Base class for all Sigar JMX MBeans. Provides a skeleton which handles * Base class for all Sigar JMX MBeans. Provides a skeleton which handles
@@ -43,24 +39,10 @@ import org.hyperic.sigar.SigarProxyCache;
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration { public abstract class AbstractMBean implements DynamicMBean {
protected static final String MBEAN_ATTR_TYPE = "type"; public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
protected static final short CACHED_30SEC = 0;
protected static final short CACHED_5SEC = 1;
protected static final short CACHED_500MS = 2;
protected static final short CACHELESS = 3;
protected static final short DEFAULT = CACHED_30SEC;
/**
* The Sigar implementation to be used to fetch information from the system.
*/
protected final Sigar sigarImpl;
/** /**
* The Sigar proxy cache to be used in case the data does not have to be * The Sigar proxy cache to be used in case the data does not have to be
@@ -73,69 +55,13 @@ public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
protected final SigarProxy sigar; protected final SigarProxy sigar;
/** /**
* The MBean server this MBean is registered to. Set during the MBean's * <p>Creates a new instance of this class. The SigarProxy instance is stored (and
* registration to the MBean server and unset to <code>null</code> when * accessible) via the {@link #sigar} member.
* the deregistration finished.
* *
* @see #preRegister(MBeanServer, ObjectName) * @param sigar The SigarProxy instance to use. Must not be <code>null</code>
* @see #postDeregister()
*/ */
protected MBeanServer mbeanServer; protected AbstractMBean(SigarProxy sigar) {
this.sigar = sigar;
/**
* <p>Creates a new instance of this class. The Sigar instance is stored (and
* accessible) via the {@link #sigarImpl} member. A second instance is
* stored within the {@link #sigar} member which is either {@link #sigarImpl}
* or an instance of {@link SigarProxyCache} with the expiration time set to
* whatever the <code>cacheMode</code> parameter specifies.</p>
*
* <p>The following cache modes exist:</p>
*
* <table border = "1">
* <tr><td><b>Constant</b></td><td><b>Description</b></td></tr>
* <tr><td>{@link #CACHELESS}</td><td>No cached instance, {@link #sigar}
* <code>==</code> {@link #sigarImpl}.</td></tr>
* <tr><td>{@link #CACHED_500MS}</td><td>500 millisecond cache, for high
* frequency queries on raw data such as reading out CPU timers each
* second. Avoids reading out multiple data sets when all attributes of
* an MBean are queried in short sequence.</td></tr>
* <tr><td>{@link #CACHED_5SEC}</td><td>5 second cache, for high frequency
* queries on calculated data such as CPU percentages.</td></tr>
* <tr><td>{@link #CACHED_30SEC}</td><td>30 second cache, for normal queries
* or data readouts such as CPU model / vendor. This is the default if
* nothing (<code>0</code>) is specified.</td></tr>
* <tr><td>{@link #DEFAULT}</td><td>Same as {@link #CACHED_30SEC}.</td></tr>
* </table>
*
* <p><b>Note:</b> Only make use of the cacheless or half second mode if you
* know what you are doing. They may have impact on system performance if
* used excessively.</p>
*
* @param sigar The Sigar impl to use. Must not be <code>null</code>
* @param cacheMode The cache mode to use for {@link #sigar} or {@link #CACHELESS}
* if no separate, cached instance is to be maintained.
*/
protected AbstractMBean(Sigar sigar, short cacheMode) {
// store Sigar
this.sigarImpl = sigar;
// create a cached instance as well
if (cacheMode == CACHELESS) {
// no cached version
this.sigar = this.sigarImpl;
} else if (cacheMode == CACHED_500MS) {
// 500ms cached version (for 1/sec queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 500);
} else if (cacheMode == CACHED_5SEC) {
// 5sec cached version (for avg'd queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 5000);
} else /* if (cacheMode == CACHED_30SEC) */{
// 30sec (default) cached version (for info and long term queries)
this.sigar = SigarProxyCache.newInstance(this.sigarImpl, 30000);
}
} }
/** /**
@@ -200,67 +126,19 @@ public abstract class AbstractMBean implements DynamicMBean, MBeanRegistration {
result.add(next); result.add(next);
} catch (AttributeNotFoundException e) { } catch (AttributeNotFoundException e) {
// ignore, as we cannot throw this exception // ignore, as we cannot throw this exception
} catch (InvalidAttributeValueException e) {
// ignore, as we cannot throw this exception
} catch (MBeanException e) {
// ignore, as we cannot throw this exception
} catch (ReflectionException e) {
// ignore, as we cannot throw this exception
} }
} }
return result; return result;
} }
// ------- public void setAttribute(Attribute attr) throws AttributeNotFoundException {
// Implementation of the MBeanRegistration interface throw new AttributeNotFoundException(attr.getName());
// -------
/**
* <p>Returns <code>new ObjectName(this.getObjectName())</code> to guarantee
* a reliable and reproducable object name.</p>
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#preRegister(MBeanServer, ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
this.mbeanServer = server;
return new ObjectName(getObjectName());
} }
/** public Object invoke(String name, Object[] params, String[] signature)
* Empty implementation, allowing aubclasses to ignore the interface. throws ReflectionException {
*
* <p><b>Note:</b> Make sure any subclass does a super call to this method,
* otherwise the implementation might be broken.</p>
*
* @see MBeanRegistration#postRegister(Boolean)
*/
public void postRegister(Boolean success) {
}
/** throw new ReflectionException(new NoSuchMethodException(name),
* Empty implementation, allowing aubclasses to ignore the interface. name);
*
* <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;
} }
} }
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,13 +16,16 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import java.lang.reflect.InvocationHandler;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarInvoker; import org.hyperic.sigar.SigarInvoker;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
import org.hyperic.sigar.util.ReferenceMap; import org.hyperic.sigar.util.ReferenceMap;
/** /**
@@ -34,6 +37,7 @@ public class SigarInvokerJMX extends SigarInvoker {
public static final String DOMAIN_NAME = "sigar"; public static final String DOMAIN_NAME = "sigar";
public static final String PROP_TYPE = "Type"; public static final String PROP_TYPE = "Type";
public static final String PROP_NAME = "Name"; //prefer Name (Arg for compat)
public static final String PROP_ARG = "Arg"; public static final String PROP_ARG = "Arg";
private String arg = null; private String arg = null;
@@ -58,6 +62,10 @@ public class SigarInvokerJMX extends SigarInvoker {
SigarInvokerJMX invoker; SigarInvokerJMX invoker;
if (!(proxy instanceof InvocationHandler) && (proxy instanceof Sigar)) {
proxy = SigarProxyCache.newInstance((Sigar)proxy);
}
int ix = name.indexOf(":"); int ix = name.indexOf(":");
if (ix > 0) { if (ix > 0) {
//skip domain name //skip domain name
@@ -82,10 +90,12 @@ public class SigarInvokerJMX extends SigarInvoker {
String key = attr.substring(0, ix); String key = attr.substring(0, ix);
String val = attr.substring(key.length()+1); String val = attr.substring(key.length()+1);
if (key.equals(PROP_TYPE)) { if (key.equalsIgnoreCase(PROP_TYPE)) {
invoker.setType(val); 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:\ //need to decode value, e.g. Arg=C%3D\ => Arg=C:\
invoker.setArg(decode(val)); invoker.setArg(decode(val));
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007, 2009 Hyperic, Inc. * Copyright (c) 2007-2009 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,246 +16,38 @@
package org.hyperic.sigar.jmx; package org.hyperic.sigar.jmx;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanException;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException; import javax.management.ReflectionException;
import org.hyperic.sigar.LoadAverage;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.SigarProxy;
/** public class SigarLoadAverage extends ReflectedMBean {
* Sigar JMX MBean implementation for the <code>LoadAverage</code> information
* package. Provides an OpenMBean conform implementation.
*
* @author Bjoern Martin
* @since 1.5
*/
public class SigarLoadAverage extends AbstractMBean {
private static final String MBEAN_TYPE = "LoadAverage"; private static final String MBEAN_TYPE = "LoadAverage";
/** public SigarLoadAverage(SigarProxy sigar) {
* Returned if {@link Sigar#getLoadAverage()}} is detected to be not super(sigar, MBEAN_TYPE);
* implemented on the platform.
*
* @see #notImplemented
*/
private static final double NOT_IMPLEMENTED_LOAD_VALUE = -1.0d;
private static final MBeanInfo MBEAN_INFO;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST1MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST5MIN;
private static final MBeanAttributeInfo MBEAN_ATTR_LAST15MIN;
private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR;
private static MBeanParameterInfo MBEAN_PARAM_SIGAR;
static {
MBEAN_ATTR_LAST1MIN = new MBeanAttributeInfo(
"LastMinute",
"double",
"The load average in the last minute, as a fraction of 1, or "
+ "-1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_ATTR_LAST5MIN = new MBeanAttributeInfo(
"LastFiveMinutes",
"double",
"The load average over the last five minutes, as a fraction "
+ "of 1, or -1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_ATTR_LAST15MIN = new MBeanAttributeInfo(
"Last15Minutes",
"double",
"The load average over the last 15 minutes, as a fraction of "
+ "1, or -1.0 if the load cannot be determined on this platform",
true, false, false);
MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class
.getName(), "The Sigar instance to use to fetch data from");
MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo(
SigarLoadAverage.class.getName(),
"Creates a new instance, using the Sigar instance specified "
+ "to fetch the data. Fails if the CPU index is out of range.",
new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR });
MBEAN_INFO = new MBeanInfo(
SigarLoadAverage.class.getName(),
"Sigar load average MBean. Provides load averages of the "
+ "system over the last one, five and 15 minutes. Due to the "
+ "long term character of that information, the fetch is done "
+ "using a Sigar proxy cache with a timeout of 30 seconds.",
new MBeanAttributeInfo[] { MBEAN_ATTR_LAST1MIN,
MBEAN_ATTR_LAST5MIN, MBEAN_ATTR_LAST15MIN },
new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null);
} }
/** public Object getAttribute(String name)
* Object name this instance will give itself when being registered to an throws AttributeNotFoundException,
* MBeanServer. MBeanException, ReflectionException {
*/
private final String objectName;
/**
* <p>Set <code>true</code> when the load average fetch failed with a
* <code>SigarException</code> that indicates the method is not implemented.
* Any subsequent call to this instance will then be answered with
* {@link #NOT_IMPLEMENTED_LOAD_VALUE}.
* </p>
*
* <p><b>FIXME</b> : This is a workaround and should be replaced by something
* more stable, as the code setting this member <code>true</code> relies on
* a substring being present within the exception. A proposal was made at
* <a href="http://jira.hyperic.com/browse/SIGAR-52">issue SIGAR-52</a>.
* </p>
*/
private boolean notImplemented;
/**
* Creates a new instance, using a new Sigar instance to fetch the data.
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs.
*/
public SigarLoadAverage() throws IllegalArgumentException {
this(new Sigar());
}
/**
* Creates a new instance, using the Sigar instance specified to fetch the
* data.
*
* @param sigar
* The Sigar instance to use to fetch data from
*
* @throws IllegalArgumentException
* If an unexpected Sigar error occurs
*/
public SigarLoadAverage(Sigar sigar) throws IllegalArgumentException {
super(sigar, CACHED_30SEC);
// all fine
this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE
+ "=" + MBEAN_TYPE;
}
/**
* Object name this instance will give itself when being registered to an
* MBeanServer.
*/
public String getObjectName() {
return this.objectName;
}
/**
* @return The load average in the last minute, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLastMinute() {
try { try {
return sigarImpl.getLoadAverage()[0]; Object val =
new LoadAverage(this.sigar.getLoadAverage()).toMap().get(name);
if (val == null) {
throw new AttributeNotFoundException(name);
}
return val;
} catch (SigarNotImplementedException e) { } catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE; return new Double(Sigar.FIELD_NOTIMPL);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e); throw new ReflectionException(e);
} }
} }
/**
* @return The load average over the last five minutes, as a fraction of 1,
* or <code>-1.0d</code> if the load cannot be determined on this
* platform
*/
public double getLastFiveMinutes() {
try {
return sigarImpl.getLoadAverage()[1];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
/**
* @return The load average over the last 15 minutes, as a fraction of 1, or
* <code>-1.0d</code> if the load cannot be determined on this platform
*/
public double getLast15Minutes() {
try {
return sigarImpl.getLoadAverage()[2];
} catch (SigarNotImplementedException e) {
return NOT_IMPLEMENTED_LOAD_VALUE;
} catch (SigarException e) {
throw unexpectedError(MBEAN_TYPE, e);
}
}
// -------
// Implementation of the DynamicMBean interface
// -------
/*
* (non-Javadoc)
*
* @see DynamicMBean#getAttribute(String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
if (MBEAN_ATTR_LAST1MIN.getName().equals(attr)) {
return new Double(getLastMinute());
} else if (MBEAN_ATTR_LAST5MIN.getName().equals(attr)) {
return new Double(getLastFiveMinutes());
} else if (MBEAN_ATTR_LAST15MIN.getName().equals(attr)) {
return new Double(getLast15Minutes());
} else {
throw new AttributeNotFoundException(attr);
}
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#setAttribute(Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#invoke(String, Object[], String[])
*/
public Object invoke(String actionName, Object[] params, String[] signature)
throws ReflectionException {
throw new ReflectionException(new NoSuchMethodException(actionName),
actionName);
}
/*
* (non-Javadoc)
*
* @see DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
}
} }
@@ -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;
}
}
@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.hyperic.sigar.jmx;
import org.hyperic.sigar.ProcCpu; import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcFd; import org.hyperic.sigar.ProcFd;
import org.hyperic.sigar.ProcMem; import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxy;
@@ -31,21 +32,25 @@ import org.hyperic.sigar.SigarProxyCache;
public class SigarProcess implements SigarProcessMBean { public class SigarProcess implements SigarProcessMBean {
private static final Long NOTIMPL = new Long(Sigar.FIELD_NOTIMPL);
private Sigar sigarImpl; private Sigar sigarImpl;
private SigarProxy sigar; private SigarProxy sigar;
private long pid = -1;
public SigarProcess() { public SigarProcess() {
this(new Sigar()); this.sigarImpl = new Sigar();
}
public SigarProcess(Sigar sigar) {
this.sigarImpl = sigar;
this.sigar = SigarProxyCache.newInstance(sigarImpl); this.sigar = SigarProxyCache.newInstance(sigarImpl);
} }
public SigarProcess(SigarProxy sigar) {
this.sigar = sigar;
}
public void close() { public void close() {
if (this.sigarImpl != null) {
this.sigarImpl.close(); this.sigarImpl.close();
} }
}
private RuntimeException unexpectedError(String type, private RuntimeException unexpectedError(String type,
SigarException e) { SigarException e) {
@@ -57,8 +62,7 @@ public class SigarProcess implements SigarProcessMBean {
private synchronized ProcMem getMem() { private synchronized ProcMem getMem() {
try { try {
long pid = this.sigar.getPid(); return this.sigar.getProcMem(getPid());
return this.sigar.getProcMem(pid);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("Mem", e); throw unexpectedError("Mem", e);
} }
@@ -66,20 +70,44 @@ public class SigarProcess implements SigarProcessMBean {
private synchronized ProcCpu getCpu() { private synchronized ProcCpu getCpu() {
try { try {
long pid = this.sigar.getPid(); return this.sigar.getProcCpu(getPid());
return this.sigar.getProcCpu(pid);
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("Cpu", e); throw unexpectedError("Cpu", e);
} }
} }
private synchronized ProcFd getFd() { private synchronized ProcFd getFd() throws SigarException {
try { return this.sigar.getProcFd(getPid());
long pid = this.sigar.getPid();
return this.sigar.getProcFd(pid);
} catch (SigarException e) {
throw unexpectedError("Fd", e);
} }
public String getObjectName() throws SigarException {
long pid = getPid();
String name = this.sigar.getProcState(pid).getName();
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() { public Long getMemSize() {
@@ -119,17 +147,10 @@ public class SigarProcess implements SigarProcessMBean {
} }
public Long getOpenFd() { public Long getOpenFd() {
try {
return new Long(getFd().getTotal()); 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());
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007, 2009 Hyperic, Inc. * Copyright (c) 2007-2009 Hyperic, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,19 +18,18 @@ package org.hyperic.sigar.jmx;
import java.util.ArrayList; import java.util.ArrayList;
import javax.management.Attribute; import javax.management.MBeanRegistration;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.management.ObjectInstance; import javax.management.ObjectInstance;
import javax.management.ObjectName; import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarProxyCache;
/** /**
* <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke * <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke
@@ -57,266 +56,173 @@ import org.hyperic.sigar.SigarException;
* @author Bjoern Martin * @author Bjoern Martin
* @since 1.5 * @since 1.5
*/ */
public class SigarRegistry extends AbstractMBean { public class SigarRegistry implements MBeanRegistration, SigarRegistryMBean {
public static final String MBEAN_DOMAIN = SigarInvokerJMX.DOMAIN_NAME;
public static final String MBEAN_ATTR_TYPE = SigarInvokerJMX.PROP_TYPE;
private static final String MBEAN_TYPE = "SigarRegistry"; private static final String MBEAN_TYPE = "SigarRegistry";
private static final int CACHE_EXPIRE = 60 * 1000;
private static final 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 { public SigarRegistry(SigarProxy sigar) {
MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo( init(sigar);
SigarRegistry.class.getName(),
"Creates a new instance of this class. Will create the Sigar "
+ "instance this class uses when constructing other MBeans",
new MBeanParameterInfo[0]);
// MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses",
// "Executes a query returning the process IDs of all processes " +
// "found on the system.",
// null /* new MBeanParameterInfo[0] */,
// String.class.getName(), MBeanOperationInfo.INFO);
MBEAN_INFO = new MBeanInfo(
SigarRegistry.class.getName(),
"Sigar MBean registry. Provides a central point for creation "
+ "and destruction of Sigar MBeans. Any Sigar MBean created via "
+ "this instance will automatically be cleaned up when this "
+ "instance is deregistered from the MBean server.",
null /*new MBeanAttributeInfo[0]*/,
new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT },
null /*new MBeanOperationInfo[0] */,
null /*new MBeanNotificationInfo[0]*/);
} }
private final String objectName; private void init(SigarProxy sigar) {
this.sigar = sigar;
private final ArrayList managedBeans; this.objectName =
MBEAN_DOMAIN + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE;
/**
* 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(); this.managedBeans = new ArrayList();
} }
/* (non-Javadoc)
* @see AbstractMBean#getObjectName()
*/
public String getObjectName() { public String getObjectName() {
return this.objectName; return this.objectName;
} }
/* public String listProcesses() { private void registerMBean(AbstractMBean mbean) {
try { try {
final long start = System.currentTimeMillis(); ObjectName name =
long[] ids = sigar.getProcList(); new ObjectName(mbean.getObjectName());
StringBuffer procNames = new StringBuffer(); if (mbeanServer.isRegistered(name)) {
for (int i = 0; i < ids.length; i++) { return;
try {
procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n');
} catch (SigarException e) {
procNames.append(ids[i] + ":" + e.getMessage()).append('\n');
} }
ObjectInstance instance =
this.mbeanServer.registerMBean(mbean, name);
this.managedBeans.add(instance.getObjectName());
} catch (Exception e) {
e.printStackTrace();
} }
final long end = System.currentTimeMillis();
procNames.append("-- Took " + (end-start) + "ms");
return procNames.toString();
} catch (SigarException e) {
throw unexpectedError("ProcList", e);
}
}
*/
/* (non-Javadoc)
* @see javax.management.DynamicMBean#getAttribute(java.lang.String)
*/
public Object getAttribute(String attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr);
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
*/
public void setAttribute(Attribute attr) throws AttributeNotFoundException {
throw new AttributeNotFoundException(attr.getName());
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#invoke(java.lang.String, java.lang.Object[], java.lang.String[])
*/
public Object invoke(String action, Object[] params, String[] signatures)
throws MBeanException, ReflectionException {
/* if (MBEAN_OPER_LISTPROCESSES.getName().equals(action))
return listProcesses();
else */
throw new ReflectionException(new NoSuchMethodException(action), action);
}
/* (non-Javadoc)
* @see javax.management.DynamicMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
return MBEAN_INFO;
} }
// ------- // -------
// Implementation of the MBeanRegistration interface // Implementation of the MBeanRegistration interface
// ------- // -------
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
//no args constructor support
if (this.sigar == null) {
this.sigarImpl = new Sigar();
init(SigarProxyCache.newInstance(this.sigarImpl, CACHE_EXPIRE));
}
this.mbeanServer = server;
if (name == null) {
return new ObjectName(getObjectName());
}
else {
return name;
}
}
/** /**
* Registers the default set of Sigar MBeans. Before doing so, a super call * Registers the default set of Sigar MBeans.
* is made to satisfy {@link AbstractMBean}.
*
* @see AbstractMBean#postRegister(Boolean)
*/ */
public void postRegister(Boolean success) { public void postRegister(Boolean success) {
ReflectedMBean mbean;
super.postRegister(success);
if (!success.booleanValue()) if (!success.booleanValue())
return; return;
// get CPUs //CPU beans
registerCpuBeans(); CpuInfo[] info;
// get memory
registerMemoryBeans();
// get system
registerSystemBeans();
}
/**
* Registers MBeans for the Sigar types <code>Cpu</code>, <code>CpuPerc</code>
* and <code>CpuInfo</code>. One instance will be registered for each CPU
* (core?) found.
*/
private void registerCpuBeans() {
ObjectInstance nextRegistered = null;
try { try {
final int cpuCount = sigar.getCpuInfoList().length; info = sigar.getCpuInfoList();
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;
}
} catch (SigarException e) { } catch (SigarException e) {
throw unexpectedError("CpuInfoList", e); info = new CpuInfo[0]; //XXX log
}
} }
/** for (int i=0; i<info.length; i++) {
* Registers MBeans for the Sigar types <code>Mem</code> and <code>Swap</code>. String idx = String.valueOf(i);
*/ mbean =
private void registerMemoryBeans() { 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 mbean = new ReflectedMBean(this.sigar, "CpuUsage");
SigarMem mem = new SigarMem(sigarImpl); mbean.setType("CpuPerc");
registerMBean(mbean);
//FileSystem beans
try { try {
if (!mbeanServer.isRegistered(new ObjectName(mem.getObjectName()))) FileSystem[] fslist = this.sigar.getFileSystemList();
nextRegistered = mbeanServer.registerMBean(mem, null); for (int i=0; i<fslist.length; i++) {
} catch (Exception e) { // ignore 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 //NetInterface beans
if (nextRegistered != null)
managedBeans.add(nextRegistered.getObjectName());
nextRegistered = null;
// add swap memory bean
SigarSwap swap = new SigarSwap(sigarImpl);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(swap.getObjectName()))) String[] ifnames = this.sigar.getNetInterfaceList();
nextRegistered = mbeanServer.registerMBean(swap, null); for (int i=0; i<ifnames.length; i++) {
} catch (Exception e) { // ignore String name = ifnames[i];
nextRegistered = null; NetInterfaceConfig ifconfig =
} this.sigar.getNetInterfaceConfig(name);
// 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);
try { try {
if (!mbeanServer.isRegistered(new ObjectName(loadAvg this.sigar.getNetInterfaceStat(name);
.getObjectName()))) } catch (SigarException e) {
nextRegistered = mbeanServer.registerMBean(loadAvg, null); continue;
} catch (Exception e) { // ignore }
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 //network info bean
if (nextRegistered != null) mbean = new ReflectedMBean(this.sigar, "NetInfo");
managedBeans.add(nextRegistered.getObjectName()); try {
nextRegistered = null; mbean.putAttribute("FQDN", this.sigar.getFQDN());
} catch (SigarException e) {
}
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 * Deregisters all Sigar MBeans that were created and registered using this
* instance. After doing so, a super call is made to satisfy {@link AbstractMBean}. * instance.
* @throws Exception * @throws Exception
* *
* @see AbstractMBean#preDeregister() * @see AbstractMBean#preDeregister()
@@ -333,8 +239,14 @@ public class SigarRegistry extends AbstractMBean {
} }
} }
} }
}
// do the super call public void postDeregister() {
super.preDeregister(); this.mbeanServer = null;
if (this.sigarImpl != null) {
this.sigarImpl.close();
this.sigarImpl = null;
this.sigar = null;
}
} }
} }
@@ -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 {
}
@@ -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;
}
}
@@ -1,6 +1,7 @@
/* /*
* Copyright (c) 2006-2008 Hyperic, Inc. * Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,6 +44,7 @@ public class SigarTestRunner extends SigarCommandBase {
private static final Class[] ALL_TESTS = { private static final Class[] ALL_TESTS = {
TestLog.class, TestLog.class,
TestInvoker.class, TestInvoker.class,
TestMx.class,
TestPTQL.class, TestPTQL.class,
TestCpu.class, TestCpu.class,
TestCpuInfo.class, TestCpuInfo.class,
@@ -77,6 +79,7 @@ public class SigarTestRunner extends SigarCommandBase {
TestThreadCpu.class, TestThreadCpu.class,
TestUptime.class, TestUptime.class,
TestVMware.class, TestVMware.class,
TestArp.class,
TestWho.class, TestWho.class,
TestHumidor.class TestHumidor.class
}; };
@@ -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;
}
}
}
@@ -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);
}
}
@@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2006-2008 Hyperic, Inc. * Copyright (c) 2006-2008 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +17,9 @@
package org.hyperic.sigar.test; package org.hyperic.sigar.test;
import java.net.InetAddress;
import java.net.Inet6Address;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarNotImplementedException;
@@ -42,6 +46,14 @@ public class TestNetIf extends SigarTestCase {
assertTrueTrace("Address", ifconfig.getAddress()); assertTrueTrace("Address", ifconfig.getAddress());
assertTrueTrace("Netmask", ifconfig.getNetmask()); assertTrueTrace("Netmask", ifconfig.getNetmask());
if (ifconfig.getPrefix6Length() != 0) {
assertTrueTrace("Address6", ifconfig.getAddress6());
InetAddress in6 =
InetAddress.getByName(ifconfig.getAddress6());
assertTrue(in6 instanceof Inet6Address);
traceln("Link=" + in6.isLinkLocalAddress());
}
if (!getStats) { if (!getStats) {
continue; continue;
} }
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class Service extends Win32 { public class Service extends Win32 {
// Service State // Service State
@@ -386,6 +387,18 @@ public class Service extends Win32 {
public void list(PrintStream out) throws Win32Exception { public void list(PrintStream out) throws Win32Exception {
getConfig().list(out); getConfig().list(out);
out.println("status........[" + getStatusString() + "]"); out.println("status........[" + getStatusString() + "]");
if (getStatus() != SERVICE_RUNNING) {
return;
}
Sigar sigar = new Sigar();
try {
long pid = sigar.getServicePid(getConfig().getName());
out.println("pid...........[" + pid + "]");
} catch (SigarException e) {
} finally {
sigar.close();
}
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@@ -18,6 +18,7 @@ package org.hyperic.sigar.win32.test;
import java.util.List; import java.util.List;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.test.SigarTestCase; import org.hyperic.sigar.test.SigarTestCase;
import org.hyperic.sigar.win32.Service; import org.hyperic.sigar.win32.Service;
@@ -25,6 +26,7 @@ import org.hyperic.sigar.win32.ServiceConfig;
import org.hyperic.sigar.win32.Win32Exception; import org.hyperic.sigar.win32.Win32Exception;
public class TestService extends SigarTestCase { public class TestService extends SigarTestCase {
private static final String EVENTLOG_NAME = "Eventlog";
private static final String TEST_NAME = "MyTestService"; private static final String TEST_NAME = "MyTestService";
private static final String PREFIX = private static final String PREFIX =
@@ -41,7 +43,7 @@ public class TestService extends SigarTestCase {
} }
public void testServiceOpen() throws Exception { public void testServiceOpen() throws Exception {
Service service = new Service("Eventlog"); Service service = new Service(EVENTLOG_NAME);
service.getConfig(); service.getConfig();
service.close(); service.close();
@@ -91,6 +93,31 @@ public class TestService extends SigarTestCase {
assertGtZeroTrace("getServiceConfigs", configs.size()); assertGtZeroTrace("getServiceConfigs", configs.size());
} }
private boolean contains(List list, String match) {
match = match.toLowerCase();
for (int i=0; i<list.size(); i++) {
String name = (String)list.get(i);
if (name.toLowerCase().equals(match)) {
return true;
}
}
return false;
}
public void testServicePtql() throws Exception {
Sigar sigar = new Sigar();
try {
long pid = sigar.getServicePid(EVENTLOG_NAME);
String ptql = "Service.Pid.eq=" + pid;
List names = Service.getServiceNames(sigar, ptql);
traceln(ptql + "==" + names);
//different case between XP (Eventlog) and 2008 (EventLog)
assertTrue(contains(names, EVENTLOG_NAME));
} finally {
sigar.close();
}
}
public void testServiceCreateDelete() throws Exception { public void testServiceCreateDelete() throws Exception {
if (!TEST_CREATE) { if (!TEST_CREATE) {
return; return;
-6
View File
@@ -1,6 +0,0 @@
copyright.year=2004-2009
version.major=1
version.minor=6
version.maint=5
version.build=0
+38
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
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
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
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
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
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
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
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
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;
}
+65
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
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())
+65
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
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
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
View File
@@ -0,0 +1,9 @@
Makefile
*.bs
*.c
*.cpp
*.o
*.old
Sigar_generated.xs
blib
pm_to_blib
+31 -19
View File
@@ -1,43 +1,55 @@
use ExtUtils::MakeMaker; use ExtUtils::MakeMaker;
use strict;
use Config; use Config;
use File::Basename qw(basename);
use File::Copy qw(copy);
use lib qw(.. lib); use lib qw(.. lib);
use SigarWrapper (); use SigarWrapper ();
use SigarBuild ();
my $gen_xs = 'Sigar_generated.xs';
my(@mm_args);
my(@clean_files) = ($gen_xs);
my $installdir;
if ($ARGV[0]) { if ($ARGV[0]) {
$installdir = $ARGV[0]; #link against installed libsigar
my $installdir = $ARGV[0];
@mm_args = (
LIBS => ["-L$installdir/lib -lsigar"],
INC => "-I$installdir/include",
);
} }
else { else {
#check binary-dist location and svn source location #all sources in Sigar.so
for (qw(../../sigar-bin ../java/sigar-bin)) { my $flags = SigarBuild::flags();
if (-e $_) { my(@inline_src) = SigarBuild::inline_src($flags);
$installdir = $_; push @clean_files, @inline_src;
last; 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 => '.'); SigarWrapper::generate(Perl => '.');
my $archname = SigarWrapper::archname();
my $libname = 'sigar';
if ($archname) {
$libname .= '-' . $archname;
}
my $ccname = $Config{ccname}; my $ccname = $Config{ccname};
my $define = { my $define = {
gcc => '-Wall -Werror', gcc => '-Wall',
cc_r => '-qhalt=w', cc_r => '-qhalt=w',
}->{$ccname} || ''; }->{$ccname} || '';
WriteMakefile( WriteMakefile(
'NAME' => 'Sigar', 'NAME' => 'Sigar',
'VERSION_FROM' => 'Sigar.pm', 'VERSION_FROM' => 'Sigar.pm',
'LIBS' => ["-L$installdir/lib -l$libname"],
'INC' => "-I$installdir/include",
'DEFINE' => $define, 'DEFINE' => $define,
'depend' => { 'Sigar.c' => 'Sigar_generated.xs' }, 'depend' => { 'Sigar.c' => $gen_xs },
'realclean' => { FILES => "@clean_files" },
@mm_args,
); );
+27
View File
@@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2004-2008 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -50,6 +51,7 @@ typedef sigar_disk_usage_t * Sigar__DiskUsage;
typedef sigar_proc_stat_t * Sigar__ProcStat; typedef sigar_proc_stat_t * Sigar__ProcStat;
typedef sigar_net_route_t * Sigar__NetRoute; typedef sigar_net_route_t * Sigar__NetRoute;
typedef sigar_net_interface_stat_t * Sigar__NetInterfaceStat; typedef sigar_net_interface_stat_t * Sigar__NetInterfaceStat;
typedef sigar_arp_t * Sigar__Arp;
typedef sigar_who_t * Sigar__Who; typedef sigar_who_t * Sigar__Who;
typedef sigar_thread_cpu_t * Sigar__ThreadCpu; typedef sigar_thread_cpu_t * Sigar__ThreadCpu;
typedef sigar_resource_limit_t * Sigar__ResourceLimit; typedef sigar_resource_limit_t * Sigar__ResourceLimit;
@@ -507,3 +509,28 @@ net_connection_list(sigar, flags)
OUTPUT: OUTPUT:
RETVAL RETVAL
SV *
arp_list(sigar)
Sigar sigar
PREINIT:
sigar_arp_list_t arp_list;
int status;
CODE:
status = sigar_arp_list_get(sigar, &arp_list);
if (status != SIGAR_OK) {
SIGAR_CROAK(sigar, "arp_list");
}
RETVAL = convert_2svav((char *)&arp_list.data[0],
arp_list.number,
sizeof(*arp_list.data),
"Sigar::Arp");
sigar_arp_list_destroy(sigar, &arp_list);
OUTPUT:
RETVAL
+2 -1
View File
@@ -29,6 +29,7 @@ Sigar::DiskUsage T_PTROBJ
Sigar::ProcStat T_PTROBJ Sigar::ProcStat T_PTROBJ
Sigar::NetRoute T_PTROBJ Sigar::NetRoute T_PTROBJ
Sigar::NetInterfaceStat T_PTROBJ Sigar::NetInterfaceStat T_PTROBJ
Sigar::Arp T_PTROBJ
Sigar::Who T_PTROBJ Sigar::Who T_PTROBJ
Sigar::ThreadCpu T_PTROBJ Sigar::ThreadCpu T_PTROBJ
Sigar::ResourceLimit T_PTROBJ Sigar::ResourceLimit T_PTROBJ
@@ -45,7 +46,7 @@ Sigar::NfsServerV3 T_PTROBJ
OUTPUT OUTPUT
T_NETADDR T_NETADDR
{ {
char addr_str[INET6_ADDRSTRLEN]; char addr_str[SIGAR_INET6_ADDRSTRLEN];
sigar_net_address_to_string(NULL, &$var, addr_str); sigar_net_address_to_string(NULL, &$var, addr_str);
sv_setpv($arg, addr_str); sv_setpv($arg, addr_str);
} }
+25
View File
@@ -1,5 +1,6 @@
/* /*
* Copyright (c) 2007 Hyperic, Inc. * Copyright (c) 2007 Hyperic, Inc.
* Copyright (c) 2010 VMware, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -190,6 +191,29 @@ static PyObject *pysigar_net_interface_list(PyObject *self, PyObject *args)
return RETVAL; 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_format_size(PyObject *self, PyObject *args) static PyObject *pysigar_format_size(PyObject *self, PyObject *args)
{ {
char buffer[56]; char buffer[56];
@@ -207,6 +231,7 @@ static PyMethodDef pysigar_methods[] = {
{ "close", pysigar_close, METH_NOARGS, NULL }, { "close", pysigar_close, METH_NOARGS, NULL },
{ "net_interface_list", pysigar_net_interface_list, METH_NOARGS, NULL }, { "net_interface_list", pysigar_net_interface_list, METH_NOARGS, NULL },
{ "file_system_list", pysigar_file_system_list, METH_NOARGS, NULL }, { "file_system_list", pysigar_file_system_list, METH_NOARGS, NULL },
{ "arp_list", pysigar_arp_list, METH_NOARGS, NULL },
PY_SIGAR_METHODS PY_SIGAR_METHODS
{NULL} {NULL}
}; };
Regular → Executable
+56 -7
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python #!/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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -16,17 +17,65 @@
# #
from distutils.core import setup, Extension from distutils.core import setup, Extension
from os import system, mkdir, path, popen
import sys
build = 'build'
options = {'perl':'perl'}
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 = Extension(
"_sigar", "_sigar",
["_sigar.c"], ["_sigar.c"],
include_dirs = ['../java/sigar-bin/include'], include_dirs = [sigar + '/include', build],
extra_compile_args = ['-Wall'], extra_compile_args = ['-Wall'],
libraries=['sigar-universal-macosx'], libraries=['sigar'],
library_dirs=['../java/sigar-bin/lib'], library_dirs=[sigar + '/lib'])
extra_link_args=[], else :
define_macros=[], print "Inlining libsigar sources"
undef_macros=[]) src = sargs('inline_src -- ' + build)
src.append('_sigar.c')
cppflags = sargs('cppflags')
cppflags.append('-Wall')
_sigar = Extension(
"_sigar",
src,
include_dirs = [build],
extra_compile_args = cppflags,
extra_link_args = sargs('ldflags'),
libraries=sargs('libs'))
setup(name="pysigar", version="0.1", setup(name="pysigar", version="0.1",
py_modules = ['sigar'], py_modules = ['sigar'],
+23
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
+24
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
+5 -2
View File
@@ -1,5 +1,6 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2009-2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
sigar = Sigar.new sigar = Sigar.new
@@ -27,6 +28,8 @@ puts num.to_s + " total CPUs.."
infos.each do |info| infos.each do |info|
puts "Vendor........" + info.vendor puts "Vendor........" + info.vendor
puts "Model........." + info.model puts "Model........." + info.model
puts "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 puts "Cache size...." + info.cache_size.to_s
end end
+8 -3
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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
def format_size(size) def format_size(size)
return Sigar.format_size(size * 1024) return Sigar.format_size(size * 1024)
@@ -27,12 +28,16 @@ puts "Filesystem\tSize\tUsed\tAvail\tUse%\tMounted on\tType\n"
fslist.each do |fs| fslist.each do |fs|
dir_name = fs.dir_name dir_name = fs.dir_name
begin
usage = sigar.file_system_usage(dir_name) usage = sigar.file_system_usage(dir_name)
total = usage.total total = usage.total
used = total - usage.free used = total - usage.free
avail = usage.avail avail = usage.avail
pct = usage.use_percent * 100 pct = usage.use_percent * 100
rescue Exception => e
#e.g. floppy or cdrom drive
used = avail = total = pct = 0;
end
puts fs.dev_name + "\t" + puts fs.dev_name + "\t" +
format_size(total) + "\t" + format_size(total) + "\t" +
+2 -1
View File
@@ -1,5 +1,6 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
sigar = Sigar.new sigar = Sigar.new
mem = sigar.mem mem = sigar.mem
+24 -6
View File
@@ -1,5 +1,7 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +16,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
sigar = Sigar.new sigar = Sigar.new
iflist = sigar.net_interface_list iflist = sigar.net_interface_list
@@ -24,6 +26,10 @@ iflist.each do |ifname|
flags = ifconfig.flags flags = ifconfig.flags
encap = ifconfig.type encap = ifconfig.type
if (flags & Sigar::IFF_UP) == 0
next
end
hwaddr = ifconfig.hwaddr hwaddr = ifconfig.hwaddr
if hwaddr == Sigar::NULL_HWADDR if hwaddr == Sigar::NULL_HWADDR
hwaddr = "" hwaddr = ""
@@ -45,16 +51,24 @@ iflist.each do |ifname|
bcast = "" bcast = ""
end end
puts "\t" + "inet addr:" + ifconfig.address + address = ifconfig.address
if address != "0.0.0.0"
puts "\t" + "inet addr:" + address +
ptp + bcast + " Mask:" + ifconfig.netmask ptp + bcast + " Mask:" + ifconfig.netmask
end
if ifconfig.prefix6_length != 0
puts "\t" + "inet6 addr: " + ifconfig.address6 + "/" +
ifconfig.prefix6_length.to_s + " Scope:" + Sigar.net_scope_to_s(ifconfig.scope6)
end
puts "\t" + puts "\t" +
Sigar.net_interface_flags_to_s(flags) + Sigar.net_interface_flags_to_s(flags) +
" MTU:" + ifconfig.mtu.to_s + " MTU:" + ifconfig.mtu.to_s +
" Metric:" + ifconfig.metric.to_s " Metric:" + ifconfig.metric.to_s
if (!ifname.include?(":"))
ifstat = sigar.net_interface_stat(ifname) ifstat = sigar.net_interface_stat(ifname)
puts "\t" + puts "\t" +
"RX packets:" + ifstat.rx_packets.to_s + "RX packets:" + ifstat.rx_packets.to_s +
" errors:" + ifstat.rx_errors.to_s + " errors:" + ifstat.rx_errors.to_s +
@@ -69,15 +83,19 @@ iflist.each do |ifname|
" overruns:" + ifstat.tx_overruns.to_s + " overruns:" + ifstat.tx_overruns.to_s +
" carrier:" + ifstat.tx_carrier.to_s " carrier:" + ifstat.tx_carrier.to_s
puts "\t" + "collisions:" + ifstat.tx_collisions.to_s puts "\t" + "collisions:" + ifstat.tx_collisions.to_s +
" txqueuelen:" + ifconfig.tx_queue_len.to_s
rx_bytes = ifstat.rx_bytes rx_bytes = ifstat.rx_bytes
tx_bytes = ifstat.tx_bytes tx_bytes = ifstat.tx_bytes
print "\t" + puts "\t" +
"RX bytes:" + rx_bytes.to_s + "RX bytes:" + rx_bytes.to_s +
" (" + Sigar.format_size(rx_bytes) + ")" + " (" + Sigar.format_size(rx_bytes) + ")" +
" " + " " +
"TX bytes:" + tx_bytes.to_s + "TX bytes:" + tx_bytes.to_s +
" (" + Sigar.format_size(tx_bytes) + ")" + "\n"; " (" + Sigar.format_size(tx_bytes) + ")" + "\n"
end
puts "\n"
end end
+58
View File
@@ -0,0 +1,58 @@
#
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Example illustrating the use of the optional logger.
require 'sigar'
require 'logger'
sigar = Sigar.new
sigar.log_level = Sigar::LOG_DEBUG
logger = Logger.new(STDERR)
logger.datetime_format = "%H:%M:%S"
# Call something that has DEBUG level logging.
fslist = sigar.file_system_list
# cache data
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
end
puts "Calling file_system_usage() for each filesystem"
puts "\nwith Logger:"
sigar.logger = logger
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
end
puts "\nwith Proc:"
sigar.logger = Proc.new do |level, msg|
puts "Level #{level}: #{msg}"
end
fslist.each do |fs|
dir_name = fs.dir_name
usage = sigar.file_system_usage(dir_name)
end
+31
View File
@@ -0,0 +1,31 @@
#
# Copyright (c) 2009-2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Example illustrating the collecting of network information.
require 'sigar'
sigar = Sigar.new
ninfo = sigar.net_info
puts "Hostname: " + ninfo.host_name
puts "Domain Name: " + ninfo.domain_name
puts "FQDN: " + sigar.fqdn
puts "Default gateway: " + ninfo.default_gateway
puts "Default gateway interface: " + ninfo.default_gateway_interface
puts "Primary DNS: " + ninfo.primary_dns
puts "Secondary DNS: " + ninfo.secondary_dns
+2 -1
View File
@@ -1,5 +1,6 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
require 'socket' require 'socket'
#XXX this example is incomplete wrt: #XXX this example is incomplete wrt:
+4 -3
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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
def output(sigar, pid) def output(sigar, pid)
args = sigar.proc_args(pid) args = sigar.proc_args(pid)
@@ -30,5 +31,5 @@ end
sigar = Sigar.new sigar = Sigar.new
ARGV.each do |pid| ARGV.each do |pid|
output(sigar, pid.to_i) output(sigar, pid)
end end
+4 -3
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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
def output(sigar, pid) def output(sigar, pid)
env = sigar.proc_env(pid) env = sigar.proc_env(pid)
@@ -26,5 +27,5 @@ end
sigar = Sigar.new sigar = Sigar.new
ARGV.each do |pid| ARGV.each do |pid|
output(sigar, pid.to_i) output(sigar, pid)
end end
+48
View File
@@ -0,0 +1,48 @@
#
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'sigar'
def flags(flags)
f = ""
if (flags & Sigar::RTF_UP) != 0
f += "U"
end
if (flags & Sigar::RTF_GATEWAY) != 0
f += "G"
end
if (flags & Sigar::RTF_HOST) != 0
f += "H"
end
f
end
def gw(addr)
addr == "0.0.0.0" ? "*" : addr
end
def dest(addr)
addr == "0.0.0.0" ? "default" : addr
end
puts "Kernel IP routing table"
fmt = "%-15s %-15s %-15s %-5s %-6s %-3s %-s\n"
printf fmt, "Destination", "Gateway", "Genmask", "Flags", "Metric", "Ref", "Iface"
Sigar.new.net_route_list.each do |route|
printf fmt, dest(route.destination), gw(route.gateway), route.mask,
flags(route.flags), route.metric.to_s, route.refcnt.to_s, route.ifname
end
+40
View File
@@ -0,0 +1,40 @@
#
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'sigar'
require 'rbconfig'
puts "Sigar version......." + Sigar::VERSION
puts "Build date.........." + Sigar::BUILD_DATE
puts "SCM rev............." + Sigar::SCM_REVISION
sys = Sigar.new.sys_info
puts "OS description......" + sys.description
puts "OS name............." + sys.name
puts "OS arch............." + sys.arch
puts "OS machine.........." + sys.machine
puts "OS version.........." + sys.version
puts "OS patch level......" + sys.patch_level
puts "OS vendor..........." + sys.vendor
puts "OS vendor version..." + sys.vendor_version
if (sys.vendor_code_name != nil)
puts "OS code name........" + sys.vendor_code_name
end
puts "Ruby version........" + RUBY_VERSION
puts "Ruby build vendor..." + ::Config::CONFIG['build_vendor']
puts "Ruby archdir........" + ::Config::CONFIG['archdir']
+2 -1
View File
@@ -1,5 +1,6 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007 Hyperic, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -14,7 +15,7 @@
# limitations under the License. # limitations under the License.
# #
require 'rbsigar' require 'sigar'
def format_time(who) def format_time(who)
return Time.at(who.time).strftime("%b %e %H:%M") return Time.at(who.time).strftime("%b %e %H:%M")
+105 -9
View File
@@ -1,5 +1,7 @@
# #
# Copyright (c) 2007 Hyperic, Inc. # Copyright (c) 2007, 2009 Hyperic, Inc.
# Copyright (c) 2009 SpringSource, Inc.
# Copyright (c) 2010 VMware, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -15,18 +17,112 @@
# #
require 'mkmf' require 'mkmf'
require 'rbconfig'
extension_name = 'rbsigar' extension_name = 'sigar'
installdir = '../java/sigar-bin' print 'Ruby platform=' + RUBY_PLATFORM + "\n"
#XXX hardwired for the moment
libname = 'sigar-universal-macosx'
$CPPFLAGS += ' -I' + installdir + '/include' case RUBY_PLATFORM
$LOCAL_LIBS += '-L' + installdir + '/lib -l' + libname when /darwin/
os = 'darwin'
sdks = Dir.glob('/Developer/SDKs/MacOSX10.*.sdk').sort.reverse
if sdks.length == 0
print "Xcode Developer Tools not installed\n"
print "Download from http://developer.apple.com/technology/xcode.html\n"
exit 1
else
print "Available SDKs...\n(*) " + sdks.join("\n ") + "\n"
sdk = sdks[0]
end
if File.file?("/usr/include/libproc.h")
$CPPFLAGS += ' -DDARWIN_HAS_LIBPROC_H'
end
$CPPFLAGS += ' -DDARWIN -I/Developer/Headers/FlatCarbon -isysroot ' + sdk
$LDFLAGS += ' -Wl,-syslibroot,' + sdk + ' -framework CoreServices -framework IOKit'
when /bsd/
os = 'darwin'
have_library("kvm")
when /mswin|mingw|cygwin|bccwin/
os = 'win32'
require 'ftools'
$CPPFLAGS += ' -DWIN32'
is_win32 = true
have_library("kernel32")
have_library("user32")
have_library("advapi32")
have_library("ws2_32")
have_library("netapi32")
have_library("shell32")
have_library("pdh")
have_library("version")
when /linux/
os = 'linux'
when /solaris|sun/
os = 'solaris'
have_library("nsl")
have_library("socket")
have_library("kstat")
when /hpux/
os = 'hpux'
#XXX have_libary no workie on hpux?
$LDFLAGS += ' -lnsl -lnm'
when /aix/
os = 'aix'
have_library("odm")
have_library("cfg")
have_library("perfstat")
else
os = RUBY_PLATFORM
end
osdir = "../../src/os/#{os}"
$CPPFLAGS += ' -I../../include' + ' -I' + osdir
$CPPFLAGS += ' -U_FILE_OFFSET_BITS' unless is_win32
if RUBY_VERSION > '1.8.4'
$CPPFLAGS += ' -DRB_HAS_RE_ERROR'
end
if RUBY_VERSION >= '1.9.0'
$CPPFLAGS += ' -DRB_RUBY_19'
end
#incase of nfs shared dir...
unless is_win32
if File.exist?('Makefile')
cmd = 'make distclean'
print cmd + "\n"
system(cmd)
end
Dir["./*.c"].each do |file|
if File.lstat(file).symlink?
print "unlink #{file}\n"
File.delete(file)
end
end
end
system('perl -Mlib=.. -MSigarWrapper -e generate Ruby .')
libname = extension_name + '.' + CONFIG['DLEXT']
system('perl -Mlib=.. -MSigarBuild -e version_file ' +
'ARCHNAME=' + RUBY_PLATFORM + ' ' +
'ARCHLIB=' + libname + ' ' +
'BINNAME=' + libname)
$distcleanfiles = ['rbsigar_generated.rx','sigar_version.c']
#XXX seems mkmf forces basename on srcs
#XXX should be linking against libsigar anyhow
(Dir["../../src/*.c"] + Dir["#{osdir}/*.c"] + Dir["#{osdir}/*.cpp"]).each do |file|
cf = File.basename(file)
print file + ' -> ' + cf + "\n"
if is_win32
File.copy(file, cf)
else
File.symlink(file, cf) unless File.file?(cf)
end
$distcleanfiles.push(cf)
end
dir_config(extension_name) dir_config(extension_name)
system('perl -Mlib=.. -MSigarWrapper -e generate Ruby .')
create_makefile(extension_name) create_makefile(extension_name)
+446 -29
View File
@@ -1,5 +1,7 @@
/* /*
* Copyright (c) 2007-2008 Hyperic, 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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -15,36 +17,153 @@
*/ */
#include <ruby.h> #include <ruby.h>
#ifdef RB_RUBY_19
#include <ruby/re.h>
#else
#include <re.h>
#endif
#include <errno.h> #include <errno.h>
#include "sigar.h" #include "sigar.h"
#include "sigar_fileinfo.h" #include "sigar_fileinfo.h"
#include "sigar_log.h"
#include "sigar_format.h" #include "sigar_format.h"
#include "sigar_ptql.h"
#define RB_SIGAR_CROAK rb_raise(rb_eArgError, "%s", sigar_strerror(sigar, status)) #define RB_SIGAR_RAISE(msg) rb_raise(rb_eArgError, "%s", msg)
#define NUM2PID NUM2UINT #define RB_SIGAR_CROAK RB_SIGAR_RAISE(sigar_strerror(sigar, status))
#define OBJ2PID(pid) rb_sigar_pid_get(rbsigar, pid)
static sigar_t *rb_sigar_get(VALUE obj) #ifndef RSTRING_PTR
{ #define RSTRING_PTR(s) RSTRING(s)->ptr
#endif
#ifndef RSTRING_LEN
#define RSTRING_LEN(s) RSTRING(s)->len
#endif
#ifdef RB_HAS_RE_ERROR
# define RB_REGEX_ERROR rb_eRegexpError
#else
# define RB_REGEX_ERROR rb_eArgError
#endif
#define SIGAR \
sigar_t *sigar = rbsigar->sigar
#define SIGAR_GET \
rb_sigar_t *rbsigar = rb_sigar_get(obj); \
SIGAR
typedef struct {
sigar_t *sigar; sigar_t *sigar;
Data_Get_Struct(obj, sigar_t, sigar); VALUE logger;
return sigar; } rb_sigar_t;
static rb_sigar_t *rb_sigar_get(VALUE obj)
{
rb_sigar_t *rbsigar;
Data_Get_Struct(obj, rb_sigar_t, rbsigar);
return rbsigar;
}
static int rbsigar_ptql_re_impl(void *data,
char *haystack, char *needle)
{
#ifdef RB_RUBY_19
/* XXX no more regex.h */
return 0;
#else
struct re_pattern_buffer *regex;
int len = strlen(haystack);
int retval;
const char *err;
regex = ALLOC(struct re_pattern_buffer);
MEMZERO((char *)regex, struct re_pattern_buffer, 1);
/* XXX cache */
if ((err = re_compile_pattern(needle, strlen(needle), regex))) {
re_free_pattern(regex);
rb_raise(RB_REGEX_ERROR, "%s", err);
return 0;
}
retval = re_match(regex, haystack, len, 0, NULL);
re_free_pattern(regex);
return retval > 0;
#endif
}
#define sigar_isdigit(c) \
(isdigit(((unsigned char)(c))))
static sigar_pid_t rb_sigar_pid_get(rb_sigar_t *rbsigar, VALUE obj)
{
SIGAR;
if (TYPE(obj) == T_STRING) {
char *pid = StringValuePtr(obj);
if (sigar_isdigit(*pid)) {
obj = rb_str2inum(obj, 10);
/* fallthru */
}
else if ((RSTRING_LEN(obj) == 2) &&
(*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;
sigar_ptql_re_impl_set(sigar, NULL, rbsigar_ptql_re_impl);
status = sigar_ptql_query_find_process(sigar, query, &qpid);
sigar_ptql_re_impl_set(sigar, NULL, NULL);
sigar_ptql_query_destroy(query);
if (status == SIGAR_OK) {
return qpid;
}
else {
RB_SIGAR_RAISE(sigar_strerror(sigar, status));
}
}
else {
RB_SIGAR_RAISE(error.message);
}
}
}
return NUM2UINT(obj);
} }
static void rb_sigar_free(void *obj) static void rb_sigar_free(void *obj)
{ {
free(obj); xfree(obj);
} }
static void rb_sigar_close(void *obj) static void rb_sigar_close(rb_sigar_t *rbsigar)
{ {
sigar_close((sigar_t *)obj); sigar_close(rbsigar->sigar);
rb_sigar_free(rbsigar);
}
static void rb_sigar_mark(rb_sigar_t *rbsigar)
{
rb_gc_mark(rbsigar->logger);
} }
static VALUE rb_sigar_new(VALUE module) static VALUE rb_sigar_new(VALUE module)
{ {
sigar_t *sigar; rb_sigar_t *rbsigar;
sigar_open(&sigar); rbsigar = ALLOC(rb_sigar_t);
return Data_Wrap_Struct(module, 0, rb_sigar_close, sigar); sigar_open(&(rbsigar->sigar));
return Data_Wrap_Struct(module, rb_sigar_mark, rb_sigar_close, rbsigar);
} }
static VALUE rb_sigar_format_size(VALUE rclass, VALUE size) static VALUE rb_sigar_format_size(VALUE rclass, VALUE size)
@@ -76,6 +195,11 @@ static VALUE rb_sigar_net_address_to_string(sigar_net_address_t *address)
return rb_str_new2(addr_str); return rb_str_new2(addr_str);
} }
static VALUE rb_sigar_net_scope_to_s(VALUE rclass, VALUE type)
{
return rb_str_new2(sigar_net_scope_to_string(NUM2INT(type)));
}
#define rb_sigar_net_address_to_s(a) rb_sigar_net_address_to_string(&a) #define rb_sigar_net_address_to_s(a) rb_sigar_net_address_to_string(&a)
static VALUE rb_sigar_new_list(char *data, unsigned long number, static VALUE rb_sigar_new_list(char *data, unsigned long number,
@@ -118,10 +242,23 @@ static VALUE rb_sigar_new_intlist(int *data, int number)
return av; return av;
} }
static VALUE rb_sigar_new_doublelist(double *data, int number)
{
int i;
VALUE av = rb_ary_new2(number);
for (i=0; i<number; i++) {
rb_ary_push(av, rb_float_new(data[i]));
}
return av;
}
static VALUE rb_sigar_net_interface_list(VALUE obj) static VALUE rb_sigar_net_interface_list(VALUE obj)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_net_interface_list_t iflist; sigar_net_interface_list_t iflist;
VALUE RETVAL; VALUE RETVAL;
@@ -139,7 +276,7 @@ static VALUE rb_sigar_net_interface_list(VALUE obj)
static int rb_sigar_str2net_address(VALUE bytes, sigar_net_address_t *address) static int rb_sigar_str2net_address(VALUE bytes, sigar_net_address_t *address)
{ {
long len = RSTRING(bytes)->len; long len = RSTRING_LEN(bytes);
switch (len) { switch (len) {
case 4: case 4:
@@ -152,7 +289,7 @@ static int rb_sigar_str2net_address(VALUE bytes, sigar_net_address_t *address)
return EINVAL; return EINVAL;
} }
memcpy(RSTRING(bytes)->ptr, &address->addr.in6, len); memcpy(RSTRING_PTR(bytes), &address->addr.in6, len);
return SIGAR_OK; return SIGAR_OK;
} }
@@ -161,9 +298,10 @@ static VALUE rb_cSigarNetStat;
static VALUE rb_sigar_net_stat_get(VALUE obj, VALUE flags, VALUE bytes, int port) static VALUE rb_sigar_net_stat_get(VALUE obj, VALUE flags, VALUE bytes, int port)
{ {
SIGAR_GET;
int status; int status;
int has_port = (port != -1); int has_port = (port != -1);
sigar_t *sigar = rb_sigar_get(obj);
sigar_net_stat_t *RETVAL = malloc(sizeof(*RETVAL)); sigar_net_stat_t *RETVAL = malloc(sizeof(*RETVAL));
sigar_net_address_t address; sigar_net_address_t address;
@@ -209,9 +347,9 @@ static VALUE rb_cSigarNetConnection;
static VALUE rb_sigar_net_connection_list(VALUE obj, VALUE flags) static VALUE rb_sigar_net_connection_list(VALUE obj, VALUE flags)
{ {
SIGAR_GET;
int status; int status;
unsigned int i;
sigar_t *sigar = rb_sigar_get(obj);
sigar_net_connection_list_t connlist; sigar_net_connection_list_t connlist;
VALUE RETVAL; VALUE RETVAL;
@@ -233,7 +371,8 @@ static VALUE rb_sigar_net_connection_list(VALUE obj, VALUE flags)
static VALUE rb_sigar_net_services_name(VALUE obj, VALUE protocol, VALUE port) static VALUE rb_sigar_net_services_name(VALUE obj, VALUE protocol, VALUE port)
{ {
sigar_t *sigar = rb_sigar_get(obj); SIGAR_GET;
char *name; char *name;
if ((name = sigar_net_services_name_get(sigar, NUM2UINT(protocol), NUM2UINT(port)))) { if ((name = sigar_net_services_name_get(sigar, NUM2UINT(protocol), NUM2UINT(port)))) {
@@ -248,8 +387,9 @@ static VALUE rb_cSigarCpuInfo;
static VALUE rb_sigar_cpu_info_list(VALUE obj) static VALUE rb_sigar_cpu_info_list(VALUE obj)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_cpu_info_list_t cpu_infos; sigar_cpu_info_list_t cpu_infos;
VALUE RETVAL; VALUE RETVAL;
@@ -268,14 +408,30 @@ static VALUE rb_sigar_cpu_info_list(VALUE obj)
return RETVAL; return RETVAL;
} }
static VALUE rb_sigar_loadavg(VALUE obj)
{
SIGAR_GET;
int status;
sigar_loadavg_t loadavg;
status = sigar_loadavg_get(sigar, &loadavg);
if (status != SIGAR_OK) {
RB_SIGAR_CROAK;
}
return rb_sigar_new_doublelist(&loadavg.loadavg[0], 3);
}
static VALUE rb_cSigarCpuPerc; static VALUE rb_cSigarCpuPerc;
static VALUE rb_cSigarFileSystem; static VALUE rb_cSigarFileSystem;
static VALUE rb_sigar_file_system_list(VALUE obj) static VALUE rb_sigar_file_system_list(VALUE obj)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_file_system_list_t fslist; sigar_file_system_list_t fslist;
VALUE RETVAL; VALUE RETVAL;
@@ -294,12 +450,38 @@ static VALUE rb_sigar_file_system_list(VALUE obj)
return RETVAL; return RETVAL;
} }
static VALUE rb_cSigarArp;
static VALUE rb_sigar_arp_list(VALUE obj)
{
SIGAR_GET;
int status;
sigar_arp_list_t list;
VALUE RETVAL;
status = sigar_arp_list_get(sigar, &list);
if (status != SIGAR_OK) {
RB_SIGAR_CROAK;
}
RETVAL = rb_sigar_new_list((char *)&list.data[0],
list.number,
sizeof(*list.data),
rb_cSigarArp);
sigar_arp_list_destroy(sigar, &list);
return RETVAL;
}
static VALUE rb_cSigarWho; static VALUE rb_cSigarWho;
static VALUE rb_sigar_who_list(VALUE obj) static VALUE rb_sigar_who_list(VALUE obj)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_who_list_t list; sigar_who_list_t list;
VALUE RETVAL; VALUE RETVAL;
@@ -322,8 +504,9 @@ static VALUE rb_cSigarNetRoute;
static VALUE rb_sigar_net_route_list(VALUE obj) static VALUE rb_sigar_net_route_list(VALUE obj)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_net_route_list_t list; sigar_net_route_list_t list;
VALUE RETVAL; VALUE RETVAL;
@@ -342,14 +525,59 @@ static VALUE rb_sigar_net_route_list(VALUE obj)
return RETVAL; return RETVAL;
} }
static VALUE rb_sigar_proc_list(int argc, VALUE *argv, VALUE obj)
{
SIGAR_GET;
int status;
sigar_proc_list_t list;
VALUE RETVAL;
VALUE vptql;
rb_scan_args(argc, argv, "01", &vptql);
if (NIL_P(vptql)) {
status = sigar_proc_list_get(sigar, &list);
if (status != SIGAR_OK) {
RB_SIGAR_CROAK;
}
}
else {
sigar_ptql_query_t *query;
sigar_ptql_error_t error;
char *ptql = StringValuePtr(vptql);
status = sigar_ptql_query_create(&query, ptql, &error);
if (status != SIGAR_OK) {
RB_SIGAR_RAISE(error.message);
}
sigar_ptql_re_impl_set(sigar, NULL, rbsigar_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) {
RB_SIGAR_RAISE(sigar_strerror(sigar, status));
}
}
RETVAL = rb_sigar_new_intlist(&list.data[0],
list.number);
sigar_proc_list_destroy(sigar, &list);
return RETVAL;
}
static VALUE rb_sigar_proc_args(VALUE obj, VALUE pid) static VALUE rb_sigar_proc_args(VALUE obj, VALUE pid)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_proc_args_t args; sigar_proc_args_t args;
VALUE RETVAL; VALUE RETVAL;
status = sigar_proc_args_get(sigar, NUM2PID(pid), &args); status = sigar_proc_args_get(sigar, OBJ2PID(pid), &args);
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
RB_SIGAR_CROAK; RB_SIGAR_CROAK;
@@ -372,10 +600,26 @@ static int rb_sigar_env_getall(void *data,
return SIGAR_OK; return SIGAR_OK;
} }
static VALUE rb_sigar_proc_port(VALUE obj, VALUE protocol, VALUE port)
{
SIGAR_GET;
int status;
sigar_pid_t RETVAL;
status = sigar_proc_port_get(sigar, NUM2INT(protocol), NUM2LL(port), &RETVAL);
if (status != SIGAR_OK) {
RB_SIGAR_CROAK;
}
return rb_int2inum(RETVAL);
}
static VALUE rb_sigar_proc_env(VALUE obj, VALUE pid) static VALUE rb_sigar_proc_env(VALUE obj, VALUE pid)
{ {
SIGAR_GET;
int status; int status;
sigar_t *sigar = rb_sigar_get(obj);
sigar_proc_env_t procenv; sigar_proc_env_t procenv;
VALUE RETVAL = rb_hash_new(); VALUE RETVAL = rb_hash_new();
@@ -383,7 +627,7 @@ static VALUE rb_sigar_proc_env(VALUE obj, VALUE pid)
procenv.env_getter = rb_sigar_env_getall; procenv.env_getter = rb_sigar_env_getall;
procenv.data = &RETVAL; procenv.data = &RETVAL;
status = sigar_proc_env_get(sigar, NUM2PID(pid), &procenv); status = sigar_proc_env_get(sigar, OBJ2PID(pid), &procenv);
if (status != SIGAR_OK) { if (status != SIGAR_OK) {
RB_SIGAR_CROAK; RB_SIGAR_CROAK;
} }
@@ -391,16 +635,152 @@ static VALUE rb_sigar_proc_env(VALUE obj, VALUE pid)
return RETVAL; return RETVAL;
} }
VALUE rb = Qnil;
static const char *logger_consts[] = {
"FATAL", /* SIGAR_LOG_FATAL */
"ERROR", /* SIGAR_LOG_ERROR */
"WARN", /* SIGAR_LOG_WARN */
"INFO", /* SIGAR_LOG_INFO */
"DEBUG", /* SIGAR_LOG_DEBUG */
"DEBUG", /* SIGAR_LOG_TRACE */
};
static void rb_sigar_logger_impl(sigar_t *sigar, void *data,
int level, char *message)
{
rb_sigar_t *rbsigar = ((rb_sigar_t*)data);
VALUE logger = rbsigar->logger;
/* XXX: cost of this, better way? */
VALUE logger_const = rb_const_get(rb_cObject, rb_intern("Logger"));
VALUE logger_level = rb_const_get(logger_const,
rb_intern(logger_consts[level]));
VALUE msg = rb_str_new2(message);
rb_funcall(logger, rb_intern ("add"), 2, logger_level, msg);
return;
}
static void rb_sigar_proc_impl(sigar_t *sigar, void *data,
int level, char *message)
{
rb_sigar_t *rbsigar = ((rb_sigar_t*)data);
VALUE logger = rbsigar->logger;
rb_funcall(logger, rb_intern("call"), 2, INT2FIX(level), rb_str_new2(message));
return;
}
static VALUE rb_sigar_logger(VALUE obj)
{
rb_sigar_t *rbsigar = rb_sigar_get(obj);
return rbsigar->logger;
}
static VALUE rb_sigar_set_logger(VALUE obj, VALUE logger)
{
SIGAR_GET;
if (rb_obj_is_kind_of(logger, rb_cProc) ||
rb_respond_to(logger, rb_intern("call"))) {
sigar_log_impl_set(sigar, rbsigar, rb_sigar_proc_impl);
rbsigar->logger = logger;
return obj;
}
/* Have to load Logger to test for it properly */
rb_require("logger");
if (rb_obj_is_kind_of(logger, rb_path2class("Logger"))) {
sigar_log_impl_set(sigar, rbsigar, rb_sigar_logger_impl);
rbsigar->logger = logger;
}
else {
rb_raise(rb_eArgError,
"value is not a proc object or subclass of Logger");
}
return obj;
}
static VALUE rb_sigar_log_level(VALUE obj)
{
SIGAR_GET;
return INT2FIX(sigar_log_level_get(sigar));
}
static VALUE rb_sigar_set_log_level(VALUE obj, VALUE level)
{
SIGAR_GET;
sigar_log_level_set(sigar, NUM2INT(level));
return obj;
}
static VALUE rb_sigar_fqdn(VALUE obj)
{
SIGAR_GET;
char fqdn[SIGAR_FQDN_LEN];
int status;
if ((status = sigar_fqdn_get(sigar, fqdn, sizeof(fqdn))) != SIGAR_OK) {
RB_SIGAR_CROAK;
}
return rb_str_new2(fqdn);
}
#include "./rbsigar_generated.rx" #include "./rbsigar_generated.rx"
static VALUE rb_sigar_cpu_list(VALUE obj)
{
SIGAR_GET;
int status;
sigar_cpu_list_t cpus;
VALUE RETVAL;
status = sigar_cpu_list_get(sigar, &cpus);
if (status != SIGAR_OK) {
RB_SIGAR_CROAK;
}
RETVAL = rb_sigar_new_list((char *)&cpus.data[0],
cpus.number,
sizeof(*cpus.data),
rb_cSigarCpu);
sigar_cpu_list_destroy(sigar, &cpus);
return RETVAL;
}
#define RB_SIGAR_CONST_INT(name) \ #define RB_SIGAR_CONST_INT(name) \
rb_define_const(rclass, #name, INT2FIX(SIGAR_##name)) rb_define_const(rclass, #name, INT2FIX(SIGAR_##name))
#define RB_SIGAR_DEFINE_CONST_STR(name, value) \
rb_define_const(rclass, name, rb_obj_freeze(rb_str_new2(value)))
#define RB_SIGAR_CONST_STR(name) \ #define RB_SIGAR_CONST_STR(name) \
rb_define_const(rclass, #name, rb_obj_freeze(rb_str_new2(SIGAR_##name))) rb_define_const(rclass, #name, rb_obj_freeze(rb_str_new2(SIGAR_##name)))
static void Init_rbsigar_constants(VALUE rclass) static void Init_rbsigar_constants(VALUE rclass)
{ {
RB_SIGAR_CONST_INT(FSTYPE_NONE);
RB_SIGAR_CONST_INT(FSTYPE_LOCAL_DISK);
RB_SIGAR_CONST_INT(FSTYPE_NETWORK);
RB_SIGAR_CONST_INT(FSTYPE_RAM_DISK);
RB_SIGAR_CONST_INT(FSTYPE_CDROM);
RB_SIGAR_CONST_INT(FSTYPE_SWAP);
RB_SIGAR_CONST_INT(IFF_UP); RB_SIGAR_CONST_INT(IFF_UP);
RB_SIGAR_CONST_INT(IFF_BROADCAST); RB_SIGAR_CONST_INT(IFF_BROADCAST);
RB_SIGAR_CONST_INT(IFF_DEBUG); RB_SIGAR_CONST_INT(IFF_DEBUG);
@@ -412,6 +792,9 @@ static void Init_rbsigar_constants(VALUE rclass)
RB_SIGAR_CONST_INT(IFF_PROMISC); RB_SIGAR_CONST_INT(IFF_PROMISC);
RB_SIGAR_CONST_INT(IFF_ALLMULTI); RB_SIGAR_CONST_INT(IFF_ALLMULTI);
RB_SIGAR_CONST_INT(IFF_MULTICAST); RB_SIGAR_CONST_INT(IFF_MULTICAST);
RB_SIGAR_CONST_INT(IFF_SLAVE);
RB_SIGAR_CONST_INT(IFF_MASTER);
RB_SIGAR_CONST_INT(IFF_DYNAMIC);
RB_SIGAR_CONST_INT(NETCONN_CLIENT); RB_SIGAR_CONST_INT(NETCONN_CLIENT);
RB_SIGAR_CONST_INT(NETCONN_SERVER); RB_SIGAR_CONST_INT(NETCONN_SERVER);
@@ -435,14 +818,41 @@ static void Init_rbsigar_constants(VALUE rclass)
RB_SIGAR_CONST_INT(TCP_BOUND); RB_SIGAR_CONST_INT(TCP_BOUND);
RB_SIGAR_CONST_INT(TCP_UNKNOWN); RB_SIGAR_CONST_INT(TCP_UNKNOWN);
RB_SIGAR_CONST_INT(RTF_UP);
RB_SIGAR_CONST_INT(RTF_GATEWAY);
RB_SIGAR_CONST_INT(RTF_HOST);
RB_SIGAR_CONST_STR(NULL_HWADDR); RB_SIGAR_CONST_STR(NULL_HWADDR);
RB_SIGAR_CONST_INT(LOG_FATAL);
RB_SIGAR_CONST_INT(LOG_ERROR);
RB_SIGAR_CONST_INT(LOG_WARN);
RB_SIGAR_CONST_INT(LOG_INFO);
RB_SIGAR_CONST_INT(LOG_DEBUG);
RB_SIGAR_CONST_INT(LOG_TRACE);
} }
void Init_rbsigar(void) static void Init_rbsigar_version(VALUE rclass)
{
sigar_version_t *sv = sigar_version_get();
RB_SIGAR_DEFINE_CONST_STR("BUILD_DATE", sv->build_date);
RB_SIGAR_DEFINE_CONST_STR("SCM_REVISION", sv->scm_revision);
RB_SIGAR_DEFINE_CONST_STR("VERSION", sv->version);
}
void Init_sigar(void)
{ {
VALUE rclass = rb_define_class("Sigar", rb_cObject); VALUE rclass = rb_define_class("Sigar", rb_cObject);
rb_define_method(rclass, "logger", rb_sigar_logger, 0);
rb_define_method(rclass, "logger=", rb_sigar_set_logger, 1);
rb_define_method(rclass, "log_level", rb_sigar_log_level, 0);
rb_define_method(rclass, "log_level=", rb_sigar_set_log_level, 1);
rb_define_method(rclass, "cpu_info_list", rb_sigar_cpu_info_list, 0); rb_define_method(rclass, "cpu_info_list", rb_sigar_cpu_info_list, 0);
rb_define_method(rclass, "cpu_list", rb_sigar_cpu_list, 0);
rb_define_method(rclass, "loadavg", rb_sigar_loadavg, 0);
rb_define_method(rclass, "file_system_list", rb_sigar_file_system_list, 0); rb_define_method(rclass, "file_system_list", rb_sigar_file_system_list, 0);
rb_define_method(rclass, "net_connection_list", rb_sigar_net_connection_list, 1); rb_define_method(rclass, "net_connection_list", rb_sigar_net_connection_list, 1);
rb_define_method(rclass, "net_interface_list", rb_sigar_net_interface_list, 0); rb_define_method(rclass, "net_interface_list", rb_sigar_net_interface_list, 0);
@@ -450,20 +860,27 @@ void Init_rbsigar(void)
rb_define_method(rclass, "net_stat", rb_sigar_net_stat, 1); rb_define_method(rclass, "net_stat", rb_sigar_net_stat, 1);
rb_define_method(rclass, "net_stat_port", rb_sigar_net_stat_port, 3); rb_define_method(rclass, "net_stat_port", rb_sigar_net_stat_port, 3);
rb_define_method(rclass, "net_route_list", rb_sigar_net_route_list, 0); rb_define_method(rclass, "net_route_list", rb_sigar_net_route_list, 0);
rb_define_method(rclass, "arp_list", rb_sigar_arp_list, 0);
rb_define_method(rclass, "who_list", rb_sigar_who_list, 0); rb_define_method(rclass, "who_list", rb_sigar_who_list, 0);
rb_define_method(rclass, "proc_list", rb_sigar_proc_list, -1);
rb_define_method(rclass, "proc_args", rb_sigar_proc_args, 1); rb_define_method(rclass, "proc_args", rb_sigar_proc_args, 1);
rb_define_method(rclass, "proc_env", rb_sigar_proc_env, 1); rb_define_method(rclass, "proc_env", rb_sigar_proc_env, 1);
rb_define_method(rclass, "proc_port", rb_sigar_proc_port, 2);
rb_define_method(rclass, "fqdn", rb_sigar_fqdn, 0);
rb_define_singleton_method(rclass, "new", rb_sigar_new, 0); rb_define_singleton_method(rclass, "new", rb_sigar_new, 0);
rb_define_singleton_method(rclass, "format_size", rb_sigar_format_size, 1); rb_define_singleton_method(rclass, "format_size", rb_sigar_format_size, 1);
rb_define_singleton_method(rclass, "net_interface_flags_to_s", rb_define_singleton_method(rclass, "net_interface_flags_to_s",
rb_sigar_net_interface_flags_to_s, 1); rb_sigar_net_interface_flags_to_s, 1);
rb_define_singleton_method(rclass, "net_scope_to_s",
rb_sigar_net_scope_to_s, 1);
rb_define_singleton_method(rclass, "net_connection_type_to_s", rb_define_singleton_method(rclass, "net_connection_type_to_s",
rb_sigar_net_connection_type_to_s, 1); rb_sigar_net_connection_type_to_s, 1);
rb_define_singleton_method(rclass, "net_connection_state_to_s", rb_define_singleton_method(rclass, "net_connection_state_to_s",
rb_sigar_net_connection_state_to_s, 1); rb_sigar_net_connection_state_to_s, 1);
Init_rbsigar_constants(rclass); Init_rbsigar_constants(rclass);
Init_rbsigar_version(rclass);
/* generated */ /* generated */
rb_sigar_define_module_methods(rclass); rb_sigar_define_module_methods(rclass);
+40
View File
@@ -0,0 +1,40 @@
#
# 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.
#
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'helper'
class CpuTest < Test::Unit::TestCase
def check_cpu(cpu)
assert_gt_eq_zero cpu.user, "user"
assert_gt_eq_zero cpu.sys, "sys"
assert_gt_eq_zero cpu.idle, "idle"
assert_gt_eq_zero cpu.wait, "wait"
assert_gt_eq_zero cpu.irq, "irq"
assert_gt_eq_zero cpu.soft_irq, "soft_irq"
assert_gt_eq_zero cpu.stolen, "stolen"
assert_gt_zero cpu.total, "total"
end
def test_cpu
sigar = Sigar.new
check_cpu sigar.cpu
sigar.cpu_list.each do |cpu|
check_cpu cpu
end
end
end
+43
View File
@@ -0,0 +1,43 @@
#
# 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.
#
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'helper'
class FileSystemTest < Test::Unit::TestCase
def test_file_system
sigar = Sigar.new
sigar.file_system_list.each do |fs|
assert_length fs.dev_name, "dev_name"
assert_length fs.dir_name, "dir_name"
assert_length fs.type_name, "type_name"
assert_length fs.sys_type_name, "sys_type_name"
assert fs.options.length >= 0, "options"
begin
usage = sigar.file_system_usage fs.dir_name
rescue err
if fs.type == Sigar::FSTYPE_LOCAL_DISK
raise err
end
# else ok, e.g. floppy drive on windows
next
end
end
end
end
+57
View File
@@ -0,0 +1,57 @@
#
# Copyright (c) 2009-2010 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'test/unit'
require 'sigar'
module Test::Unit::Assertions
def assert_gt_eq_zero(value, message)
message = build_message message, '<?> is not >= 0.', value
assert_block message do
value >= 0
end
end
def assert_gt_zero(value, message)
message = build_message message, '<?> is not > 0.', value
assert_block message do
value > 0
end
end
def assert_eq(expected, actual, message)
message = build_message message, '<?> != <?>.', expected, actual
assert_block message do
expected == actual
end
end
def assert_length(value, message)
message = build_message message, '<?>.length > 0.', value
assert_block message do
value.length > 0
end
end
def assert_any(value, message)
message = build_message message, '<?> is anything.', value
assert_block message do
true
end
end
end
+30
View File
@@ -0,0 +1,30 @@
#
# 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.
#
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'helper'
class LoadAvgTest < Test::Unit::TestCase
def test_loadavg
begin
loadavg = Sigar.new.loadavg
rescue #XXX SigarNotImplemented (win32)
return
end
assert loadavg.length == 3
end
end
+45
View File
@@ -0,0 +1,45 @@
#
# 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.
#
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'helper'
class MemTest < Test::Unit::TestCase
def test_mem
sigar = Sigar.new
mem = sigar.mem
assert_gt_zero mem.total, "total"
assert_gt_zero mem.used, "used"
assert_gt_zero mem.used_percent, "used_percent"
assert mem.used_percent <= 100, "used_percent <= 100"
assert_gt_eq_zero mem.free_percent, "free_percent"
assert mem.free_percent < 100, "free_percent < 100"
assert_gt_zero mem.free, "free"
assert_gt_zero mem.actual_used, "actual_used"
assert_gt_zero mem.actual_free, "actual_free"
assert_gt_zero mem.ram, "ram"
assert (mem.ram % 8) == 0
end
end
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more