pax_global_header00006660000000000000000000000064121013262750014511gustar00rootroot0000000000000052 comment=5a8b6138d5427d88d344cebd343b1dc67a183a95 hyperic-sigar-1.6.4+dfsg/000077500000000000000000000000001210132627500152065ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/AUTHORS000066400000000000000000000007361210132627500162640ustar00rootroot00000000000000Doug MacEachern Jan Kneschke Matthew Kent Ryan Beasley Bjoern Martin Kay Ropke Ryan Morgan Monty Taylor Trevor Pounds Jon Travis Tony Ashburner Ryan Bloom hyperic-sigar-1.6.4+dfsg/ChangeLog000066400000000000000000000716221210132627500167700ustar00rootroot000000000000002010-04-28 Doug MacEachern * 1.6.4 release * GPL v2 license -> Apache 2 license * (SIGAR-188) implement mem actual free/used on Windows 2010-04-27 Doug MacEachern * (SIGAR-215) use swapctl SC_LIST for Solaris swap_get impl 2010-04-15 Doug MacEachern * osf1 no longer supported * netware no longer supported * (SIGAR-201) JNIEnv->ExceptionCheck to avoid possible SEGV on OutOfMemoryError 2010-04-14 Doug MacEachern * (SIGAR-192) avoid possible stack corruption in Windows proc_env impl * (SIGAR-213) check ENV.ANT_HOME/lib for junit in Main-Class 2010-04-09 Doug MacEachern * (SIGAR-214) properly adjust jni.javahome when JAVA_HOME is not set 2010-04-08 Doug MacEachern * cpptasks patches moved to http://github.com/dougm/ant-contrib-cpptasks * mv tools/PerfBrowser http://github.com/dougm/csharp-perfbrowser * mv exp/ http://github.com/dougm/sigar-stuff 2010-04-07 Doug MacEachern * (SIGAR-213) remove junit.jar from distribution * (SIGAR-188) implement mem actual free/used on HPUX * (SIGAR-188) implement mem actual free/used on AIX 2010-04-05 Doug MacEachern * (SIGAR-188) implement mem actual free/used on OpenBSD and NetBSD * (SIGAR-188) implement mem actual free/used on Solaris 2010-04-02 Doug MacEachern * (SIGAR-212) pass LANG_ENGLISH to FormatMessage in Windows sigar_strerror impl 2010-04-01 Doug MacEachern * (SIGAR-188) implement mem actual free/used on Windows 2010-04-01 Trevor Pounds * (SIGAR-202) Change CreateFile() access flags to prevent potential inode calculation errors on Windows when tailing a file. 2010-04-01 Doug MacEachern * (SIGAR-207) append instance index in Pdh.getInstances() 2010-03-31 Doug MacEachern * (SIGAR-207) Add Pdh.getCounterType method * (SIGAR-207) Add Pdh.getDescription method * (SIGAR-210) recognize cifs as a network file system 2010-03-30 Doug MacEachern * (SIGAR-211) HPUX file_system_list needs to read /etc/mnttab instead of /etc/fstab 2010-02-09 Doug MacEachern * add -i (inode format) support to df command 2010-02-05 Doug MacEachern * (SIGAR-205) Vista and higher changed wireless card type to IF_TYPE_IEEE80211 2010-01-18 Doug MacEachern * rid dup in solaris route_list impl 2010-01-17 Doug MacEachern * (SIGAR-181) fill-in sigar_net_route_t.ifname on HPUX 2010-01-12 Doug MacEachern * (SIGAR-196) use pst_processor.psp_cpu_frequency to calculate cpu_info.mhz on HP-UX 11.31+ 2010-01-04 Doug MacEachern * (SIGAR-194) sigar_file_system_t.dev_name on Windows should be the network path for remote drives 2009-12-23 Doug MacEachern * (SIGAR-193) Migrate from mach/shared_memory_server.h to mach/shared_region.h on Darwin 2009-11-09 Doug MacEachern * only display event code in toString as the Event Viewer does * 'N/A' for null user in EventLogRecord.toString * include the same fields as Event Viewer in EventLogRecord.toString * (SIGAR-191) fix EventLogRecord.computerName * (SIGAR-190) add category to EventLogRecord 2009-11-05 Doug MacEachern * (SIGAR-189) ignore CP_WAIT time on HPUX 2009-11-03 Doug MacEachern * (SIGAR-187) implement proc_exe on AIX * (SIGAR-188) implement mem actual free/used on MacOSX 2009-11-02 Doug MacEachern * (SIGAR-188) implement mem actual free/used on FreeBSD 2009-10-23 Doug MacEachern * Pdh test adjustments for windows 2000 * (SIGAR-185) fix RegistryKey open on windows 2000 * (SIGAR-186) fix Win32.getFileVersion on windows 2000 2009-09-30 Doug MacEachern * hpux pa 64-bit support 2009-09-17 Doug MacEachern * 64-bit MacOSX 10.6 sdk does not support ppc64, switch from universal build to i386 only 2009-09-15 Doug MacEachern * (SIGAR-181) net_route.ifname impl for Win32 * (SIGAR-181) net_route.ifname impl for MacOSX and *BSD * (SIGAR-182) use mib2_ip_t.ipRouteEntrySize to determine mib2_ipRouteEntry_t size 2009-09-08 Doug MacEachern * fix MacOSX10.6.sdk build issues 2009-09-01 Doug MacEachern * (SIGAR-168) always fallback to wmi when peb fails for proc_args 2009-08-30 Doug MacEachern * 6.1 == Windows 7 * 10.6 == Snow Leopard 2009-08-23 Doug MacEachern * (SIGAR-179) Increase buffer size in cpu_list query from 16 to 128 2009-08-11 Jan Kneschke * (SIGAR-137) sdl_data isn't 0-terminated 2009-08-05 Doug MacEachern * try wmi if peb fails for proc_exe * add wmi proc_args wrapper 2009-07-31 Doug MacEachern * only exclude nfs/rpcv2.h on FreeBSD 8+ 2009-07-30 Doug MacEachern * net_route_list bandaid for FreeBSD 8.0 * sigar_proc_port_get does not compile on FreeBSD 8.0 * only need nfs/rpcv2.h on darwin 2009-07-18 Doug MacEachern * (SIGAR-164) return ENXIO instead of ENOENT in disk_usage win32 impl * (SIGAR-164) return ENXIO instead of ENOENT in disk_usage linux impl * (SIGAR-164) return ENXIO instead of ENOENT in disk_usage aix impl * (SIGAR-164) return ENXIO instead of ESRCH in disk_usage darwin impl 2009-07-17 Doug MacEachern * (SIGAR-163) Recognize cvfs (StorNext) as local filesystem type 2009-07-16 Doug MacEachern * (SIGAR-162) plug possible memory leak in sigar_iodev_get util 2009-07-14 Doug MacEachern * remove pdh.dll (only used on NT 4.0) 2009-07-13 Doug MacEachern * (SIGAR-155) Plug memory leak sigar_proc_exe_get Darwin impl * bump version to 1.6.4 2008-07-13 Doug MacEachern * 1.6.3 release 2009-07-08 Doug MacEachern * (SIGAR-130) Use pstat(PSTAT_GETCOMMANDLINE,...) on HP-UX < 11iv2 * (SIGAR-130) Use pstat_getcommandline on HP-UX 11iv2+ * (SIGAR-131) switch to pst_fileinfo2 on all HPUX flavors 2009-07-08 Jon Travis * (SIGAR-150) Wrapper class to synchronize Sigar method invocation 2009-07-07 Doug MacEachern * add getNetServicesName to SigarProxy interface 2009-07-02 Doug MacEachern * (SIGAR-145) default to 'Irix mode' for proc_cpu.percent * (SIGAR-144) Solaris net_interface_stat should use 64-bit kstats 2009-07-01 Doug MacEachern * (SIGAR-148) statfs usage compiled with LFS flags 2009-06-30 Doug MacEachern * (SIGAR-152) Add support for 31-bit s390 builds 2009-06-17 Doug MacEachern * darwin sigar_dlinfo_modules impl 2009-06-06 Doug MacEachern * (SIGAR-151) Add Modules support to PTQL 2009-06-01 Kay Röpke * (SIGAR-149) fix Darwin side of SIGAR-47: integer multlipcation overflow on 32bit builds with more than 4GB available memory 2009-05-24 Doug MacEachern * (SIGAR-142) loosen net_interface_list filters on MacOSX 2009-05-15 Doug MacEachern * (SIGAR-150) make SigarProxyCached.invoke synchronized 2009-05-13 Doug MacEachern * fix so SigarPermissionDeniedException is throw on open /dev/kmem EACCES * add 64-bit compile/link flags for AIX * require libperfstat on aix 2009-04-25 Doug MacEachern * getrusage on NetBSD may not return monotonically increasing values for CPU time. * (SIGAR-39) Use kern.cp_times in cpu_list on FreeBSD 7.x+ 2009-03-27 Doug MacEachern * (SIGAR-141) sigar.jar location is not required to find native library 2009-03-25 Doug MacEachern * (SIGAR-140) interface aliases are valid in sigar_net_interface_config_primary_get 2008-02-13 Doug MacEachern * 1.6.2 release 2009-02-12 Doug MacEachern * (SIGAR-134) use UNICODE in EventLog wrapper 2009-02-10 Doug MacEachern * (SIGAR-73) check for 'ocfs' in addition to 'ocfs2' 2009-02-08 Doug MacEachern * (SIGAR-138) Recognize zfs as local filesystem type 2009-02-06 Doug MacEachern * fix osx version on 64-bit platforms * [SIGAR-133] use InputStream.skip (bytes) instead of Reader.skip (chars) in onChange * [SIGAR-132] Fix possible memory leak in sigar_rpc_ping * [SIGAR-129] fix possible integer overflow in time_now_millis * [SIGAR-129] add another sanity check * [SIGAR-129] prevent possible wrapping * [SIGAR-129] prevent possible integer overflow * [SIGAR-127] use KERN_ARGMAX for KERN_PROCARGS2 buffer size * [SIGAR-126] /dev/kmem not usable in aix 6 * rid "warning: cast from pointer to integer of different size" on 64-bit builds * [SIGAR-125] bring back /private/var/vm swap impl for osx 10.3 * [SIGAR-123] do not include global shared text+data region size * [SIGAR-122] ARG_MAX undefined on glibc 2.8 2008-09-13 Doug MacEachern * include ptql and log in dist headers * dont include ant and mx4j jars in dist * add cpu_perc typemap to bindings/perl 2008-09-11 Doug MacEachern * [SIGAR-120] Support WoW registry reflection 2008-09-08 Doug MacEachern * [SIGAR-119] Use 64-bit performance counter for uptime 2008-09-06 Doug MacEachern * 1.6 released, change summary: * OpenBSD support (binaries not included) * NetBSD support (binaries not included) * CPU list functions now return entry per-core rather than per-socket rollup * Added CPU irq, softirq and stolen metrics * PTQL enhancements for Windows Services * Added interface to Windows GetFileVersionInfo function * Bug fixes: http://jira.hyperic.com/secure/IssueNavigator.jspa?requestId=10710 2008-02-01 Doug MacEachern * 1.5 released, change summary: * PTQL impl ported from Java to C * Added api for TCP-MIB metrics * Added api for NFS client+server metrics * Started bindings for Ruby, Python and PHP * Bug fixes: http://jira.hyperic.com/secure/IssueNavigator.jspa?requestId=10500 2007-04-14 Doug MacEachern * 1.4 released 2007-04-06 Doug MacEachern * [SIGAR-47] Fix sigar_mem_get on 64-bit FreeBSD 2007-04-05 Doug MacEachern * Add net_listen_address function to lookup bind address of a listen socket * Add net_stat_port function to provide metrics on specific port+address * [SIGAR-46] Fix cpu_info.{mhz,cache_size} fields in UML vms 2007-03-29 Doug MacEachern * Fix cpu ticks to msec on linux/ia64 Submitted by: Jan Kneschke 2007-03-24 Doug MacEachern * Implement proc_state_t.threads on OS X 2007-03-11 Doug MacEachern * Implement native sigar_proc_cpu_get function 2007-03-07 Doug MacEachern * Plug various handle+mem leaks on win32 Submitted by: Jan Kneschke 2007-03-04 Doug MacEachern * [SIGAR-29] Add pdh language translation support * Add RegistryKey.getMultiStringValue() * Add win32.LocaleInfo class 2007-02-28 Doug MacEachern * Add signal name lookup support 2007-02-24 Doug MacEachern * Make Java objects returned by Sigar class Serializable 2007-02-21 Doug MacEachern * Perl binding updates Submitted by: Nicolas Laurent * [SIGAR-45] Fix disk reads/writes for LVM managed volumes 2007-02-15 Doug MacEachern * [SIGAR-42] Honor Solaris mnttab ignore flag in file_system_list 2007-02-12 Doug MacEachern * [SIGAR-17] Fix possible bad cpu list number on Solaris 2007-02-07 Doug MacEachern * Make sure solaris has _POSIX_PTHREAD_SEMANTICS defined Submitted by: Jan Kneschke 2007-02-06 Doug MacEachern * Fix possible overflow in FreeBSD cpu_get impl Submitted by: Jan Kneschke 2007-02-02 Doug MacEachern * [SIGAR-40] Change win32 file_system_list to ignore removable disks such as floppy, usb, etc. 2007-01-29 Doug MacEachern * [SIGAR-38] Change win32 swap_get to use GlobalMemoryStatusEx 2007-01-24 Doug MacEachern * Add proper thread_cpu impl for OS X 2007-01-23 Doug MacEachern * Fix proc_mem.size on HP-UX Submitted by: Ragnar 2007-01-22 Doug MacEachern * [SIGAR-32] Fix FileTail on Windows 2007-01-19 Doug MacEachern * [SIGAR-31] Improve truncation detection in FileTail 2007-01-18 Doug MacEachern * Add EventLog.getLogNames() method 2007-01-17 Doug MacEachern * Various fixes for sparc64 2007-01-09 Doug MacEachern * Add XenSource vendor support to sys_info api 2006-12-10 Doug MacEachern * 1.3 released 2006-12-04 Doug MacEachern * Added Java wrapper for VMware vmcontrol API * [SIGAR-26] Change Pdh.getFormattedValue() to collect 2 counters if needed 2006-12-03 Doug MacEachern * [SIGAR-19] Change cpu time units to milliseconds 2006-11-05 Doug MacEachern * [SIGAR-23] Overhaul windows net_interface_* implementations to ensure data is reported for the correct interface 2006-11-03 Doug MacEachern * [SIGAR-24] Any network adapter with a description of "Microsoft Loopback Adapter" is now flagged LOOPBACK 2006-10-27 Doug MacEachern * [SIGAR-22] Prevent RuntimeException in FileTail impl from killing the FileWatcherThread 2006-10-24 Doug MacEachern * [SIGAR-20] Fix windows sigar_net_inteface_list to handle > 100 interfaces (internal buffer size was fixed at 8k) 2006-10-19 Doug MacEachern * Compile on Windows AMD x64 Submitted by: Jan Kneschke * Changes to compile with modern visual studios on Windows 2006-10-10 Doug MacEachern * [SIGAR-18] Change Linux impl to use strtoull() where appropriate 2006-09-30 Doug MacEachern * OperatingSystem.java has been ported to the C sigar_sys_info API 2006-09-21 Doug MacEachern * [SIGAR-15] Fix sigar_fqdn_get so 'hostname' won't be resolved to 'localhost.localdomain' 2006-09-20 Doug MacEachern * Use kstat.cpu_info.brand to determine sigar_cpu_info_t.vendor on Solaris 10+ * Fix Linux cpu_info /proc/cpuinfo parsing on ia64 2006-09-08 Doug MacEachern * [SIGAR-13] Use EnumProcesses for sigar_proc_list_get on Win32 2006-09-07 Doug MacEachern * [SIGAR-14] Fix sigar_cpu_t.total on Linux and Solaris with multi-core CPUs 2006-08-25 Doug MacEachern * Implement proc_env for Darwin 2006-08-24 Doug MacEachern * Sigar.getProc*(String) methods now convert PTQL queries 2006-08-04 Doug MacEachern * Port hpux impl to ia64 arch 2006-07-24 Doug MacEachern * [SIGAR-11] Initialize log fields in solaris_sigar.c:sigar_os_open 2006-07-15 Doug MacEachern * 1.2 released * [SIGAR-10] Fix sigar_net_info_get /etc/resolv.conf parsing 2006-07-13 Doug MacEachern * Validate that sigar.jar is binary compatible with the native library 2006-07-11 Doug MacEachern * Port linux impl to ppc64 arch * [SIGAR-9] Fix possible overflow in solaris sigar_mem_get impl 2006-07-10 Doug MacEachern * [SIGAR-4] Implement native sigar_net_stat_get and use w/ Java 2006-07-07 Doug MacEachern * [SIGAR-8] Change win32 mem_get to use GlobalMemoryStatusEx 2006-07-06 Doug MacEachern * Change AIX impl to use libperfstat where available for net_interface_stat * Change sigar_net_route_t, net_interface_config_t and sigar_net_connection_t to use sigar_net_address_t 2006-06-30 Doug MacEachern * Remove mem.shared, gone in Linux 2.6 and which only left Solaris and Win32 2006-06-27 Doug MacEachern * Created SIGAR_1_1 branch, trunk is now 1.2 * Java net.hyperic package renamed to org.hyperic 2006-06-21 Doug MacEachern * [SIGAR-7] Convert sectors to bytes in Linux file system read/write bytes metrics 2006-06-09 Doug MacEachern * [SIGAR-6] Use rounding for mem.ram on Linux rather than /proc/mtrr if write-back registers don't add up to a reasonable number * [SIGAR-5] Fix netinfo default gateway where the first gateway in the routing table had been selected without checking for the default destination == 0.0.0.0 2006-05-30 Doug MacEachern * Prevent possible integer overflow in filesystem_usage 2006-05-24 Doug MacEachern * ProcUtil.getJavaMainClass improvements 2006-05-04 Doug MacEachern * Fold UltraSPARC-T1 virtual cpus into physical cpus * Fix net_connection_list on linux to handle invalid /proc/net/tcp entries * Switch to universal binary for osx 2006-04-03 Doug MacEachern * Fix sigar_proc_args_get on linux and osx when argv has an empty "" arg 2006-03-31 Doug MacEachern * Added binary for FreeBSD 6.x 2006-03-16 Doug MacEachern * Remove Darwin proc_mem.shared impl. More trouble that it is worth and the code did not compile on x86. 2006-03-14 Doug MacEachern * Enhance native library finder to work with -jar foo.jar and within an IDE such as Eclipse 2006-03-08 Doug MacEachern * 1.1.29 released 2006-03-04 Doug MacEachern * Add net_interface_config.description * Use IFMIB (GetIfEntry) rather netbios to get hwaddr on Win32 * Add net_interface_config.mtu for Win32 2006-03-03 Doug MacEachern * Removed proc_mem.vsize (same as proc_mem.size) * Removed proc_mem.rss (same as proc_mem.resident) 2006-03-01 Doug MacEachern * 1.1.28 released 2006-02-28 Doug MacEachern * Add Sigar.getNetListenAddress method * Add Sigar.getNetInterfaceConfig() method 2006-02-26 Doug MacEachern * Replace sigar_nfs_ping with generic sigar_rpc_ping 2006-02-23 Doug MacEachern * Use asm/cpuid instead of /proc/cpuinfo to detect HyperThreading on Linux * Use gethostbyname_r in sigar_fqdn_get 2006-01-10 Doug MacEachern * Add ProcUtil class * Pdh: if counter name does not exist, try appending "/sec" * Add Win32.findExecutable method * Add win32.Service.{pause,resume} methods 2006-01-04 Doug MacEachern * Fix cpu_list on Darwin * Add FreeBSD 4.x support 2005-12-19 Doug MacEachern * 1.1.27 released * Add net_interface_config.mtu for Solaris, HPUX, AIX * Add version api for native binaries * Add dir_usage api, recursive version of dir_stat api * Add dir_stat.disk_usage field 2005-12-12 Doug MacEachern * Fix internal hash table used for caching to properly rehash * Fix overzealous cache in net_interface_stat on Darwin * Solaris fixes to keep kstat chain up-to-date * Fallback to /usr/ucb/ps on solaris for proc_args if permissions deny reading /proc/nnnnn/as * Add option to use sudo+cat with FileTail 2005-12-05 Doug MacEachern * 1.1.26 released * Filter out network interface types other than loopback and ethernet on Darwin and FreeBSD * Filter out auto-mounted filesystems on Darwin 2005-12-01 Doug MacEachern * Fix net_route_list for Solaris 10 * Add sigar_cpu_info_t.{mhz,cache_size,model} for Darwin * Fix OperatingSystem.getDescription() for Darwin 2005-11-28 Doug MacEachern * 1.1.25 released * Fix sigar_file_system_usage_t.free_files for Solaris and Darwin 2005-11-23 Doug MacEachern * Add sigar_proc_mem page fault metrics for AIX, Darwin, HPUX, Linux, Solaris and Win32 2005-11-22 Doug MacEachern * Add sigar_proc_state.processor for AIX, HPUX, Linux and Solaris * Add sigar_proc_state.threads for AIX, HPUX, Linux (2.6+), Solaris and Win32 2005-11-18 Doug MacEachern * net_interface related changes to support VMware vmnic * Add sigar_net_interface_config.type field 2005-11-11 Doug MacEachern * Add dmalloc support for linux and solaris (enable w/ -Djni.dmalloc=true) 2005-11-08 Doug MacEachern * 1.1.24 released * fix possible segv in sigar_fqdn_get * fix possible fault in sigar_filesystem_usage_get on win32 if LogicalDisk perf counters are uninstalled 2005-11-01 Doug MacEachern * proc_mem.resident for all platforms 2005-10-10 Doug MacEachern * 1.1.23 released 2005-10-08 Doug MacEachern * Add support for solaris 'bge' network interface metrics * Add win32 sigar_who_list impl * sigar_proc_args fixes for linux and solaris * java -Dsigar.nativeLogging=true enables native logging 2005-09-24 Doug MacEachern * 1.1.22 released 2005-07-18 Doug MacEachern * Add net_info function * Add various helpers to OperatingSystem class 2005-07-07 Doug MacEachern * Add resource_limit function * Fix sigar_file_attrs_get times on win32 2005-06-25 Doug MacEachern * Add win32 ServiceConfig class and Service.getConfig method 2005-06-16 Doug MacEachern * 1.1.21 released * Implement proc_mem for Darwin * Include darwin binary (OSX Tiger) 2005-06-14 Doug MacEachern * Pdh.getSingleValue renamed to Pdh.getRawValue * Added Pdh.getFormattedValue method 2005-05-25 Doug MacEachern * Implement sigar_proc_args for Darwin 2005-05-11 Doug MacEachern * 1.1.20 released * Use psapi instead of CreateTool32Snapshot in win32 sigar_proc_modules It is possible for the latter to hang on win2k, the former also works on NT. * Implement sigar_net_connection_list for AIX and HPUX * Convert Cpu times to seconds 2005-05-10 Doug MacEachern * 1.1.19 released 2005-04-27 Doug MacEachern * Add disk i/o metrics for Windows 2000 * Add file_system_usage_t.used field 2005-04-06 Doug MacEachern * Add new disk i/o metrics (disk_write_bytes, disk_read_bytes, disk_queue) for Win32, Linux, Solaris, AIX and HPUX. 2005-03-19 Doug MacEachern * Add udp support to sigar_proc_port_get win32 impl * Implement sigar_proc_port_get for FreeBSD 5.x 2005-03-15 Doug MacEachern * Change Sigar.getMountedFileSystemUsage to throw NfsUnreachableException if FileSystem is Nfs and nfs ping fails * Implement sigar_net_connection for FreeBSD * Implement sigar_proc_port_get for AIX 2005-03-11 Doug MacEachern * Add sigar.NetStat class * Add sigar_net_connection_t.state field * Add sigar_net_connection_t.{send,receive}_queue fields * Implement sigar_net_connection for solaris * Netstat enhancements 2005-03-09 Doug MacEachern * Add CpuTimer class, helper around ThreadCpu class 2005-03-01 Doug MacEachern * 1.1.18 released * fix bug in ptql args glob substring operators (Args.*.{sw,ew,ct}) * fix bug where Pentium III was reported as II * added OperatingSystem class to help determine linux vendor/version info, etc. 2005-02-24 Doug MacEachern * 1.1.17 released * Optimize aix disk i/o metric collection * Add 'time' command to the shell 2005-02-23 Doug MacEachern * 1.1.16 released * Add function to get data seen in the 'who' command 2005-02-20 Doug MacEachern * Add NfsFileSystem class w/ ping method 2005-02-16 Doug MacEachern * Add FreeBSD support * Add 64-bit linux support 2005-01-26 Doug MacEachern * 1.1.15 released * fix windows 2003 problem with metrics that use the perfdata registry interface when pdh.dll functions are used by the same process. * Pdh.getSingleValue now uses PdhGetRawCounterValue underneath * fix win32.Pdh.close method * fix win32.Service.finalize method 2005-01-07 Doug MacEachern * implement thread-cpu metrics for aix 2005-01-06 Doug MacEachern * 1.1.14 released * fix solaris bug w/ multiple network interfaces that have the same name (hme0, hme1, etc) * fix bug in MultiProc that sometimes resulted in negative numbers * add win32.Service.getServiceNames method 2004-12-11 Doug MacEachern * 1.1.13 released 2004-12-06 Doug MacEachern * add iostat shell command * implement disk io metrics for aix, solaris and hpux 2004-12-05 Doug MacEachern * added sigar_file_system_usage_t.disk_{reads,writes} fields. implement only on linux and win32 for the moment. 2004-11-29 Doug MacEachern * fix possible segfault in sigar_group_name_get if gid == -1 2004-11-22 Doug MacEachern * fix bug in RegistryKey.openSubKey under WebSphere 4.0 jdk 2004-11-21 Doug MacEachern * 1.1.11 released * merged hyperic win32bindings package into sigar.win32 * added sigar_cpu_t.wait metric 2004-11-19 Doug MacEachern * added sigar_mem_t.actual_{used,free} fields. on linux for example adjusts -/+ buffers/cache 2004-11-17 Doug MacEachern * added sigar_thread_cpu_t, per-thread cpu metrics 2004-11-16 Doug MacEachern * 1.1.10 released 2004-11-12 John Sachs * added sysinfo shell command 2004-11-10 Doug MacEachern * added MultiProcCpu and MultiProcMem classes * added mps (multi-process ps) shell command 2004-11-02 Doug MacEachern * fix cpu idle metric for windows 2000 and NT versions 2004-10-05 Doug MacEachern * make sigar_swap and sigar_mem compatible with linux 2.6 kernel 2004-09-07 Doug MacEachern * starting ChangeLog for version 1.1.10 hyperic-sigar-1.6.4+dfsg/LICENSE000066400000000000000000000251421210132627500162170ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. hyperic-sigar-1.6.4+dfsg/NOTICE000066400000000000000000000023571210132627500161210ustar00rootroot00000000000000Hyperic SIGAR includes some third-party open source components in its distribution. The list below identifies the community or organization and links to their appropriate license terms. The Hyperic team would like to thank all the communities of the projects listed below for their contributions. --------------------------------------------------------------------- The following components are included without modification: - log4j - Information: http://logging.apache.org/ License: http://www.apache.org/licenses/LICENSE-2.0 The following components are included with modification: - cpptasks - Information: http://ant-contrib.sourceforge.net/ License: http://ant-contrib.sourceforge.net/LICENSE.txt - (portions of) APR - Information: http://apr.apache.org/ License: http://www.apache.org/licenses/LICENSE-2.0 - solaris get_mib2 - Information: ftp://vic.cc.purdue.edu/pub/tools/unix/solaris/get_mib2/ License: within src/os/solaris/get_mib2.[ch] - getline by Chris Thewalt - Information: http://tinyurl.com/r438r License: within src/sigar_getline.c - PrintfFormat.java - Information: http://java.sun.com/developer/technicalArticles/Programming/sprintf/PrintfFormat.java License: within bindings/java/src/org/hyperic/sigar/util/PrintfFormat.java hyperic-sigar-1.6.4+dfsg/README000066400000000000000000000001271210132627500160660ustar00rootroot00000000000000Visit the SIGAR Wiki for documentation, bugs, support, etc.: http://sigar.hyperic.com/ hyperic-sigar-1.6.4+dfsg/bindings/000077500000000000000000000000001210132627500170035ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/SigarWrapper.pm000066400000000000000000002006021210132627500217470ustar00rootroot00000000000000# # Copyright (c) 2007-2008 Hyperic, Inc. # Copyright (c) 2010 VMware, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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. # #extension source generator for all bindings package SigarWrapper; use strict; use Config; use Cwd; use Exporter; use File::Path; use IO::File (); use vars qw(@ISA @EXPORT); @ISA = qw(Exporter); @EXPORT = qw(generate); sub archname { my $os = lc $^O; my $vers = $Config{osvers}; my $arch = $Config{archname}; if ($os =~ /win32/) { return 'x86-winnt'; } elsif ($os =~ /linux/) { if ($arch =~ /_64/) { return 'amd64-linux'; } else { return 'x86-linux'; } } elsif ($os =~ /hpux/) { if ($vers =~ /11\./) { return 'pa-hpux-11'; } } elsif ($os =~ /aix/) { return 'ppc-aix-5'; } elsif ($os =~ /solaris/) { if ($arch =~ /sun4/) { return 'sparc-solaris'; } elsif ($arch =~ /.86/) { return 'x86-solaris'; } } elsif ($os =~ /darwin/) { return 'universal-macosx'; } elsif ($os =~ /freebsd/) { if($arch =~ /.86/) { if($vers =~ /6\../ ) { return 'x86-freebsd-6'; } } elsif( $arch =~ /amd64/) { if($vers =~ /6\../ ) { return 'amd64-freebsd-6'; } } } return ''; } my %platforms = ( A => "AIX", D => "Darwin", F => "FreeBSD", H => "HPUX", L => "Linux", S => "Solaris", W => "Win32", ); my %has_name_arg = map { $_, 1 } qw(FileSystemUsage DiskUsage FileAttrs DirStat DirUsage NetInterfaceConfig NetInterfaceStat); my %proc_no_arg = map { $_, 1 } qw(stat); my %get_not_impl = map { $_, 1 } qw(net_address net_route net_connection net_stat cpu_perc who cpu_info file_system); #list funcs only sub supported_platforms { my $p = shift; return 'Undocumented' unless $p; if ($p eq '*') { return 'All'; } my @platforms; for (split //, $p) { push @platforms, $platforms{$_}; } return join ", ", @platforms; } sub hash { return unpack("%32C*", shift) % 65535; } my $nfs_v2 = [ { name => 'null', type => 'Long', }, { name => 'getattr', type => 'Long', }, { name => 'setattr', type => 'Long', }, { name => 'root', type => 'Long', }, { name => 'lookup', type => 'Long', }, { name => 'readlink', type => 'Long', }, { name => 'read', type => 'Long', }, { name => 'writecache', type => 'Long', }, { name => 'write', type => 'Long', }, { name => 'create', type => 'Long', }, { name => 'remove', type => 'Long', }, { name => 'rename', type => 'Long', }, { name => 'link', type => 'Long', }, { name => 'symlink', type => 'Long', }, { name => 'mkdir', type => 'Long', }, { name => 'rmdir', type => 'Long', }, { name => 'readdir', type => 'Long', }, { name => 'fsstat', type => 'Long', }, ]; my $nfs_v3 = [ { name => 'null', type => 'Long', }, { name => 'getattr', type => 'Long', }, { name => 'setattr', type => 'Long', }, { name => 'lookup', type => 'Long', }, { name => 'access', type => 'Long', }, { name => 'readlink', type => 'Long', }, { name => 'read', type => 'Long', }, { name => 'write', type => 'Long', }, { name => 'create', type => 'Long', }, { name => 'mkdir', type => 'Long', }, { name => 'symlink', type => 'Long', }, { name => 'mknod', type => 'Long', }, { name => 'remove', type => 'Long', }, { name => 'rmdir', type => 'Long', }, { name => 'rename', type => 'Long', }, { name => 'link', type => 'Long', }, { name => 'readdir', type => 'Long', }, { name => 'readdirplus', type => 'Long', }, { name => 'fsstat', type => 'Long', }, { name => 'fsinfo', type => 'Long', }, { name => 'pathconf', type => 'Long', }, { name => 'commit', type => 'Long', }, ]; use vars qw(%classes %cmds); %classes = ( Mem => [ { name => 'total', type => 'Long', desc => 'Total system memory', plat => '*', cmd => { AIX => 'lsattr -El sys0 -a realmem', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, { name => 'ram', type => 'Long', desc => 'System Random Access Memory (in MB)', plat => '*', cmd => { AIX => 'lsattr -El sys0 -a realmem', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'cat /proc/mtrr | head -1', Solaris => '', Win32 => '', }, }, { name => 'used', type => 'Long', desc => 'Total used system memory', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, { name => 'free', type => 'Long', desc => 'Total free system memory (e.g. Linux plus cached)', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, { name => 'actual_used', type => 'Long', desc => 'Actual total used system memory (e.g. Linux minus buffers)', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, { name => 'actual_free', type => 'Long', desc => 'Actual total free system memory', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, { name => 'used_percent', type => 'Double', desc => 'Percent total used system memory', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, { name => 'free_percent', type => 'Double', desc => 'Percent total free system memory', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => '', Win32 => 'taskman', }, }, ], Swap => [ { name => 'total', type => 'Long', desc => 'Total system swap', plat => '*', cmd => { AIX => 'lsps -s', Darwin => 'sysctl vm.swapusage', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => 'swap -s', Win32 => '', }, }, { name => 'used', type => 'Long', desc => 'Total used system swap', plat => '*', cmd => { AIX => 'lsps -s', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => 'swap -s', Win32 => '', }, }, { name => 'free', type => 'Long', desc => 'Total free system swap', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'free', Solaris => 'swap -s', Win32 => '', }, }, { name => 'page_in', type => 'Long', desc => 'Pages in', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'vmstat', Solaris => 'vmstat', Win32 => '', }, }, { name => 'page_out', type => 'Long', desc => 'Pages out', plat => '*', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'vmstat', Solaris => 'vmstat', Win32 => '', }, }, ], Cpu => [ { name => 'user', type => 'Long', desc => 'Total system cpu user time', plat => '*' }, { name => 'sys', type => 'Long', desc => 'Total system cpu kernel time', plat => '*' }, { name => 'nice', type => 'Long', desc => 'Total system cpu nice time', plat => 'DFHL' }, { name => 'idle', type => 'Long', desc => 'Total system cpu idle time', plat => '*' }, { name => 'wait', type => 'Long', desc => 'Total system cpu io wait time', plat => 'ALHS' }, { name => 'irq', type => 'Long', desc => 'Total system cpu time servicing interrupts', plat => 'FLHW' }, { name => 'soft_irq', type => 'Long', desc => 'Total system cpu time servicing softirqs', plat => 'L' }, { name => 'stolen', type => 'Long', desc => 'Total system cpu involuntary wait time', plat => 'L' }, { name => 'total', type => 'Long', desc => 'Total system cpu time', plat => '*' }, ], CpuPerc => [ { name => 'user', type => 'Double', desc => 'Percent system cpu user time', plat => '*' }, { name => 'sys', type => 'Double', desc => 'Percent system cpu kernel time', plat => '*' }, { name => 'nice', type => 'Double', desc => 'Percent system cpu nice time', plat => 'DFHL' }, { name => 'idle', type => 'Double', desc => 'Percent system cpu idle time', plat => '*' }, { name => 'wait', type => 'Double', desc => 'Percent system cpu io wait time', plat => 'ALHS' }, { name => 'irq', type => 'Double', desc => 'Percent system cpu time servicing interrupts', plat => 'FLHW' }, { name => 'soft_irq', type => 'Double', desc => 'Percent system cpu time servicing softirqs', plat => 'L' }, { name => 'stolen', type => 'Double', desc => 'Percent system cpu involuntary wait time', plat => 'L' }, { name => 'combined', type => 'Double', desc => 'Sum of User + Sys + Nice + Wait', plat => '*' }, ], CpuInfo => [ { name => 'vendor', type => 'String', desc => 'CPU vendor id', plat => 'AFLHSW' }, { name => 'model', type => 'String', desc => 'CPU model', plat => 'AFLHSW' }, { name => 'mhz', type => 'Int', desc => 'CPU speed', plat => 'AFHLSW' }, { name => 'cache_size', type => 'Long', desc => 'CPU cache size', plat => 'AL' }, { name => 'total_cores', type => 'Int', desc => 'Total CPU cores (logical)', }, { name => 'total_sockets', type => 'Int', desc => 'Total CPU sockets (physical)', }, { name => 'cores_per_socket', type => 'Int', desc => 'Number of CPU cores per CPU socket', }, ], Uptime => [ { name => 'uptime', type => 'Double', desc => 'Time since machine started in seconds', plat => '*' }, ], ProcMem => [ { name => 'size', type => 'Long', desc => 'Total process virtual memory', plat => '*' }, { name => 'resident', type => 'Long', desc => 'Total process resident memory', plat => '*' }, { name => 'share', type => 'Long', desc => 'Total process shared memory', plat => 'AHLS' }, { name => 'minor_faults', type => 'Long', desc => 'non i/o page faults', plat => 'AHLS' }, { name => 'major_faults', type => 'Long', desc => 'i/o page faults', plat => 'AHLS' }, { name => 'page_faults', type => 'Long', desc => 'Total number of page faults', plat => 'ADHLSW' }, ], ProcCred => [ { name => 'uid', type => 'Long', desc => 'Process user id', plat => 'ADFHLS' }, { name => 'gid', type => 'Long', desc => 'Process group id', plat => 'ADFHLS' }, { name => 'euid', type => 'Long', desc => 'Process effective user id', plat => 'ADFHLS' }, { name => 'egid', type => 'Long', desc => 'Process effective group id', plat => 'ADFHLS' }, ], ProcCredName => [ { name => 'user', type => 'String', desc => 'Process owner user name', plat => '*' }, { name => 'group', type => 'String', desc => 'Process owner group name', plat => '*' }, ], ProcTime => [ { name => 'start_time', type => 'Long', desc => 'Time process was started in seconds', plat => '*' }, { name => 'user', type => 'Long', desc => 'Process cpu user time', plat => '*' }, { name => 'sys', type => 'Long', desc => 'Process cpu kernel time', plat => '*' }, { name => 'total', type => 'Long', desc => 'Process cpu time (sum of User and Sys)', plat => '*' }, ], ProcCpu => [ { name => 'percent', type => 'Double', desc => 'Process cpu usage', plat => '*' }, { name => 'last_time', type => 'Long', desc => '', plat => '*' }, ], ProcState => [ { name => 'state', type => 'Char', desc => 'Process state (Running, Zombie, etc.)', plat => '*' }, { name => 'name', type => 'String', desc => 'Name of the process program', plat => '*' }, { name => 'ppid', type => 'Long', desc => 'Process parent process id', plat => '*' }, { name => 'tty', type => 'Int', desc => 'Device number of rocess controling terminal', plat => 'AHLS' }, { name => 'nice', type => 'Int', desc => 'Nice value of process', plat => 'ADFHLS' }, { name => 'priority', type => 'Int', desc => 'Kernel scheduling priority of process', plat => 'DFHLSW' }, { name => 'threads', type => 'Long', desc => 'Number of active threads', plat => 'ADHLSW' }, { name => 'processor', type => 'Int', desc => 'Processor number last run on', plat => 'AHLS' }, ], ProcFd => [ { name => 'total', type => 'Long', desc => 'Total number of open file descriptors', plat => 'AHLSW' }, ], ProcStat => [ { name => 'total', type => 'Long', desc => 'Total number of processes', plat => '*' }, { name => 'idle', type => 'Long', desc => 'Total number of processes in idle state', plat => '*' }, { name => 'running', type => 'Long', desc => 'Total number of processes in run state', plat => '*' }, { name => 'sleeping', type => 'Long', desc => 'Total number of processes in sleep state', plat => '*' }, { name => 'stopped', type => 'Long', desc => 'Total number of processes in stop state', plat => '*' }, { name => 'zombie', type => 'Long', desc => 'Total number of processes in zombie state', plat => '*' }, { name => 'threads', type => 'Long', desc => 'Total number of threads', plat => '*' }, ], ProcExe => [ { name => 'name', type => 'String', desc => 'Name of process executable', plat => 'FLSW', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'ls -l /proc/$$/exe', Solaris => '', Win32 => '', }, }, { name => 'cwd', type => 'String', desc => 'Name of process current working directory', plat => 'LSW', cmd => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'ls -l /proc/$$/cwd', Solaris => '', Win32 => '', }, }, ], ThreadCpu => [ { name => 'user', type => 'Long', desc => 'Thread cpu user time', plat => 'AHLSW' }, { name => 'sys', type => 'Long', desc => 'Thread cpu kernel time', plat => 'AHLSW' }, { name => 'total', type => 'Long', desc => 'Thread cpu time (sum of User and Sys)', plat => 'AHLSW' }, ], FileSystem => [ { name => 'dir_name', type => 'String', desc => 'Directory name', plat => '*' }, { name => 'dev_name', type => 'String', desc => 'Device name', plat => '*' }, { name => 'type_name', type => 'String', desc => 'File system generic type name', plat => '*' }, { name => 'sys_type_name', type => 'String', desc => 'File system os specific type name', plat => '*' }, { name => 'options', type => 'String', desc => 'File system mount options', plat => '*' }, { name => 'type', type => 'Int', desc => 'File system type', plat => '*' }, { name => 'flags', type => 'Long', desc => 'File system flags', plat => '*' }, ], FileSystemUsage => [ { name => 'total', type => 'Long', desc => 'Total Kbytes of filesystem', plat => '*' }, { name => 'free', type => 'Long', desc => 'Total free Kbytes on filesystem', plat => '*' }, { name => 'used', type => 'Long', desc => 'Total used Kbytes on filesystem', plat => '*' }, { name => 'avail', type => 'Long', desc => 'Total free Kbytes on filesystem available to caller', plat => '*' }, { name => 'files', type => 'Long', desc => 'Total number of file nodes on the filesystem', plat => 'ADFHLS' }, { name => 'free_files', type => 'Long', desc => 'Number of free file nodes on the filesystem', plat => 'ADFHLS' }, { name => 'disk_reads', type => 'Long', desc => 'Number of physical disk reads', plat => 'AFHLSW' }, { name => 'disk_writes', type => 'Long', desc => 'Number of physical disk writes', plat => 'AFHLSW' }, { name => 'disk_read_bytes', type => 'Long', desc => 'Number of physical disk bytes read', plat => '' }, { name => 'disk_write_bytes', type => 'Long', desc => 'Number of physical disk bytes written', plat => '' }, { name => 'disk_queue', type => 'Double', desc => '', plat => '' }, { name => 'disk_service_time', type => 'Double', desc => '', plat => '' }, { name => 'use_percent', type => 'Double', desc => 'Percent of disk used', plat => '*' }, ], DiskUsage => [ { name => 'reads', type => 'Long', desc => 'Number of physical disk reads', plat => 'AFHLSW' }, { name => 'writes', type => 'Long', desc => 'Number of physical disk writes', plat => 'AFHLSW' }, { name => 'read_bytes', type => 'Long', desc => 'Number of physical disk bytes read', plat => '' }, { name => 'write_bytes', type => 'Long', desc => 'Number of physical disk bytes written', plat => '' }, { name => 'queue', type => 'Double', desc => '', plat => '' }, { name => 'service_time', type => 'Double', desc => '', plat => '' }, ], FileAttrs => [ { name => 'permissions', type => 'Long', }, { name => 'type', type => 'Int', }, { name => 'uid', type => 'Long', }, { name => 'gid', type => 'Long', }, { name => 'inode', type => 'Long', }, { name => 'device', type => 'Long', }, { name => 'nlink', type => 'Long', }, { name => 'size', type => 'Long', }, { name => 'atime', type => 'Long', }, { name => 'ctime', type => 'Long', }, { name => 'mtime', type => 'Long', }, ], DirStat => [ { name => 'total', type => 'Long', }, { name => 'files', type => 'Long', }, { name => 'subdirs', type => 'Long', }, { name => 'symlinks', type => 'Long', }, { name => 'chrdevs', type => 'Long', }, { name => 'blkdevs', type => 'Long', }, { name => 'sockets', type => 'Long', }, { name => 'disk_usage', type => 'Long', }, ], NetInfo => [ { name => 'default_gateway', type => 'String', desc => '', plat => '' }, { name => 'host_name', type => 'String', desc => '', plat => '' }, { name => 'domain_name', type => 'String', desc => '', plat => '' }, { name => 'primary_dns', type => 'String', desc => '', plat => '' }, { name => 'secondary_dns', type => 'String', desc => '', plat => '' }, ], NetRoute => [ { name => 'destination', type => 'NetAddress', desc => '', plat => 'HLW' }, { name => 'gateway', type => 'NetAddress', desc => '', plat => 'HLW' }, { name => 'flags', type => 'Long', desc => '', plat => 'L' }, { name => 'refcnt', type => 'Long', desc => '', plat => 'L' }, { name => 'use', type => 'Long', desc => '', plat => 'L' }, { name => 'metric', type => 'Long', desc => '', plat => 'L' }, { name => 'mask', type => 'NetAddress', desc => '', plat => 'HL' }, { name => 'mtu', type => 'Long', desc => '', plat => 'L' }, { name => 'window', type => 'Long', desc => '', plat => 'L' }, { name => 'irtt', type => 'Long', desc => '', plat => 'L' }, { name => 'ifname', type => 'String', desc => '', plat => 'L' }, ], NetInterfaceConfig => [ { name => 'name', type => 'String', desc => '', plat => '*' }, { name => 'hwaddr', type => 'NetAddress', desc => '', plat => '*' }, { name => 'type', type => 'String', desc => '', plat => '*' }, { name => 'description', type => 'String', desc => '', plat => '*' }, { name => 'address', type => 'NetAddress', desc => '', plat => '*' }, { name => 'destination', type => 'NetAddress', desc => '', plat => '*' }, { name => 'broadcast', type => 'NetAddress', desc => '', plat => '*' }, { name => 'netmask', type => 'NetAddress', desc => '', plat => '*' }, { name => 'flags', type => 'Long', desc => '', plat => '*' }, { name => 'mtu', type => 'Long', desc => '', plat => 'DFL' }, { name => 'metric', type => 'Long', desc => '', plat => 'DFL' }, ], NetInterfaceStat => [ { name => 'rx_bytes', type => 'Long', desc => '', plat => '*' }, { name => 'rx_packets', type => 'Long', desc => '', plat => '*' }, { name => 'rx_errors', type => 'Long', desc => '', plat => '*' }, { name => 'rx_dropped', type => 'Long', desc => '', plat => '' }, { name => 'rx_overruns', type => 'Long', desc => '', plat => '' }, { name => 'rx_frame', type => 'Long', desc => '', plat => '' }, { name => 'tx_bytes', type => 'Long', desc => '', plat => '*' }, { name => 'tx_packets', type => 'Long', desc => '', plat => '*' }, { name => 'tx_errors', type => 'Long', desc => '*', plat => '' }, { name => 'tx_dropped', type => 'Long', desc => '', plat => '' }, { name => 'tx_overruns', type => 'Long', desc => '', plat => '' }, { name => 'tx_collisions', type => 'Long', desc => '', plat => '' }, { name => 'tx_carrier', type => 'Long', desc => '', plat => '' }, { name => 'speed', type => 'Long', desc => '', plat => '' }, ], NetConnection => [ { name => 'local_port', type => 'Long', desc => '', plat => 'LFSW' }, { name => 'local_address', type => 'NetAddress', desc => '', plat => 'LFSW' }, { name => 'remote_port', type => 'Long', desc => '', plat => 'LFSW' }, { name => 'remote_address', type => 'NetAddress', desc => '', plat => 'LFSW' }, { name => 'type', type => 'Int', desc => '', plat => 'LFSW' }, { name => 'state', type => 'Int', desc => '', plat => 'LFSW' }, { name => 'send_queue', type => 'Long', desc => '', plat => 'LFS' }, { name => 'receive_queue', type => 'Long', desc => '', plat => 'LFS' }, ], #only for jfieldId cache/setters NetStat => [ { name => 'tcp_inbound_total', type => 'Int', }, { name => 'tcp_outbound_total', type => 'Int', }, { name => 'all_inbound_total', type => 'Int', }, { name => 'all_outbound_total', type => 'Int', }, ], Tcp => [ { name => 'active_opens', type => 'Long', desc => '', plat => '' }, { name => 'passive_opens', type => 'Long', desc => '', plat => '' }, { name => 'attempt_fails', type => 'Long', desc => '', plat => '' }, { name => 'estab_resets', type => 'Long', desc => '', plat => '' }, { name => 'curr_estab', type => 'Long', desc => '', plat => '' }, { name => 'in_segs', type => 'Long', desc => '', plat => '' }, { name => 'out_segs', type => 'Long', desc => '', plat => '' }, { name => 'retrans_segs', type => 'Long', desc => '', plat => '' }, { name => 'in_errs', type => 'Long', desc => '', plat => '' }, { name => 'out_rsts', type => 'Long', desc => '', plat => '' }, ], NfsClientV2 => $nfs_v2, NfsServerV2 => $nfs_v2, NfsClientV3 => $nfs_v3, NfsServerV3 => $nfs_v3, ResourceLimit => [ { name => 'cpu_cur', }, { name => 'cpu_max', }, { name => 'file_size_cur', }, { name => 'file_size_max', }, { name => 'pipe_size_max', }, { name => 'pipe_size_cur', }, { name => 'data_cur', }, { name => 'data_max', }, { name => 'stack_cur', }, { name => 'stack_max', }, { name => 'core_cur', }, { name => 'core_max', }, { name => 'memory_cur', }, { name => 'memory_max', }, { name => 'processes_cur', }, { name => 'processes_max', }, { name => 'open_files_cur', }, { name => 'open_files_max', }, { name => 'virtual_memory_cur', }, { name => 'virtual_memory_max', }, ], SysInfo => [ { name => 'name', type => 'String', desc => '', plat => '*' }, { name => 'version', type => 'String', desc => '', plat => '*' }, { name => 'arch', type => 'String', desc => '', plat => '*' }, { name => 'machine', type => 'String', desc => '', plat => '*' }, { name => 'description', type => 'String', desc => '', plat => '*' }, { name => 'patch_level', type => 'String', desc => '', plat => 'W' }, { name => 'vendor', type => 'String', desc => '', plat => '*' }, { name => 'vendor_version', type => 'String', desc => '', plat => '*' }, { name => 'vendor_name', type => 'String', desc => '', plat => '*' }, { name => 'vendor_code_name', type => 'String', desc => '', plat => '*' }, ], Who => [ { name => 'user', type => 'String', desc => '', plat => '' }, { name => 'device', type => 'String', desc => '', plat => '' }, { name => 'host', type => 'String', desc => '', plat => '' }, { name => 'time', type => 'Long', desc => '', plat => '' }, ], ); $classes{DirUsage} = $classes{DirStat}; my(%extends) = ( ProcCpu => 'ProcTime', ); while (my($subclass, $superclass) = each %extends) { push @{ $classes{$subclass} }, @{ $classes{$superclass} }; } %cmds = ( Mem => { AIX => 'top', Darwin => 'top', FreeBSD => 'top', HPUX => 'top', Linux => 'top', Solaris => 'top', Win32 => 'taskman', }, Swap => { AIX => 'top', Darwin => 'top', FreeBSD => 'top', HPUX => 'top', Linux => 'top', Solaris => 'top', Win32 => 'taskman', }, Cpu => { AIX => 'top', Darwin => 'top', FreeBSD => 'top', HPUX => 'top', Linux => 'top', Solaris => 'top', Win32 => 'taskman', }, CpuInfo => { AIX => 'lsattr -El proc0', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'cat /proc/cpuinfo', Solaris => 'psrinfo -v', Win32 => '', }, Uptime => { AIX => 'uptime', Darwin => 'uptime', FreeBSD => 'uptime', HPUX => 'uptime', Linux => 'uptime', Solaris => 'uptime', Win32 => '', }, ProcMem => { AIX => 'top, ps', Darwin => 'top, ps', FreeBSD => 'top, ps', HPUX => 'top, ps', Linux => 'top, ps', Solaris => 'top, ps', Win32 => 'taskman', }, ProcCred => { AIX => 'top, ps', Darwin => 'top, ps', FreeBSD => 'top, ps', HPUX => 'top, ps', Linux => 'top, ps', Solaris => 'top, ps', Win32 => 'taskman', }, ProcTime => { AIX => 'top, ps', Darwin => 'top, ps', FreeBSD => 'top, ps', HPUX => 'top, ps', Linux => 'top, ps', Solaris => 'top, ps', Win32 => 'taskman', }, ProcState => { AIX => 'top, ps', Darwin => 'top, ps', FreeBSD => 'top, ps', HPUX => 'top, ps', Linux => 'top, ps', Solaris => 'top, ps', Win32 => 'taskman', }, ProcFd => { AIX => 'lsof', Darwin => 'lsof', FreeBSD => 'lsof', HPUX => 'lsof', Linux => 'lsof', Solaris => 'lsof', Win32 => '', }, ProcStat => { AIX => 'top, ps', Darwin => 'top, ps', FreeBSD => 'top, ps', HPUX => 'top, ps', Linux => 'top, ps', Solaris => 'top, ps', Win32 => 'taskman', }, FileSystemUsage => { AIX => 'df', Darwin => 'df', FreeBSD => 'df', HPUX => 'df', Linux => 'df', Solaris => 'df', Win32 => '', }, NetRoute => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'route -n', Solaris => '', Win32 => '', }, NetInterfaceConfig => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'ifconfig', Solaris => 'ifconfig -a', Win32 => '', }, NetInterfaceStat => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '/usr/sbin/lanadmin -g mibstats 0, netstat -i', Linux => 'ifconfig', Solaris => '', Win32 => '', }, NetConnection => { AIX => '', Darwin => '', FreeBSD => '', HPUX => '', Linux => 'netstat', Solaris => '', Win32 => '', }, Tcp => { Linux => 'cat /proc/net/snmp', Solaris => 'netstat -s -P tcp', }, ); sub warning_comment { my $self = shift; return "WARNING: this file was generated by $0 on $self->{timestamp}. Any changes made here will be LOST."; } sub c_warning_comment { my $self = shift; my $comment = $self->warning_comment; $comment =~ s/^/ * /mg; return < $dir, mtime => $mtime, ); my $package = __PACKAGE__ . "::$lang"; eval "require $package"; unless ($package->can('new')) { die "unsupported language: $lang"; } $@ = ''; my $wrapper = $package->new(%param); unless ($wrapper->uptodate($wrapper->sources)) { eval { $wrapper->start(); my $mappings = $wrapper->get_mappings; for my $func (@$mappings) { $wrapper->generate_class($func); } $wrapper->finish; }; } die $@ if $@; chdir $cwd; } sub new { my $class = shift; return bless { timestamp => scalar localtime, @_ }, $class; } sub uptodate { my $self = shift; for my $file (@_) { my $mtime = (stat $file)[9]; if ($mtime > $self->{mtime}) { print "$file up-to-date\n"; } else { print "$file needs update\n"; return 0; } } return 1; } my(%warning_comment) = map { $_ => \&c_warning_comment } qw(c h java); sub create { my($self, $file) = @_; my $handle = SigarWrapper::File->create($file); if ($file =~ /\.(\w+)$/) { my $comment = $warning_comment{$1}; $handle->print($self->$comment()) if $comment; } return $self->{files}->{$file} = $handle; } sub start { } sub finish { my $self = shift; while (my($file, $handle) = each %{ $self->{files} }) { next unless $handle->opened; if ($handle->close) { #print "closing $file\n"; } else { warn "close($file): $!"; } } } my @mappings; sub get_mappings { if (@mappings != 0) { return \@mappings; } while (my($name, $fields) = each %classes) { #example: FileSystemUsage -> file_system_usage (my $cname = $name) =~ s/([a-z])([A-Z])/$1_$2/g; $cname = lc $cname; my $func = { name => $name, cname => $cname, }; push @mappings, $func; if (($cname =~ /^proc_(\w+)/ and !$proc_no_arg{$1}) || ($cname =~ /^thread_cpu/)) { $func->{num_args} = 1; $func->{arg_type} = 'sigar_pid_t'; $func->{arg} = 'pid'; $func->{is_proc} = 1; } elsif ($has_name_arg{$name}) { $func->{num_args} = 1; $func->{arg_type} = 'const char *'; $func->{arg} = 'name'; } else { $func->{num_args} = 0; } if ($get_not_impl{$cname}) { $func->{has_get} = 0; } else { $func->{has_get} = 1; } my $sigar_prefix = $func->{sigar_prefix} = join '_', 'sigar', $cname; $func->{sigar_function} = join '_', $sigar_prefix, 'get'; $func->{sigar_type} = join '_', $sigar_prefix, 't'; $func->{fields} = $fields; for my $field (@$fields) { $field->{type} ||= 'Long'; } } return \@mappings; } package SigarWrapper::File; use vars qw(@ISA); @ISA = qw(IO::File); my $DEVNULL = '/dev/null'; my $has_dev_null = -e $DEVNULL; sub println { shift->print(@_, "\n"); } sub create { my($class, $file) = @_; my $handle = $class->SUPER::new($file || devnull(), "w") or die "open $file: $!"; print "generating $file\n" if $file; return $handle; } sub devnull { if ($has_dev_null) { return $DEVNULL; } else { return "./nul"; #win32 /dev/null equiv } } package SigarWrapper::Java; use vars qw(@ISA); @ISA = qw(SigarWrapper); my %field_types = ( Long => "J", Double => "D", Int => "I", Char => "C", String => "Ljava/lang/String;", ); my %init = ( String => 'null', ); my %type = ( String => 'String', ); #alias for my $j (\%field_types, \%init, \%type) { $j->{'NetAddress'} = $j->{'String'}; } #XXX kinda ugly having this here #will consider moving elsewhere if there #are more cases like this. my %extra_code = ( FileSystem => <<'EOF', public static final int TYPE_UNKNOWN = 0; public static final int TYPE_NONE = 1; public static final int TYPE_LOCAL_DISK = 2; public static final int TYPE_NETWORK = 3; public static final int TYPE_RAM_DISK = 4; public static final int TYPE_CDROM = 5; public static final int TYPE_SWAP = 6; public String toString() { return this.getDirName(); } EOF NetConnection => <<'EOF', public native String getTypeString(); public native static String getStateString(int state); public String getStateString() { return getStateString(this.state); } EOF Mem => <<'EOF', public String toString() { return "Mem: " + (this.total / 1024) + "K av, " + (this.used / 1024) + "K used, " + (this.free / 1024) + "K free"; } EOF ResourceLimit => <<'EOF', public static native long INFINITY(); EOF Swap => <<'EOF', public String toString() { return "Swap: " + (this.total / 1024) + "K av, " + (this.used / 1024) + "K used, " + (this.free / 1024) + "K free"; } EOF ProcState => <<'EOF', public static final char SLEEP = 'S'; public static final char RUN = 'R'; public static final char STOP = 'T'; public static final char ZOMBIE = 'Z'; public static final char IDLE = 'D'; EOF ProcMem => <<'EOF', /** * @deprecated * @see #getResident() */ public long getRss() { return getResident(); } /** * @deprecated * @see #getSize() */ public long getVsize() { return getSize(); } EOF ); sub new { my $class = shift; my $self = $class->SUPER::new(@_); $self->{jsrc} = 'org/hyperic/sigar'; return $self; } my $jni_file = 'javasigar_generated'; sub sources { return map { "$jni_file.$_" } qw(c h); } sub start { my $self = shift; $self->SUPER::start; my $jsrc = $self->{jsrc}; File::Path::mkpath([$jsrc], 0, 0755) unless -d $jsrc; $self->{package} = 'org.hyperic.sigar'; $self->{cfh} = $self->create("$jni_file.c"); my $hfh = $self->{hfh} = $self->create("$jni_file.h"); my %field_cache; my $i = 0; while (my($class, $fields) = each %SigarWrapper::classes) { next if $field_cache{$class}++; print $hfh "#define JSIGAR_FIELDS_\U$class $i\n"; $i++; my $n = 0; for my $field (@$fields) { my $name = $field->{name}; print $hfh "# define JSIGAR_FIELDS_\U${class}_${name} $n\n"; $n++; } print $hfh "# define JSIGAR_FIELDS_\U${class}_MAX $n\n"; } print $hfh "#define JSIGAR_FIELDS_MAX $i\n"; } sub jname { my $jname = shift; #special case for nfs return $jname eq 'null' ? "_$jname" : $jname; } #using mega-method pattern here sub generate_class { my($self, $func) = @_; my $cfh = $self->{cfh}; my $hfh = $self->{hfh}; my $class = $func->{name}; my $cname = $func->{cname}; my $java_class = "$self->{package}.$class"; (my $jni_prefix = "Java.$java_class") =~ s/\./_/g; my $args_proto = ""; my $args = ""; my $decl_string = ""; my $get_string = ""; my $release_string = ""; my $jname = lcfirst $class; if ($func->{num_args} == 1) { $args = " $func->{arg}, "; if ($func->{is_proc}) { $args_proto = ", jlong pid"; } else { $args_proto = ", jstring jname"; $decl_string = "const char *name;"; $get_string = "name = jname ? JENV->GetStringUTFChars(env, jname, 0) : NULL;"; $release_string = "if (jname) JENV->ReleaseStringUTFChars(env, jname, name);"; } } my $nativefunc = join '_', $jni_prefix, 'gather'; my $proto = join "\n", "JNIEXPORT void JNICALL $nativefunc", "(JNIEnv *env, jobject obj, jobject sigar_obj$args_proto)"; my $jfh = $self->create_jfile($class); print $cfh <{has_get}; $proto; $proto { $func->{sigar_type} s; int status; jclass cls = JENV->GetObjectClass(env, obj); $decl_string dSIGAR_VOID; $get_string status = $func->{sigar_function}(sigar,${args}&s); $release_string if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return; } EOF my $jargs_proto = 'Sigar sigar'; my $jargs = 'sigar'; if ($func->{is_proc}) { $jargs_proto .= ', long pid'; $jargs .= ", pid"; } elsif ($func->{num_args} == 1) { $jargs_proto .= ', String name'; $jargs .= ", name"; } my $cache_field_ids = 1; my $uid = 0; for my $field (@{ $func->{fields} }) { $uid += SigarWrapper::hash($field->{type}) + SigarWrapper::hash($field->{name}); } print $jfh <{package}; import java.util.HashMap; import java.util.Map; /** * $class sigar class. */ public class $class implements java.io.Serializable { private static final long serialVersionUID = ${uid}L; public $class() { } public native void gather($jargs_proto) throws SigarException; /** * This method is not intended to be called directly. * use Sigar.get$class() instead. * \@exception SigarException on failure. * \@see $self->{package}.Sigar#get$class */ static $class fetch($jargs_proto) throws SigarException { $class $jname = new $class(); $jname.gather($jargs); return $jname; } EOF my(@copy, @tostring); my $setter = "JAVA_SIGAR_SET_FIELDS_\U$class"; my $getter = "JAVA_SIGAR_GET_FIELDS_\U$class"; my @setter = ("\#define $setter(cls, obj, s)"); my @getter = ("\#define $getter(obj, s)"); my $init_define = "JAVA_SIGAR_INIT_FIELDS_\U$class"; my $field_class_ix = "JSIGAR_FIELDS_\U$class"; my $field_class_ix = "JSIGAR_FIELDS_\U$class"; my $field_class_max = $field_class_ix . '_MAX'; my $field_class = "jsigar->fields[$field_class_ix]"; my @init_fields = ("#define $init_define(cls)", " if (!$field_class) {", " $field_class = ", " malloc(sizeof(*$field_class));", " $field_class->classref = ", " (jclass)JENV->NewGlobalRef(env, cls);", " $field_class->ids = ", " malloc($field_class_max *", " sizeof(*$field_class->ids));"); for my $field (@{ $func->{fields} }) { my $type = $field->{type}; my $name = $field->{name}; my $member = $field->{member} || $name; my $desc = $field->{desc} || $name; (my $jname = $name) =~ s/_(\w)/\u$1/g; my $getter = "get\u$jname"; $jname = jname($jname); my $sig = qq("$field_types{$type}"); my $set = "JENV->Set${type}Field"; my $get = "JENV->Get${type}Field"; my $field_ix = $field_class_ix . "_\U$name"; my $get_id = qq|JENV->GetFieldID(env, cls, "$jname", $sig)|; my $id_cache = "$field_class->ids[$field_ix]"; my $id_lookup = $cache_field_ids ? $id_cache : $get_id; push @init_fields, " $id_cache = ", " $get_id;"; push @setter, qq| $set(env, obj, $id_lookup, s.$member);|; push @getter, qq| s.$member = $get(env, obj, $id_lookup);|; my $init = $init{$type} || '0'; my $jtype = $type{$type} || lcfirst($type); my $platforms = SigarWrapper::supported_platforms($field->{plat}); print $jfh " $jtype $jname = $init;\n\n"; push @copy, " copy.$jname = this.$jname;\n"; push @tostring, $jname; #documentation print $jfh " /**\n"; print $jfh " * Get the $desc.

\n"; print $jfh " * Supported Platforms: $platforms.\n"; print $jfh " *

\n"; if (my $cmd = ($field->{cmd} || $SigarWrapper::cmds{$class})) { print $jfh " * System equivalent commands:

    \n"; for my $p (sort keys %$cmd) { print $jfh " *
  • $p: $cmd->{$p}
    \n"; } print $jfh " *
\n"; } print $jfh " * \@return $desc\n"; print $jfh " */\n"; print $jfh " public $jtype $getter() { return $jname; }\n"; } print $jfh "\n void copyTo($class copy) {\n", @copy, " }\n"; my $code = $extra_code{$class}; if ($code) { print $jfh $code; } my $num_fields = @tostring; print $jfh "\n public Map toMap() {\n"; print $jfh " Map map = new HashMap();\n"; for (my $i=0; $i<$num_fields; $i++) { my $jfield = $tostring[$i]; my $sfield = "str${jfield}"; print $jfh " String $sfield = \n"; print $jfh " String.valueOf(this.$jfield);\n"; print $jfh qq{ if (!"-1".equals($sfield))\n}; print $jfh qq{ map.put("\u$jfield", $sfield);\n}; } print $jfh " return map;\n"; print $jfh " }\n"; if (!$code or $code !~ /toString/) { print $jfh "\n public String toString() {\n"; print $jfh " return toMap().toString();\n"; print $jfh " }\n"; } push @init_fields, " }"; if ($cache_field_ids) { print $hfh join(' \\' . "\n", @init_fields), "\n\n"; print $cfh "\n\n $init_define(cls);\n\n" if $func->{has_get}; } else { print $hfh "#define $init_define(cls)\n"; } print $hfh join(' \\' . "\n", @setter), "\n\n"; print $hfh join(' \\' . "\n", @getter), "\n\n"; print $cfh "\n\n $setter(cls, obj, s);" if $func->{has_get}; print $cfh "\n}\n" if $func->{has_get}; print $jfh "\n}\n"; close $jfh; } sub finish { my $self = shift; $self->SUPER::finish; } sub create_jfile { my($self, $name) = @_; my $jsrc = $self->{jsrc}; my $jfile = "$jsrc/$name.java"; if (-e "../../src/$jsrc/$name.java") { print "skipping $jfile\n"; #dont generate .java if already exists $jfile = undef; } return $self->create($jfile); } package SigarWrapper::Perl; use vars qw(@ISA); @ISA = qw(SigarWrapper); my %field_types = ( Long => "sigar_uint64_t", Double => "double", Int => "IV", Char => "char", String => "char *", NetAddress => "Sigar::NetAddress", ); my $xs_file = 'Sigar_generated.xs'; sub sources { return $xs_file; } sub start { my $self = shift; $self->SUPER::start; $self->{xfh} = $self->create($xs_file); } sub generate_class { my($self, $func) = @_; my $fh = $self->{xfh}; my $class = $func->{name}; my $cname = $func->{cname}; my $perl_class = "Sigar::$class"; my $proto = 'VALUE obj'; my $args = 'sigar'; if ($func->{num_args} == 1) { $args .= ", $func->{arg}"; } print $fh "\nMODULE = Sigar PACKAGE = Sigar PREFIX = sigar_\n\n"; print $fh <{has_get}; $perl_class $cname($args) Sigar sigar EOF if ($func->{arg}) { print $fh " $func->{arg_type} $func->{arg}\n" if $func->{has_get}; } print $fh <{has_get}; PREINIT: int status; CODE: RETVAL = safemalloc(sizeof(*RETVAL)); if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) { SIGAR_CROAK(sigar, "$cname"); } OUTPUT: RETVAL EOF print $fh <{fields} }) { my $name = $field->{name}; my $type = $field_types{ $field->{type} }; print $fh <$name; OUTPUT: RETVAL EOF } } sub finish { my $self = shift; $self->SUPER::finish; } package SigarWrapper::Ruby; use vars qw(@ISA); @ISA = qw(SigarWrapper); my %field_types = ( Long => "rb_ll2inum", Double => "rb_float_new", Int => "rb_int2inum", Char => "CHR2FIX", String => "rb_str_new2", NetAddress => "rb_sigar_net_address_to_s", ); my $rx_file = 'rbsigar_generated.rx'; sub sources { return $rx_file; } sub start { my $self = shift; $self->SUPER::start; $self->{cfh} = $self->create($rx_file); } sub add_method { my($self, $class, $name) = @_; push @{ $self->{methods}->{$class} }, $name; } sub generate_class { my($self, $func) = @_; my $fh = $self->{cfh}; my $class = $func->{name}; my $cname = $func->{cname}; my $ruby_class = "rb_cSigar$class"; my $proto = 'VALUE obj'; my $args = 'sigar'; if ($func->{num_args} == 1) { my $arg_type; if ($func->{is_proc}) { $arg_type = 'NUM2UINT'; } else { $arg_type = 'StringValuePtr'; } $proto .= ", VALUE $func->{arg}"; $args .= ", $arg_type($func->{arg})"; } print $fh <{has_get}; static VALUE $ruby_class; static VALUE rb_sigar_$cname($proto) { int status; sigar_t *sigar = rb_sigar_get(obj); $func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL)); if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) { free(RETVAL); rb_raise(rb_eArgError, "%s", sigar_strerror(sigar, status)); return Qnil; } return Data_Wrap_Struct($ruby_class, 0, rb_sigar_free, RETVAL); } EOF for my $field (@{ $func->{fields} }) { my $name = $field->{name}; my $type = $field_types{ $field->{type} }; $self->add_method($class, $name); print $fh <{sigar_type} *$cname; Data_Get_Struct(self, $func->{sigar_type}, $cname); return $type($cname->$name); } EOF } } sub finish { my $self = shift; my $fh = $self->{cfh}; print $fh "static void rb_sigar_define_module_methods(VALUE rclass)\n{\n"; my $mappings = SigarWrapper::get_mappings(); for my $func (@$mappings) { my $name = $func->{cname}; my $args = $func->{num_args}; next unless $func->{has_get}; print $fh qq{ rb_define_method(rclass, "$name", rb_sigar_$name, $args);\n}; } for my $class (sort keys %{ $self->{methods} }) { my $rclass = "rb_cSigar$class"; print $fh qq{ $rclass = rb_define_class_under(rclass, "$class", rb_cObject);\n}; for my $method (@{ $self->{methods}->{$class} }) { print $fh qq{ rb_define_method($rclass, "$method", rb_sigar_${class}_$method, 0);\n}; } } print $fh "}\n"; $self->SUPER::finish; } package SigarWrapper::PHP; use vars qw(@ISA); @ISA = qw(SigarWrapper); my %field_types = ( Long => "RETURN_LONG", Double => "RETURN_DOUBLE", Int => "RETURN_LONG", Char => "RETURN_LONG", String => "PHP_SIGAR_RETURN_STRING", NetAddress => "PHP_SIGAR_RETURN_NETADDR", ); my $php_file = 'php_sigar_generated.c'; sub sources { return $php_file; } sub start { my $self = shift; $self->SUPER::start; $self->{cfh} = $self->create($php_file); } sub generate_class { my($self, $func) = @_; my $cfh = $self->{cfh}; my $class = $func->{name}; my $cname = $func->{cname}; my $php_class = "Sigar::$class"; my $parse_args = ""; my $vars = ""; my $args = 'sigar'; my $arginfo = $args; if ($func->{num_args} == 1) { if ($func->{is_proc}) { $parse_args = 'zSIGAR_PARSE_PID;'; $arginfo .= '_pid'; $vars = "long $func->{arg};\n"; } else { $parse_args .= 'zSIGAR_PARSE_NAME;'; $arginfo .= '_name'; $vars = "char *$func->{arg}; int $func->{arg}_len;\n"; } $args .= ", $func->{arg}"; } my $prefix = "php_$func->{sigar_prefix}_"; my $functions = $prefix . 'functions'; my $handlers = $prefix . 'object_handlers'; my $init = $prefix . 'init'; my $ctor = $prefix . 'new'; my(@functions); for my $field (@{ $func->{fields} }) { my $name = $field->{name}; my $type = $field_types{ $field->{type} }; my $method = $prefix . $name; push @functions, { name => $name, me => $method }; print $cfh <{sigar_type} *$cname = ($func->{sigar_type} *)zSIGAR_OBJ; $type($cname->$name); } EOF } print $cfh <{name}, $func->{me}, NULL)\n"; } print $cfh <{has_get}; static PHP_FUNCTION($func->{sigar_function}) { int status; zSIGAR; $func->{sigar_type} *RETVAL = emalloc(sizeof(*RETVAL)); $vars $parse_args if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) { efree(RETVAL); RETURN_FALSE; } else { php_sigar_obj_new("$php_class", return_value)->ptr = RETVAL; } } EOF } sub finish { my $self = shift; my $mappings = $self->get_mappings; my $cfh = $self->{cfh}; my $nl = '\\' . "\n"; print $cfh "#define PHP_SIGAR_FUNCTIONS $nl"; for my $func (@$mappings) { next unless $func->{has_get}; #XXX PHP_ME_MAPPING has another arg in 5.2 print $cfh " PHP_ME_MAPPING($func->{cname}, $func->{sigar_function}, NULL)"; if ($func == $mappings->[-1]) { print $cfh "\n"; } else { print $cfh $nl; } } print $cfh "#define PHP_SIGAR_INIT $nl"; for my $func (@$mappings) { print $cfh " php_$func->{sigar_prefix}_init()"; if ($func == $mappings->[-1]) { print $cfh "\n"; } else { print $cfh ";$nl"; } } $self->SUPER::finish; } package SigarWrapper::Python; use vars qw(@ISA); @ISA = qw(SigarWrapper); my %field_types = ( Long => "PyLong_FromUnsignedLongLong", Double => "PyFloat_FromDouble", Int => "PyInt_FromLong", Char => "PySigarInt_FromChar", String => "PyString_FromString", NetAddress => "PySigarString_FromNetAddr", ); my $c_file = '_sigar_generated.c'; sub sources { return $c_file; } sub start { my $self = shift; $self->SUPER::start; $self->{cfh} = $self->create($c_file); } sub pyclass { my $class = shift; return "Sigar.$class"; } sub pytype { my $class = shift; return 'pysigar_PySigar' . $class . 'Type'; } sub generate_class { my($self, $func) = @_; my $cfh = $self->{cfh}; my $pyclass = pyclass($func->{name}); my $pytype = pytype($func->{name}); my $cname = $func->{cname}; my $parse_args = ""; my $vars = ""; my $args = 'sigar'; if ($func->{num_args} == 1) { if ($func->{is_proc}) { $parse_args = 'PySigar_ParsePID;'; $vars = "long $func->{arg};\n"; } else { $parse_args .= 'PySigar_ParseName;'; $vars = "char *$func->{arg}; int $func->{arg}_len;\n"; } $args .= ", $func->{arg}"; } my $prefix = "py$func->{sigar_prefix}_"; my $methods = $prefix . 'methods'; my $dtor = 'pysigar_free'; for my $field (@{ $func->{fields} }) { my $name = $field->{name}; my $type = $field_types{ $field->{type} }; my $method = $prefix . $name; print $cfh <{sigar_type} *$cname = ($func->{sigar_type} *)PySIGAR_OBJ->ptr; return $type($cname->$name); } EOF } print $cfh "static PyMethodDef $methods [] = {\n"; for my $field (@{ $func->{fields} }) { my $name = $field->{name}; print $cfh qq( { "$name", ${prefix}$name, METH_NOARGS, "$name" },\n); } print $cfh " {NULL}\n};\n"; print $cfh <{has_get}; static PyObject *py$func->{sigar_function}(PyObject *self, PyObject *args) { int status; sigar_t *sigar = PySIGAR; $func->{sigar_type} *RETVAL = malloc(sizeof(*RETVAL)); $vars $parse_args if ((status = $func->{sigar_function}($args, RETVAL)) != SIGAR_OK) { free(RETVAL); PySigar_Croak(); return NULL; } else { PyObject *self = PySigar_new($pytype); PySIGAR_OBJ->ptr = RETVAL; return self; } } EOF } sub finish { my $self = shift; my $mappings = $self->get_mappings; my $cfh = $self->{cfh}; my $nl = '\\' . "\n"; print $cfh "#define PY_SIGAR_METHODS $nl"; for my $func (@$mappings) { next unless $func->{has_get}; my $arginfo = $func->{num_args} ? 'METH_VARARGS' : 'METH_NOARGS'; print $cfh qq( {"$func->{cname}", py$func->{sigar_function}, $arginfo, NULL},); if ($func == $mappings->[-1]) { print $cfh "\n"; } else { print $cfh $nl; } } print $cfh "#define PY_SIGAR_ADD_TYPES $nl"; for my $func (@$mappings) { my $pyclass = pyclass($func->{name}); my $pytype = pytype($func->{name}); print $cfh qq{ PySigar_AddType("$pyclass", $pytype)}; if ($func == $mappings->[-1]) { print $cfh "\n"; } else { print $cfh ";$nl"; } } $self->SUPER::finish; } 1; __END__ hyperic-sigar-1.6.4+dfsg/bindings/dotnet/000077500000000000000000000000001210132627500203005ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/dotnet/default.build000066400000000000000000000023211210132627500227430ustar00rootroot00000000000000 hyperic-sigar-1.6.4+dfsg/bindings/dotnet/examples/000077500000000000000000000000001210132627500221165ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/dotnet/examples/CpuInfo.cs000066400000000000000000000022521210132627500240110ustar00rootroot00000000000000/* * Copyright (c) 2004 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. */ using System; using Hyperic.Sigar; public class CpuInfo { public static void Main() { Sigar sigar = new Sigar(); Hyperic.Sigar.CpuInfo[] infos = sigar.CpuInfoList(); System.Console.WriteLine(infos.Length + " total CPUs.."); foreach (Hyperic.Sigar.CpuInfo info in infos) { System.Console.WriteLine("Vendor........" + info.Vendor); System.Console.WriteLine("Model........." + info.Model); System.Console.WriteLine("Mhz..........." + info.Mhz); System.Console.WriteLine(""); } } } hyperic-sigar-1.6.4+dfsg/bindings/dotnet/examples/Df.cs000066400000000000000000000036721210132627500230060ustar00rootroot00000000000000/* * Copyright (c) 2004-2005 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. */ using System; using Hyperic.Sigar; public class Df { private static String FormatSize(long value) { return Sigar.FormatSize(value * 1024); } public static void Main() { Sigar sigar = new Sigar(); foreach (FileSystem fs in sigar.FileSystemList()) { FileSystemUsage usage; long used, avail, total, pct; try { usage = sigar.FileSystemUsage(fs.DirName); used = usage.Total - usage.Free; avail = usage.Avail; total = usage.Total; pct = (long)(usage.UsePercent * 100); } catch (SigarException) { used = avail = total = pct = 0; continue; } string usePct; if (pct == 0) { usePct = "-"; } else { usePct = pct + "%"; } System.Console.WriteLine(fs.DevName + "\t" + FormatSize(total) + "\t" + FormatSize(used) + "\t" + FormatSize(avail) + "\t" + usePct + "\t" + fs.DirName + "\t" + fs.SysTypeName + "/" + fs.TypeName); } } } hyperic-sigar-1.6.4+dfsg/bindings/dotnet/examples/Free.cs000066400000000000000000000024701210132627500233310ustar00rootroot00000000000000/* * Copyright (c) 2004 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. */ using System; using Hyperic.Sigar; public class Free { public static void Main() { Sigar sigar = new Sigar(); Mem mem = sigar.Mem(); Swap swap = sigar.Swap(); System.Console.WriteLine("\tTotal\tUsed\tFree"); System.Console.WriteLine("Mem:\t" + mem.Total / 1024 + "\t" + mem.Used / 1024 + "\t" + mem.Free / 1024); System.Console.WriteLine("Swap:\t" + swap.Total / 1024 + "\t" + swap.Used / 1024 + "\t" + swap.Free / 1024); System.Console.WriteLine("RAM:\t" + mem.Ram + "MB"); } } hyperic-sigar-1.6.4+dfsg/bindings/dotnet/examples/Ifconfig.cs000066400000000000000000000061551210132627500242000ustar00rootroot00000000000000/* * Copyright (c) 2004-2005 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. */ using System; using Hyperic.Sigar; public class Ifconfig { private static void println(String line) { System.Console.WriteLine(line); } private static void output(Sigar sigar, String name) { NetInterfaceConfig ifconfig = sigar.NetInterfaceConfig(name); long flags = ifconfig.Flags; String hwaddr = ""; if (!Sigar.NULL_HWADDR.Equals(ifconfig.Hwaddr)) { hwaddr = " HWaddr " + ifconfig.Hwaddr; } println(ifconfig.Name + "\t" + "Link encap:" + ifconfig.Type + hwaddr); String ptp = ""; if ((flags & Sigar.IFF_POINTOPOINT) > 0) { ptp = " P-t-P:" + ifconfig.Destination; } String bcast = ""; if ((flags & Sigar.IFF_BROADCAST) > 0) { bcast = " Bcast:" + ifconfig.Broadcast; } println("\t" + "inet addr:" + ifconfig.Address + ptp + //unlikely bcast + " Mask:" + ifconfig.Netmask); println("\t" + ifconfig.FlagsString() + " MTU:" + ifconfig.Mtu + " Metric:" + ifconfig.Metric); try { NetInterfaceStat ifstat = sigar.NetInterfaceStat(name); println("\t" + "RX packets:" + ifstat.RxPackets + " errors:" + ifstat.RxErrors + " dropped:" + ifstat.RxDropped + " overruns:" + ifstat.RxOverruns + " frame:" + ifstat.RxFrame); println("\t" + "TX packets:" + ifstat.TxPackets + " errors:" + ifstat.TxErrors + " dropped:" + ifstat.TxDropped + " overruns:" + ifstat.TxOverruns + " carrier:" + ifstat.TxCarrier); println("\t" + "collisions:" + ifstat.TxCollisions); long rxBytes = ifstat.RxBytes; long txBytes = ifstat.TxBytes; println("\t" + "RX bytes:" + rxBytes + " (" + Sigar.FormatSize(rxBytes) + ")" + " " + "TX bytes:" + txBytes + " (" + Sigar.FormatSize(txBytes) + ")"); } catch (SigarException) { } println(""); } public static void Main() { Sigar sigar = new Sigar(); foreach (String name in sigar.NetInterfaceList()) { output(sigar, name); } } } hyperic-sigar-1.6.4+dfsg/bindings/dotnet/src/000077500000000000000000000000001210132627500210675ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/dotnet/src/Sigar.cs000066400000000000000000000503761210132627500224760ustar00rootroot00000000000000/* * Copyright (c) 2004-2006 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. */ using System; using System.IO; using System.Collections; using System.Runtime.InteropServices; using System.Text; namespace Hyperic.Sigar { public class Sigar { internal const int OK = 0; internal const int SIGAR_START_ERROR = 20000; internal const int SIGAR_ENOTIMPL = (SIGAR_START_ERROR + 1); public const String NULL_HWADDR = "00:00:00:00:00:00"; public const int IFF_UP = 0x1; public const int IFF_BROADCAST = 0x2; public const int IFF_DEBUG = 0x4; public const int IFF_LOOPBACK = 0x8; public const int IFF_POINTOPOINT = 0x10; public const int IFF_NOTRAILERS = 0x20; public const int IFF_RUNNING = 0x40; public const int IFF_NOARP = 0x80; public const int IFF_PROMISC = 0x100; public const int IFF_ALLMULTI = 0x200; public const int IFF_MULTICAST = 0x800; internal const int FS_NAME_LEN = 64; //cp sigar-x86-winnt.dll sigar.dll //ln -s libsigar-x86-linux.so libsigar.so //XXX can we determine the real name at runtime? internal const string LIBSIGAR = "sigar"; internal HandleRef sigar; [DllImport(LIBSIGAR)] private static extern int sigar_open(ref IntPtr sigar); [DllImport(LIBSIGAR)] private static extern int sigar_close(IntPtr sigar); public Sigar() { IntPtr handle = IntPtr.Zero; sigar_open(ref handle); this.sigar = new HandleRef(this, handle); } [DllImport(Sigar.LIBSIGAR)] private static extern void sigar_format_size(long size, StringBuilder buffer); public static string FormatSize(long size) { StringBuilder buffer = new StringBuilder(56); sigar_format_size(size, buffer); return buffer.ToString(); } public Mem Mem() { return Hyperic.Sigar.Mem.NativeGet(this); } public Swap Swap() { return Hyperic.Sigar.Swap.NativeGet(this); } public Cpu Cpu() { return Hyperic.Sigar.Cpu.NativeGet(this); } public CpuInfo[] CpuInfoList() { return Hyperic.Sigar.CpuInfoList.NativeGet(this); } public FileSystem[] FileSystemList() { return Hyperic.Sigar.FileSystemList.NativeGet(this); } public FileSystemUsage FileSystemUsage(string dirname) { return Hyperic.Sigar.FileSystemUsage.NativeGet(this, dirname); } public String[] NetInterfaceList() { return Hyperic.Sigar.NetInterfaceList.NativeGet(this); } public NetInterfaceConfig NetInterfaceConfig(string name) { return Hyperic.Sigar.NetInterfaceConfig.NativeGet(this, name); } public NetInterfaceStat NetInterfaceStat(string name) { return Hyperic.Sigar.NetInterfaceStat.NativeGet(this, name); } ~Sigar() { sigar_close(this.sigar.Handle); } internal static IntPtr incrementIntPtr(IntPtr ptr, int size) { Int32 x = (Int32)ptr; x += size; return (IntPtr)x; } internal static SigarException FindException(Sigar sigar, int errno) { switch (errno) { case SIGAR_ENOTIMPL: return new SigarNotImplementedException(sigar, errno); default: return new SigarException(sigar, errno); } } } public class SigarException : Exception { Sigar sigar; int errno; public SigarException(Sigar sigar, int errno) : base() { this.sigar = sigar; this.errno = errno; } [DllImport(Sigar.LIBSIGAR)] private static extern string sigar_strerror(IntPtr sigar, int errno); public override string Message { get { return sigar_strerror(this.sigar.sigar.Handle, this.errno); } } } public class SigarNotImplementedException : SigarException { public SigarNotImplementedException(Sigar sigar, int errno) : base(sigar, errno) { } } [StructLayout(LayoutKind.Sequential)] public struct Mem { public readonly long Ram; public readonly long Total; public readonly long Used; public readonly long Free; public readonly long Shared; public readonly long ActualFree; public readonly long ActualUsed; [DllImport(Sigar.LIBSIGAR)] private static extern int sigar_mem_get(IntPtr sigar, IntPtr mem); internal static Mem NativeGet(Sigar sigar) { Type type = typeof(Mem); //sigar_mem_t *ptr = malloc(sizeof(*ptr)) IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type)); int status = sigar_mem_get(sigar.sigar.Handle, ptr); if (status != Sigar.OK) { Marshal.FreeHGlobal(ptr); throw Sigar.FindException(sigar, status); } //memcpy(ptr, this, sizeof(this)) Mem mem = (Mem)Marshal.PtrToStructure(ptr, type); Marshal.FreeHGlobal(ptr); return mem; } } [StructLayout(LayoutKind.Sequential)] public struct Swap { public readonly long Total; public readonly long Used; public readonly long Free; [DllImport(Sigar.LIBSIGAR)] private static extern int sigar_swap_get(IntPtr sigar, IntPtr swap); internal static Swap NativeGet(Sigar sigar) { Type type = typeof(Swap); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type)); int status = sigar_swap_get(sigar.sigar.Handle, ptr); if (status != Sigar.OK) { Marshal.FreeHGlobal(ptr); throw Sigar.FindException(sigar, status); } Swap swap = (Swap)Marshal.PtrToStructure(ptr, type); Marshal.FreeHGlobal(ptr); return swap; } } [StructLayout(LayoutKind.Sequential)] public struct Cpu { public readonly long User; public readonly long Sys; private readonly long NA_Nice; public readonly long Idle; private readonly long NA_Wait; public readonly long Total; [DllImport(Sigar.LIBSIGAR)] private static extern int sigar_cpu_get(IntPtr sigar, IntPtr cpu); internal static Cpu NativeGet(Sigar sigar) { Type type = typeof(Cpu); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type)); int status = sigar_cpu_get(sigar.sigar.Handle, ptr); if (status != Sigar.OK) { Marshal.FreeHGlobal(ptr); throw Sigar.FindException(sigar, status); } Cpu cpu = (Cpu)Marshal.PtrToStructure(ptr, type); Marshal.FreeHGlobal(ptr); return cpu; } } [StructLayout(LayoutKind.Sequential)] public struct CpuInfo { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public readonly string Vendor; //char[128] [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public readonly string Model; //char[128] public readonly int Mhz; private readonly long CacheSize; //XXX not implemented } [StructLayout(LayoutKind.Sequential)] internal struct CpuInfoList { private readonly uint Number; //sizeof(unsigned long) == 4 private readonly uint size; private readonly IntPtr data; [DllImport(Sigar.LIBSIGAR)] private static extern int sigar_cpu_info_list_get(IntPtr sigar, IntPtr cpu_infos); [DllImport(Sigar.LIBSIGAR)] private static extern int sigar_cpu_info_list_destroy(IntPtr sigar, IntPtr cpu_infos); internal static CpuInfo[] NativeGet(Sigar sigar) { Type type = typeof(CpuInfoList); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type)); int status = sigar_cpu_info_list_get(sigar.sigar.Handle, ptr); if (status != Sigar.OK) { Marshal.FreeHGlobal(ptr); throw Sigar.FindException(sigar, status); } CpuInfoList infosPtr = (CpuInfoList)Marshal.PtrToStructure(ptr, type); CpuInfo[] infos = new CpuInfo[infosPtr.Number]; IntPtr eptr = infosPtr.data; int size = Marshal.SizeOf(infos[0]); for (int i=0; i 0) retval += "UP "; if ((flags & Sigar.IFF_BROADCAST) > 0) retval += "BROADCAST "; if ((flags & Sigar.IFF_DEBUG) > 0) retval += "DEBUG "; if ((flags & Sigar.IFF_LOOPBACK) > 0) retval += "LOOPBACK "; if ((flags & Sigar.IFF_POINTOPOINT) > 0) retval += "POINTOPOINT "; if ((flags & Sigar.IFF_NOTRAILERS) > 0) retval += "NOTRAILERS "; if ((flags & Sigar.IFF_RUNNING) > 0) retval += "RUNNING "; if ((flags & Sigar.IFF_NOARP) > 0) retval += "NOARP "; if ((flags & Sigar.IFF_PROMISC) > 0) retval += "PROMISC "; if ((flags & Sigar.IFF_ALLMULTI) > 0) retval += "ALLMULTI "; if ((flags & Sigar.IFF_MULTICAST) > 0) retval += "MULTICAST "; return retval; } } [StructLayout(LayoutKind.Sequential)] public struct NetInterfaceStat { public readonly long RxPackets; public readonly long RxBytes; public readonly long RxErrors; public readonly long RxDropped; public readonly long RxOverruns; public readonly long RxFrame; public readonly long TxPackets; public readonly long TxBytes; public readonly long TxErrors; public readonly long TxDropped; public readonly long TxOverruns; public readonly long TxCollisions; public readonly long TxCarrier; [DllImport(Sigar.LIBSIGAR)] private static extern int sigar_net_interface_stat_get(IntPtr sigar, string name, IntPtr ifstat); internal static NetInterfaceStat NativeGet(Sigar sigar, string name) { Type type = typeof(NetInterfaceStat); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type)); int status = sigar_net_interface_stat_get(sigar.sigar.Handle, name, ptr); if (status != Sigar.OK) { Marshal.FreeHGlobal(ptr); throw Sigar.FindException(sigar, status); } NetInterfaceStat ifstat = (NetInterfaceStat)Marshal.PtrToStructure(ptr, type); Marshal.FreeHGlobal(ptr); return ifstat; } } } hyperic-sigar-1.6.4+dfsg/bindings/java/000077500000000000000000000000001210132627500177245ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/.classpath000066400000000000000000000010731210132627500217100ustar00rootroot00000000000000 hyperic-sigar-1.6.4+dfsg/bindings/java/.project000066400000000000000000000005541210132627500213770ustar00rootroot00000000000000 sigar org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature hyperic-sigar-1.6.4+dfsg/bindings/java/.sigar_shellrc000066400000000000000000000033221210132627500225460ustar00rootroot00000000000000#this file is loaded by the sigar shell. #commands in this file are run just as they would be if they #were typed in by hand in the shell prompt. #find weblogic nodes (-1 means last index in the array) alias ps-wls ps State.Name.eq=java,Args.-1.eq=weblogic.Server #find websphere 4.x nodes alias ps-was4 ps State.Name.eq=java,Args.*.eq=com.ibm.ejs.sm.server.ManagedServer #find websphere admin server alias ps-was4adm ps State.Name.eq=java,Args.*.eq=com.ibm.ejs.sm.server.AdminServer #find websphere 5.x nodes alias ps-was5 ps State.Name.eq=java,Args.*.eq=com.ibm.ws.runtime.WsServer #find websphere 4.x and 5.x nodes alias ps-was ps State.Name.eq=java,Args.*.eq=com.ibm.ws.bootstrap.WSLauncher #find jboss (use .sw=java to match 'java' or 'javaw') alias ps-jboss ps State.Name.sw=java,Args.*.eq=org.jboss.Main #find tomcat alias ps-tomcat ps State.Name.eq=java,Args.*.eq=org.apache.catalina.startup.Bootstrap #find apache parent processes #($1 is the return value of the first query in the string) #'Pne' => 'P' flags means parent of matched process #to filter out httpd child processes alias ps-apache ps State.Name.re=https?d.*|[Aa]pache2?$,State.Name.Pne=$1 #find ant processes (ant hangs on me sometimes) #(* matches any value in the array) alias ps-ant ps State.Name.eq=java,Args.*.eq=org.apache.tools.ant.Main #HQ agents alias ps-hqagent ps State.Name.sw=java,Args.-1.eq=org.hyperic.hq.agent.server.AgentDaemon #find all java procs except the shell itself #($$ is the current process id) alias ps-java ps State.Name.eq=java,Pid.Pid.ne=$$ alias java ps-java #find all processes owned by the current user alias ps-me ps CredName.User.eq=$user.name #VMware Server or GSX VMs alias ps-vmx ps State.Name.eq=vmware-vmx,Args.1.eq=-C hyperic-sigar-1.6.4+dfsg/bindings/java/build.xml000066400000000000000000000417041210132627500215530ustar00rootroot00000000000000 ]> &jni-build; Copyright © ${copyright.year} Hyperic]]>. All Rights Reserved. cp ${version.file.srcdir}/${version.file}.in -> ${version.tofile} hyperic-sigar-1.6.4+dfsg/bindings/java/examples/000077500000000000000000000000001210132627500215425ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/examples/ProcessState.java000066400000000000000000000042411210132627500250250ustar00rootroot00000000000000/* * Copyright (c) 2006 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. */ import org.hyperic.sigar.*; /* Example to show the process state for a given pid. Compile the example: % javac -classpath sigar-bin/lib/sigar.jar ProcessState.java State of the java process running the example: % java -classpath sigar-bin/lib/sigar.jar:. ProcessState java: Running State of the bash shell when invoking the example is running: % java -classpath sigar-bin/lib/sigar.jar:. ProcessState $$ bash: Sleeping State of emacs editor used to write the example: % java -classpath sigar-bin/lib/sigar.jar:. ProcessState 2673 emacs: Suspended See also: examples/Ps.java, examples/Top.java */ public class ProcessState { private static String getStateString(char state) { switch (state) { case ProcState.SLEEP: return "Sleeping"; case ProcState.RUN: return "Running"; case ProcState.STOP: return "Suspended"; case ProcState.ZOMBIE: return "Zombie"; case ProcState.IDLE: return "Idle"; default: return String.valueOf(state); } } public static void main(String[] args) throws SigarException { String pid; if (args.length == 0) { pid = "$$"; //default to this process } else { pid = args[0]; } Sigar sigar = new Sigar(); ProcState procState = sigar.getProcState(pid); String state; System.out.println(procState.getName() + ": " + getStateString(procState.getState())); sigar.close(); } } hyperic-sigar-1.6.4+dfsg/bindings/java/examples/ServiceStatus.java000066400000000000000000000035221210132627500252130ustar00rootroot00000000000000/* * Copyright (c) 2006 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. */ import java.util.Arrays; import java.util.List; import org.hyperic.sigar.win32.Service; import org.hyperic.sigar.win32.Win32Exception; /* Example to show the status of a Windows services. Compile the example: % javac -classpath sigar-bin/lib/sigar.jar ServiceStatus.java Status of all services: % java -classpath sigar-bin/lib/sigar.jar:. ServiceStatus Alerter: Stopped ALG: Running Apache Tomcat 4.1: Stopped Apache2: Running ... Status of a specific service: % java -classpath sigar-bin/lib/sigar.jar:. ServiceStatus Eventlog Eventlog: Running See also: examples/Win32Service.java */ public class ServiceStatus { private static void printStatus(String name) throws Win32Exception { Service service = new Service(name); System.out.println(name + ": " + service.getStatusString()); service.close(); } public static void main(String[] args) throws Exception { List services; String name; if (args.length == 0) { services = Service.getServiceNames(); } else { services = Arrays.asList(args); } for (int i=0; i java.home=${jni.javahome} hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/000077500000000000000000000000001210132627500230165ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/000077500000000000000000000000001210132627500236055ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/hyperic/000077500000000000000000000000001210132627500252505ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/hyperic/jni/000077500000000000000000000000001210132627500260305ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/hyperic/jni/ArchLoader.java000066400000000000000000000306171210132627500307060ustar00rootroot00000000000000/* * 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.jni; import java.io.File; import java.util.StringTokenizer; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; public class ArchLoader { private Object loadLock = new Object(); private boolean loaded = false; private final static String osName = System.getProperty("os.name"); public final static boolean IS_WIN32 = osName.startsWith("Windows"); public final static boolean IS_AIX = osName.equals("AIX"); public final static boolean IS_HPUX = osName.equals("HP-UX"); public final static boolean IS_SOLARIS = osName.equals("SunOS"); public final static boolean IS_LINUX = osName.equals("Linux"); public final static boolean IS_DARWIN = osName.equals("Mac OS X") || osName.equals("Darwin"); public final static boolean IS_OSF1 = osName.equals("OSF1"); public final static boolean IS_FREEBSD = osName.equals("FreeBSD"); public final static boolean IS_NETWARE = osName.equals("NetWare"); private String packageName; private String name; private String resourcePath; private Class loaderClass; private String jarName; private String libName = null; private File nativeLibrary; private String version; public ArchLoader() { } public ArchLoader(Class loaderClass) { setLoaderClass(loaderClass); //e.g. Sigar.class //argh. possible for loaderClass.getPackage() //to return null depending on ClassLoader String pname = loaderClass.getName(); int ix = pname.lastIndexOf("."); pname = pname.substring(0, ix); setPackageName(pname); //e.g. org.hyperic.sigar ix = pname.lastIndexOf("."); setName(pname.substring(ix+1)); //e.g. sigar setJarName(getName() + ".jar"); setResourcePath(toResName(pname)); //e.g. org.hyperic/sigar } public Class getLoaderClass() { return this.loaderClass; } public void setLoaderClass(Class value) { this.loaderClass = value; } public ClassLoader getClassLoader() { return getLoaderClass().getClassLoader(); } public String getName() { return this.name; } public void setName(String value) { this.name = value; } public String getPackageName() { return this.packageName; } public void setPackageName(String value) { this.packageName = value; } public String getResourcePath() { return this.resourcePath; } public void setResourcePath(String value) { this.resourcePath = value; } public String getJarName() { return this.jarName; } public void setJarName(String value) { this.jarName = value; } public String getLibName() { return this.libName; } public void setLibName(String value) { this.libName = value; } public String getArchLibName() throws ArchNotSupportedException { return getName() + "-" + ArchName.getName(); } public String getDefaultLibName() throws ArchNotSupportedException { return System.getProperty(getPackageName() + ".libname", //e.g. javasigar-x86-linux "java" + getArchLibName()); } public File getNativeLibrary() { return this.nativeLibrary; } private String toResName(String name) { StringBuffer sb = new StringBuffer(name); for (int i=0; i < sb.length(); i++) { if (sb.charAt(i) == '.') { sb.setCharAt(i, '/'); } } return sb.toString(); } public static String getLibraryPrefix() { if (IS_WIN32 || IS_NETWARE) { return ""; } return "lib"; } public static String getLibraryExtension() { if (IS_WIN32) { return ".dll"; } if (IS_NETWARE) { return ".nlm"; } if (IS_DARWIN) { return ".dylib"; } if (IS_HPUX) { return ".sl"; } return ".so"; } public String getLibraryName() throws ArchNotSupportedException { String libName; if ((libName = getLibName()) == null) { libName = getDefaultLibName(); setLibName(libName); } String prefix = getLibraryPrefix(); String ext = getLibraryExtension(); return prefix + libName + ext; } public String getVersionedLibraryName() { if (this.version == null) { return null; } try { getLibraryName(); } catch (ArchNotSupportedException e) { return null; } String prefix = getLibraryPrefix(); String ext = getLibraryExtension(); return prefix + this.libName + '-' + this.version + ext; } private boolean isJarURL(URL url) { if (url == null) { return false; } String name = url.getFile(); String jarName = getJarName(); if (name.indexOf(jarName) != -1) { return true; } int ix = jarName.indexOf(".jar"); if (ix != -1) { //check for a versioned name-x.x.jar jarName = jarName.substring(0, ix) + "-"; //lastIndex else could match "sigar-bin/" ix = name.lastIndexOf(jarName); if (ix != -1) { jarName = name.substring(ix); ix = jarName.indexOf(".jar"); if (ix == -1) { return false; } this.version = jarName.substring(jarName.indexOf('-')+1, ix); jarName = jarName.substring(0, ix+4); setJarName(jarName); //for future reference return true; } else { return false; } } else { return false; } } public String findJarPath(String libName) throws ArchLoaderException { return findJarPath(libName, true); } private String findJarPath(String libName, boolean isRequired) throws ArchLoaderException { /* * native libraries should be installed along side * ${this.name}.jar, try to find where ${this.name}.jar * is on disk and use that path. */ if (getJarName() == null) { throw new ArchLoaderException("jarName is null"); } String path = getResourcePath(); ClassLoader loader = getClassLoader(); URL url = loader.getResource(path); if (!isJarURL(url)) { url = null; } if ((url == null) && (loader instanceof URLClassLoader)) { URL[] urls = ((URLClassLoader)loader).getURLs(); for (int i=0; i -1) { return arch + "-winnt"; } else if (name.equals("SunOS")) { if (arch.startsWith("sparcv") && is64()) { arch = "sparc64"; } return arch + "-solaris"; } else if (name.equals("HP-UX")) { if (arch.startsWith("IA64")) { arch = "ia64"; } else { arch = "pa"; if (is64()) { arch += "64"; } } if (version.indexOf("11") > -1) { return arch + "-hpux-11"; } } else if (name.equals("AIX")) { if (majorVersion.equals("6")) { //v5 binary is compatible with v6 majorVersion = "5"; } //arch == "ppc" on 32-bit, "ppc64" on 64-bit return arch + "-aix-" + majorVersion; } else if (name.equals("Mac OS X") || name.equals("Darwin")) { if (is64()) { return "universal64-macosx"; } else { return "universal-macosx"; } } else if (name.equals("FreeBSD")) { //none of the 4,5,6 major versions are binary compatible return arch + "-freebsd-" + majorVersion; } else if (name.equals("OpenBSD")) { return arch + "-openbsd-" + majorVersion; } else if (name.equals("NetBSD")) { return arch + "-netbsd-" + majorVersion; } else if (name.equals("OSF1")) { return "alpha-osf1-" + majorVersion; } else if (name.equals("NetWare")) { return "x86-netware-" + majorVersion; } String desc = arch + "-" + name + "-" + version; throw new ArchNotSupportedException("platform (" + desc + ") not supported"); } private ArchName () { } } hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/hyperic/jni/ArchNameTask.java000066400000000000000000000157541210132627500312100ustar00rootroot00000000000000/* * Copyright (c) 2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.jni; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.Reader; import java.util.Arrays; import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; public class ArchNameTask extends Task { public void execute() throws BuildException { String osArch = System.getProperty("os.arch"); String osVers = System.getProperty("os.version"); if (getProject().getProperty("jni.dmalloc") != null) { ArchName.useDmalloc = true; } String archName; try { archName = ArchName.getName(); } catch (ArchNotSupportedException e) { //ok: can still compile *.java System.out.println(e.getMessage()); return; } System.out.println(archName); getProject().setProperty("jni.libarch", archName); getProject().setProperty("jni.libpre", ArchLoader.getLibraryPrefix()); getProject().setProperty("jni.libext", ArchLoader.getLibraryExtension()); String compiler; if (ArchLoader.IS_WIN32) { compiler = "msvc"; } else if (ArchLoader.IS_HPUX) { compiler = "hp"; } else if (ArchLoader.IS_AIX) { compiler = "xlc_r"; } else { compiler = "gcc"; getProject().setProperty("jni.compiler.isgcc", "true"); } getProject().setProperty("jni.compiler", compiler); if (ArchName.is64()) { getProject().setProperty("jni.arch64", "true"); if (ArchLoader.IS_LINUX) { if (!osArch.equals("ia64")) { getProject().setProperty("jni.gccm", "-m64"); } } } else { if (ArchLoader.IS_LINUX && osArch.equals("s390")) { //gcc defaults to m64 on s390x platforms getProject().setProperty("jni.gccm", "-m31"); } } if (ArchLoader.IS_DARWIN) { //default to most recent SDK //MacOSX10.3.9.sdk, MacOSX10.4u.sdk, MacOSX10.5.sdk,etc. File[] sdks = new File("/Developer/SDKs").listFiles(new FileFilter() { public boolean accept(File file) { String name = file.getName(); return name.startsWith("MacOSX10.") && name.endsWith(".sdk"); } }); if (sdks != null) { Arrays.sort(sdks); String prop = "uni.sdk"; String sdk = getProject().getProperty(prop); String defaultMin = "10.3"; if (sdk == null) { int ix = sdks.length-1; sdk = sdks[ix].getPath(); if ((sdk.indexOf("10.6") != -1) && (ix > 0)) { sdk = sdks[ix-1].getPath(); //downgrade due to 64-bit ppc issues XXX defaultMin = "10.5"; } getProject().setProperty(prop, sdk); } String version = osVers.substring(0, 4); int minorVers = Integer.parseInt(osVers.substring(3,4)); boolean usingLatestSDK = (sdk.indexOf(version) != -1); System.out.println("Using SDK=" + sdk); if ((minorVers >= 6) && ArchName.is64() && usingLatestSDK) { //64-bit 10.6 sdk does not support ppc64 //switch from universal build to i386 only getProject().setProperty("jni.cc", "jni-cc"); getProject().setProperty("uni.arch", "i386"); System.out.println("Note: SDK version does not support ppc64"); } prop = "osx.min"; String min = getProject().getProperty(prop); if (min == null) { min = defaultMin; getProject().setProperty(prop, min); } System.out.println("Using -mmacosx-version-min=" + min); } } getProject().setProperty("jni.scmrev", getSourceRevision()); //jni.javahome required to find include/jni.h String home = getProject().getProperty("jni.javahome"); if (home == null) { home = System.getProperty("java.home"); } File dir = new File(home); if (!new File(dir, "include").exists()) { dir = dir.getParentFile(); //was /jre } getProject().setProperty("jni.javahome", dir.getPath()); } //XXX source rev stuff should be in another task private String readLine(String filename) { Reader reader = null; try { reader = new FileReader(filename); return new BufferedReader(reader).readLine(); } catch (Exception e) { } finally { if (reader != null) { try { reader.close(); } catch (Exception e) {} } } return null; } private String getSourceRevision() { final String exported = "exported"; String sha1 = getGitSourceRevision(); if (sha1 == null) { return exported; } else { return sha1; } } //same as: git rev-parse --short HEAD //same as: (cd .git && cat HEAD | awk '{print $2}' | xargs cat | cut -b 1-7) private String getGitSourceRevision() { String git = getProject().getProperty("jni.git"); if (git == null) { git = ".git"; } if (new File(git).exists()) { String head = readLine(git + "/HEAD"); if (head != null) { String sha1; final String refp = "ref: "; if (head.startsWith(refp)) { //branch String ref = head.substring(refp.length()).trim(); sha1 = readLine(git + "/" + ref); } else { //git checkout -f origin/branch-name (no branch) sha1 = head; } return sha1.substring(0, 7); } } return null; } } ArchNotSupportedException.java000066400000000000000000000015001210132627500337330ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/hyperic/jni/* * 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.jni; public class ArchNotSupportedException extends Exception { public ArchNotSupportedException() { super(); } public ArchNotSupportedException(String msg) { super(msg); } } hyperic-sigar-1.6.4+dfsg/bindings/java/hyperic_jni/src/org/hyperic/jni/CopyDependsTask.java000066400000000000000000000033171210132627500317370ustar00rootroot00000000000000/* * 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.jni; import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.Copy; public class CopyDependsTask extends Copy { private File depends; protected void validateAttributes() throws BuildException { super.validateAttributes(); if (this.depends == null) { throw new BuildException("missing depends attribute"); } } public void execute() throws BuildException { if (this.destFile.exists()) { String state; if (this.depends.lastModified() > this.destFile.lastModified()) { this.setOverwrite(true); state = "out of date"; } else { state = "up to date"; } log(this.destFile + " " + state + " with " + this.depends); } super.execute(); } public File getDepends() { return this.depends; } public void setDepends(String depends) { this.depends = new File(depends); } } hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/000077500000000000000000000000001210132627500215775ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/include/000077500000000000000000000000001210132627500232225ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/include/sigar.h000066400000000000000000000557221210132627500245130ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 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. */ #ifndef SIGAR_H #define SIGAR_H /* System Information Gatherer And Reporter */ #include #ifdef __cplusplus extern "C" { #endif #if defined(_LP64) || \ defined(__LP64__) || \ defined(__64BIT__) || \ defined(__powerpc64__) || \ defined(__osf__) #define SIGAR_64BIT #endif /* for printf sigar_uint64_t */ #ifdef SIGAR_64BIT # define SIGAR_F_U64 "%lu" #else # define SIGAR_F_U64 "%Lu" #endif #if defined(WIN32) typedef unsigned __int32 sigar_uint32_t; typedef unsigned __int64 sigar_uint64_t; typedef __int32 sigar_int32_t; typedef __int64 sigar_int64_t; #elif ULONG_MAX > 4294967295UL typedef unsigned int sigar_uint32_t; typedef unsigned long sigar_uint64_t; typedef int sigar_int32_t; typedef long sigar_int64_t; #else typedef unsigned int sigar_uint32_t; typedef unsigned long long sigar_uint64_t; typedef int sigar_int32_t; typedef long long sigar_int64_t; #endif #define SIGAR_FIELD_NOTIMPL -1 #define SIGAR_OK 0 #define SIGAR_START_ERROR 20000 #define SIGAR_ENOTIMPL (SIGAR_START_ERROR + 1) #define SIGAR_OS_START_ERROR (SIGAR_START_ERROR*2) #ifdef WIN32 # define SIGAR_ENOENT ERROR_FILE_NOT_FOUND # define SIGAR_EACCES ERROR_ACCESS_DENIED # define SIGAR_ENXIO ERROR_BAD_DRIVER_LEVEL #else # define SIGAR_ENOENT ENOENT # define SIGAR_EACCES EACCES # define SIGAR_ENXIO ENXIO #endif #ifdef WIN32 # define SIGAR_DECLARE(type) \ __declspec(dllexport) type __stdcall #else # define SIGAR_DECLARE(type) type #endif #if defined(PATH_MAX) # define SIGAR_PATH_MAX PATH_MAX #elif defined(MAXPATHLEN) # define SIGAR_PATH_MAX MAXPATHLEN #else # define SIGAR_PATH_MAX 4096 #endif #ifdef WIN32 typedef sigar_uint64_t sigar_pid_t; typedef unsigned long sigar_uid_t; typedef unsigned long sigar_gid_t; #else #include typedef pid_t sigar_pid_t; typedef uid_t sigar_uid_t; typedef gid_t sigar_gid_t; #endif typedef struct sigar_t sigar_t; SIGAR_DECLARE(int) sigar_open(sigar_t **sigar); SIGAR_DECLARE(int) sigar_close(sigar_t *sigar); SIGAR_DECLARE(sigar_pid_t) sigar_pid_get(sigar_t *sigar); SIGAR_DECLARE(int) sigar_proc_kill(sigar_pid_t pid, int signum); SIGAR_DECLARE(int) sigar_signum_get(char *name); SIGAR_DECLARE(char *) sigar_strerror(sigar_t *sigar, int err); /* system memory info */ typedef struct { sigar_uint64_t ram, total, used, free, actual_used, actual_free; double used_percent; double free_percent; } sigar_mem_t; SIGAR_DECLARE(int) sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem); typedef struct { sigar_uint64_t total, used, free, page_in, page_out; } sigar_swap_t; SIGAR_DECLARE(int) sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap); typedef struct { sigar_uint64_t user, sys, nice, idle, wait, irq, soft_irq, stolen, total; } sigar_cpu_t; SIGAR_DECLARE(int) sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu); typedef struct { unsigned long number; unsigned long size; sigar_cpu_t *data; } sigar_cpu_list_t; SIGAR_DECLARE(int) sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist); SIGAR_DECLARE(int) sigar_cpu_list_destroy(sigar_t *sigar, sigar_cpu_list_t *cpulist); typedef struct { char vendor[128]; char model[128]; int mhz; sigar_uint64_t cache_size; int total_sockets; int total_cores; int cores_per_socket; } sigar_cpu_info_t; typedef struct { unsigned long number; unsigned long size; sigar_cpu_info_t *data; } sigar_cpu_info_list_t; SIGAR_DECLARE(int) sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos); SIGAR_DECLARE(int) sigar_cpu_info_list_destroy(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos); typedef struct { double uptime; } sigar_uptime_t; SIGAR_DECLARE(int) sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime); typedef struct { double loadavg[3]; } sigar_loadavg_t; SIGAR_DECLARE(int) sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg); typedef struct { unsigned long number; unsigned long size; sigar_pid_t *data; } sigar_proc_list_t; typedef struct { /* RLIMIT_CPU */ sigar_uint64_t cpu_cur, cpu_max; /* RLIMIT_FSIZE */ sigar_uint64_t file_size_cur, file_size_max; /* PIPE_BUF */ sigar_uint64_t pipe_size_cur, pipe_size_max; /* RLIMIT_DATA */ sigar_uint64_t data_cur, data_max; /* RLIMIT_STACK */ sigar_uint64_t stack_cur, stack_max; /* RLIMIT_CORE */ sigar_uint64_t core_cur, core_max; /* RLIMIT_RSS */ sigar_uint64_t memory_cur, memory_max; /* RLIMIT_NPROC */ sigar_uint64_t processes_cur, processes_max; /* RLIMIT_NOFILE */ sigar_uint64_t open_files_cur, open_files_max; /* RLIMIT_AS */ sigar_uint64_t virtual_memory_cur, virtual_memory_max; } sigar_resource_limit_t; SIGAR_DECLARE(int) sigar_resource_limit_get(sigar_t *sigar, sigar_resource_limit_t *rlimit); SIGAR_DECLARE(int) sigar_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist); SIGAR_DECLARE(int) sigar_proc_list_destroy(sigar_t *sigar, sigar_proc_list_t *proclist); typedef struct { sigar_uint64_t total; sigar_uint64_t sleeping; sigar_uint64_t running; sigar_uint64_t zombie; sigar_uint64_t stopped; sigar_uint64_t idle; sigar_uint64_t threads; } sigar_proc_stat_t; SIGAR_DECLARE(int) sigar_proc_stat_get(sigar_t *sigar, sigar_proc_stat_t *procstat); typedef struct { sigar_uint64_t size, resident, share, minor_faults, major_faults, page_faults; } sigar_proc_mem_t; SIGAR_DECLARE(int) sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem); typedef struct { sigar_uid_t uid; sigar_gid_t gid; sigar_uid_t euid; sigar_gid_t egid; } sigar_proc_cred_t; SIGAR_DECLARE(int) sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred); #define SIGAR_CRED_NAME_MAX 512 typedef struct { char user[SIGAR_CRED_NAME_MAX]; char group[SIGAR_CRED_NAME_MAX]; } sigar_proc_cred_name_t; SIGAR_DECLARE(int) sigar_proc_cred_name_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_name_t *proccredname); typedef struct { sigar_uint64_t start_time, user, sys, total; } sigar_proc_time_t; SIGAR_DECLARE(int) sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime); typedef struct { /* must match sigar_proc_time_t fields */ sigar_uint64_t start_time, user, sys, total; sigar_uint64_t last_time; double percent; } sigar_proc_cpu_t; SIGAR_DECLARE(int) sigar_proc_cpu_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cpu_t *proccpu); #define SIGAR_PROC_STATE_SLEEP 'S' #define SIGAR_PROC_STATE_RUN 'R' #define SIGAR_PROC_STATE_STOP 'T' #define SIGAR_PROC_STATE_ZOMBIE 'Z' #define SIGAR_PROC_STATE_IDLE 'D' #define SIGAR_PROC_NAME_LEN 128 typedef struct { char name[SIGAR_PROC_NAME_LEN]; char state; sigar_pid_t ppid; int tty; int priority; int nice; int processor; sigar_uint64_t threads; } sigar_proc_state_t; SIGAR_DECLARE(int) sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate); typedef struct { unsigned long number; unsigned long size; char **data; } sigar_proc_args_t; SIGAR_DECLARE(int) sigar_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs); SIGAR_DECLARE(int) sigar_proc_args_destroy(sigar_t *sigar, sigar_proc_args_t *procargs); typedef struct { void *data; /* user data */ enum { SIGAR_PROC_ENV_ALL, SIGAR_PROC_ENV_KEY } type; /* used for SIGAR_PROC_ENV_KEY */ const char *key; int klen; int (*env_getter)(void *, const char *, int, char *, int); } sigar_proc_env_t; SIGAR_DECLARE(int) sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv); typedef struct { sigar_uint64_t total; /* XXX - which are files, sockets, etc. */ } sigar_proc_fd_t; SIGAR_DECLARE(int) sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd); typedef struct { char name[SIGAR_PATH_MAX+1]; char cwd[SIGAR_PATH_MAX+1]; char root[SIGAR_PATH_MAX+1]; } sigar_proc_exe_t; SIGAR_DECLARE(int) sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe); typedef struct { void *data; /* user data */ int (*module_getter)(void *, char *, int); } sigar_proc_modules_t; SIGAR_DECLARE(int) sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods); typedef struct { sigar_uint64_t user; sigar_uint64_t sys; sigar_uint64_t total; } sigar_thread_cpu_t; SIGAR_DECLARE(int) sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu); typedef enum { SIGAR_FSTYPE_UNKNOWN, SIGAR_FSTYPE_NONE, SIGAR_FSTYPE_LOCAL_DISK, SIGAR_FSTYPE_NETWORK, SIGAR_FSTYPE_RAM_DISK, SIGAR_FSTYPE_CDROM, SIGAR_FSTYPE_SWAP, SIGAR_FSTYPE_MAX } sigar_file_system_type_e; #define SIGAR_FS_NAME_LEN SIGAR_PATH_MAX #define SIGAR_FS_INFO_LEN 256 typedef struct { char dir_name[SIGAR_FS_NAME_LEN]; char dev_name[SIGAR_FS_NAME_LEN]; char type_name[SIGAR_FS_INFO_LEN]; /* e.g. "local" */ char sys_type_name[SIGAR_FS_INFO_LEN]; /* e.g. "ext3" */ char options[SIGAR_FS_INFO_LEN]; sigar_file_system_type_e type; unsigned long flags; } sigar_file_system_t; typedef struct { unsigned long number; unsigned long size; sigar_file_system_t *data; } sigar_file_system_list_t; SIGAR_DECLARE(int) sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist); SIGAR_DECLARE(int) sigar_file_system_list_destroy(sigar_t *sigar, sigar_file_system_list_t *fslist); typedef struct { sigar_uint64_t reads; sigar_uint64_t writes; sigar_uint64_t write_bytes; sigar_uint64_t read_bytes; sigar_uint64_t rtime; sigar_uint64_t wtime; sigar_uint64_t qtime; sigar_uint64_t time; sigar_uint64_t snaptime; double service_time; double queue; } sigar_disk_usage_t; /* XXX for sigar_file_system_usage_t compat */ #define disk_reads disk.reads #define disk_writes disk.writes #define disk_write_bytes disk.write_bytes #define disk_read_bytes disk.read_bytes #define disk_queue disk.queue #define disk_service_time disk.service_time typedef struct { sigar_disk_usage_t disk; double use_percent; sigar_uint64_t total; sigar_uint64_t free; sigar_uint64_t used; sigar_uint64_t avail; sigar_uint64_t files; sigar_uint64_t free_files; } sigar_file_system_usage_t; #undef SIGAR_DISK_USAGE_T SIGAR_DECLARE(int) sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage); SIGAR_DECLARE(int) sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *disk); SIGAR_DECLARE(int) sigar_file_system_ping(sigar_t *sigar, sigar_file_system_t *fs); typedef struct { enum { SIGAR_AF_UNSPEC, SIGAR_AF_INET, SIGAR_AF_INET6, SIGAR_AF_LINK } family; union { sigar_uint32_t in; sigar_uint32_t in6[4]; unsigned char mac[8]; } addr; } sigar_net_address_t; #define SIGAR_INET6_ADDRSTRLEN 46 #define SIGAR_MAXDOMAINNAMELEN 256 #define SIGAR_MAXHOSTNAMELEN 256 typedef struct { char default_gateway[SIGAR_INET6_ADDRSTRLEN]; char host_name[SIGAR_MAXHOSTNAMELEN]; char domain_name[SIGAR_MAXDOMAINNAMELEN]; char primary_dns[SIGAR_INET6_ADDRSTRLEN]; char secondary_dns[SIGAR_INET6_ADDRSTRLEN]; } sigar_net_info_t; SIGAR_DECLARE(int) sigar_net_info_get(sigar_t *sigar, sigar_net_info_t *netinfo); #define SIGAR_RTF_UP 0x1 #define SIGAR_RTF_GATEWAY 0x2 #define SIGAR_RTF_HOST 0x4 typedef struct { sigar_net_address_t destination; sigar_net_address_t gateway; sigar_net_address_t mask; sigar_uint64_t flags, refcnt, use, metric, mtu, window, irtt; char ifname[16]; } sigar_net_route_t; typedef struct { unsigned long number; unsigned long size; sigar_net_route_t *data; } sigar_net_route_list_t; SIGAR_DECLARE(int) sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist); SIGAR_DECLARE(int) sigar_net_route_list_destroy(sigar_t *sigar, sigar_net_route_list_t *routelist); /* * platforms define most of these "standard" flags, * but of course, with different values in some cases. */ #define SIGAR_IFF_UP 0x1 #define SIGAR_IFF_BROADCAST 0x2 #define SIGAR_IFF_DEBUG 0x4 #define SIGAR_IFF_LOOPBACK 0x8 #define SIGAR_IFF_POINTOPOINT 0x10 #define SIGAR_IFF_NOTRAILERS 0x20 #define SIGAR_IFF_RUNNING 0x40 #define SIGAR_IFF_NOARP 0x80 #define SIGAR_IFF_PROMISC 0x100 #define SIGAR_IFF_ALLMULTI 0x200 #define SIGAR_IFF_MULTICAST 0x800 #define SIGAR_IFF_SLAVE 0x1000 #define SIGAR_NULL_HWADDR "00:00:00:00:00:00" typedef struct { char name[16]; char type[64]; char description[256]; sigar_net_address_t hwaddr; sigar_net_address_t address; sigar_net_address_t destination; sigar_net_address_t broadcast; sigar_net_address_t netmask; sigar_uint64_t flags, mtu, metric; } sigar_net_interface_config_t; SIGAR_DECLARE(int) sigar_net_interface_config_get(sigar_t *sigar, const char *name, sigar_net_interface_config_t *ifconfig); SIGAR_DECLARE(int) sigar_net_interface_config_primary_get(sigar_t *sigar, sigar_net_interface_config_t *ifconfig); typedef struct { sigar_uint64_t /* received */ rx_packets, rx_bytes, rx_errors, rx_dropped, rx_overruns, rx_frame, /* transmitted */ tx_packets, tx_bytes, tx_errors, tx_dropped, tx_overruns, tx_collisions, tx_carrier, speed; } sigar_net_interface_stat_t; SIGAR_DECLARE(int) sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat); typedef struct { unsigned long number; unsigned long size; char **data; } sigar_net_interface_list_t; SIGAR_DECLARE(int) sigar_net_interface_list_get(sigar_t *sigar, sigar_net_interface_list_t *iflist); SIGAR_DECLARE(int) sigar_net_interface_list_destroy(sigar_t *sigar, sigar_net_interface_list_t *iflist); #define SIGAR_NETCONN_CLIENT 0x01 #define SIGAR_NETCONN_SERVER 0x02 #define SIGAR_NETCONN_TCP 0x10 #define SIGAR_NETCONN_UDP 0x20 #define SIGAR_NETCONN_RAW 0x40 #define SIGAR_NETCONN_UNIX 0x80 enum { SIGAR_TCP_ESTABLISHED = 1, SIGAR_TCP_SYN_SENT, SIGAR_TCP_SYN_RECV, SIGAR_TCP_FIN_WAIT1, SIGAR_TCP_FIN_WAIT2, SIGAR_TCP_TIME_WAIT, SIGAR_TCP_CLOSE, SIGAR_TCP_CLOSE_WAIT, SIGAR_TCP_LAST_ACK, SIGAR_TCP_LISTEN, SIGAR_TCP_CLOSING, SIGAR_TCP_IDLE, SIGAR_TCP_BOUND, SIGAR_TCP_UNKNOWN }; typedef struct { unsigned long local_port; sigar_net_address_t local_address; unsigned long remote_port; sigar_net_address_t remote_address; sigar_uid_t uid; unsigned long inode; int type; int state; unsigned long send_queue; unsigned long receive_queue; } sigar_net_connection_t; typedef struct { unsigned long number; unsigned long size; sigar_net_connection_t *data; } sigar_net_connection_list_t; SIGAR_DECLARE(int) sigar_net_connection_list_get(sigar_t *sigar, sigar_net_connection_list_t *connlist, int flags); SIGAR_DECLARE(int) sigar_net_connection_list_destroy(sigar_t *sigar, sigar_net_connection_list_t *connlist); typedef struct sigar_net_connection_walker_t sigar_net_connection_walker_t; /* alternative to sigar_net_connection_list_get */ struct sigar_net_connection_walker_t { sigar_t *sigar; int flags; void *data; /* user data */ int (*add_connection)(sigar_net_connection_walker_t *walker, sigar_net_connection_t *connection); }; SIGAR_DECLARE(int) sigar_net_connection_walk(sigar_net_connection_walker_t *walker); typedef struct { int tcp_states[SIGAR_TCP_UNKNOWN]; sigar_uint32_t tcp_inbound_total; sigar_uint32_t tcp_outbound_total; sigar_uint32_t all_inbound_total; sigar_uint32_t all_outbound_total; } sigar_net_stat_t; SIGAR_DECLARE(int) sigar_net_stat_get(sigar_t *sigar, sigar_net_stat_t *netstat, int flags); SIGAR_DECLARE(int) sigar_net_stat_port_get(sigar_t *sigar, sigar_net_stat_t *netstat, int flags, sigar_net_address_t *address, unsigned long port); /* TCP-MIB */ typedef struct { sigar_uint64_t active_opens; sigar_uint64_t passive_opens; sigar_uint64_t attempt_fails; sigar_uint64_t estab_resets; sigar_uint64_t curr_estab; sigar_uint64_t in_segs; sigar_uint64_t out_segs; sigar_uint64_t retrans_segs; sigar_uint64_t in_errs; sigar_uint64_t out_rsts; } sigar_tcp_t; SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp); typedef struct { sigar_uint64_t null; sigar_uint64_t getattr; sigar_uint64_t setattr; sigar_uint64_t root; sigar_uint64_t lookup; sigar_uint64_t readlink; sigar_uint64_t read; sigar_uint64_t writecache; sigar_uint64_t write; sigar_uint64_t create; sigar_uint64_t remove; sigar_uint64_t rename; sigar_uint64_t link; sigar_uint64_t symlink; sigar_uint64_t mkdir; sigar_uint64_t rmdir; sigar_uint64_t readdir; sigar_uint64_t fsstat; } sigar_nfs_v2_t; typedef sigar_nfs_v2_t sigar_nfs_client_v2_t; typedef sigar_nfs_v2_t sigar_nfs_server_v2_t; SIGAR_DECLARE(int) sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs); SIGAR_DECLARE(int) sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs); typedef struct { sigar_uint64_t null; sigar_uint64_t getattr; sigar_uint64_t setattr; sigar_uint64_t lookup; sigar_uint64_t access; sigar_uint64_t readlink; sigar_uint64_t read; sigar_uint64_t write; sigar_uint64_t create; sigar_uint64_t mkdir; sigar_uint64_t symlink; sigar_uint64_t mknod; sigar_uint64_t remove; sigar_uint64_t rmdir; sigar_uint64_t rename; sigar_uint64_t link; sigar_uint64_t readdir; sigar_uint64_t readdirplus; sigar_uint64_t fsstat; sigar_uint64_t fsinfo; sigar_uint64_t pathconf; sigar_uint64_t commit; } sigar_nfs_v3_t; typedef sigar_nfs_v3_t sigar_nfs_client_v3_t; typedef sigar_nfs_v3_t sigar_nfs_server_v3_t; SIGAR_DECLARE(int) sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs); SIGAR_DECLARE(int) sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs); SIGAR_DECLARE(int) sigar_net_listen_address_get(sigar_t *sigar, unsigned long port, sigar_net_address_t *address); typedef struct { char user[32]; char device[32]; char host[256]; sigar_uint64_t time; } sigar_who_t; typedef struct { unsigned long number; unsigned long size; sigar_who_t *data; } sigar_who_list_t; SIGAR_DECLARE(int) sigar_who_list_get(sigar_t *sigar, sigar_who_list_t *wholist); SIGAR_DECLARE(int) sigar_who_list_destroy(sigar_t *sigar, sigar_who_list_t *wholist); SIGAR_DECLARE(int) sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid); typedef struct { const char *build_date; const char *scm_revision; const char *version; const char *archname; const char *archlib; const char *binname; const char *description; int major, minor, maint, build; } sigar_version_t; SIGAR_DECLARE(sigar_version_t *) sigar_version_get(void); #define SIGAR_SYS_INFO_LEN SIGAR_MAXHOSTNAMELEN /* more than enough */ typedef struct { char name[SIGAR_SYS_INFO_LEN]; /* canonicalized sysname */ char version[SIGAR_SYS_INFO_LEN]; /* utsname.release */ char arch[SIGAR_SYS_INFO_LEN]; char machine[SIGAR_SYS_INFO_LEN]; char description[SIGAR_SYS_INFO_LEN]; char patch_level[SIGAR_SYS_INFO_LEN]; char vendor[SIGAR_SYS_INFO_LEN]; char vendor_version[SIGAR_SYS_INFO_LEN]; char vendor_name[SIGAR_SYS_INFO_LEN]; /* utsname.sysname */ char vendor_code_name[SIGAR_SYS_INFO_LEN]; } sigar_sys_info_t; SIGAR_DECLARE(int) sigar_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo); #define SIGAR_FQDN_LEN 512 SIGAR_DECLARE(int) sigar_fqdn_get(sigar_t *sigar, char *name, int namelen); SIGAR_DECLARE(int) sigar_rpc_ping(char *hostname, int protocol, unsigned long program, unsigned long version); SIGAR_DECLARE(char *) sigar_rpc_strerror(int err); SIGAR_DECLARE(char *) sigar_password_get(const char *prompt); #ifdef __cplusplus } #endif #endif hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/include/sigar_fileinfo.h000066400000000000000000000145451210132627500263640ustar00rootroot00000000000000/* * Copyright (c) 2004-2005 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. */ /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ #include "sigar.h" typedef enum { SIGAR_FILETYPE_NOFILE = 0, /**< no file type determined */ SIGAR_FILETYPE_REG, /**< a regular file */ SIGAR_FILETYPE_DIR, /**< a directory */ SIGAR_FILETYPE_CHR, /**< a character device */ SIGAR_FILETYPE_BLK, /**< a block device */ SIGAR_FILETYPE_PIPE, /**< a FIFO / pipe */ SIGAR_FILETYPE_LNK, /**< a symbolic link */ SIGAR_FILETYPE_SOCK, /**< a [unix domain] socket */ SIGAR_FILETYPE_UNKFILE /**< a file of some other unknown type */ } sigar_file_type_e; #define SIGAR_UREAD 0x0400 /**< Read by user */ #define SIGAR_UWRITE 0x0200 /**< Write by user */ #define SIGAR_UEXECUTE 0x0100 /**< Execute by user */ #define SIGAR_GREAD 0x0040 /**< Read by group */ #define SIGAR_GWRITE 0x0020 /**< Write by group */ #define SIGAR_GEXECUTE 0x0010 /**< Execute by group */ #define SIGAR_WREAD 0x0004 /**< Read by others */ #define SIGAR_WWRITE 0x0002 /**< Write by others */ #define SIGAR_WEXECUTE 0x0001 /**< Execute by others */ typedef struct { /** The access permissions of the file. Mimics Unix access rights. */ sigar_uint64_t permissions; sigar_file_type_e type; /** The user id that owns the file */ sigar_uid_t uid; /** The group id that owns the file */ sigar_gid_t gid; /** The inode of the file. */ sigar_uint64_t inode; /** The id of the device the file is on. */ sigar_uint64_t device; /** The number of hard links to the file. */ sigar_uint64_t nlink; /** The size of the file */ sigar_uint64_t size; /** The time the file was last accessed */ sigar_uint64_t atime; /** The time the file was last modified */ sigar_uint64_t mtime; /** The time the file was last changed */ sigar_uint64_t ctime; } sigar_file_attrs_t; typedef struct { sigar_uint64_t total; sigar_uint64_t files; sigar_uint64_t subdirs; sigar_uint64_t symlinks; sigar_uint64_t chrdevs; sigar_uint64_t blkdevs; sigar_uint64_t sockets; sigar_uint64_t disk_usage; } sigar_dir_stat_t; typedef sigar_dir_stat_t sigar_dir_usage_t; SIGAR_DECLARE(const char *) sigar_file_attrs_type_string_get(sigar_file_type_e type); SIGAR_DECLARE(int) sigar_file_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs); SIGAR_DECLARE(int) sigar_link_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs); SIGAR_DECLARE(int)sigar_file_attrs_mode_get(sigar_uint64_t permissions); SIGAR_DECLARE(char *) sigar_file_attrs_permissions_string_get(sigar_uint64_t permissions, char *str); SIGAR_DECLARE(int) sigar_dir_stat_get(sigar_t *sigar, const char *dir, sigar_dir_stat_t *dirstats); SIGAR_DECLARE(int) sigar_dir_usage_get(sigar_t *sigar, const char *dir, sigar_dir_usage_t *dirusage); hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/include/sigar_format.h000066400000000000000000000042001210132627500260440ustar00rootroot00000000000000/* * Copyright (c) 2007-2008 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. */ #ifndef SIGAR_FORMAT_H #define SIGAR_FORMAT_H typedef struct { double user; double sys; double nice; double idle; double wait; double irq; double soft_irq; double stolen; double combined; } sigar_cpu_perc_t; SIGAR_DECLARE(int) sigar_cpu_perc_calculate(sigar_cpu_t *prev, sigar_cpu_t *curr, sigar_cpu_perc_t *perc); SIGAR_DECLARE(int) sigar_uptime_string(sigar_t *sigar, sigar_uptime_t *uptime, char *buffer, int buflen); SIGAR_DECLARE(char *) sigar_format_size(sigar_uint64_t size, char *buf); SIGAR_DECLARE(int) sigar_net_address_equals(sigar_net_address_t *addr1, sigar_net_address_t *addr2); SIGAR_DECLARE(int) sigar_net_address_to_string(sigar_t *sigar, sigar_net_address_t *address, char *addr_str); SIGAR_DECLARE(sigar_uint32_t) sigar_net_address_hash(sigar_net_address_t *address); SIGAR_DECLARE(const char *)sigar_net_connection_type_get(int type); SIGAR_DECLARE(const char *)sigar_net_connection_state_get(int state); SIGAR_DECLARE(char *) sigar_net_interface_flags_to_string(sigar_uint64_t flags, char *buf); SIGAR_DECLARE(char *)sigar_net_services_name_get(sigar_t *sigar, int protocol, unsigned long port); #endif hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/include/sigar_log.h000066400000000000000000000043541210132627500253470ustar00rootroot00000000000000/* * Copyright (c) 2004, 2006 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. */ #ifndef SIGAR_LOG_H #define SIGAR_LOG_H #include #define SIGAR_LOG_FATAL 0 #define SIGAR_LOG_ERROR 1 #define SIGAR_LOG_WARN 2 #define SIGAR_LOG_INFO 3 #define SIGAR_LOG_DEBUG 4 #define SIGAR_LOG_TRACE 5 #define SIGAR_LOG_IS_FATAL(sigar) \ (sigar->log_level >= SIGAR_LOG_FATAL) #define SIGAR_LOG_IS_ERROR(sigar) \ (sigar->log_level >= SIGAR_LOG_ERROR) #define SIGAR_LOG_IS_WARN(sigar) \ (sigar->log_level >= SIGAR_LOG_WARN) #define SIGAR_LOG_IS_INFO(sigar) \ (sigar->log_level >= SIGAR_LOG_INFO) #define SIGAR_LOG_IS_DEBUG(sigar) \ (sigar->log_level >= SIGAR_LOG_DEBUG) #define SIGAR_LOG_IS_TRACE(sigar) \ (sigar->log_level >= SIGAR_LOG_TRACE) #define SIGAR_STRINGIFY(n) #n #define SIGAR_LOG_FILELINE \ __FILE__ ":" SIGAR_STRINGIFY(__LINE__) #if defined(__GNUC__) # if (__GNUC__ > 2) # define SIGAR_FUNC __func__ # else # define SIGAR_FUNC __FUNCTION__ # endif #else # define SIGAR_FUNC SIGAR_LOG_FILELINE #endif typedef void (*sigar_log_impl_t)(sigar_t *, void *, int, char *); SIGAR_DECLARE(void) sigar_log_printf(sigar_t *sigar, int level, const char *format, ...); SIGAR_DECLARE(void) sigar_log(sigar_t *sigar, int level, char *message); SIGAR_DECLARE(void) sigar_log_impl_set(sigar_t *sigar, void *data, sigar_log_impl_t impl); SIGAR_DECLARE(void) sigar_log_impl_file(sigar_t *sigar, void *data, int level, char *message); SIGAR_DECLARE(int) sigar_log_level_get(sigar_t *sigar); SIGAR_DECLARE(void) sigar_log_level_set(sigar_t *sigar, int level); #endif /* SIGAR_LOG_H */ hyperic-sigar-1.6.4+dfsg/bindings/java/sigar-bin/include/sigar_ptql.h000066400000000000000000000036461210132627500255510ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SIGAR_PTQL_H #define SIGAR_PTQL_H #define SIGAR_PTQL_MALFORMED_QUERY -1 typedef struct sigar_ptql_query_t sigar_ptql_query_t; #define SIGAR_PTQL_ERRMSG_SIZE 1024 typedef struct { char message[SIGAR_PTQL_ERRMSG_SIZE]; } sigar_ptql_error_t; typedef int (*sigar_ptql_re_impl_t)(void *, char *, char *); SIGAR_DECLARE(void) sigar_ptql_re_impl_set(sigar_t *sigar, void *data, sigar_ptql_re_impl_t impl); SIGAR_DECLARE(int) sigar_ptql_query_create(sigar_ptql_query_t **query, char *ptql, sigar_ptql_error_t *error); SIGAR_DECLARE(int) sigar_ptql_query_match(sigar_t *sigar, sigar_ptql_query_t *query, sigar_pid_t pid); SIGAR_DECLARE(int) sigar_ptql_query_destroy(sigar_ptql_query_t *query); SIGAR_DECLARE(int) sigar_ptql_query_find_process(sigar_t *sigar, sigar_ptql_query_t *query, sigar_pid_t *pid); SIGAR_DECLARE(int) sigar_ptql_query_find(sigar_t *sigar, sigar_ptql_query_t *query, sigar_proc_list_t *proclist); #endif /*SIGAR_PTQL_H*/ hyperic-sigar-1.6.4+dfsg/bindings/java/src/000077500000000000000000000000001210132627500205135ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/000077500000000000000000000000001210132627500212735ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/javasigar.c000066400000000000000000001254611210132627500234170ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 #include "sigar.h" #include "sigar_fileinfo.h" #include "sigar_log.h" #include "sigar_private.h" #include "sigar_ptql.h" #include "sigar_util.h" #include "sigar_os.h" #include "sigar_format.h" #include #ifdef WIN32 #include #else #include #include #include #include # ifdef __FreeBSD__ # include # if (__FreeBSD_version < 700000) # include # endif # else # include # endif #include #endif #include "javasigar_generated.h" #include "javasigar.h" #ifdef SIGAR_64BIT #define SIGAR_POINTER_LONG #endif typedef struct { jclass classref; jfieldID *ids; } jsigar_field_cache_t; typedef struct { JNIEnv *env; jobject logger; sigar_t *sigar; jsigar_field_cache_t *fields[JSIGAR_FIELDS_MAX]; int open_status; jthrowable not_impl; } jni_sigar_t; #define dSIGAR_GET \ jni_sigar_t *jsigar = sigar_get_jpointer(env, sigar_obj); \ sigar_t *sigar #define dSIGAR_VOID \ dSIGAR_GET; \ if (!jsigar) return; \ sigar = jsigar->sigar; \ jsigar->env = env #define dSIGAR(val) \ dSIGAR_GET; \ if (!jsigar) return val; \ sigar = jsigar->sigar; \ jsigar->env = env JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { #ifdef DMALLOC char *options = getenv("DMALLOC_OPTIONS"); if (!options) { options = "debug=0x4f47d03," "lockon=20," "log=dmalloc-sigar.log"; } dmalloc_debug_setup(options); #endif return JNI_VERSION_1_2; } JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { #ifdef DMALLOC dmalloc_shutdown(); #endif } static void sigar_throw_exception(JNIEnv *env, char *msg) { jclass errorClass = SIGAR_FIND_CLASS("SigarException"); JENV->ThrowNew(env, errorClass, msg); } #define SIGAR_NOTIMPL_EX "SigarNotImplementedException" static void sigar_throw_notimpl(JNIEnv *env, char *msg) { jclass errorClass = SIGAR_FIND_CLASS(SIGAR_NOTIMPL_EX); JENV->ThrowNew(env, errorClass, msg); } static void sigar_throw_ptql_malformed(JNIEnv *env, char *msg) { jclass errorClass = SIGAR_FIND_CLASS("ptql/MalformedQueryException"); JENV->ThrowNew(env, errorClass, msg); } static void sigar_throw_error(JNIEnv *env, jni_sigar_t *jsigar, int err) { jclass errorClass; int err_type = err; /* * support: * #define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES) * this allows for os impl specific message * (e.g. Failed to open /dev/kmem) but still map to the proper * Sigar*Exception */ if (err_type > SIGAR_OS_START_ERROR) { err_type -= SIGAR_OS_START_ERROR; } switch (err_type) { case SIGAR_ENOENT: errorClass = SIGAR_FIND_CLASS("SigarFileNotFoundException"); break; case SIGAR_EACCES: errorClass = SIGAR_FIND_CLASS("SigarPermissionDeniedException"); break; case SIGAR_ENOTIMPL: if (jsigar->not_impl == NULL) { jfieldID id; jthrowable not_impl; errorClass = SIGAR_FIND_CLASS(SIGAR_NOTIMPL_EX); id = JENV->GetStaticFieldID(env, errorClass, "INSTANCE", SIGAR_CLASS_SIG(SIGAR_NOTIMPL_EX)); not_impl = JENV->GetStaticObjectField(env, errorClass, id); jsigar->not_impl = JENV->NewGlobalRef(env, not_impl); } JENV->Throw(env, jsigar->not_impl); return; default: errorClass = SIGAR_FIND_CLASS("SigarException"); break; } JENV->ThrowNew(env, errorClass, sigar_strerror(jsigar->sigar, err)); } static void *sigar_get_pointer(JNIEnv *env, jobject obj) { jfieldID pointer_field; jclass cls = JENV->GetObjectClass(env, obj); #ifdef SIGAR_POINTER_LONG pointer_field = JENV->GetFieldID(env, cls, "longSigarWrapper", "J"); return (void *)JENV->GetLongField(env, obj, pointer_field); #else pointer_field = JENV->GetFieldID(env, cls, "sigarWrapper", "I"); return (void *)JENV->GetIntField(env, obj, pointer_field); #endif } static jni_sigar_t *sigar_get_jpointer(JNIEnv *env, jobject obj) { jni_sigar_t *jsigar = (jni_sigar_t *)sigar_get_pointer(env, obj); if (!jsigar) { sigar_throw_exception(env, "sigar has been closed"); return NULL; } if (jsigar->open_status != SIGAR_OK) { sigar_throw_error(env, jsigar, jsigar->open_status); return NULL; } return jsigar; } static void sigar_set_pointer(JNIEnv *env, jobject obj, const void *ptr) { jfieldID pointer_field; jclass cls = JENV->GetObjectClass(env, obj); #ifdef SIGAR_POINTER_LONG pointer_field = JENV->GetFieldID(env, cls, "longSigarWrapper", "J"); JENV->SetLongField(env, obj, pointer_field, (jlong)ptr); #else pointer_field = JENV->GetFieldID(env, cls, "sigarWrapper", "I"); JENV->SetIntField(env, obj, pointer_field, (int)ptr); #endif } /* for jni/win32 */ sigar_t *jsigar_get_sigar(JNIEnv *env, jobject sigar_obj) { dSIGAR(NULL); return jsigar->sigar; } int jsigar_list_init(JNIEnv *env, jsigar_list_t *obj) { jclass listclass = JENV->FindClass(env, "java/util/ArrayList"); jmethodID listid = JENV->GetMethodID(env, listclass, "", "()V"); jmethodID addid = JENV->GetMethodID(env, listclass, "add", "(Ljava/lang/Object;)" "Z"); obj->env = env; obj->obj = JENV->NewObject(env, listclass, listid); obj->id = addid; return JENV->ExceptionCheck(env) ? !SIGAR_OK : SIGAR_OK; } int jsigar_list_add(void *data, char *value, int len) { jsigar_list_t *obj = (jsigar_list_t *)data; JNIEnv *env = obj->env; JENV->CallBooleanMethod(env, obj->obj, obj->id, JENV->NewStringUTF(env, value)); return JENV->ExceptionCheck(env) ? !SIGAR_OK : SIGAR_OK; } JNIEXPORT jstring SIGAR_JNIx(formatSize) (JNIEnv *env, jclass cls, jlong size) { char buf[56]; sigar_format_size(size, buf); return JENV->NewStringUTF(env, buf); } JNIEXPORT jstring SIGAR_JNIx(getNativeVersion) (JNIEnv *env, jclass cls) { sigar_version_t *version = sigar_version_get(); return JENV->NewStringUTF(env, version->version); } JNIEXPORT jstring SIGAR_JNIx(getNativeBuildDate) (JNIEnv *env, jclass cls) { sigar_version_t *version = sigar_version_get(); return JENV->NewStringUTF(env, version->build_date); } JNIEXPORT jstring SIGAR_JNIx(getNativeScmRevision) (JNIEnv *env, jclass cls) { sigar_version_t *version = sigar_version_get(); return JENV->NewStringUTF(env, version->scm_revision); } JNIEXPORT void SIGAR_JNIx(open) (JNIEnv *env, jobject obj) { jni_sigar_t *jsigar = malloc(sizeof(*jsigar)); memset(jsigar, '\0', sizeof(*jsigar)); sigar_set_pointer(env, obj, jsigar); /* this method is called by the constructor. * if != SIGAR_OK save status and throw exception * when methods are invoked (see sigar_get_pointer). */ if ((jsigar->open_status = sigar_open(&jsigar->sigar)) != SIGAR_OK) { sigar_throw_error(env, jsigar, jsigar->open_status); return; } } JNIEXPORT jint SIGAR_JNIx(nativeClose) (JNIEnv *env, jobject sigar_obj) { jint status; int i; dSIGAR(0); /* only place it is possible this would be something other than * SIGAR_OK is on win32 if RegCloseKey fails, which i don't think * is possible either. */ status = sigar_close(sigar); if (jsigar->logger != NULL) { JENV->DeleteGlobalRef(env, jsigar->logger); } if (jsigar->not_impl != NULL) { JENV->DeleteGlobalRef(env, jsigar->not_impl); } for (i=0; ifields[i]) { JENV->DeleteGlobalRef(env, jsigar->fields[i]->classref); free(jsigar->fields[i]->ids); free(jsigar->fields[i]); } } free(jsigar); sigar_set_pointer(env, sigar_obj, NULL); return status; } JNIEXPORT jlong SIGAR_JNIx(getPid) (JNIEnv *env, jobject sigar_obj) { dSIGAR(0); return sigar_pid_get(sigar); } JNIEXPORT void SIGAR_JNIx(kill) (JNIEnv *env, jobject sigar_obj, jlong pid, jint signum) { int status; dSIGAR_VOID; if ((status = sigar_proc_kill(pid, signum)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); } } JNIEXPORT jint SIGAR_JNIx(getSigNum) (JNIEnv *env, jclass cls_obj, jstring jname) { jboolean is_copy; const char *name; int num; name = JENV->GetStringUTFChars(env, jname, &is_copy); num = sigar_signum_get((char *)name); if (is_copy) { JENV->ReleaseStringUTFChars(env, jname, name); } return num; } #define SetStringField(env, obj, fieldID, val) \ SetObjectField(env, obj, fieldID, JENV->NewStringUTF(env, val)) static jstring jnet_address_to_string(JNIEnv *env, sigar_t *sigar, sigar_net_address_t *val) { char addr_str[SIGAR_INET6_ADDRSTRLEN]; sigar_net_address_to_string(sigar, val, addr_str); return JENV->NewStringUTF(env, addr_str); } #define SetNetAddressField(env, obj, fieldID, val) \ SetObjectField(env, obj, fieldID, jnet_address_to_string(env, sigar, &val)) #include "javasigar_generated.c" enum { FS_FIELD_DIRNAME, FS_FIELD_DEVNAME, FS_FIELD_SYS_TYPENAME, FS_FIELD_OPTIONS, FS_FIELD_TYPE, FS_FIELD_TYPENAME, FS_FIELD_MAX }; #define STRING_SIG "Ljava/lang/String;" JNIEXPORT jobjectArray SIGAR_JNIx(getFileSystemListNative) (JNIEnv *env, jobject sigar_obj) { int status; unsigned int i; sigar_file_system_list_t fslist; jobjectArray fsarray; jfieldID ids[FS_FIELD_MAX]; jclass nfs_cls=NULL, cls = SIGAR_FIND_CLASS("FileSystem"); dSIGAR(NULL); if ((status = sigar_file_system_list_get(sigar, &fslist)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } ids[FS_FIELD_DIRNAME] = JENV->GetFieldID(env, cls, "dirName", STRING_SIG); ids[FS_FIELD_DEVNAME] = JENV->GetFieldID(env, cls, "devName", STRING_SIG); ids[FS_FIELD_TYPENAME] = JENV->GetFieldID(env, cls, "typeName", STRING_SIG); ids[FS_FIELD_SYS_TYPENAME] = JENV->GetFieldID(env, cls, "sysTypeName", STRING_SIG); ids[FS_FIELD_OPTIONS] = JENV->GetFieldID(env, cls, "options", STRING_SIG); ids[FS_FIELD_TYPE] = JENV->GetFieldID(env, cls, "type", "I"); fsarray = JENV->NewObjectArray(env, fslist.number, cls, 0); SIGAR_CHEX; for (i=0; itype == SIGAR_FSTYPE_NETWORK) && (strcmp(fs->sys_type_name, "nfs") == 0) && strstr(fs->dev_name, ":/")) { if (!nfs_cls) { nfs_cls = SIGAR_FIND_CLASS("NfsFileSystem"); } obj_cls = nfs_cls; } else { obj_cls = cls; } #endif fsobj = JENV->AllocObject(env, obj_cls); SIGAR_CHEX; JENV->SetStringField(env, fsobj, ids[FS_FIELD_DIRNAME], fs->dir_name); JENV->SetStringField(env, fsobj, ids[FS_FIELD_DEVNAME], fs->dev_name); JENV->SetStringField(env, fsobj, ids[FS_FIELD_SYS_TYPENAME], fs->sys_type_name); JENV->SetStringField(env, fsobj, ids[FS_FIELD_OPTIONS], fs->options); JENV->SetStringField(env, fsobj, ids[FS_FIELD_TYPENAME], fs->type_name); JENV->SetIntField(env, fsobj, ids[FS_FIELD_TYPE], fs->type); JENV->SetObjectArrayElement(env, fsarray, i, fsobj); SIGAR_CHEX; } sigar_file_system_list_destroy(sigar, &fslist); return fsarray; } JNIEXPORT jint SIGAR_JNI(RPC_ping) (JNIEnv *env, jclass cls_obj, jstring jhostname, jint protocol, jlong program, jlong version) { #ifdef WIN32 return JNI_FALSE; /*XXX*/ #else jboolean is_copy; const char *hostname; int status; if (!jhostname) { return 13; /* RPC_UNKNOWNHOST */ } hostname = JENV->GetStringUTFChars(env, jhostname, &is_copy); status = sigar_rpc_ping((char *)hostname, protocol, program, version); if (is_copy) { JENV->ReleaseStringUTFChars(env, jhostname, hostname); } return status; #endif } JNIEXPORT jstring SIGAR_JNI(RPC_strerror) (JNIEnv *env, jclass cls_obj, jint err) { #ifdef WIN32 return NULL; #else return JENV->NewStringUTF(env, sigar_rpc_strerror(err)); #endif } JNIEXPORT jobjectArray SIGAR_JNIx(getCpuInfoList) (JNIEnv *env, jobject sigar_obj) { int status; unsigned int i; sigar_cpu_info_list_t cpu_infos; jobjectArray cpuarray; jclass cls = SIGAR_FIND_CLASS("CpuInfo"); dSIGAR(NULL); if ((status = sigar_cpu_info_list_get(sigar, &cpu_infos)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } JAVA_SIGAR_INIT_FIELDS_CPUINFO(cls); cpuarray = JENV->NewObjectArray(env, cpu_infos.number, cls, 0); SIGAR_CHEX; for (i=0; iAllocObject(env, cls); SIGAR_CHEX; JAVA_SIGAR_SET_FIELDS_CPUINFO(cls, info_obj, cpu_infos.data[i]); JENV->SetObjectArrayElement(env, cpuarray, i, info_obj); SIGAR_CHEX; } sigar_cpu_info_list_destroy(sigar, &cpu_infos); return cpuarray; } JNIEXPORT jobjectArray SIGAR_JNIx(getCpuListNative) (JNIEnv *env, jobject sigar_obj) { int status; unsigned int i; sigar_cpu_list_t cpulist; jobjectArray cpuarray; jclass cls = SIGAR_FIND_CLASS("Cpu"); dSIGAR(NULL); if ((status = sigar_cpu_list_get(sigar, &cpulist)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } JAVA_SIGAR_INIT_FIELDS_CPU(cls); cpuarray = JENV->NewObjectArray(env, cpulist.number, cls, 0); SIGAR_CHEX; for (i=0; iAllocObject(env, cls); SIGAR_CHEX; JAVA_SIGAR_SET_FIELDS_CPU(cls, info_obj, cpulist.data[i]); JENV->SetObjectArrayElement(env, cpuarray, i, info_obj); SIGAR_CHEX; } sigar_cpu_list_destroy(sigar, &cpulist); return cpuarray; } JNIEXPORT void SIGAR_JNI(CpuPerc_gather) (JNIEnv *env, jobject jperc, jobject sigar_obj, jobject jprev, jobject jcurr) { sigar_cpu_t prev, curr; sigar_cpu_perc_t perc; dSIGAR_VOID; JAVA_SIGAR_GET_FIELDS_CPU(jprev, prev); JAVA_SIGAR_GET_FIELDS_CPU(jcurr, curr); sigar_cpu_perc_calculate(&prev, &curr, &perc); JAVA_SIGAR_INIT_FIELDS_CPUPERC(JENV->GetObjectClass(env, jperc)); JAVA_SIGAR_SET_FIELDS_CPUPERC(NULL, jperc, perc); } JNIEXPORT jlongArray SIGAR_JNIx(getProcList) (JNIEnv *env, jobject sigar_obj) { int status; jlongArray procarray; sigar_proc_list_t proclist; jlong *pids = NULL; dSIGAR(NULL); if ((status = sigar_proc_list_get(sigar, &proclist)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } procarray = JENV->NewLongArray(env, proclist.number); SIGAR_CHEX; if (sizeof(jlong) == sizeof(sigar_pid_t)) { pids = (jlong *)proclist.data; } else { unsigned int i; pids = (jlong *)malloc(sizeof(jlong) * proclist.number); for (i=0; iSetLongArrayRegion(env, procarray, 0, proclist.number, pids); if (pids != (jlong *)proclist.data) { free(pids); } sigar_proc_list_destroy(sigar, &proclist); return procarray; } JNIEXPORT jobjectArray SIGAR_JNIx(getProcArgs) (JNIEnv *env, jobject sigar_obj, jlong pid) { int status; unsigned int i; sigar_proc_args_t procargs; jobjectArray argsarray; jclass stringclass = JENV->FindClass(env, "java/lang/String"); dSIGAR(NULL); if ((status = sigar_proc_args_get(sigar, pid, &procargs)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } argsarray = JENV->NewObjectArray(env, procargs.number, stringclass, 0); SIGAR_CHEX; for (i=0; iNewStringUTF(env, procargs.data[i]); JENV->SetObjectArrayElement(env, argsarray, i, s); SIGAR_CHEX; } sigar_proc_args_destroy(sigar, &procargs); return argsarray; } typedef struct { JNIEnv *env; jobject map; jmethodID id; } jni_env_put_t; static int jni_env_getall(void *data, const char *key, int klen, char *val, int vlen) { jni_env_put_t *put = (jni_env_put_t *)data; JNIEnv *env = put->env; JENV->CallObjectMethod(env, put->map, put->id, JENV->NewStringUTF(env, key), JENV->NewStringUTF(env, val)); return JENV->ExceptionCheck(env) ? !SIGAR_OK : SIGAR_OK; } #define MAP_PUT_SIG \ "(Ljava/lang/Object;Ljava/lang/Object;)" \ "Ljava/lang/Object;" JNIEXPORT jobject SIGAR_JNI(ProcEnv_getAll) (JNIEnv *env, jobject cls, jobject sigar_obj, jlong pid) { int status; sigar_proc_env_t procenv; jobject hashmap; jni_env_put_t put; jclass mapclass = JENV->FindClass(env, "java/util/HashMap"); jmethodID mapid = JENV->GetMethodID(env, mapclass, "", "()V"); jmethodID putid = JENV->GetMethodID(env, mapclass, "put", MAP_PUT_SIG); dSIGAR(NULL); hashmap = JENV->NewObject(env, mapclass, mapid); SIGAR_CHEX; put.env = env; put.id = putid; put.map = hashmap; procenv.type = SIGAR_PROC_ENV_ALL; procenv.env_getter = jni_env_getall; procenv.data = &put; if ((status = sigar_proc_env_get(sigar, pid, &procenv)) != SIGAR_OK) { JENV->DeleteLocalRef(env, hashmap); sigar_throw_error(env, jsigar, status); return NULL; } return hashmap; } typedef struct { JNIEnv *env; const char *key; int klen; jstring val; } jni_env_get_t; static int jni_env_getvalue(void *data, const char *key, int klen, char *val, int vlen) { jni_env_get_t *get = (jni_env_get_t *)data; JNIEnv *env = get->env; if ((get->klen == klen) && (strcmp(get->key, key) == 0)) { get->val = JENV->NewStringUTF(env, val); return !SIGAR_OK; /* foundit; stop iterating */ } return SIGAR_OK; } JNIEXPORT jstring SIGAR_JNI(ProcEnv_getValue) (JNIEnv *env, jobject cls, jobject sigar_obj, jlong pid, jstring key) { int status; sigar_proc_env_t procenv; jni_env_get_t get; dSIGAR(NULL); get.env = env; get.key = JENV->GetStringUTFChars(env, key, 0); get.klen = JENV->GetStringUTFLength(env, key); get.val = NULL; procenv.type = SIGAR_PROC_ENV_KEY; procenv.key = get.key; procenv.klen = get.klen; procenv.env_getter = jni_env_getvalue; procenv.data = &get; if ((status = sigar_proc_env_get(sigar, pid, &procenv)) != SIGAR_OK) { JENV->ReleaseStringUTFChars(env, key, get.key); sigar_throw_error(env, jsigar, status); return NULL; } JENV->ReleaseStringUTFChars(env, key, get.key); return get.val; } JNIEXPORT jobject SIGAR_JNIx(getProcModulesNative) (JNIEnv *env, jobject sigar_obj, jlong pid) { int status; sigar_proc_modules_t procmods; jsigar_list_t obj; dSIGAR(NULL); if (jsigar_list_init(env, &obj) != SIGAR_OK) { return NULL; /* Exception thrown */ } procmods.module_getter = jsigar_list_add; procmods.data = &obj; if ((status = sigar_proc_modules_get(sigar, pid, &procmods)) != SIGAR_OK) { JENV->DeleteLocalRef(env, obj.obj); sigar_throw_error(env, jsigar, status); return NULL; } return obj.obj; } JNIEXPORT jdoubleArray SIGAR_JNIx(getLoadAverage) (JNIEnv *env, jobject sigar_obj) { int status; jlongArray avgarray; sigar_loadavg_t loadavg; dSIGAR(NULL); if ((status = sigar_loadavg_get(sigar, &loadavg)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } avgarray = JENV->NewDoubleArray(env, 3); SIGAR_CHEX; JENV->SetDoubleArrayRegion(env, avgarray, 0, 3, loadavg.loadavg); return avgarray; } JNIEXPORT jobjectArray SIGAR_JNIx(getNetRouteList) (JNIEnv *env, jobject sigar_obj) { int status; unsigned int i; jarray routearray; jclass cls = SIGAR_FIND_CLASS("NetRoute"); sigar_net_route_list_t routelist; dSIGAR(NULL); if ((status = sigar_net_route_list_get(sigar, &routelist)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } JAVA_SIGAR_INIT_FIELDS_NETROUTE(cls); routearray = JENV->NewObjectArray(env, routelist.number, cls, 0); SIGAR_CHEX; for (i=0; iAllocObject(env, cls); SIGAR_CHEX; JAVA_SIGAR_SET_FIELDS_NETROUTE(cls, obj, routelist.data[i]); JENV->SetObjectArrayElement(env, routearray, i, obj); SIGAR_CHEX; } sigar_net_route_list_destroy(sigar, &routelist); return routearray; } JNIEXPORT jstring SIGAR_JNI(NetFlags_getIfFlagsString) (JNIEnv *env, jclass cls, jlong flags) { char buf[1024]; sigar_net_interface_flags_to_string(flags, buf); return JENV->NewStringUTF(env, buf); } JNIEXPORT jobjectArray SIGAR_JNIx(getNetConnectionList) (JNIEnv *env, jobject sigar_obj, jint flags) { int status; unsigned int i; jarray connarray; jclass cls = SIGAR_FIND_CLASS("NetConnection"); sigar_net_connection_list_t connlist; dSIGAR(NULL); status = sigar_net_connection_list_get(sigar, &connlist, flags); if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } JAVA_SIGAR_INIT_FIELDS_NETCONNECTION(cls); connarray = JENV->NewObjectArray(env, connlist.number, cls, 0); SIGAR_CHEX; for (i=0; iAllocObject(env, cls); SIGAR_CHEX; JAVA_SIGAR_SET_FIELDS_NETCONNECTION(cls, obj, connlist.data[i]); JENV->SetObjectArrayElement(env, connarray, i, obj); SIGAR_CHEX; } sigar_net_connection_list_destroy(sigar, &connlist); return connarray; } static int jbyteArray_to_sigar_net_address(JNIEnv *env, jbyteArray jaddress, sigar_net_address_t *address) { jsize len = JENV->GetArrayLength(env, jaddress); JENV->GetByteArrayRegion(env, jaddress, 0, len, (jbyte *)&address->addr.in6); switch (len) { case 4: address->family = SIGAR_AF_INET; break; case 4*4: address->family = SIGAR_AF_INET6; break; default: return EINVAL; } return SIGAR_OK; } JNIEXPORT void SIGAR_JNI(NetStat_stat) (JNIEnv *env, jobject obj, jobject sigar_obj, jint flags, jbyteArray jaddress, jlong port) { int status; sigar_net_stat_t netstat; jclass cls; jfieldID id; jintArray states; jint tcp_states[SIGAR_TCP_UNKNOWN]; sigar_net_address_t address; jboolean has_port = (port != -1); dSIGAR_VOID; if (has_port) { status = jbyteArray_to_sigar_net_address(env, jaddress, &address); if (status == SIGAR_OK) { status = sigar_net_stat_port_get(sigar, &netstat, flags, &address, port); } } else { status = sigar_net_stat_get(sigar, &netstat, flags); } if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return; } cls = JENV->GetObjectClass(env, obj); JAVA_SIGAR_INIT_FIELDS_NETSTAT(cls); JAVA_SIGAR_SET_FIELDS_NETSTAT(cls, obj, netstat); if (sizeof(tcp_states[0]) == sizeof(netstat.tcp_states[0])) { memcpy(&tcp_states[0], &netstat.tcp_states[0], sizeof(netstat.tcp_states)); } else { int i; for (i=0; iNewIntArray(env, SIGAR_TCP_UNKNOWN); if (JENV->ExceptionCheck(env)) { return; } JENV->SetIntArrayRegion(env, states, 0, SIGAR_TCP_UNKNOWN, tcp_states); id = JENV->GetFieldID(env, cls, "tcpStates", "[I"); JENV->SetObjectField(env, obj, id, states); } JNIEXPORT jstring SIGAR_JNIx(getNetListenAddress) (JNIEnv *env, jobject sigar_obj, jlong port) { int status; sigar_net_address_t address; dSIGAR(NULL); status = sigar_net_listen_address_get(sigar, port, &address); if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } return jnet_address_to_string(env, sigar, &address); } JNIEXPORT jstring SIGAR_JNIx(getNetServicesName) (JNIEnv *env, jobject sigar_obj, jint protocol, jlong port) { char *name; dSIGAR(NULL); if ((name = sigar_net_services_name_get(sigar, protocol, port))) { return JENV->NewStringUTF(env, name); } else { return NULL; } } JNIEXPORT jstring SIGAR_JNI(NetConnection_getTypeString) (JNIEnv *env, jobject obj) { jclass cls = JENV->GetObjectClass(env, obj); jfieldID field = JENV->GetFieldID(env, cls, "type", "I"); jint type = JENV->GetIntField(env, obj, field); return JENV->NewStringUTF(env, sigar_net_connection_type_get(type)); } JNIEXPORT jstring SIGAR_JNI(NetConnection_getStateString) (JNIEnv *env, jobject cls, jint state) { return JENV->NewStringUTF(env, sigar_net_connection_state_get(state)); } JNIEXPORT jobjectArray SIGAR_JNIx(getWhoList) (JNIEnv *env, jobject sigar_obj) { int status; unsigned int i; sigar_who_list_t wholist; jobjectArray whoarray; jclass cls = SIGAR_FIND_CLASS("Who"); dSIGAR(NULL); if ((status = sigar_who_list_get(sigar, &wholist)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } JAVA_SIGAR_INIT_FIELDS_WHO(cls); whoarray = JENV->NewObjectArray(env, wholist.number, cls, 0); SIGAR_CHEX; for (i=0; iAllocObject(env, cls); SIGAR_CHEX; JAVA_SIGAR_SET_FIELDS_WHO(cls, info_obj, wholist.data[i]); JENV->SetObjectArrayElement(env, whoarray, i, info_obj); SIGAR_CHEX; } sigar_who_list_destroy(sigar, &wholist); return whoarray; } /* XXX perhaps it would be better to duplicate these strings * in java land as static final so we dont create a new String * everytime. */ JNIEXPORT jstring SIGAR_JNI(FileInfo_getTypeString) (JNIEnv *env, jclass cls, jint type) { return JENV->NewStringUTF(env, sigar_file_attrs_type_string_get(type)); } JNIEXPORT jstring SIGAR_JNI(FileInfo_getPermissionsString) (JNIEnv *env, jclass cls, jlong perms) { char str[24]; return JENV->NewStringUTF(env, sigar_file_attrs_permissions_string_get(perms, str)); } JNIEXPORT jint SIGAR_JNI(FileInfo_getMode) (JNIEnv *env, jclass cls, jlong perms) { return sigar_file_attrs_mode_get(perms); } /* * copy of the generated FileAttrs_gather function * but we call the lstat wrapper instead. */ JNIEXPORT void SIGAR_JNI(FileInfo_gatherLink) (JNIEnv *env, jobject obj, jobject sigar_obj, jstring name) { sigar_file_attrs_t s; int status; jclass cls = JENV->GetObjectClass(env, obj); const char *utf; dSIGAR_VOID; utf = JENV->GetStringUTFChars(env, name, 0); status = sigar_link_attrs_get(sigar, utf, &s); JENV->ReleaseStringUTFChars(env, name, utf); if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return; } JAVA_SIGAR_INIT_FIELDS_FILEATTRS(cls); JAVA_SIGAR_SET_FIELDS_FILEATTRS(cls, obj, s); } JNIEXPORT jlong SIGAR_JNIx(getProcPort) (JNIEnv *env, jobject sigar_obj, jint protocol, jlong port) { int status; sigar_pid_t pid; dSIGAR(0); status = sigar_proc_port_get(sigar, protocol, (unsigned long)port, &pid); if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return -1; } return pid; } JNIEXPORT jobjectArray SIGAR_JNIx(getNetInterfaceList) (JNIEnv *env, jobject sigar_obj) { int status; unsigned int i; sigar_net_interface_list_t iflist; jobjectArray ifarray; jclass stringclass = JENV->FindClass(env, "java/lang/String"); dSIGAR(NULL); if ((status = sigar_net_interface_list_get(sigar, &iflist)) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } ifarray = JENV->NewObjectArray(env, iflist.number, stringclass, 0); SIGAR_CHEX; for (i=0; iNewStringUTF(env, iflist.data[i]); JENV->SetObjectArrayElement(env, ifarray, i, s); SIGAR_CHEX; } sigar_net_interface_list_destroy(sigar, &iflist); return ifarray; } JNIEXPORT jstring SIGAR_JNIx(getPasswordNative) (JNIEnv *env, jclass classinstance, jstring prompt) { const char *prompt_str; char *password; if (getenv("NO_NATIVE_GETPASS")) { sigar_throw_notimpl(env, "disabled with $NO_NATIVE_GETPASS"); return NULL; } prompt_str = JENV->GetStringUTFChars(env, prompt, 0); password = sigar_password_get(prompt_str); JENV->ReleaseStringUTFChars(env, prompt, prompt_str); return JENV->NewStringUTF(env, password); } JNIEXPORT jstring SIGAR_JNIx(getFQDN) (JNIEnv *env, jobject sigar_obj) { char fqdn[SIGAR_FQDN_LEN]; int status; dSIGAR(NULL); if ((status = sigar_fqdn_get(sigar, fqdn, sizeof(fqdn))) != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } return JENV->NewStringUTF(env, fqdn); } typedef struct { JNIEnv *env; jobject obj; jclass cls; jmethodID id; } jni_ptql_re_data_t; static int jsigar_ptql_re_impl(void *data, char *haystack, char *needle) { jni_ptql_re_data_t *re = (jni_ptql_re_data_t *)data; JNIEnv *env = re->env; if (!re->cls) { re->cls = JENV->GetObjectClass(env, re->obj); re->id = JENV->GetStaticMethodID(env, re->cls, "re", "(Ljava/lang/String;Ljava/lang/String;)" "Z"); if (!re->id) { return 0; } } return JENV->CallStaticBooleanMethod(env, re->cls, re->id, JENV->NewStringUTF(env, haystack), JENV->NewStringUTF(env, needle)); } static void re_impl_set(JNIEnv *env, sigar_t *sigar, jobject obj, jni_ptql_re_data_t *re) { re->env = env; re->cls = NULL; re->obj = obj; re->id = NULL; sigar_ptql_re_impl_set(sigar, re, jsigar_ptql_re_impl); } JNIEXPORT jboolean SIGAR_JNI(ptql_SigarProcessQuery_match) (JNIEnv *env, jobject obj, jobject sigar_obj, jlong pid) { int status; jni_ptql_re_data_t re; sigar_ptql_query_t *query = (sigar_ptql_query_t *)sigar_get_pointer(env, obj); dSIGAR(JNI_FALSE); re_impl_set(env, sigar, obj, &re); status = sigar_ptql_query_match(sigar, query, pid); sigar_ptql_re_impl_set(sigar, NULL, NULL); if (status == SIGAR_OK) { return JNI_TRUE; } else { return JNI_FALSE; } } JNIEXPORT void SIGAR_JNI(ptql_SigarProcessQuery_create) (JNIEnv *env, jobject obj, jstring jptql) { int status; jboolean is_copy; const char *ptql; sigar_ptql_query_t *query; sigar_ptql_error_t error; ptql = JENV->GetStringUTFChars(env, jptql, &is_copy); status = sigar_ptql_query_create(&query, (char *)ptql, &error); if (is_copy) { JENV->ReleaseStringUTFChars(env, jptql, ptql); } if (status != SIGAR_OK) { sigar_throw_ptql_malformed(env, error.message); } else { sigar_set_pointer(env, obj, query); } } JNIEXPORT void SIGAR_JNI(ptql_SigarProcessQuery_destroy) (JNIEnv *env, jobject obj) { sigar_ptql_query_t *query = (sigar_ptql_query_t *)sigar_get_pointer(env, obj); if (query) { sigar_ptql_query_destroy(query); sigar_set_pointer(env, obj, 0); } } JNIEXPORT jlong SIGAR_JNI(ptql_SigarProcessQuery_findProcess) (JNIEnv *env, jobject obj, jobject sigar_obj) { sigar_pid_t pid; int status; jni_ptql_re_data_t re; sigar_ptql_query_t *query = (sigar_ptql_query_t *)sigar_get_pointer(env, obj); dSIGAR(0); re_impl_set(env, sigar, obj, &re); status = sigar_ptql_query_find_process(sigar, query, &pid); sigar_ptql_re_impl_set(sigar, NULL, NULL); if (status < 0) { sigar_throw_exception(env, sigar->errbuf); } else if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); } return pid; } JNIEXPORT jlongArray SIGAR_JNI(ptql_SigarProcessQuery_find) (JNIEnv *env, jobject obj, jobject sigar_obj) { int status; jlongArray procarray; sigar_proc_list_t proclist; jlong *pids = NULL; jni_ptql_re_data_t re; sigar_ptql_query_t *query = (sigar_ptql_query_t *)sigar_get_pointer(env, obj); dSIGAR(NULL); re_impl_set(env, sigar, obj, &re); status = sigar_ptql_query_find(sigar, query, &proclist); sigar_ptql_re_impl_set(sigar, NULL, NULL); if (status < 0) { sigar_throw_exception(env, sigar->errbuf); return NULL; } else if (status != SIGAR_OK) { sigar_throw_error(env, jsigar, status); return NULL; } procarray = JENV->NewLongArray(env, proclist.number); SIGAR_CHEX; if (sizeof(jlong) == sizeof(sigar_pid_t)) { pids = (jlong *)proclist.data; } else { unsigned int i; pids = (jlong *)malloc(sizeof(jlong) * proclist.number); for (i=0; iSetLongArrayRegion(env, procarray, 0, proclist.number, pids); if (pids != (jlong *)proclist.data) { free(pids); } sigar_proc_list_destroy(sigar, &proclist); return procarray; } #include "sigar_getline.h" JNIEXPORT jboolean SIGAR_JNI(util_Getline_isatty) (JNIEnv *env, jclass cls) { return sigar_isatty(sigar_fileno(stdin)) ? JNI_TRUE : JNI_FALSE; } JNIEXPORT jstring SIGAR_JNI(util_Getline_getline) (JNIEnv *env, jobject sigar_obj, jstring prompt) { const char *prompt_str; char *line; jboolean is_copy; prompt_str = JENV->GetStringUTFChars(env, prompt, &is_copy); line = sigar_getline((char *)prompt_str); if (is_copy) { JENV->ReleaseStringUTFChars(env, prompt, prompt_str); } if ((line == NULL) || sigar_getline_eof()) { jclass eof_ex = JENV->FindClass(env, "java/io/EOFException"); JENV->ThrowNew(env, eof_ex, ""); return NULL; } return JENV->NewStringUTF(env, line); } JNIEXPORT void SIGAR_JNI(util_Getline_histadd) (JNIEnv *env, jobject sigar_obj, jstring hist) { const char *hist_str; jboolean is_copy; hist_str = JENV->GetStringUTFChars(env, hist, &is_copy); sigar_getline_histadd((char *)hist_str); if (is_copy) { JENV->ReleaseStringUTFChars(env, hist, hist_str); } } JNIEXPORT void SIGAR_JNI(util_Getline_histinit) (JNIEnv *env, jobject sigar_obj, jstring hist) { const char *hist_str; jboolean is_copy; hist_str = JENV->GetStringUTFChars(env, hist, &is_copy); sigar_getline_histinit((char *)hist_str); if (is_copy) { JENV->ReleaseStringUTFChars(env, hist, hist_str); } } static struct { JNIEnv *env; jobject obj; jmethodID id; jclass clazz; } jsigar_completer; static int jsigar_getline_completer(char *buffer, int offset, int *pos) { JNIEnv *env = jsigar_completer.env; jstring jbuffer; jstring completion; const char *line; int len, cur; jboolean is_copy; jbuffer = JENV->NewStringUTF(env, buffer); completion = JENV->CallObjectMethod(env, jsigar_completer.obj, jsigar_completer.id, jbuffer); if (JENV->ExceptionCheck(env)) { JENV->ExceptionDescribe(env); return 0; } if (!completion) { return 0; } line = JENV->GetStringUTFChars(env, completion, &is_copy); len = JENV->GetStringUTFLength(env, completion); cur = *pos; if (len != cur) { strcpy(buffer, line); *pos = len; } if (is_copy) { JENV->ReleaseStringUTFChars(env, completion, line); } return cur; } JNIEXPORT void SIGAR_JNI(util_Getline_setCompleter) (JNIEnv *env, jclass classinstance, jobject completer) { if (completer == NULL) { sigar_getline_completer_set(NULL); return; } jsigar_completer.env = env; jsigar_completer.obj = completer; jsigar_completer.clazz = JENV->GetObjectClass(env, completer); jsigar_completer.id = JENV->GetMethodID(env, jsigar_completer.clazz, "complete", "(Ljava/lang/String;)Ljava/lang/String;"); sigar_getline_completer_set(jsigar_getline_completer); } JNIEXPORT void SIGAR_JNI(util_Getline_redraw) (JNIEnv *env, jobject obj) { sigar_getline_redraw(); } JNIEXPORT void SIGAR_JNI(util_Getline_reset) (JNIEnv *env, jobject obj) { sigar_getline_reset(); } static const char *log_methods[] = { "fatal", /* SIGAR_LOG_FATAL */ "error", /* SIGAR_LOG_ERROR */ "warn", /* SIGAR_LOG_WARN */ "info", /* SIGAR_LOG_INFO */ "debug", /* SIGAR_LOG_DEBUG */ /* XXX trace is only in commons-logging??? */ "debug", /* SIGAR_LOG_TRACE */ }; static void jsigar_log_impl(sigar_t *sigar, void *data, int level, char *message) { jni_sigar_t *jsigar = (jni_sigar_t *)data; JNIEnv *env = jsigar->env; jobject logger = jsigar->logger; jobject message_obj; /* XXX should cache method id lookups */ jmethodID id = JENV->GetMethodID(env, JENV->GetObjectClass(env, logger), log_methods[level], "(Ljava/lang/Object;)V"); if (JENV->ExceptionCheck(env)) { JENV->ExceptionDescribe(env); return; } message_obj = (jobject)JENV->NewStringUTF(env, message); JENV->CallVoidMethod(env, logger, id, message_obj); } JNIEXPORT void SIGAR_JNI(SigarLog_setLogger) (JNIEnv *env, jclass classinstance, jobject sigar_obj, jobject logger) { dSIGAR_VOID; if (jsigar->logger != NULL) { JENV->DeleteGlobalRef(env, jsigar->logger); jsigar->logger = NULL; } if (logger) { jsigar->logger = JENV->NewGlobalRef(env, logger); sigar_log_impl_set(sigar, jsigar, jsigar_log_impl); } else { sigar_log_impl_set(sigar, NULL, NULL); } } JNIEXPORT void SIGAR_JNI(SigarLog_setLevel) (JNIEnv *env, jclass classinstance, jobject sigar_obj, jint level) { dSIGAR_VOID; sigar_log_level_set(sigar, level); } JNIEXPORT jlong SIGAR_JNIx(getServicePid) (JNIEnv *env, jobject sigar_obj, jstring jname) { #ifdef WIN32 const char *name; jboolean is_copy; jlong pid = 0; int status; dSIGAR(0); name = JENV->GetStringUTFChars(env, jname, &is_copy); status = sigar_service_pid_get(sigar, (char *)name, &pid); if (is_copy) { JENV->ReleaseStringUTFChars(env, jname, name); } if (status != ERROR_SUCCESS) { sigar_throw_error(env, jsigar, status); } return pid; #else dSIGAR(0); sigar_throw_error(env, jsigar, SIGAR_ENOTIMPL); return 0; #endif } JNIEXPORT jlong SIGAR_JNI(ResourceLimit_INFINITY) (JNIEnv *env, jclass cls) { #ifdef WIN32 return 0x7fffffff; #else return RLIM_INFINITY; #endif } JNIEXPORT jstring SIGAR_JNI(win32_Win32_findExecutable) (JNIEnv *env, jclass sigar_class, jstring jname) { #ifdef WIN32 #include "shellapi.h" const char *name; jboolean is_copy; char exe[MAX_PATH]; LONG result; jstring jexe = NULL; name = JENV->GetStringUTFChars(env, jname, &is_copy); if ((result = (LONG)FindExecutable(name, ".", exe)) > 32) { jexe = JENV->NewStringUTF(env, exe); } if (is_copy) { JENV->ReleaseStringUTFChars(env, jname, name); } return jexe; #else sigar_throw_notimpl(env, "win32 only"); return NULL; #endif } JNIEXPORT jboolean SIGAR_JNI(win32_FileVersion_gather) (JNIEnv *env, jobject obj, jstring jname) { #ifdef WIN32 int status; sigar_file_version_t version; jboolean is_copy; jfieldID id; jclass cls = JENV->GetObjectClass(env, obj); const char *name = JENV->GetStringUTFChars(env, jname, &is_copy); sigar_proc_env_t infocb; jobject hashmap; jni_env_put_t put; id = JENV->GetFieldID(env, cls, "string_file_info", "Ljava/util/Map;"); hashmap = JENV->GetObjectField(env, obj, id); put.env = env; put.id = JENV->GetMethodID(env, JENV->GetObjectClass(env, hashmap), "put", MAP_PUT_SIG); put.map = hashmap; infocb.type = SIGAR_PROC_ENV_ALL; infocb.env_getter = jni_env_getall; infocb.data = &put; status = sigar_file_version_get(&version, (char *)name, &infocb); if (is_copy) { JENV->ReleaseStringUTFChars(env, jname, name); } if (status != SIGAR_OK) { return JNI_FALSE; } #define set_vfield(name) \ id = JENV->GetFieldID(env, cls, #name, "I"); \ JENV->SetIntField(env, obj, id, version.name) set_vfield(product_major); set_vfield(product_minor); set_vfield(product_build); set_vfield(product_revision); set_vfield(file_major); set_vfield(file_minor); set_vfield(file_build); set_vfield(file_revision); #undef set_vfield return JNI_TRUE; #else return JNI_FALSE; #endif } hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/javasigar.h000066400000000000000000000026231210132627500234160ustar00rootroot00000000000000/* * Copyright (c) 2004, 2006, 2008 Hyperic, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 #include "sigar.h" #define JENV (*env) #define SIGAR_PACKAGE "org/hyperic/sigar/" #define SIGAR_JNI(m) JNICALL Java_org_hyperic_sigar_##m #define SIGAR_JNIx(m) JNICALL Java_org_hyperic_sigar_Sigar_##m #define SIGAR_FIND_CLASS(name) \ JENV->FindClass(env, SIGAR_PACKAGE name) #define SIGAR_CLASS_SIG(name) \ "L" SIGAR_PACKAGE name ";" /* CHeck EXception */ #define SIGAR_CHEX if (JENV->ExceptionCheck(env)) return NULL typedef struct { JNIEnv *env; jobject obj; jmethodID id; } jsigar_list_t; #ifdef __cplusplus extern "C" { #endif int jsigar_list_init(JNIEnv *env, jsigar_list_t *obj); int jsigar_list_add(void *data, char *value, int len); sigar_t *jsigar_get_sigar(JNIEnv *env, jobject sigar_obj); #ifdef __cplusplus } #endif hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/vmware/000077500000000000000000000000001210132627500225745ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/vmware/javavmware.c000066400000000000000000000426451210132627500251160ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include "vmcontrol_wrapper.h" #ifdef VMCONTROL_WRAPPER_SUPPORTED #define JENV (*env) #define VMWARE_PACKAGE "org/hyperic/sigar/vmware/" #define VMWARE_JNI(m) JNICALL Java_org_hyperic_sigar_vmware_##m #define VMWARE_FIND_CLASS(name) \ JENV->FindClass(env, VMWARE_PACKAGE name) #define VMWARE_CLASS_SIG(name) \ "L" VMWARE_PACKAGE name ";" #define VMWARE_EX_SERVER 1 #define VMWARE_EX_VM 2 static void vmware_throw_last_error(JNIEnv *env, void *ptr, int type) { jclass errorClass = VMWARE_FIND_CLASS("VMwareException"); char *msg; int retval; switch (type) { case VMWARE_EX_SERVER: retval = VMControl_ServerGetLastError((VMControlServer *)ptr, &msg); break; case VMWARE_EX_VM: retval = VMControl_VMGetLastError((VMControlVM *)ptr, &msg); break; } JENV->ThrowNew(env, errorClass, msg); free(msg); } #define vmware_throw_last_vm_error() \ vmware_throw_last_error(env, vm, VMWARE_EX_VM); #define vmware_throw_last_server_error() \ vmware_throw_last_error(env, server, VMWARE_EX_SERVER) static void *vmware_get_pointer(JNIEnv *env, jobject obj) { jclass cls = JENV->GetObjectClass(env, obj); #ifdef __LP64__ jfieldID field = JENV->GetFieldID(env, cls, "ptr64", "J"); return (void *)JENV->GetLongField(env, obj, field); #else jfieldID field = JENV->GetFieldID(env, cls, "ptr", "I"); return (void *)JENV->GetIntField(env, obj, field); #endif } static void vmware_set_pointer(JNIEnv *env, jobject obj, const void *ptr) { jfieldID pointer_field; jclass cls = JENV->GetObjectClass(env, obj); #ifdef __LP64__ pointer_field = JENV->GetFieldID(env, cls, "ptr64", "J"); JENV->SetLongField(env, obj, pointer_field, (jlong)ptr); #else pointer_field = JENV->GetFieldID(env, cls, "ptr", "I"); JENV->SetIntField(env, obj, pointer_field, (int)ptr); #endif } #define dVM(obj) \ VMControlVM *vm = \ (VMControlVM *)vmware_get_pointer(env, obj) #define dSERVER(obj) \ VMControlServer *server = \ (VMControlServer *)vmware_get_pointer(env, obj) #define dPARAMS(obj) \ VMControlConnectParams *params = \ (VMControlConnectParams *)vmware_get_pointer(env, obj) JNIEXPORT jboolean VMWARE_JNI(VMwareObject_init) (JNIEnv *env, jclass classinstance, jstring jlib) { const char *lib; int retval; if (jlib) { lib = JENV->GetStringUTFChars(env, jlib, NULL); } else { lib = getenv("VMCONTROL_SHLIB"); } retval = vmcontrol_wrapper_api_init(lib); if (jlib) { JENV->ReleaseStringUTFChars(env, jlib, lib); } if (retval != 0) { return JNI_FALSE; } return VMControl_Init() && VMControl_VMInit(); } JNIEXPORT void VMWARE_JNI(ConnectParams_create) (JNIEnv *env, jobject obj, jstring jhost, jint port, jstring juser, jstring jpass) { VMControlConnectParams *params; const char *host=NULL; const char *user=NULL; const char *pass=NULL; if (jhost) { host = JENV->GetStringUTFChars(env, jhost, NULL); } if (juser) { user = JENV->GetStringUTFChars(env, juser, NULL); } if (jpass) { pass = JENV->GetStringUTFChars(env, jpass, NULL); } params = VMControl_ConnectParamsNew(host, port, user, pass); if (host) { JENV->ReleaseStringUTFChars(env, jhost, host); } if (user) { JENV->ReleaseStringUTFChars(env, juser, user); } if (pass) { JENV->ReleaseStringUTFChars(env, jpass, pass); } vmware_set_pointer(env, obj, params); } JNIEXPORT void VMWARE_JNI(ConnectParams_destroy) (JNIEnv *env, jobject obj) { dPARAMS(obj); VMControl_ConnectParamsDestroy(params); } JNIEXPORT void VMWARE_JNI(VMwareServer_create) (JNIEnv *env, jobject obj) { vmware_set_pointer(env, obj, VMControl_ServerNewEx()); } JNIEXPORT void VMWARE_JNI(VMwareServer_destroy) (JNIEnv *env, jclass obj) { dSERVER(obj); VMControl_ServerDestroy(server); } JNIEXPORT void VMWARE_JNI(VMwareServer_disconnect) (JNIEnv *env, jclass obj) { dSERVER(obj); VMControl_ServerDisconnect(server); } JNIEXPORT jboolean VMWARE_JNI(VMwareServer_isConnected) (JNIEnv *env, jclass obj) { dSERVER(obj); return VMControl_ServerIsConnected(server); } JNIEXPORT void VMWARE_JNI(VMwareServer_connect) (JNIEnv *env, jobject obj, jobject params_obj) { dSERVER(obj); dPARAMS(params_obj); if (!VMControl_ServerConnectEx(server, params)) { vmware_throw_last_server_error(); } } JNIEXPORT jboolean VMWARE_JNI(VMwareServer_isRegistered) (JNIEnv *env, jclass obj, jstring jconfig) { dSERVER(obj); const char *config = JENV->GetStringUTFChars(env, jconfig, NULL); Bool value; Bool retval = VMControl_ServerIsRegistered(server, config, &value); JENV->ReleaseStringUTFChars(env, jconfig, config); if (!retval) { vmware_throw_last_server_error(); return JNI_FALSE; } return value ? JNI_TRUE : JNI_FALSE; } JNIEXPORT jobject VMWARE_JNI(VMwareServer_getRegisteredVmNames) (JNIEnv *env, jclass obj) { dSERVER(obj); char **ptr, **names; jobject listobj; jclass listclass = JENV->FindClass(env, "java/util/ArrayList"); jmethodID listid = JENV->GetMethodID(env, listclass, "", "()V"); jmethodID addid = JENV->GetMethodID(env, listclass, "add", "(Ljava/lang/Object;)Z"); listobj = JENV->NewObject(env, listclass, listid); ptr = names = VMControl_ServerEnumerate(server); if (ptr) { while (*ptr) { JENV->CallBooleanMethod(env, listobj, addid, JENV->NewStringUTF(env, *ptr)); if (JENV->ExceptionOccurred(env)) { JENV->ExceptionDescribe(env); } free(*ptr); ptr++; } free(names); } return listobj; } JNIEXPORT jstring VMWARE_JNI(VMwareServer_getResource) (JNIEnv *env, jclass obj, jstring jkey) { dSERVER(obj); jstring retval; const char *key = JENV->GetStringUTFChars(env, jkey, NULL); char *value = VMControl_ServerGetResource(server, (char *)key); JENV->ReleaseStringUTFChars(env, jkey, key); if (!value) { vmware_throw_last_server_error(); return NULL; } retval = JENV->NewStringUTF(env, value); free(value); return retval; } JNIEXPORT jstring VMWARE_JNI(VMwareServer_exec) (JNIEnv *env, jclass obj, jstring jxml) { dSERVER(obj); jstring retval; const char *xml = JENV->GetStringUTFChars(env, jxml, NULL); char *value = VMControl_ServerExec(server, xml); JENV->ReleaseStringUTFChars(env, jxml, xml); if (!value) { vmware_throw_last_server_error(); return NULL; } retval = JENV->NewStringUTF(env, value); free(value); return retval; } JNIEXPORT void VMWARE_JNI(VM_create) (JNIEnv *env, jclass obj) { vmware_set_pointer(env, obj, VMControl_VMNewEx()); } JNIEXPORT void VMWARE_JNI(VM_destroy) (JNIEnv *env, jclass obj) { dVM(obj); VMControl_VMDestroy(vm); } JNIEXPORT void VMWARE_JNI(VM_disconnect) (JNIEnv *env, jclass obj) { dVM(obj); VMControl_VMDisconnect(vm); } JNIEXPORT jboolean VMWARE_JNI(VM_isConnected) (JNIEnv *env, jclass obj) { dVM(obj); return VMControl_VMIsConnected(vm); } JNIEXPORT void VMWARE_JNI(VM_connect) (JNIEnv *env, jobject obj, jobject params_obj, jstring jconfig, jint mks) { dVM(obj); dPARAMS(params_obj); const char *config = JENV->GetStringUTFChars(env, jconfig, NULL); Bool retval = VMControl_VMConnectEx(vm, params, config, mks); JENV->ReleaseStringUTFChars(env, jconfig, config); if (!retval) { vmware_throw_last_vm_error(); } } JNIEXPORT jint VMWARE_JNI(VM_getExecutionState) (JNIEnv *env, jclass obj) { dVM(obj); int state; if (!VMControl_VMGetExecutionState(vm, &state)) { vmware_throw_last_vm_error(); return -1; } return state; } JNIEXPORT jint VMWARE_JNI(VM_getRemoteConnections) (JNIEnv *env, jclass obj) { dVM(obj); unsigned int num; if (!VMControl_VMGetRemoteConnections(vm, &num)) { vmware_throw_last_vm_error(); return -1; } return num; } JNIEXPORT jint VMWARE_JNI(VM_getUptime) (JNIEnv *env, jclass obj) { dVM(obj); unsigned int uptime; if (!VMControl_VMGetUptime(vm, &uptime)) { vmware_throw_last_vm_error(); return -1; } return uptime; } JNIEXPORT jint VMWARE_JNI(VM_getHeartbeat) (JNIEnv *env, jclass obj) { dVM(obj); unsigned int heartbeat; if (!VMControl_VMGetHeartbeat(vm, &heartbeat)) { vmware_throw_last_vm_error(); return -1; } return heartbeat; } JNIEXPORT jint VMWARE_JNI(VM_getToolsLastActive) (JNIEnv *env, jclass obj) { dVM(obj); int seconds; if (!VMControl_VMToolsLastActive(vm, &seconds)) { vmware_throw_last_vm_error(); return -1; } return seconds; } JNIEXPORT jstring VMWARE_JNI(VM_getRunAsUser) (JNIEnv *env, jclass obj) { dVM(obj); char *user; jstring juser; if (!VMControl_VMGetRunAsUser(vm, &user)) { vmware_throw_last_vm_error(); return NULL; } juser = JENV->NewStringUTF(env, user); free(user); return juser; } JNIEXPORT jint VMWARE_JNI(VM_getPermissions) (JNIEnv *env, jclass obj) { dVM(obj); unsigned int permissions; if (!VMControl_VMGetCapabilities(vm, &permissions)) { vmware_throw_last_vm_error(); return -1; } return permissions; } JNIEXPORT jstring VMWARE_JNI(VM_getConfig) (JNIEnv *env, jclass obj, jstring jkey) { dVM(obj); jstring retval; const char *key = JENV->GetStringUTFChars(env, jkey, NULL); char *value = VMControl_VMGetConfig(vm, (char *)key); JENV->ReleaseStringUTFChars(env, jkey, key); if (!value) { vmware_throw_last_vm_error(); return NULL; } retval = JENV->NewStringUTF(env, value); free(value); return retval; } JNIEXPORT void VMWARE_JNI(VM_setConfig) (JNIEnv *env, jclass obj, jstring jkey, jstring jvalue) { dVM(obj); jboolean retval; const char *key = JENV->GetStringUTFChars(env, jkey, NULL); const char *value = JENV->GetStringUTFChars(env, jvalue, NULL); retval = VMControl_VMSetConfig(vm, (char *)key, (char *)value); JENV->ReleaseStringUTFChars(env, jkey, key); JENV->ReleaseStringUTFChars(env, jvalue, value); if (!retval) { vmware_throw_last_vm_error(); } } JNIEXPORT jstring VMWARE_JNI(VM_getResource) (JNIEnv *env, jclass obj, jstring jkey) { dVM(obj); jstring retval; const char *key = JENV->GetStringUTFChars(env, jkey, NULL); char *value = VMControl_VMGetResource(vm, (char *)key); JENV->ReleaseStringUTFChars(env, jkey, key); if (!value) { vmware_throw_last_vm_error(); return NULL; } retval = JENV->NewStringUTF(env, value); free(value); return retval; } JNIEXPORT jstring VMWARE_JNI(VM_getGuestInfo) (JNIEnv *env, jclass obj, jstring jkey) { dVM(obj); jstring retval; const char *key = JENV->GetStringUTFChars(env, jkey, NULL); char *value = VMControl_VMGetGuestInfo(vm, (char *)key); JENV->ReleaseStringUTFChars(env, jkey, key); if (!value) { vmware_throw_last_vm_error(); return NULL; } retval = JENV->NewStringUTF(env, value); free(value); return retval; } JNIEXPORT void VMWARE_JNI(VM_setGuestInfo) (JNIEnv *env, jclass obj, jstring jkey, jstring jvalue) { dVM(obj); jboolean retval; const char *key = JENV->GetStringUTFChars(env, jkey, NULL); const char *value = JENV->GetStringUTFChars(env, jvalue, NULL); retval = VMControl_VMSetGuestInfo(vm, (char *)key, (char *)value); JENV->ReleaseStringUTFChars(env, jkey, key); JENV->ReleaseStringUTFChars(env, jvalue, value); if (!retval) { vmware_throw_last_vm_error(); } } JNIEXPORT jint VMWARE_JNI(VM_getProductInfo) (JNIEnv *env, jclass obj, jint type) { dVM(obj); int value; if (!VMControl_VMGetProductInfo(vm, type, &value)) { vmware_throw_last_vm_error(); return -1; } return value; } JNIEXPORT void VMWARE_JNI(VM_start) (JNIEnv *env, jclass obj, jint mode) { dVM(obj); if (!VMControl_VMStart(vm, mode)) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_stop) (JNIEnv *env, jclass obj, jint mode) { dVM(obj); if (!VMControl_VMStopOrReset(vm, 1, mode)) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_reset) (JNIEnv *env, jclass obj, jint mode) { dVM(obj); if (!VMControl_VMStopOrReset(vm, 0, mode)) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_suspend) (JNIEnv *env, jclass obj, jint mode) { dVM(obj); if (!VMControl_VMSuspendToDisk(vm, mode)) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_createNamedSnapshot) (JNIEnv *env, jclass obj, jstring jname, jstring jdescr, jboolean quiesce, jboolean memory) { dVM(obj); const char *name = JENV->GetStringUTFChars(env, jname, NULL); const char *descr = JENV->GetStringUTFChars(env, jdescr, NULL); if (!VMControl_VMCreateSnapshot(vm, name, descr, quiesce, memory)) { vmware_throw_last_vm_error(); } JENV->ReleaseStringUTFChars(env, jname, name); JENV->ReleaseStringUTFChars(env, jdescr, descr); } /* VMware server version has no args */ typedef Bool (*VMControl_VMmakeSnapshot)(VMControlVM *); JNIEXPORT void VMWARE_JNI(VM_createDefaultSnapshot) (JNIEnv *env, jclass obj) { dVM(obj); VMControl_VMmakeSnapshot makeSnapshot = (VMControl_VMmakeSnapshot)VMControl_VMCreateSnapshot; if (!makeSnapshot(vm)) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_revertToSnapshot) (JNIEnv *env, jclass obj) { dVM(obj); if (!VMControl_VMRevertToSnapshot(vm)) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_removeAllSnapshots) (JNIEnv *env, jclass obj) { dVM(obj); if (!VMControl_VMRemoveAllSnapshots(vm)) { vmware_throw_last_vm_error(); } } JNIEXPORT jboolean VMWARE_JNI(VM_hasSnapshot) (JNIEnv *env, jclass obj) { dVM(obj); Bool value; if (!VMControl_VMHasSnapshot(vm, &value)) { vmware_throw_last_vm_error(); return JNI_FALSE; } return value ? JNI_TRUE : JNI_FALSE; } JNIEXPORT jlong VMWARE_JNI(VM_getPid) (JNIEnv *env, jclass obj) { dVM(obj); unsigned int pid; if (!VMControl_VMGetPid(vm, &pid)) { vmware_throw_last_vm_error(); return -1; } return (jlong)pid; } JNIEXPORT jint VMWARE_JNI(VM_getId) (JNIEnv *env, jclass obj) { dVM(obj); unsigned int id; if (!VMControl_VMGetId(vm, &id)) { vmware_throw_last_vm_error(); return -1; } return id; } JNIEXPORT void VMWARE_JNI(VM_saveScreenshot) (JNIEnv *env, jclass obj, jstring jname) { dVM(obj); jboolean retval; const char *name = JENV->GetStringUTFChars(env, jname, NULL); retval = VMControl_MKSSaveScreenshot(vm, name, "PNG"); JENV->ReleaseStringUTFChars(env, jname, name); if (!retval) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_deviceConnect) (JNIEnv *env, jclass obj, jstring jdevice) { dVM(obj); const char *device = JENV->GetStringUTFChars(env, jdevice, NULL); jboolean retval = VMControl_VMDeviceConnect(vm, device); JENV->ReleaseStringUTFChars(env, jdevice, device); if (!retval) { vmware_throw_last_vm_error(); } } JNIEXPORT void VMWARE_JNI(VM_deviceDisconnect) (JNIEnv *env, jclass obj, jstring jdevice) { dVM(obj); const char *device = JENV->GetStringUTFChars(env, jdevice, NULL); jboolean retval = VMControl_VMDeviceDisconnect(vm, device); JENV->ReleaseStringUTFChars(env, jdevice, device); if (!retval) { vmware_throw_last_vm_error(); } } JNIEXPORT jboolean VMWARE_JNI(VM_deviceIsConnected) (JNIEnv *env, jclass obj, jstring jdevice) { dVM(obj); const char *device = JENV->GetStringUTFChars(env, jdevice, NULL); Bool isConnected; Bool retval = VMControl_VMDeviceIsConnected(vm, device, &isConnected); JENV->ReleaseStringUTFChars(env, jdevice, device); if (!retval) { vmware_throw_last_vm_error(); return JNI_FALSE; } return isConnected ? JNI_TRUE : JNI_FALSE; } #endif /* VMCONTROL_WRAPPER_SUPPORTED */ hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/vmware/vmcontrol_wrapper.c000066400000000000000000000143421210132627500265270ustar00rootroot00000000000000/* * Copyright (c) 2006 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. */ #include "vmcontrol_wrapper.h" #ifdef VMCONTROL_WRAPPER_SUPPORTED #ifdef WIN32 #include #else #include #include #include #include #endif #include #ifdef WIN32 #define DL_LOAD(lib) LoadLibrary(lib) #define DL_CLOSE(h) FreeLibrary(h) #define DL_SYM GetProcAddress #define DL_ERR GetLastError() #define DL_ENOENT ERROR_FILE_NOT_FOUND #else #define DL_LOAD(lib) dlopen(lib, RTLD_LAZY) #define DL_CLOSE(h) dlclose(h) #define DL_SYM dlsym #define DL_ERR errno #define DL_ENOENT ENOENT #endif typedef struct { const char *name; unsigned long offset; const char *alias; } vmcontrol_entry_t; #define OffsetOf(structure, field) \ (unsigned long)(&((structure *)NULL)->field) #define VMCONTROL_ENTRY(name) \ { #name, OffsetOf(vmcontrol_wrapper_api_t, x##name), NULL } #define VMCONTROL_ENTRY_ALIAS(name, alias) \ { #name, OffsetOf(vmcontrol_wrapper_api_t, x##name), alias } static vmcontrol_entry_t vmcontrol_entries[] = { VMCONTROL_ENTRY(VMControl_ConnectParamsDestroy), VMCONTROL_ENTRY(VMControl_ConnectParamsNew), VMCONTROL_ENTRY(VMControl_Init), VMCONTROL_ENTRY(VMControl_MKSSaveScreenshot), VMCONTROL_ENTRY(VMControl_ServerConnectEx), VMCONTROL_ENTRY(VMControl_ServerDestroy), VMCONTROL_ENTRY(VMControl_ServerDisconnect), VMCONTROL_ENTRY(VMControl_ServerEnumerate), VMCONTROL_ENTRY(VMControl_ServerExec), VMCONTROL_ENTRY(VMControl_ServerGetLastError), VMCONTROL_ENTRY(VMControl_ServerGetResource), VMCONTROL_ENTRY(VMControl_ServerIsConnected), VMCONTROL_ENTRY(VMControl_ServerIsRegistered), VMCONTROL_ENTRY(VMControl_ServerNewEx), VMCONTROL_ENTRY(VMControl_VMConnectEx), VMCONTROL_ENTRY(VMControl_VMCreateSnapshot), VMCONTROL_ENTRY(VMControl_VMDestroy), VMCONTROL_ENTRY(VMControl_VMDeviceConnect), VMCONTROL_ENTRY(VMControl_VMDeviceDisconnect), VMCONTROL_ENTRY(VMControl_VMDeviceIsConnected), VMCONTROL_ENTRY(VMControl_VMDisconnect), VMCONTROL_ENTRY(VMControl_VMGetCapabilities), VMCONTROL_ENTRY(VMControl_VMGetConfig), VMCONTROL_ENTRY(VMControl_VMGetConfigFileName), VMCONTROL_ENTRY(VMControl_VMGetExecutionState), VMCONTROL_ENTRY(VMControl_VMGetGuestInfo), VMCONTROL_ENTRY(VMControl_VMGetHeartbeat), VMCONTROL_ENTRY(VMControl_VMGetId), VMCONTROL_ENTRY(VMControl_VMGetLastError), VMCONTROL_ENTRY(VMControl_VMGetPid), VMCONTROL_ENTRY(VMControl_VMGetProductInfo), VMCONTROL_ENTRY(VMControl_VMGetRemoteConnections), VMCONTROL_ENTRY(VMControl_VMGetResource), VMCONTROL_ENTRY(VMControl_VMGetRunAsUser), VMCONTROL_ENTRY(VMControl_VMGetUptime), VMCONTROL_ENTRY(VMControl_VMHasSnapshot), VMCONTROL_ENTRY(VMControl_VMInit), VMCONTROL_ENTRY(VMControl_VMIsConnected), VMCONTROL_ENTRY(VMControl_VMNewEx), VMCONTROL_ENTRY_ALIAS(VMControl_VMRemoveAllSnapshots, "VMControl_VMDeleteSnapshot"), VMCONTROL_ENTRY_ALIAS(VMControl_VMRevertToSnapshot, "VMControl_VMRevertSnapshot"), VMCONTROL_ENTRY(VMControl_VMSetConfig), VMCONTROL_ENTRY(VMControl_VMSetGuestInfo), VMCONTROL_ENTRY(VMControl_VMStart), VMCONTROL_ENTRY(VMControl_VMStopOrReset), VMCONTROL_ENTRY(VMControl_VMSuspendToDisk), VMCONTROL_ENTRY(VMControl_VMToolsLastActive), { NULL, 0, NULL } }; static vmcontrol_wrapper_api_t *vmcontrol_api = NULL; vmcontrol_wrapper_api_t *vmcontrol_wrapper_api_get(void) { return vmcontrol_api; } typedef void (*any_function_t)(void); static int unsupported_function(void *obj, ...) { return 0; } int vmcontrol_wrapper_api_init(const char *lib) { int i; char *api; int dl_debug = getenv("VMCONTROL_DEBUG") != NULL; if (vmcontrol_api) { return 0; } if (!lib) { /* sanity check */ if (dl_debug) { fprintf(stderr, "[vmcontrol_init] lib==NULL\n"); } return DL_ENOENT; } vmcontrol_api = malloc(sizeof(*vmcontrol_api)); api = (char *)vmcontrol_api; memset(vmcontrol_api, 0, sizeof(*vmcontrol_api)); if (!(vmcontrol_api->handle = DL_LOAD(lib))) { return DL_ERR; } for (i=0; vmcontrol_entries[i].name; i++) { any_function_t *ptr = (any_function_t *)(api + (int)(long)vmcontrol_entries[i].offset); *ptr = (any_function_t)DL_SYM(vmcontrol_api->handle, vmcontrol_entries[i].name); if ((*ptr == NULL) && vmcontrol_entries[i].alias) { *ptr = (any_function_t)DL_SYM(vmcontrol_api->handle, vmcontrol_entries[i].alias); if (dl_debug) { fprintf(stderr, "[vmcontrol_init] alias %s -> %s\n", vmcontrol_entries[i].name, vmcontrol_entries[i].alias); } } if (!*ptr) { if (dl_debug) { fprintf(stderr, "[vmcontrol_init] %s -> UNDEFINED\n", vmcontrol_entries[i].name); } *ptr = (any_function_t)unsupported_function; } } if ((void *)vmcontrol_api->xVMControl_VMInit == (void *)&unsupported_function) { if (dl_debug) { fprintf(stderr, "[vmcontrol_init] %s unuseable\n", lib); } vmcontrol_wrapper_api_shutdown(); return DL_ENOENT; } return 0; } int vmcontrol_wrapper_api_shutdown(void) { if (vmcontrol_api) { if (vmcontrol_api->handle) { DL_CLOSE(vmcontrol_api->handle); } free(vmcontrol_api); vmcontrol_api = NULL; } return 0; } #endif /* WIN32 || linux */ hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/vmware/vmcontrol_wrapper.h000066400000000000000000000211521210132627500265310ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef VMCONTROL_WRAPPER_H #define VMCONTROL_WRAPPER_H #if defined(WIN32) || defined(__linux__) #define VMCONTROL_WRAPPER_SUPPORTED /* types defined by vmcontrol.h */ typedef struct VMControlServer VMControlServer; typedef struct VMControlVM VMControlVM; typedef char Bool; typedef struct { const char *hostname; int port; const char *username; char *password; } VMControlConnectParams; /* function pointers to api defined by vmcontrol.h */ typedef struct { void *handle; void (*xVMControl_ConnectParamsDestroy)(VMControlConnectParams *); VMControlConnectParams * (*xVMControl_ConnectParamsNew)(const char *, int, const char *, const char *); Bool (*xVMControl_Init)(void); Bool (*xVMControl_MKSSaveScreenshot)(VMControlVM *, const char *, const char *); Bool (*xVMControl_ServerConnectEx)(VMControlServer *, VMControlConnectParams *); void (*xVMControl_ServerDestroy)(VMControlServer *); void (*xVMControl_ServerDisconnect)(VMControlServer *); char ** (*xVMControl_ServerEnumerate)(VMControlServer *); char * (*xVMControl_ServerExec)(VMControlServer *, const char *); int (*xVMControl_ServerGetLastError)(VMControlServer *, char **); char * (*xVMControl_ServerGetResource)(VMControlServer *, char *); Bool (*xVMControl_ServerIsConnected)(VMControlServer *); Bool (*xVMControl_ServerIsRegistered)(VMControlServer *, const char *, Bool *); VMControlServer * (*xVMControl_ServerNewEx)(void); Bool (*xVMControl_VMConnectEx)(VMControlVM *, VMControlConnectParams *, const char *, Bool); Bool (*xVMControl_VMCreateSnapshot)(VMControlVM *, const char *, const char *, Bool, Bool); void (*xVMControl_VMDestroy)(VMControlVM *); Bool (*xVMControl_VMDeviceConnect)(VMControlVM *, const char *); Bool (*xVMControl_VMDeviceDisconnect)(VMControlVM *, const char *); Bool (*xVMControl_VMDeviceIsConnected)(VMControlVM *, const char *, Bool *); void (*xVMControl_VMDisconnect)(VMControlVM *); Bool (*xVMControl_VMGetCapabilities)(VMControlVM *, unsigned int *); char * (*xVMControl_VMGetConfig)(VMControlVM *, char *); char * (*xVMControl_VMGetConfigFileName)(VMControlVM *); Bool (*xVMControl_VMGetExecutionState)(VMControlVM *, int *); char * (*xVMControl_VMGetGuestInfo)(VMControlVM *, char *); Bool (*xVMControl_VMGetHeartbeat)(VMControlVM *, unsigned int *); Bool (*xVMControl_VMGetId)(VMControlVM *, unsigned int *); int (*xVMControl_VMGetLastError)(VMControlVM *, char **); Bool (*xVMControl_VMGetPid)(VMControlVM *, unsigned int * ); Bool (*xVMControl_VMGetProductInfo)(VMControlVM *, int, int *); Bool (*xVMControl_VMGetRemoteConnections)(VMControlVM *, unsigned int *); char * (*xVMControl_VMGetResource)(VMControlVM *, char *); Bool (*xVMControl_VMGetRunAsUser)(VMControlVM *, char **); Bool (*xVMControl_VMGetUptime)(VMControlVM *, unsigned int *); Bool (*xVMControl_VMHasSnapshot)(VMControlVM *, Bool *); char (*xVMControl_VMInit)(void); Bool (*xVMControl_VMIsConnected)(VMControlVM *); VMControlVM * (*xVMControl_VMNewEx)(void); Bool (*xVMControl_VMRemoveAllSnapshots)(VMControlVM *); Bool (*xVMControl_VMRevertToSnapshot)(VMControlVM *); Bool (*xVMControl_VMSetConfig)(VMControlVM *, char *, char *); Bool (*xVMControl_VMSetGuestInfo)(VMControlVM *, char *, char *); Bool (*xVMControl_VMStart)(VMControlVM *, int); Bool (*xVMControl_VMStopOrReset)(VMControlVM *, Bool, int); Bool (*xVMControl_VMSuspendToDisk)(VMControlVM *, int); Bool (*xVMControl_VMToolsLastActive)(VMControlVM *, int *); } vmcontrol_wrapper_api_t; int vmcontrol_wrapper_api_init(const char *lib); int vmcontrol_wrapper_api_shutdown(void); vmcontrol_wrapper_api_t *vmcontrol_wrapper_api_get(void); #define VMControl_ConnectParamsDestroy \ vmcontrol_wrapper_api_get()->xVMControl_ConnectParamsDestroy #define VMControl_ConnectParamsNew \ vmcontrol_wrapper_api_get()->xVMControl_ConnectParamsNew #define VMControl_Init \ vmcontrol_wrapper_api_get()->xVMControl_Init #define VMControl_MKSSaveScreenshot \ vmcontrol_wrapper_api_get()->xVMControl_MKSSaveScreenshot #define VMControl_ServerConnectEx \ vmcontrol_wrapper_api_get()->xVMControl_ServerConnectEx #define VMControl_ServerDestroy \ vmcontrol_wrapper_api_get()->xVMControl_ServerDestroy #define VMControl_ServerDisconnect \ vmcontrol_wrapper_api_get()->xVMControl_ServerDisconnect #define VMControl_ServerEnumerate \ vmcontrol_wrapper_api_get()->xVMControl_ServerEnumerate #define VMControl_ServerExec \ vmcontrol_wrapper_api_get()->xVMControl_ServerExec #define VMControl_ServerGetLastError \ vmcontrol_wrapper_api_get()->xVMControl_ServerGetLastError #define VMControl_ServerGetResource \ vmcontrol_wrapper_api_get()->xVMControl_ServerGetResource #define VMControl_ServerIsConnected \ vmcontrol_wrapper_api_get()->xVMControl_ServerIsConnected #define VMControl_ServerIsRegistered \ vmcontrol_wrapper_api_get()->xVMControl_ServerIsRegistered #define VMControl_ServerNewEx \ vmcontrol_wrapper_api_get()->xVMControl_ServerNewEx #define VMControl_VMConnectEx \ vmcontrol_wrapper_api_get()->xVMControl_VMConnectEx #define VMControl_VMCreateSnapshot \ vmcontrol_wrapper_api_get()->xVMControl_VMCreateSnapshot #define VMControl_VMDestroy \ vmcontrol_wrapper_api_get()->xVMControl_VMDestroy #define VMControl_VMDeviceConnect \ vmcontrol_wrapper_api_get()->xVMControl_VMDeviceConnect #define VMControl_VMDeviceDisconnect \ vmcontrol_wrapper_api_get()->xVMControl_VMDeviceDisconnect #define VMControl_VMDeviceIsConnected \ vmcontrol_wrapper_api_get()->xVMControl_VMDeviceIsConnected #define VMControl_VMDisconnect \ vmcontrol_wrapper_api_get()->xVMControl_VMDisconnect #define VMControl_VMGetCapabilities \ vmcontrol_wrapper_api_get()->xVMControl_VMGetCapabilities #define VMControl_VMGetConfig \ vmcontrol_wrapper_api_get()->xVMControl_VMGetConfig #define VMControl_VMGetConfigFileName \ vmcontrol_wrapper_api_get()->xVMControl_VMGetConfigFileName #define VMControl_VMGetExecutionState \ vmcontrol_wrapper_api_get()->xVMControl_VMGetExecutionState #define VMControl_VMGetGuestInfo \ vmcontrol_wrapper_api_get()->xVMControl_VMGetGuestInfo #define VMControl_VMGetHeartbeat \ vmcontrol_wrapper_api_get()->xVMControl_VMGetHeartbeat #define VMControl_VMGetId \ vmcontrol_wrapper_api_get()->xVMControl_VMGetId #define VMControl_VMGetLastError \ vmcontrol_wrapper_api_get()->xVMControl_VMGetLastError #define VMControl_VMGetPid \ vmcontrol_wrapper_api_get()->xVMControl_VMGetPid #define VMControl_VMGetProductInfo \ vmcontrol_wrapper_api_get()->xVMControl_VMGetProductInfo #define VMControl_VMGetRemoteConnections \ vmcontrol_wrapper_api_get()->xVMControl_VMGetRemoteConnections #define VMControl_VMGetResource \ vmcontrol_wrapper_api_get()->xVMControl_VMGetResource #define VMControl_VMGetRunAsUser \ vmcontrol_wrapper_api_get()->xVMControl_VMGetRunAsUser #define VMControl_VMGetUptime \ vmcontrol_wrapper_api_get()->xVMControl_VMGetUptime #define VMControl_VMHasSnapshot \ vmcontrol_wrapper_api_get()->xVMControl_VMHasSnapshot #define VMControl_VMInit \ vmcontrol_wrapper_api_get()->xVMControl_VMInit #define VMControl_VMIsConnected \ vmcontrol_wrapper_api_get()->xVMControl_VMIsConnected #define VMControl_VMNewEx \ vmcontrol_wrapper_api_get()->xVMControl_VMNewEx #define VMControl_VMRemoveAllSnapshots \ vmcontrol_wrapper_api_get()->xVMControl_VMRemoveAllSnapshots #define VMControl_VMRevertToSnapshot \ vmcontrol_wrapper_api_get()->xVMControl_VMRevertToSnapshot #define VMControl_VMSetConfig \ vmcontrol_wrapper_api_get()->xVMControl_VMSetConfig #define VMControl_VMSetGuestInfo \ vmcontrol_wrapper_api_get()->xVMControl_VMSetGuestInfo #define VMControl_VMStart \ vmcontrol_wrapper_api_get()->xVMControl_VMStart #define VMControl_VMStopOrReset \ vmcontrol_wrapper_api_get()->xVMControl_VMStopOrReset #define VMControl_VMSuspendToDisk \ vmcontrol_wrapper_api_get()->xVMControl_VMSuspendToDisk #define VMControl_VMToolsLastActive \ vmcontrol_wrapper_api_get()->xVMControl_VMToolsLastActive #endif #endif /* VMCONTROL_WRAPPER_H */ hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/win32/000077500000000000000000000000001210132627500222355ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/win32/eventlog.c000066400000000000000000000264711210132627500242360ustar00rootroot00000000000000/* * Copyright (c) 2004-2007, 2009 Hyperic, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ #ifdef WIN32 #define UNICODE #define _UNICODE #include "javasigar.h" #include "win32bindings.h" #define MAX_MSG_LENGTH 8192 #define MAX_ERROR_LENGTH 1024 #define REG_MSGFILE_ROOT L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\" #define FILESEP L";" #define STRING_SIG "Ljava/lang/String;" #define UNICODE_SetStringField(field, str) \ id = JENV->GetFieldID(env, cls, field, STRING_SIG); \ value = JENV->NewString(env, (const jchar *)str, wcslen(str)); \ JENV->SetObjectField(env, obj, id, value) #define ARRLEN(arr) (sizeof(arr) / sizeof(arr[0])) static void win32_set_pointer(JNIEnv *env, jobject obj, const void *ptr) { jfieldID pointer_field; int pointer_int; jclass cls; cls = JENV->GetObjectClass(env, obj); pointer_field = JENV->GetFieldID(env, cls, "eventLogHandle", "I"); pointer_int = (int)ptr; JENV->SetIntField(env, obj, pointer_field, pointer_int); } static HANDLE win32_get_pointer(JNIEnv *env, jobject obj) { jfieldID pointer_field; HANDLE h; jclass cls; cls = JENV->GetObjectClass(env, obj); pointer_field = JENV->GetFieldID(env, cls, "eventLogHandle", "I"); h = (HANDLE)JENV->GetIntField(env, obj, pointer_field); if (!h) { win32_throw_exception(env, "Event log not opened"); } return h; } static int get_messagefile_dll(LPWSTR app, LPWSTR source, LPWSTR entry, LPWSTR dllfile) { HKEY hk; WCHAR buf[MAX_MSG_LENGTH]; DWORD type, data = sizeof(buf); LONG rc; wcscpy(buf, REG_MSGFILE_ROOT); wcscat(buf, app); wcscat(buf, L"\\"); wcscat(buf, source); rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, buf, 0, KEY_READ, &hk); if (rc) { return rc; } rc = RegQueryValueEx(hk, entry, NULL, &type, (LPBYTE)buf, &data); if (rc) { RegCloseKey(hk); return rc; } wcsncpy(dllfile, buf, MAX_MSG_LENGTH); dllfile[MAX_MSG_LENGTH-1] = '\0'; RegCloseKey(hk); return ERROR_SUCCESS; } static int get_formatted_message(EVENTLOGRECORD *pevlr, DWORD id, LPWSTR dllfile, LPWSTR msg) { LPVOID msgbuf = NULL; WCHAR msgdll[MAX_MSG_LENGTH]; LPWSTR insert_strs[56], ptr; int i, max = ARRLEN(insert_strs); const DWORD flags = FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_MAX_WIDTH_MASK; if (!ExpandEnvironmentStrings(dllfile, msgdll, ARRLEN(msgdll))) { return GetLastError(); } memset(insert_strs, '\0', sizeof(insert_strs)); if (pevlr) { ptr = (LPWSTR)((LPBYTE)pevlr + pevlr->StringOffset); for (i = 0; i < pevlr->NumStrings && i < max; i++) { insert_strs[i] = ptr; ptr += wcslen(ptr) + 1; } } ptr = wcstok(msgdll, FILESEP); while (ptr) { HINSTANCE hlib; hlib = LoadLibraryEx(ptr, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hlib) { FormatMessage(flags, hlib, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_ENGLISH_US), (LPWSTR) &msgbuf, sizeof(msgbuf), //min bytes w/ FORMAT_MESSAGE_ALLOCATE_BUFFER (va_list *)insert_strs); FreeLibrary(hlib); if (msgbuf) { break; } } ptr = wcstok(NULL, FILESEP); } if (msgbuf) { wcsncpy(msg, msgbuf, MAX_MSG_LENGTH); msg[MAX_MSG_LENGTH-1] = '\0'; LocalFree(msgbuf); return ERROR_SUCCESS; } else { return !ERROR_SUCCESS; } } static int get_formatted_event_message(EVENTLOGRECORD *pevlr, LPWSTR name, LPWSTR source, LPWSTR msg) { WCHAR dllfile[MAX_MSG_LENGTH]; if (get_messagefile_dll(name, source, L"EventMessageFile", dllfile) != ERROR_SUCCESS) { return !ERROR_SUCCESS; } return get_formatted_message(pevlr, pevlr->EventID, dllfile, msg); } static int get_formatted_event_category(EVENTLOGRECORD *pevlr, LPWSTR name, LPWSTR source, LPWSTR msg) { WCHAR dllfile[MAX_MSG_LENGTH]; if (get_messagefile_dll(name, source, L"CategoryMessageFile", dllfile) != ERROR_SUCCESS) { return !ERROR_SUCCESS; } return get_formatted_message(NULL, pevlr->EventCategory, dllfile, msg); } JNIEXPORT void SIGAR_JNI(win32_EventLog_openlog) (JNIEnv *env, jobject obj, jstring lpSourceName) { HANDLE h; LPWSTR name; name = (LPWSTR)JENV->GetStringChars(env, lpSourceName, NULL); h = OpenEventLog(NULL, name); if (h == NULL) { char buf[MAX_ERROR_LENGTH]; DWORD lastError = GetLastError(); sprintf(buf, "Unable to open event log: %d", lastError); JENV->ReleaseStringChars(env, lpSourceName, name); win32_throw_exception(env, buf); return; } JENV->ReleaseStringChars(env, lpSourceName, name); /* Save the handle for later use */ win32_set_pointer(env, obj, h); } JNIEXPORT void SIGAR_JNI(win32_EventLog_close) (JNIEnv *env, jobject obj) { HANDLE h = win32_get_pointer(env, obj); CloseEventLog(h); win32_set_pointer(env, obj, NULL); } JNIEXPORT jint SIGAR_JNI(win32_EventLog_getNumberOfRecords) (JNIEnv *env, jobject obj) { DWORD records; HANDLE h = win32_get_pointer(env, obj); if (!GetNumberOfEventLogRecords(h, &records)) { win32_throw_last_error(env); return 0; } return records; } JNIEXPORT jint SIGAR_JNI(win32_EventLog_getOldestRecord) (JNIEnv *env, jobject obj) { DWORD oldest; HANDLE h = win32_get_pointer(env, obj); if (!GetOldestEventLogRecord(h, &oldest)) { win32_throw_last_error(env); return 0; } return oldest; } JNIEXPORT jobject SIGAR_JNI(win32_EventLog_readlog) (JNIEnv *env, jobject obj, jstring jname, jint recordOffset) { EVENTLOGRECORD *pevlr; BYTE buffer[8192]; WCHAR msg[MAX_MSG_LENGTH]; DWORD dwRead, dwNeeded; LPWSTR source, machineName; HANDLE h; BOOL rv; jclass cls = WIN32_FIND_CLASS("EventLogRecord"); jfieldID id; jstring value; LPWSTR name; BOOL has_category = FALSE; /* 1.6.x compat */ h = win32_get_pointer(env, obj); pevlr = (EVENTLOGRECORD *)&buffer; rv = ReadEventLog(h, EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ, recordOffset, pevlr, sizeof(buffer), &dwRead, &dwNeeded); if (!rv) { char buf[MAX_ERROR_LENGTH]; DWORD lastError = GetLastError(); if (lastError == ERROR_INSUFFICIENT_BUFFER) { /* XXX need to handle this */ sprintf(buf, "Buffer size (%d) too small (%d needed)", sizeof(buffer), dwNeeded); } else { sprintf(buf, "Error reading from the event log: %d", lastError); } win32_throw_exception(env, buf); return NULL; } obj = JENV->AllocObject(env, cls); SIGAR_CHEX; id = JENV->GetFieldID(env, cls, "recordNumber", "J"); JENV->SetLongField(env, obj, id, pevlr->RecordNumber); id = JENV->GetFieldID(env, cls, "timeGenerated", "J"); JENV->SetLongField(env, obj, id, pevlr->TimeGenerated); id = JENV->GetFieldID(env, cls, "timeWritten", "J"); JENV->SetLongField(env, obj, id, pevlr->TimeWritten); id = JENV->GetFieldID(env, cls, "eventId", "J"); JENV->SetLongField(env, obj, id, pevlr->EventID); id = JENV->GetFieldID(env, cls, "eventType", "S"); JENV->SetShortField(env, obj, id, pevlr->EventType); if (!JENV->ExceptionCheck(env)) { /* careful not to clear any existing exception */ id = JENV->GetFieldID(env, cls, "category", "S"); if (JENV->ExceptionCheck(env)) { /* older version of sigar.jar being used with sigar.dll */ JENV->ExceptionClear(env); } else { has_category = TRUE; JENV->SetShortField(env, obj, id, pevlr->EventCategory); } } /* Extract string data from the end of the structure. Lame. */ source = (LPWSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD)); UNICODE_SetStringField("source", source); name = (LPWSTR)JENV->GetStringChars(env, jname, NULL); /* Get the formatted message */ if ((pevlr->NumStrings > 0) && (get_formatted_event_message(pevlr, name, source, msg) == ERROR_SUCCESS)) { UNICODE_SetStringField("message", msg); } else if (pevlr->NumStrings > 0) { LPWSTR tmp = (LPWSTR)((LPBYTE)pevlr + pevlr->StringOffset); UNICODE_SetStringField("message", tmp); } /* Get the formatted category */ if (has_category && (get_formatted_event_category(pevlr, name, source, msg) == ERROR_SUCCESS)) { UNICODE_SetStringField("categoryString", msg); } JENV->ReleaseStringChars(env, jname, name); /* Increment up to the machine name. */ machineName = (LPWSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD) + (wcslen(source) + 1) * sizeof(WCHAR)); UNICODE_SetStringField("computerName", machineName); /* Get user id info */ if (pevlr->UserSidLength > 0) { WCHAR name[256]; WCHAR domain[256]; DWORD namelen = ARRLEN(name); DWORD domainlen = ARRLEN(domain); DWORD len; SID_NAME_USE snu; PSID sid; sid = (PSID)((LPBYTE)pevlr + pevlr->UserSidOffset); if (LookupAccountSid(NULL, sid, name, &namelen, domain, &domainlen, &snu)) { UNICODE_SetStringField("user", name); } } return obj; } JNIEXPORT void SIGAR_JNI(win32_EventLog_waitForChange) (JNIEnv *env, jobject obj, jint timeout) { HANDLE h, hEvent; DWORD millis; h = win32_get_pointer(env, obj); hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (hEvent == NULL) { win32_throw_exception(env, "Unable to create event"); return; } if (timeout == -1) millis = INFINITE; else millis = timeout; if(!(NotifyChangeEventLog(h, hEvent))) { char buf[MAX_ERROR_LENGTH]; sprintf(buf, "Error registering for event log to change: %d", GetLastError()); win32_throw_exception(env, buf); return; } if (WaitForSingleObject(hEvent, millis) == WAIT_FAILED) { char buf[MAX_ERROR_LENGTH]; sprintf(buf, "Error waiting for event log change: %d", GetLastError()); win32_throw_exception(env, buf); } return; } #endif /* WIN32 */ hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/win32/pdh.c000066400000000000000000000404011210132627500231530ustar00rootroot00000000000000/* * Copyright (c) 2004-2007 Hyperic, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ #ifdef WIN32 #define UNICODE #define _UNICODE #include #include #include "win32bindings.h" #include "javasigar.h" #ifdef __cplusplus extern "C" { #endif #ifndef PDH_ACCESS_DENIED #define PDH_ACCESS_DENIED ((DWORD)0xC0000BDBL) #endif /** * Hack around not being able to format error codes using * FORMAT_MESSAGE_FROM_HMODULE. We only define the error * codes that could be possibly returned. */ static char *get_error_message(PDH_STATUS status) { switch (status) { case PDH_CSTATUS_NO_MACHINE: return "The computer is unavailable"; case PDH_CSTATUS_NO_OBJECT: return "The specified object could not be found on the computer"; case PDH_INVALID_ARGUMENT: return "A required argument is invalid"; case PDH_MEMORY_ALLOCATION_FAILURE: return "A required temporary buffer could not be allocated"; case PDH_INVALID_HANDLE: return "The query handle is not valid"; case PDH_NO_DATA: return "The query does not currently have any counters"; case PDH_CSTATUS_BAD_COUNTERNAME: return "The counter name path string could not be parsed or " "interpreted"; case PDH_CSTATUS_NO_COUNTER: return "The specified counter was not found"; case PDH_CSTATUS_NO_COUNTERNAME: return "An empty counter name path string was passed in"; case PDH_FUNCTION_NOT_FOUND: return "The calculation function for this counter could not " "be determined"; case PDH_ACCESS_DENIED: return "Access denied"; default: return "Unknown error"; } } JNIEXPORT jint SIGAR_JNI(win32_Pdh_validate) (JNIEnv *env, jclass cur, jstring jpath) { PDH_STATUS status; jboolean is_copy; LPCTSTR path = JENV->GetStringChars(env, jpath, &is_copy); status = PdhValidatePath(path); if (is_copy) { JENV->ReleaseStringChars(env, jpath, path); } return status; } JNIEXPORT void SIGAR_JNI(win32_Pdh_pdhConnectMachine) (JNIEnv *env, jobject cur, jstring jhost) { PDH_STATUS status; LPCTSTR host = JENV->GetStringChars(env, jhost, NULL); status = PdhConnectMachine(host); JENV->ReleaseStringChars(env, jhost, host); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); } } JNIEXPORT jlong JNICALL SIGAR_JNI(win32_Pdh_pdhOpenQuery) (JNIEnv *env, jobject cur) { HQUERY h_query; PDH_STATUS status; status = PdhOpenQuery(NULL, 0, &h_query); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return 0; } return (jlong)h_query; } JNIEXPORT void SIGAR_JNI(win32_Pdh_pdhCloseQuery) (JNIEnv *env, jclass cur, jlong query) { HQUERY h_query = (HQUERY)query; PDH_STATUS status; // Close the query and the log file. status = PdhCloseQuery(h_query); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return; } } JNIEXPORT jlong SIGAR_JNI(win32_Pdh_pdhAddCounter) (JNIEnv *env, jclass cur, jlong query, jstring cp) { HCOUNTER h_counter; HQUERY h_query = (HQUERY)query; PDH_STATUS status; LPCTSTR counter_path = JENV->GetStringChars(env, cp, NULL); /* Add the counter that created the data in the log file. */ status = PdhAddCounter(h_query, counter_path, 0, &h_counter); if (status == PDH_CSTATUS_NO_COUNTER) { /* if given counter does not exist, * try the same name w/ "/sec" appended */ TCHAR counter_sec[MAX_PATH]; lstrcpy(counter_sec, counter_path); lstrcat(counter_sec, _T("/sec")); status = PdhAddCounter(h_query, counter_sec, 0, &h_counter); } JENV->ReleaseStringChars(env, cp, counter_path); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return 0; } return (jlong)h_counter; } JNIEXPORT void SIGAR_JNI(win32_Pdh_pdhRemoveCounter) (JNIEnv *env, jclass cur, jlong counter) { HCOUNTER h_counter = (HCOUNTER)counter; PDH_STATUS status; status = PdhRemoveCounter(h_counter); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return; } } JNIEXPORT jdouble SIGAR_JNI(win32_Pdh_pdhGetValue) (JNIEnv *env, jclass cur, jlong query, jlong counter, jboolean fmt) { HCOUNTER h_counter = (HCOUNTER)counter; HQUERY h_query = (HQUERY)query; PDH_STATUS status; PDH_RAW_COUNTER raw_value; PDH_FMT_COUNTERVALUE fmt_value; DWORD type; status = PdhCollectQueryData(h_query); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return 0; } if (fmt) { /* may require 2 counters, see msdn docs */ int i=0; for (i=0; i<2; i++) { status = PdhGetFormattedCounterValue(h_counter, PDH_FMT_DOUBLE, (LPDWORD)NULL, &fmt_value); if (status == ERROR_SUCCESS) { break; } PdhCollectQueryData(h_query); } } else { status = PdhGetRawCounterValue(h_counter, &type, &raw_value); } if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return 0; } if (fmt) { return fmt_value.doubleValue; } else { return (jdouble)raw_value.FirstValue; } } JNIEXPORT jstring SIGAR_JNI(win32_Pdh_pdhGetDescription) (JNIEnv *env, jclass cur, jlong counter) { HCOUNTER h_counter = (HCOUNTER)counter; PDH_COUNTER_INFO *info = NULL; jstring retval = NULL; DWORD size = 0; PDH_STATUS status; status = PdhGetCounterInfo(h_counter, TRUE, &size, NULL); if (status != PDH_MORE_DATA) { win32_throw_exception(env, get_error_message(status)); return NULL; } info = malloc(size); status = PdhGetCounterInfo(h_counter, 1, &size, info); if (status == ERROR_SUCCESS) { if (info->szExplainText) { retval = JENV->NewString(env, info->szExplainText, lstrlen(info->szExplainText)); } } else { win32_throw_exception(env, get_error_message(status)); } free(info); return retval; } JNIEXPORT jlong SIGAR_JNI(win32_Pdh_pdhGetCounterType) (JNIEnv *env, jclass cur, jlong counter) { HCOUNTER h_counter = (HCOUNTER)counter; PDH_COUNTER_INFO info; DWORD size = sizeof(info); PDH_STATUS status; status = PdhGetCounterInfo(h_counter, FALSE, &size, &info); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return -1; } return info.dwType; } JNIEXPORT jobjectArray SIGAR_JNI(win32_Pdh_pdhGetInstances) (JNIEnv *env, jclass cur, jstring cp) { PDH_STATUS status = ERROR_SUCCESS; DWORD counter_list_size = 0; DWORD instance_list_size = 8096; LPTSTR instance_list_buf = (LPTSTR)malloc ((instance_list_size * sizeof (TCHAR))); LPTSTR cur_object = NULL; LPCTSTR counter_path = JENV->GetStringChars(env, cp, 0); jobjectArray array = NULL; status = PdhEnumObjectItems(NULL, NULL, counter_path, NULL, &counter_list_size, instance_list_buf, &instance_list_size, PERF_DETAIL_WIZARD, FALSE); if (status == PDH_MORE_DATA && instance_list_size > 0) { // Allocate the buffers and try the call again. if (instance_list_buf != NULL) free(instance_list_buf); instance_list_buf = (LPTSTR)malloc((instance_list_size * sizeof (TCHAR))); counter_list_size = 0; status = PdhEnumObjectItems (NULL, NULL, counter_path, NULL, &counter_list_size, instance_list_buf, &instance_list_size, PERF_DETAIL_WIZARD, FALSE); } JENV->ReleaseStringChars(env, cp, counter_path); // Still may get PDH_ERROR_MORE data after the first reallocation, // but that is OK for just browsing the instances if (status == ERROR_SUCCESS || status == PDH_MORE_DATA) { int i, count; for (cur_object = instance_list_buf, count = 0; *cur_object != 0; cur_object += lstrlen(cur_object) + 1, count++); array = JENV->NewObjectArray(env, count, JENV->FindClass(env, "java/lang/String"), JENV->NewStringUTF(env, "")); if (JENV->ExceptionCheck(env)) { free(instance_list_buf); return NULL; } /* Walk the return instance list, creating an array */ for (cur_object = instance_list_buf, i = 0; *cur_object != 0; i++) { int len = lstrlen(cur_object); jstring s = JENV->NewString(env, (const jchar *)cur_object, len); JENV->SetObjectArrayElement(env, array, i, s); if (JENV->ExceptionCheck(env)) { free(instance_list_buf); return NULL; } cur_object += len + 1; } } else { if (instance_list_buf != NULL) free(instance_list_buf); // An error occured win32_throw_exception(env, get_error_message(status)); return NULL; } if (instance_list_buf != NULL) free(instance_list_buf); return array; } JNIEXPORT jobjectArray SIGAR_JNI(win32_Pdh_pdhGetKeys) (JNIEnv *env, jclass cur, jstring cp) { PDH_STATUS status = ERROR_SUCCESS; DWORD counter_list_size = 8096; DWORD instance_list_size = 0; LPTSTR instance_list_buf = (LPTSTR)malloc (counter_list_size * sizeof(TCHAR)); LPTSTR cur_object = NULL; LPCTSTR counter_path = JENV->GetStringChars(env, cp, NULL); jobjectArray array = NULL; status = PdhEnumObjectItems(NULL, NULL, counter_path, instance_list_buf, &counter_list_size, NULL, &instance_list_size, PERF_DETAIL_WIZARD, FALSE); if (status == PDH_MORE_DATA) { /* Allocate the buffers and try the call again. */ if (instance_list_buf != NULL) free(instance_list_buf); instance_list_buf = (LPTSTR)malloc(counter_list_size * sizeof(TCHAR)); instance_list_size = 0; status = PdhEnumObjectItems (NULL, NULL, counter_path, instance_list_buf, &counter_list_size, NULL, &instance_list_size, PERF_DETAIL_WIZARD, 0); } JENV->ReleaseStringChars(env, cp, counter_path); if (status == ERROR_SUCCESS || status == PDH_MORE_DATA) { int i, count; for (cur_object = instance_list_buf, count = 0; *cur_object != 0; cur_object += lstrlen(cur_object) + 1, count++); array = JENV->NewObjectArray(env, count, JENV->FindClass(env, "java/lang/String"), JENV->NewStringUTF(env, "")); if (JENV->ExceptionCheck(env)) { free(instance_list_buf); return NULL; } /* Walk the return instance list, creating an array */ for (cur_object = instance_list_buf, i = 0; *cur_object != 0; i++) { int len = lstrlen(cur_object); jstring s = JENV->NewString(env, (const jchar *)cur_object, len); JENV->SetObjectArrayElement(env, array, i, s); if (JENV->ExceptionCheck(env)) { free(instance_list_buf); return NULL; } cur_object += len + 1; } } else { // An error occured if (instance_list_buf != NULL) free(instance_list_buf); // An error occured win32_throw_exception(env, get_error_message(status)); return NULL; } if (instance_list_buf != NULL) free(instance_list_buf); return array; } JNIEXPORT jobjectArray SIGAR_JNI(win32_Pdh_pdhGetObjects) (JNIEnv *env, jclass cur) { PDH_STATUS status; DWORD list_size = 8096; LPTSTR list_buf = (LPTSTR)malloc(list_size * sizeof(TCHAR)); LPTSTR cur_object; DWORD i, num_objects = 0; jobjectArray array = NULL; status = PdhEnumObjects(NULL, NULL, list_buf, &list_size, PERF_DETAIL_WIZARD, FALSE); if (status == PDH_MORE_DATA) { // Re-try call with a larger buffer if (list_buf != NULL) free(list_buf); list_buf = (LPTSTR)malloc(list_size * sizeof(TCHAR)); status = PdhEnumObjects(NULL, NULL, list_buf, &list_size, PERF_DETAIL_WIZARD, FALSE); } if (status != ERROR_SUCCESS) { if (list_buf != NULL) free(list_buf); win32_throw_exception(env, get_error_message(status)); return NULL; } // Walk the return buffer counting the number of objects for (cur_object = list_buf, num_objects = 0; *cur_object != 0; cur_object += lstrlen(cur_object) + 1, num_objects++); array = JENV->NewObjectArray(env, num_objects, JENV->FindClass(env, "java/lang/String"), JENV->NewStringUTF(env, "")); if (JENV->ExceptionCheck(env)) { free(list_buf); return NULL; } for (cur_object = list_buf, i = 0; *cur_object != 0; i++) { int len = lstrlen(cur_object); jstring s = JENV->NewString(env, (const jchar *)cur_object, len); JENV->SetObjectArrayElement(env, array, i, s); if (JENV->ExceptionCheck(env)) { free(list_buf); return NULL; } cur_object += len + 1; } if (list_buf != NULL) free(list_buf); return array; } JNIEXPORT jstring SIGAR_JNI(win32_Pdh_pdhLookupPerfName) (JNIEnv *env, jclass cur, jint index) { TCHAR path[MAX_PATH + 1]; DWORD len = sizeof(path) / sizeof(TCHAR); /* len is number of TCHAR's, not sizeof(path) */ PDH_STATUS status = PdhLookupPerfNameByIndex(NULL, index, path, &len); if (status == ERROR_SUCCESS) { return JENV->NewString(env, (const jchar *)path, len); } else { win32_throw_exception(env, get_error_message(status)); return NULL; } } JNIEXPORT jint SIGAR_JNI(win32_Pdh_pdhLookupPerfIndex) (JNIEnv *env, jclass cur, jstring jname) { DWORD index; LPCTSTR name = JENV->GetStringChars(env, jname, NULL); PDH_STATUS status = PdhLookupPerfIndexByNameW(NULL, name, &index); JENV->ReleaseStringChars(env, jname, name); if (status == ERROR_SUCCESS) { return index; } else { win32_throw_exception(env, get_error_message(status)); return -1; } } #ifdef __cplusplus } #endif #endif /* WIN32 */ hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/win32/util.c000066400000000000000000000025001210132627500233530ustar00rootroot00000000000000/* * Copyright (c) 2004-2006, 2008 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. */ #ifdef WIN32 #include #include #include "sigar.h" #include "sigar_private.h" #include "win32bindings.h" #include "javasigar.h" /** * Set of common utilities for all win32bindings objects */ #ifdef __cplusplus extern "C" { #endif void win32_throw_exception(JNIEnv *env, char *msg) { jclass exceptionClass = WIN32_FIND_CLASS("Win32Exception"); JENV->ThrowNew(env, exceptionClass, msg); } void win32_throw_last_error(JNIEnv *env) { win32_throw_error(env, GetLastError()); } void win32_throw_error(JNIEnv *env, LONG err) { char msg[8192]; win32_throw_exception(env, sigar_strerror_get(err, msg, sizeof(msg))); } #ifdef __cplusplus } #endif #endif /* WIN32 */ hyperic-sigar-1.6.4+dfsg/bindings/java/src/jni/win32/win32bindings.h000066400000000000000000000026231210132627500250710ustar00rootroot00000000000000/* * Copyright (c) 2004-2006 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. */ #ifndef WIN32_BINDINGS_H #define WIN32_BINDINGS_H /* Exclude rarely-used stuff from windows headers */ #define WIN32_LEAN_AND_MEAN /* Windows Header Files */ #include #include /* Include java jni headers */ #include #define WIN32_PACKAGE "org/hyperic/sigar/win32/" #define WIN32_FIND_CLASS(name) \ JENV->FindClass(env, WIN32_PACKAGE name) #define WIN32_ALLOC_OBJECT(name) \ JENV->AllocObject(env, WIN32_FIND_CLASS(name)) #define SetStringField(env, obj, fieldID, val) \ JENV->SetObjectField(env, obj, fieldID, JENV->NewStringUTF(env, val)) #ifdef __cplusplus extern "C" { #endif void win32_throw_exception(JNIEnv *env, char *msg); void win32_throw_error(JNIEnv *env, LONG err); void win32_throw_last_error(JNIEnv *env); #ifdef __cplusplus } #endif #endif hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/000077500000000000000000000000001210132627500213025ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/000077500000000000000000000000001210132627500227455ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/000077500000000000000000000000001210132627500240525ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/CpuPerc.java000066400000000000000000000053241210132627500262620ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 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; /** * CPU percentage usage */ public class CpuPerc implements java.io.Serializable { private static final long serialVersionUID = 05242007L; private double user; private double sys; private double nice; private double idle; private double wait; private double irq; private double softIrq; private double stolen; private double combined; CpuPerc() {} native void gather(Sigar sigar, Cpu oldCpu, Cpu curCpu); static CpuPerc fetch(Sigar sigar, Cpu oldCpu, Cpu curCpu) { CpuPerc perc = new CpuPerc(); perc.gather(sigar, oldCpu, curCpu); return perc; } /** * @deprecated */ public static CpuPerc calculate(Cpu oldCpu, Cpu curCpu) { Sigar sigar = new Sigar(); try { return fetch(sigar, oldCpu, curCpu); } finally { sigar.close(); } } public double getUser() { return this.user; } public double getSys() { return this.sys; } public double getNice() { return this.nice; } public double getIdle() { return this.idle; } public double getWait() { return this.wait; } public double getIrq() { return this.irq; } public double getSoftIrq() { return this.softIrq; } public double getStolen() { return this.stolen; } /** * @return Sum of User + Sys + Nice + Wait */ public double getCombined() { return this.combined; } public static String format(double val) { String p = String.valueOf(val * 100.0); //cant wait for sprintf. int ix = p.indexOf(".") + 1; String percent = p.substring(0, ix) + p.substring(ix, ix+1); return percent + "%"; } public String toString() { return "CPU states: " + format(this.user) + " user, " + format(this.sys) + " system, " + format(this.nice) + " nice, " + format(this.wait) + " wait, " + format(this.idle) + " idle"; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/CpuTimer.java000066400000000000000000000131661210132627500264540ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar; import org.hyperic.sigar.jmx.CpuTimerMBean; import java.io.PrintStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class CpuTimer implements CpuTimerMBean { private static final Map timers = Collections.synchronizedMap(new HashMap()); private Sigar sigar; private long totalTime; private long cpuTotal; private long cpuUser; private long cpuSys; private long cpuSampleFirst; private long cpuSampleLast; private long cpuSampleTime; private ThreadCpu cpu = new ThreadCpu(); private long startTime, stopTime; public CpuTimer() { this(null); } public CpuTimer(Sigar sigar) { clear(); this.sigar = sigar; } public void clear() { this.startTime = -1; this.stopTime = -1; this.totalTime = 0; this.cpuTotal = 0; this.cpuUser = 0; this.cpuSys = 0; this.cpuSampleFirst = 0; this.cpuSampleLast = 0; this.cpuSampleTime = 0; } private void stamp(CpuTimer timer) { if (this.cpuSampleFirst == 0) { this.cpuSampleFirst = toMillis(timer.cpu.total); this.cpuSampleTime = timer.startTime; } else { this.cpuSampleLast = toMillis(timer.cpu.total); } } public void add(CpuTimer timer) { stamp(timer); this.cpuTotal += timer.cpuTotal; this.cpuUser += timer.cpuUser; this.cpuSys += timer.cpuSys; this.totalTime += timer.totalTime; } public void start() { start(this.sigar); } public void start(Sigar sigar) { this.startTime = System.currentTimeMillis(); try { this.cpu.gather(sigar, 0); } catch (SigarException e) { throw new IllegalArgumentException(e.toString()); } stamp(this); } public void stop() { stop(this.sigar); } public void stop(Sigar sigar) { ThreadCpu diff = getDiff(sigar); this.cpuTotal += diff.total; this.cpuUser += diff.user; this.cpuSys += diff.sys; this.stopTime = System.currentTimeMillis(); double timeDiff = this.stopTime - this.startTime; this.totalTime += timeDiff; } public ThreadCpu getDiff() { return getDiff(this.sigar); } public ThreadCpu getDiff(Sigar sigar) { long startTotal = this.cpu.total; long startUser = this.cpu.user; long startSys = this.cpu.sys; ThreadCpu diff = new ThreadCpu(); try { this.cpu.gather(sigar, 0); } catch (SigarException e) { throw new IllegalArgumentException(e.toString()); } diff.total = this.cpu.total - startTotal; diff.user = this.cpu.user - startUser; diff.sys = this.cpu.sys - startSys; stamp(this); return diff; } public long getTotalTime() { return this.totalTime; } private long toMillis(long ns) { return ns / 1000000; //convert nanos to millis } public long getCpuTotal() { return toMillis(this.cpuTotal); } public long getCpuUser() { return toMillis(this.cpuUser); } public long getCpuSys() { return toMillis(this.cpuSys); } //expecting start/stop/add to be called more often than this, //so we give percentage over time in between calls. public double getCpuUsage() { if ((this.cpuSampleFirst == 0) || (this.cpuSampleLast == 0)) { return 0.0; } long timeNow = System.currentTimeMillis(); double diff = timeNow - this.cpuSampleTime; if (diff == 0) { return 0.0; } double usage = (this.cpuSampleLast - this.cpuSampleFirst) / diff; this.cpuSampleFirst = 0; this.cpuSampleLast = 0; this.cpuSampleTime = 0; return usage; } public long getLastSampleTime() { return this.stopTime; } public static CpuTimer getInstance(String name) { CpuTimer timer = (CpuTimer)timers.get(name); if (timer == null) { timer = new CpuTimer(); timers.put(name, timer); } return timer; } public String format(long elap) { String fraction = (elap % 1000) + ""; int pad = 3 - fraction.length(); StringBuffer buf = new StringBuffer() .append(elap / 1000).append('.'); //for example, 15 millseconds formatted as ".015" rather than ".15" while (pad-- > 0) { buf.append("0"); } buf.append(fraction).append(" seconds"); return buf.toString(); } public void list(PrintStream out) { out.println("real....." + format(getTotalTime())); out.println("user....." + format(getCpuUser())); out.println("sys......" + format(getCpuSys())); out.println("usage...." + CpuPerc.format(getCpuUsage())); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/CurrentProcessSummary.java000066400000000000000000000017401210132627500312560ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar; /** * @deprecated * @see org.hyperic.sigar.ProcStat */ public class CurrentProcessSummary extends ProcStat { public static CurrentProcessSummary get(SigarProxy sigar) throws SigarException { CurrentProcessSummary stat = new CurrentProcessSummary(); stat.gather(SigarProxyCache.getSigar(sigar)); return stat; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/FileInfo.java000066400000000000000000000304461210132627500264170ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class FileInfo extends FileAttrs implements java.io.Serializable { private static final long serialVersionUID = 02242007L; private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd HH:mm"); String name; private transient Sigar sigar; private boolean dirStatEnabled = false; private DirStat stat = null; private boolean lstat; private FileInfo oldInfo = null; /** * No file type determined. */ public static final int TYPE_NOFILE = 0; /** * A regular file. */ public static final int TYPE_REG = 1; /** * A directory. */ public static final int TYPE_DIR = 2; /** * A character device. */ public static final int TYPE_CHR = 3; /** * A block device. */ public static final int TYPE_BLK = 4; /** * A FIFO / pipe. */ public static final int TYPE_PIPE = 5; /** * A symbolic link. */ public static final int TYPE_LNK = 6; /** * A [unix domain] socket. */ public static final int TYPE_SOCK = 7; /** * A file of unknown type. */ public static final int TYPE_UNKFILE = 8; /** * Readable by user. */ public static final int MODE_UREAD = 0x0400; /** * Writable by user. */ public static final int MODE_UWRITE = 0x0200; /** * Executable by user. */ public static final int MODE_UEXECUTE = 0x0100; /** * Readable by group. */ public static final int MODE_GREAD = 0x0040; /** * Writable by group. */ public static final int MODE_GWRITE = 0x0020; /** * Executable by group. */ public static final int MODE_GEXECUTE = 0x0010; /** * Readable by others. */ public static final int MODE_WREAD = 0x0004; /** * Writable by others. */ public static final int MODE_WWRITE = 0x0002; /** * Executable by others. */ public static final int MODE_WEXECUTE = 0x0001; private static native String getTypeString(int type); native void gatherLink(Sigar sigar, String name) throws SigarException; public String getTypeString() { return FileInfo.getTypeString(this.type); } public char getTypeChar() { switch (this.type) { case TYPE_DIR: return 'd'; case TYPE_CHR: return 'c'; case TYPE_BLK: return 'b'; case TYPE_PIPE: return 'p'; case TYPE_LNK: return 'l'; case TYPE_SOCK: return 's'; default: return '-'; } } public String getName() { return this.name; } public int hashCode() { return this.name.hashCode(); } public boolean equals(Object o) { return o.equals(this.name); } private static native String getPermissionsString(long type); public String getPermissionsString() { return FileInfo.getPermissionsString(this.permissions); } private static native int getMode(long permissions); /** * Convert permissions bit mask to human readable number. * Example: * MODE_UREAD|MODE_UWRITE|MODE_GREAD|MODE_WREAD * converts to 644. * @return The file permissions mode. */ public int getMode() { return FileInfo.getMode(this.permissions); } public void enableDirStat(boolean value) { this.dirStatEnabled = value; if (value) { if (this.type != TYPE_DIR) { throw new IllegalArgumentException(this.name + " is not a directory"); } try { if (this.stat == null) { this.stat = this.sigar.getDirStat(this.name); } else { this.stat.gather(this.sigar, this.name); } } catch (SigarException e) { //ok for now } } } private class Diff { private String attr, old, cur; Diff(String attr, String old, String cur) { this.attr = attr; this.old = old; this.cur = cur; } Diff(String attr, int old, int cur) { this(attr, String.valueOf(old), String.valueOf(cur)); } Diff(String attr, long old, long cur) { this(attr, String.valueOf(old), String.valueOf(cur)); } public String toString() { return this.attr + ": " + this.old + "|" + this.cur; } } private StringBuffer format(ArrayList changes) { StringBuffer sb = new StringBuffer(); if (changes.size() == 0) { return sb; } int size = changes.size(); for (int i=0; i 0) { in.skip(offset); //use InputStream to skip bytes } reader = new InputStreamReader(in); tail(info, reader); } catch (IOException e) { error(name, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } } } public FileInfo add(String file) throws SigarException { FileInfo info = super.add(file); if (isDebug) { log.debug("add: " + file + "=" + info); } return info; } protected boolean changed(FileInfo info) throws SigarException, SigarFileNotFoundException { return info.modified() || (info.getPreviousInfo().size != info.size); } private long getOffset(FileInfo current) { FileInfo previous = current.getPreviousInfo(); if (previous == null) { if (isDebug) { log.debug(current.getName() + ": first stat"); } return current.size; } if (current.inode != previous.inode) { if (isDebug) { log.debug(current.getName() + ": file inode changed"); } return -1; } if (current.size < previous.size) { if (isDebug) { log.debug(current.getName() + ": file truncated"); } return -1; } if (isDebug) { long diff = current.size - previous.size; log.debug(current.getName() + ": " + diff + " new bytes"); } return previous.size; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/FileWatcher.java000066400000000000000000000064221210132627500271160ustar00rootroot00000000000000/* * Copyright (c) 2006 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.io.File; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public abstract class FileWatcher { private Sigar sigar; private long interval = 0; private long lastTime = 0; private Set files = Collections.synchronizedSet(new HashSet()); public abstract void onChange(FileInfo info); public void onNotFound(FileInfo info) { } public void onException(FileInfo info, SigarException e) { } public FileWatcher(Sigar sigar) { this.sigar = sigar; } public void setInterval(long interval) { this.interval = interval; } public long getInterval() { return this.interval; } public FileInfo add(File file) throws SigarException { return add(file.getAbsolutePath()); } public FileInfo add(String file) throws SigarException { FileInfo info = this.sigar.getFileInfo(file); this.files.add(info); return info; } public void add(File[] files) throws SigarException { for (int i=0; i= 1.0) { cpu.percent = 0.99; } return cpu; } /** * @return Processes CPU usage percentage. */ public double getPercent() { return this.percent; } /** * @return Number of processes matched by query. */ public int getProcesses() { return this.nproc; } /** * @return Pid of the process. */ public int hashCode() { return (int)this.pid; } public boolean equals(Object cpu) { if (!(cpu instanceof MultiProcCpu)) { return false; } return ((MultiProcCpu)cpu).pid == this.pid; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/MultiProcMem.java000066400000000000000000000026571210132627500273040ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 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 org.hyperic.sigar.ptql.ProcessFinder; public class MultiProcMem extends ProcMem { static ProcMem get(Sigar sigar, String query) throws SigarException { ProcMem mem = new ProcMem(); mem.share = Sigar.FIELD_NOTIMPL; long[] pids = ProcessFinder.find(sigar, query); for (int i=0; i this.expire) { return true; } else { return false; } } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ProcUtil.java000066400000000000000000000072261210132627500264650ustar00rootroot00000000000000/* * Copyright (c) 2006 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.io.File; import java.io.IOException; import java.util.jar.Attributes; import java.util.jar.JarFile; public class ProcUtil { private static boolean isClassName(String name) { int len = name.length(); if (len == 0) { return false; } for (int i=0; i sizeof(int) // lastCpu is used to calculate the cpuPerc; private Cpu lastCpu; private Cpu[] lastCpuList; private ProcessFinder processFinder = null; static { String nativeVersion = "unknown"; String nativeBuildDate = "unknown"; String nativeScmRevision = "unknown"; try { loadLibrary(); nativeVersion = getNativeVersion(); nativeBuildDate = getNativeBuildDate(); nativeScmRevision = getNativeScmRevision(); checkVersion(nativeVersion); } catch (SigarException e) { loadError = e.getMessage(); try { SigarLog.debug(loadError, e); } catch (NoClassDefFoundError ne) { //no log4j.jar System.err.println(loadError); e.printStackTrace(); } } NATIVE_VERSION_STRING = nativeVersion; NATIVE_BUILD_DATE = nativeBuildDate; NATIVE_SCM_REVISION = nativeScmRevision; } private static void checkVersion(String nativeVersionString) throws SigarException { StringTokenizer javaVersion = new StringTokenizer(VERSION_STRING, "."); StringTokenizer nativeVersion = new StringTokenizer(nativeVersionString, "."); String[] desc = { "major", "minor" }; for (int i=0; i * Supported Platforms: Linux, Solaris and Windows. * @param pid The process id. * @return List of loaded modules. * @exception SigarException on failure. */ private native List getProcModulesNative(long pid) throws SigarException; public List getProcModules(long pid) throws SigarException { return getProcModulesNative(pid); } public List getProcModules(String pid) throws SigarException { return getProcModules(convertPid(pid)); } /** * Find the pid of the process which is listening on the given port.

* Supported Platforms: Linux, Windows 2003, Windows XP, AIX. * @param protocol NetFlags.CONN_TCP or NetFlags.CONN_UDP. * @param port The port number. * @return pid of the process. * @exception SigarException on failure. */ public native long getProcPort(int protocol, long port) throws SigarException; /** * @param protocol "tcp" or "udp". * @param port The port number. * @return pid of the process. * @exception SigarException on failure. */ public long getProcPort(String protocol, String port) throws SigarException { return getProcPort(NetFlags.getConnectionProtocol(protocol), Integer.parseInt(port)); } /** * Get the cumulative cpu time for the calling thread. */ public ThreadCpu getThreadCpu() throws SigarException { return ThreadCpu.fetch(this, 0); } private native FileSystem[] getFileSystemListNative() throws SigarException; /** * Get list of file systems. * @exception SigarException on failure. */ public FileSystem[] getFileSystemList() throws SigarException { FileSystem[] fslist = getFileSystemListNative(); if (this.mounts != null) { this.mounts.init(fslist); } return fslist; } /** * Get file system usage. * @param name Name of the directory on which filesystem is mounted. * @exception SigarException on failure. */ public FileSystemUsage getFileSystemUsage(String name) throws SigarException { if (name == null) { throw new SigarException("name cannot be null"); } return FileSystemUsage.fetch(this, name); } /** * Get disk usage. * @param name Name of disk * @exception SigarException on failure. */ public DiskUsage getDiskUsage(String name) throws SigarException { if (name == null) { throw new SigarException("name cannot be null"); } return DiskUsage.fetch(this, name); } /** * Get file system usage of a mounted directory. * This method checks that the given directory is mounted. * Unlike getFileSystemUsage() which only requires that the * directory exists within a mounted file system. * This method will also check that NFS servers are reachable via RPC * before attempting to get the file system stats to prevent application * hang when an NFS server is down. * @param name Name of the directory on which filesystem is mounted. * @exception SigarException If given directory is not mounted. * @exception NfsUnreachableException If NFS server is unreachable. * @see org.hyperic.sigar.Sigar#getFileSystemUsage */ public FileSystemUsage getMountedFileSystemUsage(String name) throws SigarException, NfsUnreachableException { FileSystem fs = getFileSystemMap().getFileSystem(name); if (fs == null) { throw new SigarException(name + " is not a mounted filesystem"); } if (fs instanceof NfsFileSystem) { NfsFileSystem nfs = (NfsFileSystem)fs; if (!nfs.ping()) { throw nfs.getUnreachableException(); } } return FileSystemUsage.fetch(this, name); } public FileSystemMap getFileSystemMap() throws SigarException { if (this.mounts == null) { this.mounts = new FileSystemMap(); } getFileSystemList(); //this.mounts.init() return this.mounts; } public FileInfo getFileInfo(String name) throws SigarException { return FileInfo.fetchFileInfo(this, name); } public FileInfo getLinkInfo(String name) throws SigarException { return FileInfo.fetchLinkInfo(this, name); } public DirStat getDirStat(String name) throws SigarException { return DirStat.fetch(this, name); } public DirUsage getDirUsage(String name) throws SigarException { return DirUsage.fetch(this, name); } /** * Get list of cpu infomation. * @exception SigarException on failure. */ public native CpuInfo[] getCpuInfoList() throws SigarException; private native Cpu[] getCpuListNative() throws SigarException; /** * Get list of per-cpu metrics. * @exception SigarException on failure. */ public Cpu[] getCpuList() throws SigarException { return getCpuListNative(); } /** * Get list of network routes. * @exception SigarException on failure. */ public native NetRoute[] getNetRouteList() throws SigarException; /** * Get list of network connections. * @exception SigarException on failure. */ public native NetConnection[] getNetConnectionList(int flags) throws SigarException; /** * Get the TCP listen address for the given port. * If there is not a listener on the given port, null will be returned. */ public native String getNetListenAddress(long port) throws SigarException; public String getNetListenAddress(String port) throws SigarException { return getNetListenAddress(Long.parseLong(port)); } public native String getNetServicesName(int protocol, long port); public NetStat getNetStat() throws SigarException { NetStat netstat = new NetStat(); netstat.stat(this); return netstat; } public NetStat getNetStat(byte[] address, long port) throws SigarException { NetStat netstat = new NetStat(); netstat.stat(this, address, port); return netstat; } public native Who[] getWhoList() throws SigarException; /** * TCP-MIB stats * @exception SigarException on failure. */ public Tcp getTcp() throws SigarException { return Tcp.fetch(this); } public NfsClientV2 getNfsClientV2() throws SigarException { return NfsClientV2.fetch(this); } public NfsServerV2 getNfsServerV2() throws SigarException { return NfsServerV2.fetch(this); } public NfsClientV3 getNfsClientV3() throws SigarException { return NfsClientV3.fetch(this); } public NfsServerV3 getNfsServerV3() throws SigarException { return NfsServerV3.fetch(this); } /** * Get general network info. * @exception SigarException on failure. */ public NetInfo getNetInfo() throws SigarException { return NetInfo.fetch(this); } /** * Get network interface configuration info. * @exception SigarException on failure. */ public NetInterfaceConfig getNetInterfaceConfig(String name) throws SigarException { return NetInterfaceConfig.fetch(this, name); } /** * Get default network interface configuration info. * Iterates getNetInterfaceList(), returning the first * available ethernet interface. * @exception SigarException on failure. */ public NetInterfaceConfig getNetInterfaceConfig() throws SigarException { String[] interfaces = getNetInterfaceList(); for (int i=0; i 0) { continue; } if ((flags & NetFlags.IFF_LOOPBACK) > 0) { continue; } return ifconfig; } String msg = "No ethernet interface available"; throw new SigarException(msg); } /** * Get network interface stats. * @exception SigarException on failure. */ public NetInterfaceStat getNetInterfaceStat(String name) throws SigarException { return NetInterfaceStat.fetch(this, name); } /** * Get the list of configured network interface names. * @exception SigarException on failure. */ public native String[] getNetInterfaceList() throws SigarException; /** * Prompt for a password, disabling terminal echo * during user input. * @param prompt Text printed before disabling echo * @return Text entered by the user. * @throws IOException If input could not be read. * @throws SigarNotImplementedException If the native method * is not implemented on the current platform. */ native static String getPasswordNative(String prompt) throws IOException, SigarNotImplementedException; /** * Prompt for a password, disabling terminal echo * during user input if possible. * @param prompt Text printed before disabling echo * @return Text entered by the user. * @throws IOException If input could not be read. */ public static String getPassword(String prompt) throws IOException { try { return getPasswordNative(prompt); } catch (IOException e) { throw e; } catch (SigarNotImplementedException e) { //fallthrough } //fallback if native .so was not loaded or not supported System.out.print(prompt); return (new BufferedReader(new InputStreamReader(System.in))). readLine(); } /** * Reliably retrieve the FQDN for a machine * * @return The fully qualified domain name of the machine. * @exception SigarException on failure. */ public native String getFQDN() throws SigarException; /** * Enabling logging in the native Sigar code. * This method will hook log4j into the Sigar * native logging methods. Note that the majority * of logging in the native code is only at the DEBUG * level. */ public void enableLogging(boolean value) { if (value) { SigarLog.enable(this); } else { SigarLog.disable(this); } } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarCacheObject.java000066400000000000000000000013031210132627500300320ustar00rootroot00000000000000/* * Copyright (c) 2006 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; class SigarCacheObject { long timestamp = 0; Object value = null; } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarException.java000066400000000000000000000021241210132627500276400ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar; /** * Sigar base exception class. */ public class SigarException extends Exception { private String message; public SigarException () { super(); } public SigarException (String s) { super(s); } public String getMessage() { if (this.message != null) { return this.message; } else { return super.getMessage(); } } void setMessage(String message) { this.message = message; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarFileNotFoundException.java000066400000000000000000000013701210132627500321170ustar00rootroot00000000000000/* * Copyright (c) 2006 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 SigarFileNotFoundException extends SigarException { public SigarFileNotFoundException(String s) { super(s); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarInvoker.java000066400000000000000000000265141210132627500273300ustar00rootroot00000000000000/* * Copyright (c) 2006, 2008 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.Arrays; import java.util.HashMap; import java.lang.reflect.Proxy; import java.lang.reflect.Method; /** * This class provides a string-ish interface to sigar. * It is intended for use via JMX and Hyperic HQ measurement * plugins. Method lookups are cached and the like for better * performance. */ public class SigarInvoker { private static HashMap attrCache = new HashMap(); private static HashMap compatTypes = new HashMap(); private static HashMap compatAttrs = new HashMap(); static { //XXX backwards compat for HQ because metric template //updating does not work. compatTypes.put("NetIfconfig", "NetInterfaceConfig"); compatTypes.put("NetIfstat", "NetInterfaceStat"); compatTypes.put("DirStats", "DirStat"); compatAttrs.put("Utime", "User"); compatAttrs.put("Stime", "Sys"); } //avoid object creation as much as possible private static final Class[] VOID_SIGNATURE = new Class[0]; private Class[] ARG_SIGNATURE = new Class[] { String.class }; private Class[] ARG2_SIGNATURE = new Class[] { String.class, String.class }; private static final Object[] VOID_ARGS = new Object[0]; private Object[] ARG_ARGS = new Object[1]; private String type = null; private boolean typeIsArray = false; private int arrayIdx = -1; private boolean hasArrayIdx = false; private int typeArrayType; private static final int ARRAY_TYPE_OBJECT = 1; private static final int ARRAY_TYPE_DOUBLE = 2; private static final int ARRAY_TYPE_LONG = 3; private Method typeMethod; private SigarProxy sigarProxy; private SigarProxyCache handler; protected SigarInvoker() { } /** * @param proxy SigarProxy implementation such as SigarProxyCache * @param type The sigar type. Valid name is any of the SigarProxy * interface methods (minus the 'get' prefix). */ public SigarInvoker(SigarProxy proxy, String type) { setProxy(proxy); setType(type); } protected void setProxy(SigarProxy proxy) { try { this.handler = (SigarProxyCache)Proxy.getInvocationHandler(proxy); } catch (IllegalArgumentException e) { e.printStackTrace(); //XXX we can still deal w/o this.handler } this.sigarProxy = proxy; } protected void setType(String val) { String alias = (String)compatTypes.get(val); if (alias != null) { val = alias; } this.type = val; } /** * The type of this instance, as passed to the constructor. */ public String getType() { return this.type; } private int getAttributeIndex(String attr) { try { return Integer.valueOf(attr).intValue(); } catch (NumberFormatException e) { return -1; } } private Method getTypeMethod(Object[] args) throws SigarException { if (this.typeMethod == null) { Class[] sig = VOID_SIGNATURE; boolean argIsArrayIdx = false; int argLength = 0; String getter = "get" + getType(); if (args != null) { argLength = args.length; switch (argLength) { case 1: sig = ARG_SIGNATURE; break; case 2: sig = ARG2_SIGNATURE; break; default: throw new IllegalArgumentException(); } } try { this.typeMethod = Sigar.class.getMethod(getter, sig); } catch (Exception e) { try { this.typeMethod = Sigar.class.getMethod(getter, VOID_SIGNATURE); if (argLength == 1) { argIsArrayIdx = true; } } catch (Exception e2) { String msg = "Unable to determine getter for " + type; throw new SigarException(msg); } } Class typeClass = this.typeMethod.getReturnType(); if (typeClass.isArray()) { this.typeIsArray = true; if (argIsArrayIdx) { try { this.arrayIdx = Integer.parseInt((String)args[0]); } catch (NumberFormatException ne) { String msg = getType() + ": '" + args[0] + "' is not a number"; throw new SigarException(msg); } this.hasArrayIdx = true; } Class componentClass = typeClass.getComponentType(); if (componentClass.isPrimitive()) { //e.g. getLoadAverage if (componentClass == Double.TYPE) { this.typeArrayType = ARRAY_TYPE_DOUBLE; } //e.g. getProcList else if (componentClass == Long.TYPE) { this.typeArrayType = ARRAY_TYPE_LONG; } else { //won't happen. throw new SigarException("unsupported array type: " + componentClass.getName()); } } else { this.typeArrayType = ARRAY_TYPE_OBJECT; } } else { this.typeIsArray = false; } } return this.typeMethod; } public Object invoke(Object arg, String attr) throws SigarException, SigarNotImplementedException, SigarPermissionDeniedException { Object[] args = null; if (arg != null) { args = ARG_ARGS; args[0] = arg; } return invoke(args, attr); } private String aobMsg(int idx, int length) { return "Array index " + idx + " out of bounds " + length; } public Object invoke(Object[] args, String attr) throws SigarException, SigarNotImplementedException, SigarPermissionDeniedException { Method typeGetter, attrGetter; Object typeObject; typeGetter = getTypeMethod(args); if (this.hasArrayIdx) { args = null; } try { typeObject = this.handler.invoke(this.sigarProxy, typeGetter, args); } catch (Throwable t) { String parms = (args == null) ? "" : Arrays.asList(args).toString(); String msg = "Failed to invoke " + typeGetter.getName() + parms + ": " + t.getMessage(); if (t instanceof SigarNotImplementedException) { throw (SigarNotImplementedException)t; } else if (t instanceof SigarPermissionDeniedException) { throw (SigarPermissionDeniedException)t; } throw new SigarException(msg); } if (attr == null) { return typeObject; } /* * if the return type is an array and we've been given * an attr, the attr is an index into the array, e.g. * for getLoadAverage which returns a double[]. * working with primitive arrays here kinda sucks. */ if (this.typeIsArray) { if (this.hasArrayIdx) { Object[] array = (Object[])typeObject; if (this.arrayIdx >= array.length) { throw new SigarException(aobMsg(this.arrayIdx, array.length)); } typeObject = array[this.arrayIdx]; } else { int idx = getAttributeIndex(attr); if (idx < 0) { throw new SigarException("Invalid array index: " + attr); } switch (this.typeArrayType) { case ARRAY_TYPE_DOUBLE: double[] d_array = (double[])typeObject; if (idx >= d_array.length) { throw new SigarException(aobMsg(idx, d_array.length)); } return new Double(d_array[idx]); case ARRAY_TYPE_LONG: long[] l_array = (long[])typeObject; if (idx >= l_array.length) { throw new SigarException(aobMsg(idx, l_array.length)); } return new Long(l_array[idx]); case ARRAY_TYPE_OBJECT: Object[] o_array = (Object[])typeObject; if (idx >= o_array.length) { throw new SigarException(aobMsg(idx, o_array.length)); } return o_array[idx]; } } } attrGetter = getAttributeMethod(attr); try { return attrGetter.invoke(typeObject, VOID_ARGS); } catch (Throwable t) { throw new SigarException(t.getMessage()); } } private Method getAttributeMethod(String attr) throws SigarException { String alias = (String)compatAttrs.get(attr); if (alias != null) { attr = alias; } Method attrMethod; Class type = getTypeMethod(null).getReturnType(); HashMap attrs; if (this.hasArrayIdx) { type = type.getComponentType(); } //Class.getMethod can be expensive so cache the lookups synchronized (attrCache) { attrs = (HashMap)attrCache.get(type); if (attrs == null) { attrs = new HashMap(); attrCache.put(type, attrs); } else { if ((attrMethod = (Method)attrs.get(attr)) != null) { return attrMethod; } } } try { attrMethod = type.getMethod("get" + attr, VOID_SIGNATURE); } catch (Exception e) { String msg = "Failed to invoke get" + attr + ": " + e.getMessage(); throw new SigarException(msg); } synchronized (attrs) { attrs.put(attr, attrMethod); } return attrMethod; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarLoader.java000066400000000000000000000057111210132627500271150ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 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 org.hyperic.jni.ArchLoader; import org.hyperic.jni.ArchLoaderException; import org.hyperic.jni.ArchName; import org.hyperic.jni.ArchNotSupportedException; public class SigarLoader extends ArchLoader { public static final String PROP_SIGAR_JAR_NAME = "sigar.jar.name"; private static String location = null; private static String nativeName = null; public SigarLoader(Class loaderClass) { super(loaderClass); } //XXX same as super.getArchLibName() //but db2monitor.jar gets loaded first in jboss //results in NoSuchMethodError public String getArchLibName() throws ArchNotSupportedException { return getName() + "-" + ArchName.getName(); } public String getDefaultLibName() throws ArchNotSupportedException { return getArchLibName(); //drop "java" prefix } //override these methods to ensure our ClassLoader //loads the native library. protected void systemLoadLibrary(String name) { System.loadLibrary(name); } protected void systemLoad(String name) { System.load(name); } public String getJarName() { return System.getProperty(PROP_SIGAR_JAR_NAME, super.getJarName()); } public static void setSigarJarName(String jarName) { System.setProperty(PROP_SIGAR_JAR_NAME, jarName); } public static String getSigarJarName() { return System.getProperty(PROP_SIGAR_JAR_NAME); } /** * Returns the path where sigar.jar is located. */ public synchronized static String getLocation() { if (location == null) { SigarLoader loader = new SigarLoader(Sigar.class); try { location = loader.findJarPath(getSigarJarName()); } catch (ArchLoaderException e) { location = "."; } } return location; } /** * Returns the name of the native sigar library. */ public synchronized static String getNativeLibraryName() { if (nativeName == null) { SigarLoader loader = new SigarLoader(Sigar.class); try { nativeName = loader.getLibraryName(); } catch (ArchNotSupportedException e) { nativeName = null; } } return nativeName; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarLog.java000066400000000000000000000056171210132627500264350ustar00rootroot00000000000000/* * Copyright (c) 2006 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 org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; public class SigarLog { //from sigar_log.h private static final int LOG_FATAL = 0; private static final int LOG_ERROR = 1; private static final int LOG_WARN = 2; private static final int LOG_INFO = 3; private static final int LOG_DEBUG = 4; private static native void setLogger(Sigar sigar, Logger log); public static native void setLevel(Sigar sigar, int level); private static boolean isLogConfigured() { //funny, log4j has no api to determine if logging has been //configured? .. yet bitches at you like a mo-fo when logging //has not been configured. return Logger.getRootLogger().getAllAppenders().hasMoreElements(); } private static Logger getLogger() { return getLogger("Sigar"); } public static Logger getLogger(String name) { Logger log = Logger.getLogger(name); if (!isLogConfigured()) { BasicConfigurator.configure(); } return log; } static void error(String msg, Throwable exc) { getLogger().error(msg, exc); } static void debug(String msg, Throwable exc) { getLogger().debug(msg, exc); } //XXX want to make this automatic, but also dont always //want to turn on logging, since most sigar logging will be DEBUG public static void enable(Sigar sigar) { Logger log = getLogger(); Level level = log.getLevel(); if (level == null) { level = Logger.getRootLogger().getLevel(); if (level == null) { return; } } switch (level.toInt()) { case Level.FATAL_INT: setLevel(sigar, LOG_FATAL); break; case Level.ERROR_INT: setLevel(sigar, LOG_ERROR); break; case Level.WARN_INT: setLevel(sigar, LOG_WARN); break; case Level.INFO_INT: setLevel(sigar, LOG_INFO); break; case Level.DEBUG_INT: setLevel(sigar, LOG_DEBUG); break; } setLogger(sigar, log); } public static void disable(Sigar sigar) { setLogger(sigar, null); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarNotImplementedException.java000066400000000000000000000021661210132627500325130ustar00rootroot00000000000000/* * Copyright (c) 2006 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; /** * Sigar exception class, thrown for methods which are not implemented * on a given platform. */ public class SigarNotImplementedException extends SigarException { private static final String msg = "This method has not been implemented on this platform"; public static final SigarNotImplementedException INSTANCE = new SigarNotImplementedException(msg); public SigarNotImplementedException () { super(); } public SigarNotImplementedException (String s) { super(s); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarPermissionDeniedException.java000066400000000000000000000025411210132627500330250ustar00rootroot00000000000000/* * Copyright (c) 2006 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 SigarPermissionDeniedException extends SigarException { public static String getUserDeniedMessage(SigarProxy sigar, long pid) { String user="unknown", owner="unknown"; try { user = sigar.getProcCredName(sigar.getPid()).getUser(); } catch (SigarException e) { } try { owner = sigar.getProcCredName(pid).getUser(); } catch (SigarException e) { } return "User " + user + " denied access to process " + pid + " owned by " + owner; } public SigarPermissionDeniedException(String s) { super(s); } public SigarPermissionDeniedException(SigarProxy sigar, long pid) { super(getUserDeniedMessage(sigar, pid)); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarProxy.java000066400000000000000000000130011210132627500270170ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.List; import java.util.Map; /** * The proxyable interface for caching via SigarProxyCache. * This interface includes all methods which leave java land and * gather info from the system. All other accessors, such as the objects * returned by these methods do not leave java land. */ public interface SigarProxy { public long getPid(); public long getServicePid(String name) throws SigarException; public Mem getMem() throws SigarException; public Swap getSwap() throws SigarException; public Cpu getCpu() throws SigarException; public CpuPerc getCpuPerc() throws SigarException; public Uptime getUptime() throws SigarException; public ResourceLimit getResourceLimit() throws SigarException; public double[] getLoadAverage() throws SigarException; public long[] getProcList() throws SigarException; public ProcStat getProcStat() throws SigarException; public ProcMem getProcMem(long pid) throws SigarException; public ProcMem getProcMem(String pid) throws SigarException; public ProcMem getMultiProcMem(String query) throws SigarException; public ProcState getProcState(long pid) throws SigarException; public ProcState getProcState(String pid) throws SigarException; public ProcTime getProcTime(long pid) throws SigarException; public ProcTime getProcTime(String pid) throws SigarException; public ProcCpu getProcCpu(long pid) throws SigarException; public ProcCpu getProcCpu(String pid) throws SigarException; public MultiProcCpu getMultiProcCpu(String query) throws SigarException; public ProcCred getProcCred(long pid) throws SigarException; public ProcCred getProcCred(String pid) throws SigarException; public ProcCredName getProcCredName(long pid) throws SigarException; public ProcCredName getProcCredName(String pid) throws SigarException; public ProcFd getProcFd(long pid) throws SigarException; public ProcFd getProcFd(String pid) throws SigarException; public ProcExe getProcExe(long pid) throws SigarException; public ProcExe getProcExe(String pid) throws SigarException; public String[] getProcArgs(long pid) throws SigarException; public String[] getProcArgs(String pid) throws SigarException; public Map getProcEnv(long pid) throws SigarException; public Map getProcEnv(String pid) throws SigarException; public String getProcEnv(long pid, String key) throws SigarException; public String getProcEnv(String pid, String key) throws SigarException; public List getProcModules(long pid) throws SigarException; public List getProcModules(String pid) throws SigarException; public long getProcPort(int protocol, long port) throws SigarException; public long getProcPort(String protocol, String port) throws SigarException; public FileSystem[] getFileSystemList() throws SigarException; public FileSystemMap getFileSystemMap() throws SigarException; public FileSystemUsage getMountedFileSystemUsage(String name) throws SigarException; public FileSystemUsage getFileSystemUsage(String name) throws SigarException; public DiskUsage getDiskUsage(String name) throws SigarException; public FileInfo getFileInfo(String name) throws SigarException; public FileInfo getLinkInfo(String name) throws SigarException; public DirStat getDirStat(String name) throws SigarException; public DirUsage getDirUsage(String name) throws SigarException; public CpuInfo[] getCpuInfoList() throws SigarException; public Cpu[] getCpuList() throws SigarException; public CpuPerc[] getCpuPercList() throws SigarException; public NetRoute[] getNetRouteList() throws SigarException; public NetInterfaceConfig getNetInterfaceConfig(String name) throws SigarException; public NetInterfaceConfig getNetInterfaceConfig() throws SigarException; public NetInterfaceStat getNetInterfaceStat(String name) throws SigarException; public String[] getNetInterfaceList() throws SigarException; public NetConnection[] getNetConnectionList(int flags) throws SigarException; public String getNetListenAddress(long port) throws SigarException; public String getNetListenAddress(String port) throws SigarException; public NetStat getNetStat() throws SigarException; public String getNetServicesName(int protocol, long port); public Who[] getWhoList() throws SigarException; public Tcp getTcp() throws SigarException; public NfsClientV2 getNfsClientV2() throws SigarException; public NfsServerV2 getNfsServerV2() throws SigarException; public NfsClientV3 getNfsClientV3() throws SigarException; public NfsServerV3 getNfsServerV3() throws SigarException; public NetInfo getNetInfo() throws SigarException; public String getFQDN() throws SigarException; } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarProxyCache.java000066400000000000000000000162651210132627500277620ustar00rootroot00000000000000/* * Copyright (c) 2006-2009 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.Map; import java.lang.reflect.Proxy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import org.hyperic.sigar.util.ReferenceMap; /** * This class implements a caching mechanism to avoid system calls * with heavy Sigar usage in a short period of time. It is intended * for use in applications such as Top. */ public class SigarProxyCache implements InvocationHandler { private Sigar sigar; private Map cache = ReferenceMap.newInstance(); public static final int EXPIRE_DEFAULT = 30 * 1000; //30 seconds private int expire; private static final boolean debugEnabled = "debug".equals(System.getProperty("sigar.log")); public SigarProxyCache(Sigar sigar, int expire) { this.sigar = sigar; this.expire = expire; } public static SigarProxy newInstance() { return newInstance(new Sigar()); } public static SigarProxy newInstance(Sigar sigar) { return newInstance(sigar, EXPIRE_DEFAULT); } public static SigarProxy newInstance(Sigar sigar, int expire) { SigarProxyCache handler = new SigarProxyCache(sigar, expire); SigarProxy proxy; proxy = (SigarProxy) Proxy.newProxyInstance(SigarProxy.class.getClassLoader(), new Class[] { SigarProxy.class }, handler); return proxy; } //poor mans logging private void debug(String msg) { SigarLog.getLogger("SigarProxyCache").debug(msg); } /** * @deprecated */ public static void setExpire(SigarProxy proxy, String type, int expire) throws SigarException { } private static SigarProxyCache getHandler(Object proxy) { return (SigarProxyCache)Proxy.getInvocationHandler(proxy); } public static void clear(Object proxy) { getHandler(proxy).cache.clear(); } public static Sigar getSigar(Object proxy) { if (proxy.getClass() == Sigar.class) { return (Sigar)proxy; } else { return getHandler(proxy).sigar; } } private String getDebugArgs(Object[] args, Object argKey) { if (args.length == 0) { return null; } StringBuffer dargs = new StringBuffer(args[0].toString()); for (int i=1; i this.expire) { if (debugEnabled) { debug("expiring " + method.getName() + " from cache" + argDebug); } cacheVal.value = null; } } else { if (debugEnabled) { debug(method.getName() + " NOT in cache" + argDebug); } } if (cacheVal.value == null) { try { retval = method.invoke(this.sigar, args); } catch (InvocationTargetException e) { Throwable t = ((InvocationTargetException)e). getTargetException(); String msg; if (t instanceof SigarException) { msg = ""; } else { msg = t.getClass().getName() + ": "; } msg += t.getMessage(); if (argKey != null) { msg += ": " + getDebugArgs(args, argKey); } if (t instanceof SigarNotImplementedException) { throw new SigarNotImplementedException(msg); } else if (t instanceof SigarPermissionDeniedException) { throw new SigarPermissionDeniedException(msg); } throw new SigarException(msg); } catch (Exception e) { String msg = e.getClass().getName() + ": " + e.getMessage(); if (argKey != null) { msg += ": " + getDebugArgs(args, argKey); } throw new SigarException(msg); } cacheVal.value = retval; cacheVal.timestamp = timeNow; if (args == null) { this.cache.put(method, cacheVal); } else { argMap.put(argKey, cacheVal); this.cache.put(method, argMap); } } else { retval = cacheVal.value; } return retval; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SigarVersion.java.in000066400000000000000000000003471210132627500277410ustar00rootroot00000000000000package org.hyperic.sigar; class SigarVersion { static final String BUILD_DATE = "@@BUILD_DATE@@"; static final String SCM_REVISION = "@@SCM_REVISION@@"; static final String VERSION_STRING = "@@VERSION_STRING@@"; } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/SudoFileInputStream.java000066400000000000000000000043601210132627500306260ustar00rootroot00000000000000/* * Copyright (c) 2006 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.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * InputStream wrapper for 'sudo cat filename' */ public class SudoFileInputStream extends InputStream { private Process process; private InputStream is; public SudoFileInputStream(String file) throws IOException, FileNotFoundException { this(new File(file)); } public SudoFileInputStream(File file) throws IOException, FileNotFoundException { if (!file.exists()) { throw new FileNotFoundException(); } String[] args = { "sudo", "cat", file.toString() }; this.process = Runtime.getRuntime().exec(args); this.is = this.process.getInputStream(); } public void close() throws IOException { this.process.destroy(); } /* passthru all other InputStream methods */ public int read() throws IOException { return this.is.read(); } public int read(byte b[]) throws IOException { return this.is.read(b); } public int read(byte b[], int off, int len) throws IOException { return this.is.read(b, off, len); } public long skip(long n) throws IOException { return this.is.skip(n); } public int available() throws IOException { return this.is.available(); } public synchronized void mark(int readlimit) { this.is.mark(readlimit); } public synchronized void reset() throws IOException { this.is.reset(); } public boolean markSupported() { return this.is.markSupported(); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/000077500000000000000000000000001210132627500246155ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/CpuInfo.java000066400000000000000000000062131210132627500270250ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarLoader; import org.hyperic.sigar.SigarException; /** * Display cpu information for each cpu found on the system. */ public class CpuInfo extends SigarCommandBase { public boolean displayTimes = true; public CpuInfo(Shell shell) { super(shell); } public CpuInfo() { super(); } public String getUsageShort() { return "Display cpu information"; } private void output(CpuPerc cpu) { println("User Time....." + CpuPerc.format(cpu.getUser())); println("Sys Time......" + CpuPerc.format(cpu.getSys())); println("Idle Time....." + CpuPerc.format(cpu.getIdle())); println("Wait Time....." + CpuPerc.format(cpu.getWait())); println("Nice Time....." + CpuPerc.format(cpu.getNice())); println("Combined......" + CpuPerc.format(cpu.getCombined())); println("Irq Time......" + CpuPerc.format(cpu.getIrq())); if (SigarLoader.IS_LINUX) { println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq())); println("Stolen Time...." + CpuPerc.format(cpu.getStolen())); } println(""); } public void output(String[] args) throws SigarException { org.hyperic.sigar.CpuInfo[] infos = this.sigar.getCpuInfoList(); CpuPerc[] cpus = this.sigar.getCpuPercList(); org.hyperic.sigar.CpuInfo info = infos[0]; long cacheSize = info.getCacheSize(); println("Vendor........." + info.getVendor()); println("Model.........." + info.getModel()); println("Mhz............" + info.getMhz()); println("Total CPUs....." + info.getTotalCores()); if ((info.getTotalCores() != info.getTotalSockets()) || (info.getCoresPerSocket() > info.getTotalCores())) { println("Physical CPUs.." + info.getTotalSockets()); println("Cores per CPU.." + info.getCoresPerSocket()); } if (cacheSize != Sigar.FIELD_NOTIMPL) { println("Cache size...." + cacheSize); } println(""); if (!this.displayTimes) { return; } for (int i=0; i 0) { FileSystemMap mounts = this.proxy.getFileSystemMap(); for (int i=0; i= 1; } public String getUsageShort() { return "Display file version info"; } public void output(String[] args) throws SigarException { for (int i=0; i 0) { sb.append('.'); } sb.append(val); println(sb.toString()); } public void output(String exe) throws SigarException { FileVersion info = Win32.getFileVersion(exe); if (info == null) { return; } println("Version info for file '" + exe + "':"); output("FileVersion", info.getFileVersion()); output("ProductVersion", info.getProductVersion()); for (Iterator it = info.getInfo().entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); output((String)entry.getKey(), (String)entry.getValue()); } } public static void main(String[] args) throws Exception { new FileVersionInfo().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Free.java000066400000000000000000000045151210132627500263460ustar00rootroot00000000000000/* * Copyright (c) 2006 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import org.hyperic.sigar.Mem; import org.hyperic.sigar.Swap; import org.hyperic.sigar.SigarException; /** * Display amount of free and used memory in the system. */ public class Free extends SigarCommandBase { public Free(Shell shell) { super(shell); } public Free() { super(); } public String getUsageShort() { return "Display information about free and used memory"; } private static Long format(long value) { return new Long(value / 1024); } public void output(String[] args) throws SigarException { Mem mem = this.sigar.getMem(); Swap swap = this.sigar.getSwap(); Object[] header = new Object[] { "total", "used", "free" }; Object[] memRow = new Object[] { format(mem.getTotal()), format(mem.getUsed()), format(mem.getFree()) }; Object[] actualRow = new Object[] { format(mem.getActualUsed()), format(mem.getActualFree()) }; Object[] swapRow = new Object[] { format(swap.getTotal()), format(swap.getUsed()), format(swap.getFree()) }; printf("%18s %10s %10s", header); printf("Mem: %10ld %10ld %10ld", memRow); //e.g. linux if ((mem.getUsed() != mem.getActualUsed()) || (mem.getFree() != mem.getActualFree())) { printf("-/+ buffers/cache: " + "%10ld %10d", actualRow); } printf("Swap: %10ld %10ld %10ld", swapRow); printf("RAM: %10ls", new Object[] { mem.getRam() + "MB" }); } public static void main(String[] args) throws Exception { new Free().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Ifconfig.java000066400000000000000000000112371210132627500272100ustar00rootroot00000000000000/* * Copyright (c) 2006 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.util.Arrays; import java.util.Collection; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.NetInterfaceStat; import org.hyperic.sigar.NetFlags; /** * Display network interface configuration and metrics. */ public class Ifconfig extends SigarCommandBase { public Ifconfig(Shell shell) { super(shell); } public Ifconfig() { super(); } protected boolean validateArgs(String[] args) { return args.length <= 1; } public String getSyntaxArgs() { return "[interface]"; } public String getUsageShort() { return "Network interface information"; } public Collection getCompletions() { String[] ifNames; try { ifNames = this.proxy.getNetInterfaceList(); } catch (SigarException e) { return super.getCompletions(); } return Arrays.asList(ifNames); } public void output(String[] args) throws SigarException { String[] ifNames; if (args.length == 1) { ifNames = args; } else { ifNames = this.proxy.getNetInterfaceList(); } for (int i=0; i 0) { ptp = " P-t-P:" + ifconfig.getDestination(); } String bcast = ""; if ((flags & NetFlags.IFF_BROADCAST) > 0) { bcast = " Bcast:" + ifconfig.getBroadcast(); } println("\t" + "inet addr:" + ifconfig.getAddress() + ptp + //unlikely bcast + " Mask:" + ifconfig.getNetmask()); println("\t" + NetFlags.getIfFlagsString(flags) + " MTU:" + ifconfig.getMtu() + " Metric:" + ifconfig.getMetric()); try { NetInterfaceStat ifstat = this.sigar.getNetInterfaceStat(name); println("\t" + "RX packets:" + ifstat.getRxPackets() + " errors:" + ifstat.getRxErrors() + " dropped:" + ifstat.getRxDropped() + " overruns:" + ifstat.getRxOverruns() + " frame:" + ifstat.getRxFrame()); println("\t" + "TX packets:" + ifstat.getTxPackets() + " errors:" + ifstat.getTxErrors() + " dropped:" + ifstat.getTxDropped() + " overruns:" + ifstat.getTxOverruns() + " carrier:" + ifstat.getTxCarrier()); println("\t" + "collisions:" + ifstat.getTxCollisions()); long rxBytes = ifstat.getRxBytes(); long txBytes = ifstat.getTxBytes(); println("\t" + "RX bytes:" + rxBytes + " (" + Sigar.formatSize(rxBytes) + ")" + " " + "TX bytes:" + txBytes + " (" + Sigar.formatSize(txBytes) + ")"); } catch (SigarException e) { } println(""); } public static void main(String[] args) throws Exception { new Ifconfig().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Iostat.java000066400000000000000000000125441210132627500267310ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.util.ArrayList; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.FileSystemMap; import org.hyperic.sigar.FileSystemUsage; import org.hyperic.sigar.DiskUsage; import org.hyperic.sigar.shell.FileCompleter; import org.hyperic.sigar.util.GetlineCompleter; /** * Report filesytem disk space usage. */ public class Iostat extends SigarCommandBase { private static final String OUTPUT_FORMAT = "%-15s %-15s %10s %10s %7s %7s %5s %5s"; private static final String[] HEADER = new String[] { "Filesystem", "Mounted on", "Reads", "Writes", "R-bytes", "W-bytes", "Queue", "Svctm", }; private GetlineCompleter completer; public Iostat(Shell shell) { super(shell); setOutputFormat(OUTPUT_FORMAT); this.completer = new FileCompleter(shell); } public Iostat() { super(); setOutputFormat(OUTPUT_FORMAT); } public GetlineCompleter getCompleter() { return this.completer; } protected boolean validateArgs(String[] args) { return args.length <= 1; } public String getSyntaxArgs() { return "[filesystem]"; } public String getUsageShort() { return "Report filesystem disk i/o"; } public void printHeader() { printf(HEADER); } private String svctm(double val) { return sprintf("%3.2f", new Object[] { new Double(val) }); } public void output(String[] args) throws SigarException { if (args.length == 1) { String arg = args[0]; if ((arg.indexOf('/') != -1) || (arg.indexOf('\\') != -1)) { outputFileSystem(arg); } else { outputDisk(arg); } } else { FileSystem[] fslist = this.proxy.getFileSystemList(); printHeader(); for (int i=0; i"; } public String getUsageShort() { return "Send signal to a process"; } public boolean isPidCompleter() { return true; } public void output(String[] args) throws SigarException { String signal = "SIGTERM"; long[] pids; String query; if (args.length == 2) { signal = args[0]; query = args[1]; } else { query = args[0]; } pids = this.shell.findPids(new String[] { query }); for (int i=0; i " + new File(file).getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } println(link.getTypeChar() + info.getPermissionsString() + "\t" + info.getUid() + "\t" + info.getGid() + "\t" + info.getSize() + "\t" + getDate(info.getMtime()) + "\t" + file); } public static void main(String[] args) throws Exception { new Ls().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/MemWatch.java000066400000000000000000000046651210132627500272000ustar00rootroot00000000000000/* * Copyright (c) 2006 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.ProcMem; /** * Watch for changes in program memory usage. */ public class MemWatch { static final int SLEEP_TIME = 1000 * 10; public static void main(String[] args) throws Exception { Sigar sigar = new Sigar(); if (args.length != 1) { throw new Exception("Usage: MemWatch pid"); } long pid = Long.parseLong(args[0]); long lastTime = System.currentTimeMillis(); ProcMem last = sigar.getProcMem(pid); while (true) { ProcMem cur = sigar.getProcMem(pid); StringBuffer diff = diff(last, cur); if (diff.length() == 0) { System.out.println("no change " + "(size=" + Sigar.formatSize(cur.getSize()) + ")"); } else { long curTime = System.currentTimeMillis(); long timeDiff = curTime - lastTime; lastTime = curTime; diff.append(" after " + timeDiff + "ms"); System.out.println(diff); } last = cur; Thread.sleep(SLEEP_TIME); } } private static StringBuffer diff(ProcMem last, ProcMem cur) { StringBuffer buf = new StringBuffer(); long diff; diff = cur.getSize() - last.getSize(); if (diff != 0) { buf.append("size=" + diff); } diff = cur.getResident() - last.getResident(); if (diff != 0) { buf.append(", resident=" + diff); } diff = cur.getShare() - last.getShare(); if (diff != 0) { buf.append(", share=" + diff); } return buf; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/MultiPs.java000066400000000000000000000040211210132627500270520ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.MultiProcCpu; import org.hyperic.sigar.ProcMem; /** * Show multi process status. */ public class MultiPs extends SigarCommandBase { public MultiPs(Shell shell) { super(shell); } public MultiPs() { super(); } protected boolean validateArgs(String[] args) { return args.length == 1; } public String getSyntaxArgs() { return "query"; } public String getUsageShort() { return "Show multi process status"; } public boolean isPidCompleter() { return true; } public void output(String[] args) throws SigarException { String query = args[0]; MultiProcCpu cpu = this.proxy.getMultiProcCpu(query); println("Number of processes: " + cpu.getProcesses()); println("Cpu usage: " + CpuPerc.format(cpu.getPercent())); println("Cpu time: " + Ps.getCpuTime(cpu.getTotal())); ProcMem mem = this.proxy.getMultiProcMem(query); println("Size: " + Sigar.formatSize(mem.getSize())); println("Resident: " + Sigar.formatSize(mem.getResident())); println("Share: " + Sigar.formatSize(mem.getShare())); } public static void main(String[] args) throws Exception { new MultiPs().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/NetInfo.java000066400000000000000000000040401210132627500270200ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.SigarException; /** * Display network info. */ public class NetInfo extends SigarCommandBase { public NetInfo(Shell shell) { super(shell); } public NetInfo() { super(); } public String getUsageShort() { return "Display network info"; } public void output(String[] args) throws SigarException { NetInterfaceConfig config = this.sigar.getNetInterfaceConfig(null); println("primary interface....." + config.getName()); println("primary ip address...." + config.getAddress()); println("primary mac address..." + config.getHwaddr()); println("primary netmask......." + config.getNetmask()); org.hyperic.sigar.NetInfo info = this.sigar.getNetInfo(); println("host name............." + info.getHostName()); println("domain name..........." + info.getDomainName()); println("default gateway......." + info.getDefaultGateway()); println("primary dns..........." + info.getPrimaryDns()); println("secondary dns........." + info.getSecondaryDns()); } public static void main(String[] args) throws Exception { new NetInfo().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Netstat.java000066400000000000000000000172551210132627500271140ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.NetConnection; import org.hyperic.sigar.NetFlags; import org.hyperic.sigar.Tcp; /** * Display network connections. */ public class Netstat extends SigarCommandBase { private static final int LADDR_LEN = 20; private static final int RADDR_LEN = 35; private static final String[] HEADER = new String[] { "Proto", "Local Address", "Foreign Address", "State", "" }; private static boolean isNumeric, wantPid, isStat; public Netstat(Shell shell) { super(shell); } public Netstat() { super(); } protected boolean validateArgs(String[] args) { return true; } public String getUsageShort() { return "Display network connections"; } //poor mans getopt. public static int getFlags(String[] args, int flags) { int proto_flags = 0; isNumeric = false; wantPid = false; isStat = false; for (int i=0; i max) { address = address.substring(0, max); } return address + ":" + port; } private void outputTcpStats() throws SigarException { Tcp stat = this.sigar.getTcp(); final String dnt = " "; println(dnt + stat.getActiveOpens() + " active connections openings"); println(dnt + stat.getPassiveOpens() + " passive connection openings"); println(dnt + stat.getAttemptFails() + " failed connection attempts"); println(dnt + stat.getEstabResets() + " connection resets received"); println(dnt + stat.getCurrEstab() + " connections established"); println(dnt + stat.getInSegs() + " segments received"); println(dnt + stat.getOutSegs() + " segments send out"); println(dnt + stat.getRetransSegs() + " segments retransmited"); println(dnt + stat.getInErrs() + " bad segments received."); println(dnt + stat.getOutRsts() + " resets sent"); } private void outputStats(int flags) throws SigarException { if ((flags & NetFlags.CONN_TCP) != 0) { println("Tcp:"); try { outputTcpStats(); } catch (SigarException e) { println(" " + e); } } } //XXX currently weak sauce. should end up like netstat command. public void output(String[] args) throws SigarException { //default int flags = NetFlags.CONN_CLIENT | NetFlags.CONN_PROTOCOLS; if (args.length > 0) { flags = getFlags(args, flags); if (isStat) { outputStats(flags); return; } } NetConnection[] connections = this.sigar.getNetConnectionList(flags); printf(HEADER); for (int i=0; i 0; } public String getSyntaxArgs() { return "query"; } public String getUsageShort() { return "Find the process ID of a running program"; } public void output(String[] args) throws SigarException { long[] pids = this.shell.findPids(args); for (int i=0; i" + argv[i] + "<="); } } public static void main(String[] args) throws Exception { new ShowArgs().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/ShowEnv.java000066400000000000000000000037261210132627500270610ustar00rootroot00000000000000/* * Copyright (c) 2006 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.util.Map; import java.util.Iterator; import org.hyperic.sigar.SigarException; /** * Show process environment. */ public class ShowEnv extends SigarCommandBase { public ShowEnv(Shell shell) { super(shell); } public ShowEnv() { super(); } protected boolean validateArgs(String[] args) { return true; } public String getUsageShort() { return "Show process environment"; } public boolean isPidCompleter() { return true; } public void output(String[] args) throws SigarException { long[] pids = this.shell.findPids(args); for (int i=0; i max[i]) { max[i] = len; } } } StringBuffer format = new StringBuffer(); for (int i=0; i= 1) && Character.isDigit(line.charAt(0))) { return line; } return this.ptqlCompleter.complete(line); } public String complete(String line) { if (isPidCompleter()) { return completePid(line); } GetlineCompleter c = getCompleter(); if (c != null) { return c.complete(line); } this.completer.setCollection(getCompletions()); return this.completer.complete(line); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/SysInfo.java000066400000000000000000000036541210132627500270620ustar00rootroot00000000000000/* * Copyright (c) 2006 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.util.Arrays; import org.hyperic.sigar.SigarException; /** * Display System Information */ public class SysInfo extends SigarCommandBase { public SysInfo(Shell shell) { super(shell); } public SysInfo() { super(); } public String getUsageShort() { return "Display system information"; } public void output(String[] args) throws SigarException { //sigar/os info Version.printInfo(this.out); println(""); //uptime new Uptime(this.shell).output(args); println(""); //cpu info CpuInfo cpuinfo = new CpuInfo(this.shell); cpuinfo.displayTimes = false; cpuinfo.output(args); println(""); //memory info new Free(this.shell).output(args); println(""); println("File Systems........." + Arrays.asList(this.sigar.getFileSystemList())); println(""); println("Network Interfaces..." + Arrays.asList(this.sigar.getNetInterfaceList())); println(""); //system resource limits println("System resource limits:"); new Ulimit(this.shell).output(args); } public static void main(String[] args) throws Exception { new SysInfo().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Tail.java000066400000000000000000000060651210132627500263600ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.io.IOException; import java.io.BufferedReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.FileInfo; import org.hyperic.sigar.FileTail; import org.hyperic.sigar.FileWatcherThread; /** * Display the last part of files to the standard output. */ public class Tail { public boolean follow; public int number = 10; public List files = new ArrayList(); public void parseArgs(String args[]) throws SigarException { for (int i=0; i 1) { System.out.println("==> " + info.getName() + " <=="); } try { while ((line = buffer.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println(e); } } }; for (int i=0; i= 1; } public String getSyntaxArgs() { return "[command] [...]"; } public String getUsageShort() { return "Time command"; } public void output(String[] args) throws SigarException { boolean isInteractive = this.shell.isInteractive(); //turn off paging. this.shell.setInteractive(false); CpuTimer cpu = new CpuTimer(this.sigar); int num; if (Character.isDigit(args[0].charAt(0))) { num = Integer.parseInt(args[0]); String[] xargs = new String[args.length-1]; System.arraycopy(args, 1, xargs, 0, xargs.length); args = xargs; } else { num = 1; } cpu.start(); try { for (int i=0; i * This version of the top command requires a ptql query to select which * processes to display. * * Example to display java processes only:
* % java -jar sigar-bin/lib/sigar.jar Top State.Name.eq=java */ public class Top { private static final int SLEEP_TIME = 1000 * 5; private static final String HEADER = "PID\tUSER\tSTIME\tSIZE\tRSS\tSHARE\tSTATE\tTIME\t%CPU\tCOMMAND"; private static String toString(ProcStat stat) { return stat.getTotal() + " processes: " + stat.getSleeping() + " sleeping, " + stat.getRunning() + " running, " + stat.getZombie() + " zombie, " + stat.getStopped() + " stopped... " + stat.getThreads() + " threads"; } public static void main(String[] args) throws Exception { Sigar sigarImpl = new Sigar(); SigarProxy sigar = SigarProxyCache.newInstance(sigarImpl, SLEEP_TIME); while (true) { Shell.clearScreen(); System.out.println(Uptime.getInfo(sigar)); System.out.println(toString(sigar.getProcStat())); System.out.println(sigar.getCpuPerc()); System.out.println(sigar.getMem()); System.out.println(sigar.getSwap()); System.out.println(); System.out.println(HEADER); long[] pids = Shell.getPids(sigar, args); for (int i=0; i 1) ? "days" : "day") + ", "; } minutes = (int)uptime / 60; hours = minutes / 60; hours %= 24; minutes %= 60; if (hours != 0) { retval += hours + ":" + minutes; } else { retval += minutes + " min"; } return retval; } private static String getCurrentTime() { return new SimpleDateFormat("h:mm a").format(new Date()); } //pretty close to uptime command, but we don't output number of users yet public static void main(String[] args) throws Exception { new Uptime().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Version.java000066400000000000000000000110701210132627500271040ustar00rootroot00000000000000/* * Copyright (c) 2006-2009 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 java.io.File; import java.io.PrintStream; import java.net.InetAddress; import java.net.UnknownHostException; import org.hyperic.sigar.OperatingSystem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarLoader; import org.hyperic.sigar.win32.LocaleInfo; /** * Display Sigar, java and system version information. */ public class Version extends SigarCommandBase { public Version(Shell shell) { super(shell); } public Version() { super(); } public String getUsageShort() { return "Display sigar and system version info"; } private static String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "unknown"; } } private static void printNativeInfo(PrintStream os) { String version = "java=" + Sigar.VERSION_STRING + ", native=" + Sigar.NATIVE_VERSION_STRING; String build = "java=" + Sigar.BUILD_DATE + ", native=" + Sigar.NATIVE_BUILD_DATE; String scm = "java=" + Sigar.SCM_REVISION + ", native=" + Sigar.NATIVE_SCM_REVISION; String archlib = SigarLoader.getNativeLibraryName(); os.println("Sigar version......." + version); os.println("Build date.........." + build); os.println("SCM rev............." + scm); String host = getHostName(); String fqdn; Sigar sigar = new Sigar(); try { File lib = sigar.getNativeLibrary(); if (lib != null) { archlib = lib.getName(); } fqdn = sigar.getFQDN(); } catch (SigarException e) { fqdn = "unknown"; } finally { sigar.close(); } os.println("Archlib............." + archlib); os.println("Current fqdn........" + fqdn); if (!fqdn.equals(host)) { os.println("Hostname............" + host); } if (SigarLoader.IS_WIN32) { LocaleInfo info = new LocaleInfo(); os.println("Language............" + info); os.println("Perflib lang id....." + info.getPerflibLangId()); } } public static void printInfo(PrintStream os) { try { printNativeInfo(os); } catch (UnsatisfiedLinkError e) { os.println("*******ERROR******* " + e); } os.println("Current user........" + System.getProperty("user.name")); os.println(""); OperatingSystem sys = OperatingSystem.getInstance(); os.println("OS description......" + sys.getDescription()); os.println("OS name............." + sys.getName()); os.println("OS arch............." + sys.getArch()); os.println("OS machine.........." + sys.getMachine()); os.println("OS version.........." + sys.getVersion()); os.println("OS patch level......" + sys.getPatchLevel()); os.println("OS vendor..........." + sys.getVendor()); os.println("OS vendor version..." + sys.getVendorVersion()); if (sys.getVendorCodeName() != null) { os.println("OS code name........" + sys.getVendorCodeName()); } os.println("OS data model......." + sys.getDataModel()); os.println("OS cpu endian......." + sys.getCpuEndian()); os.println("Java vm version....." + System.getProperty("java.vm.version")); os.println("Java vm vendor......" + System.getProperty("java.vm.vendor")); os.println("Java home..........." + System.getProperty("java.home")); } public void output(String[] args) { printInfo(this.out); } public static void main(String[] args) throws Exception { new Version().processCommand(args); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/cmd/Watch.java000066400000000000000000000124411210132627500265300ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.cmd; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Date; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.DirStat; import org.hyperic.sigar.FileInfo; import org.hyperic.sigar.FileWatcher; import org.hyperic.sigar.FileWatcherThread; import org.hyperic.sigar.ProcFileMirror; /** * Watch a file or directory displaying attribute changes. */ public class Watch { private static void printHeader(Sigar sigar, FileInfo info) throws SigarException { String file = info.getName(); FileInfo link = sigar.getLinkInfo(file); if (link.getType() == FileInfo.TYPE_LNK) { try { System.out.println(file + " -> " + new File(file).getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } } System.out.println(link.getTypeChar() + info.getPermissionsString() + "\t" + info.getUid() + "\t" + info.getGid() + "\t" + info.getSize() + "\t" + new Date(info.getMtime()) + "\t" + file); if (info.getType() == FileInfo.TYPE_DIR) { info.enableDirStat(true); DirStat stats = sigar.getDirStat(file); System.out.println(" Files......." + stats.getFiles()); System.out.println(" Subdirs....." + stats.getSubdirs()); System.out.println(" Symlinks...." + stats.getSymlinks()); System.out.println(" Chrdevs....." + stats.getChrdevs()); System.out.println(" Blkdevs....." + stats.getBlkdevs()); System.out.println(" Sockets....." + stats.getSockets()); System.out.println(" Total......." + stats.getTotal()); System.out.println(" Disk Usage.." + stats.getDiskUsage()); } } private static void add(Sigar sigar, FileWatcher watcher, String file, boolean recurse) throws SigarException { FileInfo info = watcher.add(file); printHeader(sigar, info); if (!recurse) { return; } if (info.getType() == FileInfo.TYPE_DIR) { File[] dirs = new File(info.getName()).listFiles(new FileFilter() { public boolean accept(File file) { return file.isDirectory() && file.canRead(); } }); for (int i=0; inull when * the deregistration finished. * * @see #preRegister(MBeanServer, ObjectName) * @see #postDeregister() */ protected MBeanServer mbeanServer; /** *

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 cacheMode parameter specifies.

* *

The following cache modes exist:

* * * * * * * * *
ConstantDescription
{@link #CACHELESS}No cached instance, {@link #sigar} * == {@link #sigarImpl}.
{@link #CACHED_500MS}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.
{@link #CACHED_5SEC}5 second cache, for high frequency * queries on calculated data such as CPU percentages.
{@link #CACHED_30SEC}30 second cache, for normal queries * or data readouts such as CPU model / vendor. This is the default if * nothing (0) is specified.
{@link #DEFAULT}Same as {@link #CACHED_30SEC}.
* *

Note: 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.

* * @param sigar The Sigar impl to use. Must not be null * @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); } } /** * Returns the object name the MBean is registered with within the * MBeanServer. May be null in case the instance is not * registered to an MBeanServer, but used standalone. * * @return The object name or null if not registered to an * MBeanServer */ public abstract String getObjectName(); /** * Returns a runtime exception for the type and SigarException specified. * * @param type * The type that was called * @param e * The exception that was raised * @return A runtime exception encapsulating the information specified */ protected RuntimeException unexpectedError(String type, SigarException e) { String msg = "Unexected error in Sigar.get" + type + ": " + e.getMessage(); return new IllegalArgumentException(msg); } /** * Loops over all attributes and calls * {@link DynamicMBean#getAttribute(java.lang.String)} method for each * attribute sequentially. Any exception thrown by those methods are ignored * and simply cause the attribute not being added to the result. */ public AttributeList getAttributes(String[] attrs) { final AttributeList result = new AttributeList(); for (int i = 0; i < attrs.length; i++) { try { result.add(new Attribute(attrs[i], getAttribute(attrs[i]))); } catch (AttributeNotFoundException 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; } /** * Loops over all attributes and calls * {@link DynamicMBean#setAttribute(Attribute)} for each attribute * sequentially. Any exception thrown by those methods are ignored and * simply cause the attribute not being added to the result. */ public AttributeList setAttributes(AttributeList attrs) { final AttributeList result = new AttributeList(); for (int i = 0; i < attrs.size(); i++) { try { final Attribute next = (Attribute) attrs.get(i); setAttribute(next); result.add(next); } catch (AttributeNotFoundException e) { // ignore, as we cannot throw this exception } catch (InvalidAttributeValueException e) { // ignore, as we cannot throw this exception } catch (MBeanException e) { // ignore, as we cannot throw this exception } catch (ReflectionException e) { // ignore, as we cannot throw this exception } } return result; } // ------- // Implementation of the MBeanRegistration interface // ------- /** *

Returns new ObjectName(this.getObjectName()) to guarantee * a reliable and reproducable object name.

* *

Note: Make sure any subclass does a super call to this method, * otherwise the implementation might be broken.

* * @see MBeanRegistration#preRegister(MBeanServer, ObjectName) */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.mbeanServer = server; return new ObjectName(getObjectName()); } /** * Empty implementation, allowing aubclasses to ignore the interface. * *

Note: Make sure any subclass does a super call to this method, * otherwise the implementation might be broken.

* * @see MBeanRegistration#postRegister(Boolean) */ public void postRegister(Boolean success) { } /** * Empty implementation, allowing aubclasses to ignore the interface. * *

Note: Make sure any subclass does a super call to this method, * otherwise the implementation might be broken.

* * @see MBeanRegistration#preDeregister() */ public void preDeregister() throws Exception { } /** * Empty implementation, allowing aubclasses to ignore the interface. * *

Note: Make sure any subclass does a super call to this method, * otherwise the implementation might be broken.

* * @see MBeanRegistration#postDeregister() */ public void postDeregister() { this.mbeanServer = null; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/CpuTimerMBean.java000066400000000000000000000015431210132627500301510ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.jmx; public interface CpuTimerMBean { public long getCpuTotal(); public long getCpuUser(); public long getCpuSys(); public double getCpuUsage(); public long getTotalTime(); public long getLastSampleTime(); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarCpu.java000066400000000000000000000263351210132627500272410ustar00rootroot00000000000000/* * 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 Cpu 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 >= 0 * 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 * >= 0 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; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarCpuInfo.java000066400000000000000000000235461210132627500300560ustar00rootroot00000000000000/* * 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 CpuInfo 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 * >= 0 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 * >= 0 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; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarCpuPerc.java000066400000000000000000000270321210132627500300460ustar00rootroot00000000000000/* * 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 CpuPerc information * package. Provides an OpenMBean conform implementation.

* * @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 * >= 0 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 * >= 0 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; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarInvokerJMX.java000066400000000000000000000125451210132627500305040ustar00rootroot00000000000000/* * Copyright (c) 2006 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 java.util.Map; import java.util.StringTokenizer; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarInvoker; import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.util.ReferenceMap; /** * Extension of SigarInvoker to provide JMX style ObjectName * interface to sigar. */ public class SigarInvokerJMX extends SigarInvoker { public static final String DOMAIN_NAME = "sigar"; public static final String PROP_TYPE = "Type"; public static final String PROP_ARG = "Arg"; private String arg = null; private static Map cache = ReferenceMap.synchronizedMap(); /** * Get an invoker instance for the given object name. * A cache is maintained so only 1 invoker object per * unique object name will be constructed. The object name * is in the format of: * domainName:prop=val,prop2=val2 * Only two properties are currently recognized: * Type == The SigarProxy name, required. (e.g. Cpu, Mem) * Arg == Argument (if any) for the given type, optional. (e.g. Arg=eth0) * @param proxy The SigarProxy object (e.g. SigarProxyCache) * @param name The object Name (e.g. sigar:Type=NetIfStat,Arg=eth0) */ public static SigarInvokerJMX getInstance(SigarProxy proxy, String name) { SigarInvokerJMX invoker; int ix = name.indexOf(":"); if (ix > 0) { //skip domain name name = name.substring(ix + 1); } if ((invoker = (SigarInvokerJMX)cache.get(name)) != null) { invoker.setProxy(proxy); return invoker; } invoker = new SigarInvokerJMX(); invoker.setProxy(proxy); StringTokenizer st = new StringTokenizer(name, ","); while (st.hasMoreTokens()) { String attr = st.nextToken(); ix = attr.indexOf('='); String key = attr.substring(0, ix); String val = attr.substring(key.length()+1); if (key.equals(PROP_TYPE)) { invoker.setType(val); } else if (key.equals(PROP_ARG)) { //need to decode value, e.g. Arg=C%3D\ => Arg=C:\ invoker.setArg(decode(val)); } } cache.put(name, invoker); return invoker; } //like URLDecoder but we only look for escaped ObjectName //delimiters ':', '=' and ',' public static String decode(String val) { StringBuffer buf = new StringBuffer(val.length()); boolean changed = false; int len = val.length(); int i = 0; while (i < len) { char c = val.charAt(i); if (c == '%') { char d; if (i+2 > len) { break; } String s = val.substring(i+1, i+3); if (s.equals("3A")) { d = ':'; } else if (s.equals("3D")) { d = '='; } else if (s.equals("2C")) { d = ','; } else { buf.append(c); i++; continue; } changed = true; buf.append(d); i += 3; } else { buf.append(c); i++; } } return changed ? buf.toString() : val; } private void setArg(String val) { this.arg = val; } /** * The value of the parsed Arg property. */ public String getArg() { return this.arg; } /** * Returns a JMX style object name with given property values. */ public static String getObjectName(String type, String arg) { String s = DOMAIN_NAME + ":"; s += PROP_TYPE + "=" + type; if (arg != null) { s += "," + PROP_ARG + "=" + arg; } return s; } /** * Returns a JMX style object that represents this instance. */ public String getObjectName() { return getObjectName(getType(), getArg()); } public String toString() { return getObjectName(); } /** * Invoke an attribute method for the given object. * Example: * SigarInvokerJMX invoker = new SigarInvokerJMX(proxy, "Type=Mem"); * Object val = invoker.invoke("Free"); * * @param attr The attribute name (e.g. Total) * @exception SigarException If invocation fails. */ public Object invoke(String attr) throws SigarException, SigarNotImplementedException { return super.invoke(getArg(), attr); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarLoadAverage.java000066400000000000000000000213021210132627500306510ustar00rootroot00000000000000/* * 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; import org.hyperic.sigar.SigarNotImplementedException; /** * Sigar JMX MBean implementation for the LoadAverage 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"; /** * Returned if {@link Sigar#getLoadAverage()}} is detected to be not * implemented on the platform. * * @see #notImplemented */ private static final double NOT_IMPLEMENTED_LOAD_VALUE = -1.0d; private static final MBeanInfo MBEAN_INFO; private static final MBeanAttributeInfo MBEAN_ATTR_LAST1MIN; private static final MBeanAttributeInfo MBEAN_ATTR_LAST5MIN; private static final MBeanAttributeInfo MBEAN_ATTR_LAST15MIN; private static final MBeanConstructorInfo MBEAN_CONSTR_SIGAR; private static MBeanParameterInfo MBEAN_PARAM_SIGAR; static { MBEAN_ATTR_LAST1MIN = new MBeanAttributeInfo( "LastMinute", "double", "The load average in the last minute, as a fraction of 1, or " + "-1.0 if the load cannot be determined on this platform", true, false, false); MBEAN_ATTR_LAST5MIN = new MBeanAttributeInfo( "LastFiveMinutes", "double", "The load average over the last five minutes, as a fraction " + "of 1, or -1.0 if the load cannot be determined on this platform", true, false, false); MBEAN_ATTR_LAST15MIN = new MBeanAttributeInfo( "Last15Minutes", "double", "The load average over the last 15 minutes, as a fraction of " + "1, or -1.0 if the load cannot be determined on this platform", true, false, false); MBEAN_PARAM_SIGAR = new MBeanParameterInfo("sigar", Sigar.class .getName(), "The Sigar instance to use to fetch data from"); MBEAN_CONSTR_SIGAR = new MBeanConstructorInfo( SigarLoadAverage.class.getName(), "Creates a new instance, using the Sigar instance specified " + "to fetch the data. Fails if the CPU index is out of range.", new MBeanParameterInfo[] { MBEAN_PARAM_SIGAR }); MBEAN_INFO = new MBeanInfo( SigarLoadAverage.class.getName(), "Sigar load average MBean. Provides load averages of the " + "system over the last one, five and 15 minutes. Due to the " + "long term character of that information, the fetch is done " + "using a Sigar proxy cache with a timeout of 30 seconds.", new MBeanAttributeInfo[] { MBEAN_ATTR_LAST1MIN, MBEAN_ATTR_LAST5MIN, MBEAN_ATTR_LAST15MIN }, new MBeanConstructorInfo[] { MBEAN_CONSTR_SIGAR }, null, null); } /** * Object name this instance will give itself when being registered to an * MBeanServer. */ private final String objectName; /** *

Set true when the load average fetch failed with a * SigarException that indicates the method is not implemented. * Any subsequent call to this instance will then be answered with * {@link #NOT_IMPLEMENTED_LOAD_VALUE}. *

* *

FIXME : This is a workaround and should be replaced by something * more stable, as the code setting this member true relies on * a substring being present within the exception. A proposal was made at * issue SIGAR-52. *

*/ 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 * -1.0d if the load cannot be determined on this platform */ public double getLastMinute() { try { return sigarImpl.getLoadAverage()[0]; } catch (SigarNotImplementedException e) { return NOT_IMPLEMENTED_LOAD_VALUE; } catch (SigarException e) { throw unexpectedError(MBEAN_TYPE, e); } } /** * @return The load average over the last five minutes, as a fraction of 1, * or -1.0d 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 * -1.0d 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; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarMem.java000066400000000000000000000201051210132627500272150ustar00rootroot00000000000000/* * 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 Mem 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; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarProcess.java000066400000000000000000000073361210132627500301300ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.jmx; import org.hyperic.sigar.ProcCpu; import org.hyperic.sigar.ProcFd; import org.hyperic.sigar.ProcMem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxyCache; /** * Implement the SigarProcessMBean to provide current process info * via JMX. */ public class SigarProcess implements SigarProcessMBean { private Sigar sigarImpl; private SigarProxy sigar; public SigarProcess() { this(new Sigar()); } public SigarProcess(Sigar sigar) { this.sigarImpl = sigar; this.sigar = SigarProxyCache.newInstance(sigarImpl); } public void close() { this.sigarImpl.close(); } private RuntimeException unexpectedError(String type, SigarException e) { String msg = "Unexected error in Sigar.get" + type + ": " + e.getMessage(); return new IllegalArgumentException(msg); } private synchronized ProcMem getMem() { try { long pid = this.sigar.getPid(); return this.sigar.getProcMem(pid); } catch (SigarException e) { throw unexpectedError("Mem", e); } } private synchronized ProcCpu getCpu() { try { long pid = this.sigar.getPid(); return this.sigar.getProcCpu(pid); } catch (SigarException e) { throw unexpectedError("Cpu", e); } } private synchronized ProcFd getFd() { try { long pid = this.sigar.getPid(); return this.sigar.getProcFd(pid); } catch (SigarException e) { throw unexpectedError("Fd", e); } } public Long getMemSize() { return new Long(getMem().getSize()); } /** * @deprecated * @see getMemSize */ public Long getMemVsize() { return getMemSize(); } public Long getMemResident() { return new Long(getMem().getResident()); } public Long getMemShare() { return new Long(getMem().getShare()); } public Long getMemPageFaults() { return new Long(getMem().getPageFaults()); } public Long getTimeUser() { return new Long(getCpu().getUser()); } public Long getTimeSys() { return new Long(getCpu().getSys()); } public Double getCpuUsage() { return new Double(getCpu().getPercent()); } public Long getOpenFd() { return new Long(getFd().getTotal()); } 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()); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarProcessMBean.java000066400000000000000000000021731210132627500310250ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.jmx; /* * yeah, yeah, we could generate this class via xdoclet, * whoopdi-friggin-do... by hand is much less pain. */ public interface SigarProcessMBean { public Long getMemSize(); /** * @deprecated * @see getMemSize */ public Long getMemVsize(); public Long getMemResident(); public Long getMemShare(); public Long getMemPageFaults(); public Long getTimeUser(); public Long getTimeSys(); public Double getCpuUsage(); public Long getOpenFd(); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarRegistry.java000066400000000000000000000275711210132627500303250ustar00rootroot00000000000000/* * 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 java.util.ArrayList; import javax.management.Attribute; import javax.management.AttributeNotFoundException; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; /** *

Registry of all Sigar MBeans. Can be used as a convenient way to invoke * Sigar MBeans at a central point. This brings a bunch of advantages with * it:

* *
    *
  • This class can be instantiated and registered to the MBean server by * simply calling {@link MBeanServer#createMBean(String, ObjectName)}, * resulting in the automatic creation of all known default Sigar MBeans such * as CPU and memory monitoring beans.
  • *
  • Any Sigar MBean spawned by an instance of this class will use the same * {@link org.hyperic.sigar.Sigar} instance, saving resources in the * process.
  • *
  • When this instance is deregistered from the MBean server, it will * automatically deregister all instances it created, cleaning up behind * itself.
  • *
* *

So using this class to manage the Sigar MBeans requires one line of code * for creation, registration and MBean spawning, and one line of code to shut * it all down again.

* * @author Bjoern Martin * @since 1.5 */ public class SigarRegistry extends AbstractMBean { private static final String MBEAN_TYPE = "SigarRegistry"; private static final MBeanInfo MBEAN_INFO; private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT; // private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES; static { MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo( SigarRegistry.class.getName(), "Creates a new instance of this class. Will create the Sigar " + "instance this class uses when constructing other MBeans", new MBeanParameterInfo[0]); // MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses", // "Executes a query returning the process IDs of all processes " + // "found on the system.", // null /* new MBeanParameterInfo[0] */, // String.class.getName(), MBeanOperationInfo.INFO); MBEAN_INFO = new MBeanInfo( SigarRegistry.class.getName(), "Sigar MBean registry. Provides a central point for creation " + "and destruction of Sigar MBeans. Any Sigar MBean created via " + "this instance will automatically be cleaned up when this " + "instance is deregistered from the MBean server.", null /*new MBeanAttributeInfo[0]*/, new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT }, null /*new MBeanOperationInfo[0] */, null /*new MBeanNotificationInfo[0]*/); } private final String objectName; private final ArrayList managedBeans; /** * Creates a new instance of this class. Will create the Sigar instance this * class uses when constructing other MBeans. */ public SigarRegistry() { super(new Sigar(), CACHELESS); this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE; this.managedBeans = new ArrayList(); } /* (non-Javadoc) * @see AbstractMBean#getObjectName() */ public String getObjectName() { return this.objectName; } /* public String listProcesses() { try { final long start = System.currentTimeMillis(); long[] ids = sigar.getProcList(); StringBuffer procNames = new StringBuffer(); for (int i = 0; i < ids.length; i++) { try { procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n'); } catch (SigarException e) { procNames.append(ids[i] + ":" + e.getMessage()).append('\n'); } } final long end = System.currentTimeMillis(); procNames.append("-- Took " + (end-start) + "ms"); return procNames.toString(); } catch (SigarException e) { throw unexpectedError("ProcList", e); } } */ /* (non-Javadoc) * @see javax.management.DynamicMBean#getAttribute(java.lang.String) */ public Object getAttribute(String attr) throws AttributeNotFoundException { 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 // ------- /** * Registers the default set of Sigar MBeans. Before doing so, a super call * is made to satisfy {@link AbstractMBean}. * * @see AbstractMBean#postRegister(Boolean) */ public void postRegister(Boolean success) { super.postRegister(success); if (!success.booleanValue()) return; // get CPUs registerCpuBeans(); // get memory registerMemoryBeans(); // get system registerSystemBeans(); } /** * Registers MBeans for the Sigar types Cpu, CpuPerc * and CpuInfo. One instance will be registered for each CPU * (core?) found. */ private void registerCpuBeans() { ObjectInstance nextRegistered = null; try { final int cpuCount = sigar.getCpuInfoList().length; for (int i = 0; i < cpuCount; i++) { // add CPU bean SigarCpu nextCpu = new SigarCpu(sigarImpl, i); try { if (!mbeanServer.isRegistered(new ObjectName(nextCpu .getObjectName()))) nextRegistered = mbeanServer.registerMBean(nextCpu, null); } catch (Exception e) { // ignore } // add MBean to set of managed beans if (nextRegistered != null) managedBeans.add(nextRegistered.getObjectName()); nextRegistered = null; // add CPU percentage bean SigarCpuPerc nextCpuPerc = new SigarCpuPerc(sigarImpl, i); try { if (!mbeanServer.isRegistered(new ObjectName(nextCpuPerc .getObjectName()))) nextRegistered = mbeanServer.registerMBean(nextCpuPerc, null); } catch (Exception e) { // ignore } // add MBean to set of managed beans if (nextRegistered != null) managedBeans.add(nextRegistered.getObjectName()); nextRegistered = null; // add CPU info bean SigarCpuInfo nextCpuInfo = new SigarCpuInfo(sigarImpl, i); try { if (!mbeanServer.isRegistered(new ObjectName(nextCpuInfo .getObjectName()))) nextRegistered = mbeanServer.registerMBean(nextCpuInfo, null); } catch (Exception e) { // ignore } // add MBean to set of managed beans if (nextRegistered != null) managedBeans.add(nextRegistered.getObjectName()); nextRegistered = null; } } catch (SigarException e) { throw unexpectedError("CpuInfoList", e); } } /** * Registers MBeans for the Sigar types Mem and Swap. */ private void registerMemoryBeans() { ObjectInstance nextRegistered = null; // add physical memory bean SigarMem mem = new SigarMem(sigarImpl); try { if (!mbeanServer.isRegistered(new ObjectName(mem.getObjectName()))) nextRegistered = mbeanServer.registerMBean(mem, null); } catch (Exception e) { // ignore } // add MBean to set of managed beans if (nextRegistered != null) managedBeans.add(nextRegistered.getObjectName()); nextRegistered = null; // add swap memory bean SigarSwap swap = new SigarSwap(sigarImpl); try { if (!mbeanServer.isRegistered(new ObjectName(swap.getObjectName()))) nextRegistered = mbeanServer.registerMBean(swap, null); } catch (Exception e) { // ignore nextRegistered = null; } // add MBean to set of managed beans if (nextRegistered != null) managedBeans.add(nextRegistered.getObjectName()); nextRegistered = null; } /** * Registers MBeans for the Sigar types LoadAverage... */ private void registerSystemBeans() { ObjectInstance nextRegistered = null; // add load average bean SigarLoadAverage loadAvg = new SigarLoadAverage(sigarImpl); try { if (!mbeanServer.isRegistered(new ObjectName(loadAvg .getObjectName()))) nextRegistered = mbeanServer.registerMBean(loadAvg, null); } catch (Exception e) { // ignore } // add MBean to set of managed beans if (nextRegistered != null) managedBeans.add(nextRegistered.getObjectName()); nextRegistered = null; } /** * Deregisters all Sigar MBeans that were created and registered using this * instance. After doing so, a super call is made to satisfy {@link AbstractMBean}. * @throws Exception * * @see AbstractMBean#preDeregister() */ public void preDeregister() throws Exception { // count backwards to remove ONs immediately for (int i = managedBeans.size() - 1; i >= 0; i--) { ObjectName next = (ObjectName) managedBeans.remove(i); if (mbeanServer.isRegistered(next)) { try { mbeanServer.unregisterMBean(next); } catch (Exception e) { // ignore } } } // do the super call super.preDeregister(); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/jmx/SigarSwap.java000066400000000000000000000143271210132627500274220ustar00rootroot00000000000000/* * 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 Swap 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; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/000077500000000000000000000000001210132627500251505ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/DefaultPagerProcessor.java000066400000000000000000000024631210132627500322630ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; /** * The default page processor does not process any elements * that you're paging. This is useful if you're only looking * to page through an existing collection, and you don't need * to perform any transformations on the elements that are * found to belong in the resultant page. */ public class DefaultPagerProcessor implements PagerProcessor { /** * Default processor does not process anything, it just * returns what was passed in. * @param o The object to process. * @return The same (completely unmodified) object that was passed in. * @see PagerProcessor#processElement */ public Object processElement(Object o) { return o; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/ListPageFetcher.java000066400000000000000000000067011210132627500310300ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.ListIterator; /** * A PageFetcher which works with a pre-fetched list as the * data backing the fetcher. */ public class ListPageFetcher extends PageFetcher { private List data; private int sortOrder; public ListPageFetcher(List data) { super(); this.data = data; this.sortOrder = PageControl.SORT_UNSORTED; } public PageList getPage(PageControl control) { PageList res = new PageList(); int startIdx, curIdx, endIdx; if (this.data.size() == 0) { return new PageList(); } this.ensureSortOrder(control); res.setTotalSize(this.data.size()); startIdx = clamp(control.getPageEntityIndex(), 0, this.data.size() - 1); curIdx = startIdx; if (control.getPagesize() == PageControl.SIZE_UNLIMITED) { endIdx = this.data.size(); } else { endIdx = clamp(startIdx + control.getPagesize(), startIdx, this.data.size()); } for (ListIterator i=this.data.listIterator(startIdx); i.hasNext() && curIdx < endIdx; curIdx++) { res.add(i.next()); } return res; } private class DescSorter implements Comparator { public int compare(Object o1, Object o2){ return -((Comparable)o1).compareTo((Comparable)o2); } public boolean equals(Object other){ return false; } } private void ensureSortOrder(PageControl control) { if (control.getSortorder() == this.sortOrder) { return; } this.sortOrder = control.getSortorder(); if (this.sortOrder == PageControl.SORT_UNSORTED) { return; } else if(this.sortOrder == PageControl.SORT_ASC) { Collections.sort(data); } else if(this.sortOrder == PageControl.SORT_DESC) { Collections.sort(data, new DescSorter()); } else { throw new IllegalStateException("Unknown control sorting type: " + this.sortOrder); } } /** * Clamp a value to a range. If the passed value is * less than the minimum, return the minimum. If it * is greater than the maximum, assign the maximum. * else return the passed value. */ private static int clamp(int val, int min, int max) { return (int)clamp((long)val, (long)min, (long)max); } private static long clamp(long val, long min, long max) { if (val < min) { return min; } if (val > max) { return max; } return val; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PageControl.java000066400000000000000000000120421210132627500302270ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; import java.io.Serializable; /** * A utility class to wrap up all the paging/sorting options that * are frequently used with finders and other methods that return * lists of things. */ public class PageControl implements Serializable, Cloneable { public static final int SIZE_UNLIMITED = -1; public static final int SORT_UNSORTED = 0; public static final int SORT_ASC = 1; public static final int SORT_DESC = 2; private int pagenum = 0; private int pagesize = SIZE_UNLIMITED; private int sortorder = SORT_UNSORTED; private int sortattribute = SortAttribute.DEFAULT; private Serializable metaData; // Meta-data that PageLists have returned public PageControl() {} public PageControl(int pagenum, int pagesize) { this.pagenum = pagenum; this.pagesize = pagesize; } public PageControl(int pagenum, int pagesize, int sortorder, int sortattribute) { this.pagenum = pagenum; this.pagesize = pagesize; this.sortorder = sortorder; this.sortattribute = sortattribute; } public boolean isAscending() { return this.sortorder == SORT_ASC; } public boolean isDescending() { return this.sortorder == SORT_DESC; } /** * sets the initial defaults for the PageControl. Sort attribute specifies * which attribute to sort on. * * @param pc * @param defaultSortAttr specifies the attribute to sort on. * @return PageControl */ public static PageControl initDefaults(PageControl pc, int defaultSortAttr) { if (pc == null) { pc = new PageControl(); } else { pc = (PageControl) pc.clone(); } if (pc.getSortattribute() == SortAttribute.DEFAULT) { pc.setSortattribute(defaultSortAttr); } if (pc.getSortorder() == SORT_UNSORTED) { pc.setSortorder(SORT_ASC); } return pc; } /** @return The current page number (0-based) */ public int getPagenum() { return this.pagenum; } /** @param pagenum Set the current page number to pagenum */ public void setPagenum(int pagenum) { this.pagenum = pagenum; } /** @return The current page size */ public int getPagesize() { return this.pagesize; } /** @param pagesize Set the current page size to this value */ public void setPagesize(int pagesize) { this.pagesize = pagesize; } /** @return The sort order used. This is one of the SORT_XXX constants. */ public int getSortorder() { return this.sortorder; } /** @param sortorder Sort order to use, one of the SORT_XXX constants. */ public void setSortorder(int sortorder) { this.sortorder = sortorder; } /** @return The attribute that the sort is based on. */ public int getSortattribute() { return this.sortattribute; } /** @param attr Set the attribute that the sort is based on. */ public void setSortattribute(int attr) { this.sortattribute = attr; } public Serializable getMetaData() { return this.metaData; } public void getMetaData(Serializable metaData) { this.metaData = metaData; } /** * Get the index of the first item on the page as dictated by the * page size and page number. */ public int getPageEntityIndex() { return this.pagenum * this.pagesize; } public String toString() { StringBuffer s = new StringBuffer("{"); s.append("pn=" + this.pagenum + " "); s.append("ps=" + this.pagesize + " "); s.append("so="); switch(this.sortorder) { case SORT_ASC: s.append("asc "); break; case SORT_DESC: s.append("desc"); break; case SORT_UNSORTED: s.append("unsorted "); break; default: s.append(' '); } s.append("sa=" + this.sortattribute + " "); s.append("}"); return s.toString(); } public Object clone() { PageControl res = new PageControl(this.pagenum, this.pagesize, this.sortorder, this.sortattribute); res.metaData = metaData; return res; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PageFetchException.java000066400000000000000000000014561210132627500315260ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; public class PageFetchException extends Exception { public PageFetchException() { super(); } public PageFetchException(String s) { super(s); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PageFetcher.java000066400000000000000000000017111210132627500301700ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; /** * A class which abstracts the fetching of the data for the pages * so callers can deal directly with a single object. */ public abstract class PageFetcher { /** * Get a page of data, as specified by the control. */ public abstract PageList getPage(PageControl control) throws PageFetchException; } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PageList.java000066400000000000000000000052351210132627500275300ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; /** * A utility class that contains all a "page" of data that is viewable *
* this list may or may not conain the entire list of information. * generally this list conains a subset of data. *
* ex. say we have a list of 5000 users. the entire list does not need to be * returned to only display the first 15 items, the user is only going to see * the first 15 both the user and the application the user will want to know * that there are 5000 users in the system. *
* */ public class PageList extends ArrayList implements Serializable { private int totalSize = 0; private boolean isUnbounded; // Is the total size of the list known? private Serializable metaData; public PageList() { super(); this.isUnbounded = false; } public PageList(Collection c, int totalSize) { super(c); this.totalSize = totalSize; this.isUnbounded = false; } public String toString() { StringBuffer s = new StringBuffer("{"); s.append("totalSize=" + totalSize + " "); s.append("}"); return super.toString() + s.toString(); } /** returns the total size of the "masterlist" that this page is a * subset of. * @return Value of property listSize. */ public int getTotalSize() { return Math.max(this.size(), this.totalSize); } /** Sets the total size of the "masterlist" that this page is a subset of. * @param totalSize New value of property listSize. * */ public void setTotalSize(int totalSize) { this.totalSize = totalSize; } public void setMetaData(Serializable metaData){ this.metaData = metaData; } public Serializable getMetaData(){ return this.metaData; } public boolean isUnbounded(){ return this.isUnbounded; } public void setUnbounded(boolean isUnbounded){ this.isUnbounded = isUnbounded; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/Pager.java000066400000000000000000000312071210132627500270540ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Implements a generic pager. What is a pager? Let's say you * have a large collection of objects, perhaps a long list of * EJB Local Interfaces. You're interested in breaking the * mammoth list out into a number pages, each with 25 items on it. * You're interested in returning page #17 of such a collection. * Why bother implementing the "skip past a bunch of things, then * return pagesize items in the resultant colleciton" over and over * again. * * You can also have the elements go through a processor that you * supply as they move from the source collection to the * destination collection. */ public class Pager { public static final String DEFAULT_PROCESSOR_CLASSNAME = "org.hyperic.sigar.pager.DefaultPagerProcessor"; private static Map PagerProcessorMap = Collections.synchronizedMap(new HashMap()); private PagerProcessor processor = null; private boolean skipNulls = false; private PagerEventHandler eventHandler = null; private Pager ( PagerProcessor processor ) { this.processor = processor; this.skipNulls = false; this.eventHandler = null; if ( this.processor instanceof PagerProcessorExt ) { this.skipNulls = ((PagerProcessorExt) this.processor).skipNulls(); this.eventHandler = ((PagerProcessorExt) this.processor).getEventHandler(); } } public static Pager getDefaultPager () { try { return getPager(DEFAULT_PROCESSOR_CLASSNAME); } catch ( Exception e ) { throw new IllegalStateException("This should never happen: " + e); } } /** * Get a pager based on the PagerProcessor supplied. */ public static Pager getPager (String pageProcessorClassName) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Pager p = null; p = (Pager) PagerProcessorMap.get(pageProcessorClassName); if ( p == null ) { PagerProcessor processor = (PagerProcessor) Class.forName(pageProcessorClassName).newInstance(); p = new Pager(processor); PagerProcessorMap.put(pageProcessorClassName, p); } return p; } /** * Seek to the specified pagenum in the source collection and * return pagsize numberof of elements in the List. * If pagenum or pagesize is -1, then everything in the * source collection will be returned. * * @param source The source collection to seek through. * @param pagenum The page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @param pagesize The size of each page. * @return PageList containing results of seek. */ public PageList seek ( Collection source, int pagenum, int pagesize ) { return seek(source,pagenum,pagesize,null); } /** * Seek to the specified pagenum in the source collection and return pagsize * numberof of elements in the List, as specified the PageControl object. * If pagenum or pagesize is -1, then everything in the * source collection will be returned. * * @param source The source collection to seek through. * @param pc The page control used for page size and page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @return PageList containing results of seek. */ public PageList seek ( Collection source, PageControl pc ) { if (pc == null) pc = new PageControl(); return seek(source, pc.getPagenum(), pc.getPagesize(), null); } /** * Seek to the specified pagenum in the source collection and * return pagsize numberof of elements in the List. * If pagenum or pagesize is -1, then everything in the * source collection will be returned. * * @param source The source collection to seek through. * @param pagenum The page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @param pagesize The size of each page. * @param procData - any data object required by the processor. * @return PageList containing results of seek. */ public PageList seek ( Collection source, int pagenum, int pagesize, Object procData ) { PageList dest = new PageList(); seek(source, dest, pagenum, pagesize, procData); dest.setTotalSize(source.size()); return dest; } /** * Seek to the specified pagenum in the source collection and place * pagesize number of elements into the dest collection. * If pagenum or pagesize is -1, then everything in the * source collection will be placed in the dest collection. * * @param source The source collection to seek through. * @param dest The collection to place results into. * @param pagenum The page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @param pagesize The size of each page. */ public void seek ( Collection source, Collection dest, int pagenum, int pagesize ) { seek(source,dest,pagenum,pagesize,null); } /** * Seek to the specified pagenum in the source collection and place * pagesize number of elements into the dest collection. * If pagenum or pagesize is -1, then everything in the * source collection will be placed in the dest collection. * * @param source The source collection to seek through. * @param dest The collection to place results into. * @param pagenum The page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @param pagesize The size of each page. * @param procData any object required to process the item. */ public void seek ( Collection source, Collection dest, int pagenum, int pagesize, Object procData) { Iterator iter = source.iterator(); int i, currentPage; if ( pagesize == -1 || pagenum == -1 ) { pagenum = 0; pagesize = Integer.MAX_VALUE; } for ( i=0, currentPage=0; iter.hasNext() && currentPage < pagenum; i++, currentPage += (i % pagesize == 0) ? 1:0 ) { iter.next(); } if ( this.eventHandler != null ) this.eventHandler.init(); if ( this.skipNulls ) { Object elt; while ( iter.hasNext() && dest.size() < pagesize ) { if (this.processor instanceof PagerProcessorExt) elt = ((PagerProcessorExt)this.processor) .processElement(iter.next(), procData); else elt = this.processor.processElement(iter.next()); if ( elt == null ) continue; dest.add(elt); } } else { while ( iter.hasNext() && dest.size() < pagesize ) { dest.add(this.processor.processElement(iter.next())); } } if ( this.eventHandler != null ) this.eventHandler.cleanup(); } /** * Seek to the specified pagenum in the source collection and place * pagesize number of elements into the dest collection. Unlike, * seek(), all items are passed to the Processor or ProcessorExt * regardless whether they are placed in dest collection. If pagenum * or pagesize is -1, then everything in the source collection will * be placed in the dest collection. * * @param source The source collection to seek through. * @param pagenum The page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @param pagesize The size of each page. * @param procData any object required to process the item. */ public PageList seekAll ( Collection source, int pagenum, int pagesize, Object procData ) { PageList dest = new PageList(); seekAll(source, dest, pagenum, pagesize, procData); dest.setTotalSize(source.size()); return dest; } /** * Seek to the specified pagenum in the source collection and place * pagesize number of elements into the dest collection. Unlike, * seek(), all items are passed to the Processor or ProcessorExt * regardless whether they are placed in dest collection. If pagenum * or pagesize is -1, then everything in the source collection will * be placed in the dest collection. * * @param source The source collection to seek through. * @param dest The collection to place results into. * @param pagenum The page number to seek to. If there not * enough pages in the collection, then an empty list will be returned. * @param pagesize The size of each page. * @param procData any object required to process the item. */ public void seekAll ( Collection source, Collection dest, int pagenum, int pagesize, Object procData) { Iterator iter = source.iterator(); int i, currentPage; if ( pagesize == -1 || pagenum == -1 ) { pagenum = 0; pagesize = Integer.MAX_VALUE; } // PR:8434 : Multi-part paging fixes. // 1.) Invoke the pager processor external which in many cases may // be keeping track of element [in|ex]clusion. // 2.) The counter 'i' is used with modulus arithmetic to determine // which page we should be on. Don't increment it if the proc-ext // indicated that the element should not be paged. // 3.) 'i' begins it's existance at 0. Zero modulus anything yields // zero. So the ternary expression needs to check for this initial // condition and not increment the page number. for ( i=0, currentPage=0; iter.hasNext() && currentPage < pagenum; currentPage += (i != 0 && i % pagesize == 0) ? 1:0 ) { if (this.processor instanceof PagerProcessorExt) { Object ret = ((PagerProcessorExt)this.processor) .processElement(iter.next(), procData); if (ret != null) { i++; } } else { this.processor.processElement(iter.next()); i++; } } if ( this.eventHandler != null ) this.eventHandler.init(); if ( this.skipNulls ) { Object elt; while ( iter.hasNext() ) { if (this.processor instanceof PagerProcessorExt) elt = ((PagerProcessorExt)this.processor) .processElement(iter.next(), procData); else elt = this.processor.processElement(iter.next()); if ( elt == null ) continue; if (dest.size() < pagesize) dest.add(elt); } } else { while ( iter.hasNext() ) { Object elt = this.processor.processElement(iter.next()); if (dest.size() < pagesize) dest.add(elt); } } if ( this.eventHandler != null ) this.eventHandler.cleanup(); } /** Process all objects in the source page list and return the destination * page list with the same total size */ public PageList processAll(PageList source) { PageList dest = new PageList(); for (Iterator it = source.iterator(); it.hasNext(); ) { Object elt = this.processor.processElement(it.next()); if ( elt == null ) continue; dest.add(elt); } dest.setTotalSize(source.getTotalSize()); return dest; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PagerEventHandler.java000066400000000000000000000017321210132627500313540ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; /** * This class is useful for classes that implement PagerProcessorExt and * need to do some initialization before paging begins and some cleanup * after paging has ended. */ public interface PagerEventHandler { /** Called before paging begins. */ public void init(); /** Called after paging ends. */ public void cleanup(); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PagerProcessor.java000066400000000000000000000022541210132627500307540ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; /** * Provides a point of extensibility in the paging behavior. * If you supply a PagerProcessor when you get a Pager, * then that processor will be called to process each element * as the pager moves it from the source collection to the * destination collection. */ public interface PagerProcessor { /** * Process an element as the pager moves it from the source * collection to the destination collection. * @param o The object to process. * @return The processed object. */ public Object processElement(Object o); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/PagerProcessorExt.java000066400000000000000000000035651210132627500314430ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; /** * Provides a point of extensibility in the paging behavior. * If you supply a PagerProcessor when you get a Pager, * then that processor will be called to process each element * as the pager moves it from the source collection to the * destination collection. */ public interface PagerProcessorExt extends PagerProcessor { /** * Get the event handler for this pager. May return null to indicate * that no event handler should be used. */ public PagerEventHandler getEventHandler(); /** * Determines if null values are included in the Pager's results. * @return If this method returns true, then when the processElement * method returns null, that element will not be included in the results. * If this methods returns false, then nulls may be added to the result * page. */ public boolean skipNulls(); /** * Process an element as the pager moves it from the source * collection to the destination collection. This version * allows an additional argument to be passed along. * @param o1 The object to process. * @param o2 Additional data required to processElement. * @return The processed object. */ public Object processElement(Object o1, Object o2); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/SortAttribute.java000066400000000000000000000045721210132627500306360ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; import java.io.Serializable; public class SortAttribute implements Serializable { private SortAttribute () {} public static final int DEFAULT = 0; // Generic attributes public static final int NAME = 1; public static final int CTIME = 2; // Authz sort attributes - specifieds which column to store on // for example, for 'subject_name', sort on column #3 public static final int ROLE_NAME = 1; public static final int RESGROUP_NAME = 2; public static final int RESTYPE_NAME = 4; public static final int RESOURCE_NAME = 5; public static final int OPERATION_NAME = 6; public static final int ROLE_MEMBER_CNT= 17; public static final int SUBJECT_NAME = 3; public static final int FIRST_NAME = 7; public static final int LAST_NAME = 8; // Event sort attributes public static final int EVENT_LOG_CTIME = 1; // Control sort attributes public static final int CONTROL_ACTION = 9; public static final int CONTROL_STATUS = 10; public static final int CONTROL_STARTED = 11; public static final int CONTROL_ELAPSED = 12; public static final int CONTROL_DATESCHEDULED = 13; public static final int CONTROL_DESCRIPTION = 14; public static final int CONTROL_NEXTFIRE = 15; public static final int CONTROL_ENTITYNAME = 16; public static final int OWNER_NAME = 21; public static final int SERVICE_NAME = 22; public static final int SERVICE_TYPE = 23; public static final int RT_NAME = 24; public static final int RT_LOW = 25; public static final int RT_AVG = 26; public static final int RT_PEAK = 27; } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/pager/StaticPageFetcher.java000066400000000000000000000033411210132627500313410ustar00rootroot00000000000000/* * Copyright (c) 2006 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.pager; import java.util.Arrays; import java.util.List; /** * A fetcher which uses a static array of strings to page * through. */ public class StaticPageFetcher extends PageFetcher { private List data; public StaticPageFetcher(String[] data) { this.data = Arrays.asList(data); } public StaticPageFetcher(List data) { this.data = data; } public PageList getPage(PageControl control) throws PageFetchException { PageList res = new PageList(); int startIdx, endIdx; res.setTotalSize(this.data.size()); if (control.getPagesize() == PageControl.SIZE_UNLIMITED || control.getPagenum() == -1) { res.addAll(this.data); return res; } startIdx = control.getPageEntityIndex(); endIdx = startIdx + control.getPagesize(); if (startIdx >= this.data.size()) { return res; } if (endIdx > this.data.size()) { endIdx = this.data.size(); } res.addAll(this.data.subList(startIdx, endIdx)); return res; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/000077500000000000000000000000001210132627500250325ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/MalformedQueryException.java000066400000000000000000000016721210132627500325160ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.ptql; import org.hyperic.sigar.SigarException; /** * Exception for malformed process queries which cannot * be parsed. */ public class MalformedQueryException extends SigarException { public MalformedQueryException() { } public MalformedQueryException(String message) { super(message); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/ProcessFinder.java000066400000000000000000000037061210132627500304510ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.ptql; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxyCache; public class ProcessFinder { private Sigar sigar; private ProcessQueryFactory qf; /** * @deprecated */ public ProcessFinder(SigarProxy proxy) { this(SigarProxyCache.getSigar(proxy)); } public ProcessFinder(Sigar sigar) { this.sigar = sigar; this.qf = ProcessQueryFactory.getInstance(); } public long findSingleProcess(String query) throws SigarException { return findSingleProcess(this.qf.getQuery(query)); } public long findSingleProcess(ProcessQuery query) throws SigarException { return query.findProcess(this.sigar); } public static long[] find(Sigar sigar, String query) throws SigarException { return new ProcessFinder(sigar).find(query); } public static long[] find(SigarProxy sigar, String query) throws SigarException { return new ProcessFinder(sigar).find(query); } public long[] find(String query) throws SigarException { return find(this.qf.getQuery(query)); } public long[] find(ProcessQuery query) throws SigarException { return query.find(this.sigar); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/ProcessQuery.java000066400000000000000000000017121210132627500303420ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.ptql; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.Sigar; public interface ProcessQuery { public boolean match(Sigar sigar, long pid) throws SigarException; public long findProcess(Sigar sigar) throws SigarException; public long[] find(Sigar sigar) throws SigarException; } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/ProcessQueryFactory.java000066400000000000000000000041411210132627500316710ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 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.ptql; import java.util.Iterator; import java.util.Map; import java.util.HashMap; public class ProcessQueryFactory { private static ProcessQueryFactory instance = null; private Map cache = new HashMap(); public ProcessQueryFactory() {} public void clear() { for (Iterator it=this.cache.values().iterator(); it.hasNext();) { SigarProcessQuery query = (SigarProcessQuery)it.next(); query.destroy(); } this.cache.clear(); } public static ProcessQueryFactory getInstance() { if (instance == null) { instance = new ProcessQueryFactory(); } return instance; } public ProcessQuery getQuery(String query) throws MalformedQueryException { if (query == null) { throw new MalformedQueryException("null query"); } if (query.length() == 0) { throw new MalformedQueryException("empty query"); } ProcessQuery pQuery = (ProcessQuery)this.cache.get(query); if (pQuery != null) { return pQuery; } pQuery = new SigarProcessQuery(); ((SigarProcessQuery)pQuery).create(query); this.cache.put(query, pQuery); return pQuery; } /** * @deprecated * @see #getQuery(String) */ public static ProcessQuery getInstance(String query) throws MalformedQueryException { return getInstance().getQuery(query); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/QueryLoadException.java000066400000000000000000000015141210132627500314620ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.ptql; /** * @deprecated */ public class QueryLoadException extends RuntimeException { public QueryLoadException() { } public QueryLoadException(String message) { super(message); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/SigarProcessQuery.java000066400000000000000000000030331210132627500313260ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.ptql; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; public class SigarProcessQuery implements ProcessQuery { int sigarWrapper = 0; //holds the sigar_ptql_query_t * long longSigarWrapper = 0; //same, but where sizeof(void*) > sizeof(int) native void create(String ptql) throws MalformedQueryException; native void destroy(); protected void finalize() { destroy(); } public native boolean match(Sigar sigar, long pid) throws SigarException; public native long findProcess(Sigar sigar) throws SigarException; public native long[] find(Sigar sigar) throws SigarException; static boolean re(String haystack, String needle) { if (haystack == null) { return false; } if (needle == null) { return false; } return StringPattern.matches(haystack, needle); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/ptql/StringPattern.java000066400000000000000000000024211210132627500305000ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.ptql; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hyperic.sigar.util.ReferenceMap; public class StringPattern { private static Map patterns = ReferenceMap.synchronizedMap(); /** * Wrapper around Pattern.compile(regex).matcher(source).find() */ public static boolean matches(String source, String regex) { Pattern pattern = (Pattern)patterns.get(regex); if (pattern == null) { pattern = Pattern.compile(regex); patterns.put(regex, pattern); } Matcher matcher = pattern.matcher(source); return matcher.find(); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/000077500000000000000000000000001210132627500251615ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/CollectionCompleter.java000066400000000000000000000076101210132627500317760ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.hyperic.sigar.util.GetlineCompleter; /** * GetlineCompleter implementation looks for possible completions * using an Iterator. */ public class CollectionCompleter implements GetlineCompleter { private ArrayList completions = new ArrayList(); private ShellBase shell = null; private PrintStream out = System.out; private Collection collection; public CollectionCompleter() { } public CollectionCompleter(ShellBase shell) { this.shell = shell; this.out = shell.getOutStream(); } public CollectionCompleter(ShellBase shell, Collection collection) { this(shell); setCollection(collection); } public Iterator getIterator() { return getCollection().iterator(); } public Collection getCollection() { return this.collection; } public void setCollection(Collection collection) { this.collection = collection; } private boolean startsWith(String substr, String[] possible) { for (int i=0; i 0) { return partial; } return null; } public String complete(String line) { this.completions.clear(); int len = line.length(); for (Iterator it = getIterator(); it.hasNext(); ) { String name = (String)it.next(); if ((len == 0) || name.startsWith(line)) { this.completions.add(name); } } int size = this.completions.size(); switch (size) { case 0: return line; case 1: return (String)this.completions.get(0); default: String partial = displayPossible(this.completions); if (partial != null) { return partial; } return line; } } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/FileCompleter.java000066400000000000000000000100411210132627500305520ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.io.File; import java.io.FilenameFilter; import java.util.Iterator; import org.hyperic.sigar.SigarLoader; public class FileCompleter extends CollectionCompleter implements FilenameFilter { private static final String HOME = System.getProperty("user.home"); private String name; public FileCompleter() { super(); } public FileCompleter(ShellBase shell) { super(shell); } public static String expand(String name) { if (name.startsWith("~")) { return HOME + name.substring(1, name.length()); } return name; } public boolean accept(File dir, String name) { if (name.equals(".") || name.equals("..")) { return false; } return name.startsWith(this.name); } public Iterator getIterator() { return null; //unused } private String appendSep(String name) { if (name.endsWith(File.separator)) { return name; } return name + File.separator; } //e.g. we don't want "~/." treated as a directory //but we do want "." to be. private boolean isDotFile(File file) { return file.getName().equals(".") && (file.getParentFile() != null); } public String complete(String line) { String fileName = line; boolean isHome = false; if (line.length() == 0) { return appendSep("."); } else if (fileName.startsWith("~")) { isHome = true; fileName = expand(fileName); } File file = new File(fileName); File dir; if (file.exists() && !isDotFile(file)) { if (file.isDirectory()) { this.name = null; dir = file; if (!fileName.endsWith(File.separator)) { return line + File.separator; } } else { return line; } } else { this.name = file.getName(); dir = file.getParentFile(); if (dir == null) { if (SigarLoader.IS_WIN32 && (line.length() == 1) && Character.isLetter(line.charAt(0))) { //e.g. C:\ return line + ":\\"; } return line; } if (!(dir.exists() && dir.isDirectory())) { return line; } } String[] list; if (this.name == null) { list = dir.list(); } else { list = dir.list(this); } if (list.length == 1) { fileName = appendSep(dir.toString()) + list[0]; if (new File(fileName).isDirectory()) { fileName = appendSep(fileName); } if (isHome) { return "~" + fileName.substring(HOME.length(), fileName.length()); } return fileName; } String partial = displayPossible(list); if (partial != null) { return appendSep(dir.toString()) + partial; } return line; } public static void main(String[] args) throws Exception { String line = new FileCompleter().complete(args[0]); System.out.println("\nsigar> '" + line + "'"); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/MultiwordShellCommand.java000066400000000000000000000110201210132627500322730ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.hyperic.sigar.util.PrintfFormat; public class MultiwordShellCommand extends ShellCommandBase { private Map itsSubHandlerMap = new HashMap(); public ShellCommandHandler getSubHandler(String subName) { return (ShellCommandHandler)itsSubHandlerMap.get(subName); } public Set getHandlerNames() { return this.itsSubHandlerMap.keySet(); } public void registerSubHandler(String subName, ShellCommandHandler handler) throws ShellCommandInitException { if (!itsSubHandlerMap.containsValue(handler)) { // Only init the handler if it has not been added yet. // We do this because a single handler could be // registered for multiple subName's (as in the case // of aliasing). handler.init(getCommandName() + " " + subName, getShell()); } itsSubHandlerMap.put(subName, handler); } public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { String cmdName = getCommandName(); ShellCommandHandler handler; String[] subArgs; if (args.length < 1) { throw new ShellCommandUsageException(cmdName + " command " + "requires an argument."); } handler = (ShellCommandHandler) itsSubHandlerMap.get(args[0].toLowerCase()); if (handler == null) { throw new ShellCommandUsageException("don't know how to " + cmdName + " " + args[0]); } subArgs = new String[args.length - 1]; System.arraycopy(args, 1, subArgs, 0, subArgs.length); handler.processCommand(subArgs); } public String getSyntaxArgs() { StringBuffer res = new StringBuffer(); res.append("<"); for (Iterator i=this.getHandlerNames().iterator(); i.hasNext();) { res.append((String)i.next()); if (i.hasNext()) { res.append(" | "); } } res.append(">"); return res.toString(); } public String getUsageHelp(String[] args) { ShellCommandHandler handler; String[] subArgs; if (args.length == 0) { StringBuffer res = new StringBuffer(); Object[] fArgs = new Object[2]; PrintfFormat fmt; String fmtStr; int maxLen; res.append(" " + this.getUsageShort()); res.append(".\n For further help on each subcommand, "); res.append("type 'help "); res.append(this.getCommandName() + " '\n\n"); maxLen = 0; for (Iterator i=this.getHandlerNames().iterator(); i.hasNext();) { String cmdName = (String)i.next(); if (cmdName.length() > maxLen) maxLen = cmdName.length(); } fmtStr = " %-" + (maxLen + 1) + "s %s"; fmt = new PrintfFormat(fmtStr); for (Iterator i=this.getHandlerNames().iterator(); i.hasNext();) { String cmdName = (String)i.next(); ShellCommandHandler sub = this.getSubHandler(cmdName); fArgs[0] = cmdName + ":"; fArgs[1] = sub.getUsageShort(); res.append(fmt.sprintf(fArgs)); if (i.hasNext()) res.append("\n"); } return res.toString(); } if ((handler = getSubHandler(args[0].toLowerCase())) == null) { return null; } subArgs = new String[args.length - 1]; System.arraycopy(args, 1, subArgs, 0, subArgs.length); return handler.getUsageHelp(subArgs); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/NormalQuitCommandException.java000066400000000000000000000015141210132627500332760ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; /** * This exception is thrown when a command wants to exit the * shell completely. Typically this is only done for quit commands. */ public class NormalQuitCommandException extends RuntimeException { } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ProcessQueryCompleter.java000066400000000000000000000122461210132627500323500ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.shell; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.util.GetlineCompleter; public class ProcessQueryCompleter implements GetlineCompleter { private static final String SIGAR_PACKAGE = "org.hyperic.sigar."; private static final Map METHODS = new HashMap(); private static final Collection NOPS = Arrays.asList(new String[] { "eq", "ne", "gt", "ge", "lt", "le" }); private static final Collection SOPS = Arrays.asList(new String[] { "eq", "ne", "re", "ct", "ew", "sw" }); private static final Class[] NOPARAM = new Class[0]; private static final String PROC_PREFIX = "getProc"; private ShellBase shell; private GetlineCompleter m_completer; private Map methods; static { Method[] methods = SigarProxy.class.getMethods(); for (int i=0; i ", false); } catch (EOFException e) { break; } catch (Exception e) { err.println("Fatal error reading input line: " + e); e.printStackTrace(err); return; } if (input == null || input.trim().length() == 0) { if (!Getline.isTTY()) { break; } else { continue; } } try { handleCommand(input); } catch (NormalQuitCommandException nqce) { break; } } if (Getline.isTTY()) { out.println("Goodbye."); } } public void handleCommand(String line) { String[] args; try { args = explodeQuoted(line); } catch(IllegalArgumentException exc) { this.out.println("Syntax error: Unbalanced quotes"); return; } if (args.length != 0) { handleCommand(line, args); } } public void handleCommand(String line, String[] args) { ShellCommandHandler handler = null; PrintStream oldSysOut = null, oldOut = null; String command = args[0]; String[] subArgs; int useArgs; if (args.length == 0) { return; } handler = getHandler(command); if (handler == null) { String[] aliasArgs = ShellCommand_alias.getAlias(command); if (aliasArgs == null) { err.println("unknown command: " + command); return; } handleCommand(line, aliasArgs); return; } useArgs = args.length; if (args.length > 2 && args[args.length - 2].equals(">")) { PrintStream newOut; oldSysOut = System.out; oldOut = this.out; // Re-direction, baby try { FileOutputStream fOut; fOut = new FileOutputStream(args[args.length -1]); newOut = new PrintStream(fOut); } catch(IOException exc) { this.err.println("Failed to redirect to output file: " + exc); return; } this.isRedirected = true; this.out = newOut; System.setOut(newOut); useArgs = useArgs - 2; } subArgs = new String[useArgs - 1]; System.arraycopy(args, 1, subArgs, 0, subArgs.length); try { processCommand(handler, subArgs); } catch (ShellCommandUsageException e) { String msg = e.getMessage(); if (msg == null || msg.trim().length() == 0) { msg = "an unknown error occurred"; } err.println(command + ": " + msg); } catch (ShellCommandExecException e) { err.println(e.getMessage()); } catch (NormalQuitCommandException e) { throw e; } catch (Exception e) { err.println("Unexpected exception processing " + "command '" + command + "': " + e); e.printStackTrace(err); } finally { if (this.doHistoryAdd) { this.gl.addToHistory(line); } if (oldSysOut != null) { this.isRedirected = false; System.setOut(oldSysOut); this.out = oldOut; } } } public void processCommand(ShellCommandHandler handler, String args[]) throws ShellCommandUsageException, ShellCommandExecException { handler.processCommand(args); } public PrintStream getOutStream() { return this.out; } public PrintStream getErrStream() { return this.err; } public Getline getGetline() { return this.gl; } public boolean hasCompleter(ShellCommandHandler handler) { return GetlineCompleter.class.isAssignableFrom(handler.getClass()); } public String complete(ShellCommandHandler handler, String line) { if (hasCompleter(handler)) { return ((GetlineCompleter)handler).complete(line); } return line; } public String complete(String line) { if (line == null) { return null; } int ix = line.indexOf(" "); if (ix != -1) { //if the command name has been completed //hand off completion of the rest to the command handler //if it implements GetlineHandler String cmd = line.substring(0, ix); String sub = line.substring(ix+1, line.length()); ShellCommandHandler handler = getHandler(cmd); if (handler != null) { String hline = complete(handler, sub); return cmd + " " + hline; } return line; } line = this.completer.complete(line); if (getHandler(line) != null) { return line + " "; } return line; } /** * @see ShellCommandMapper#getHandler */ public ShellCommandHandler getHandler(String command) { if (command == null) { return null; } return (ShellCommandHandler)this.handlers.get(command.toLowerCase()); } public void setHandlerHidden(String handlerName, boolean isHidden) { if (getHandler(handlerName) == null) { throw new IllegalArgumentException("Unknown handler: " + handlerName); } this.hiddenCommands.put(handlerName, isHidden ? Boolean.TRUE : Boolean.FALSE); } public boolean handlerIsHidden(String handlerName) { return this.hiddenCommands.get(handlerName) != null; } /** * @see ShellCommandMapper#getCommandNameIterator */ public Iterator getCommandNameIterator() { ArrayList keyArray = new ArrayList(); String[] keys; for (Iterator i = this.handlers.keySet().iterator(); i.hasNext();) { String keyName = (String)i.next(); if (!handlerIsHidden(keyName)) { keyArray.add(keyName); } } keys = (String[])keyArray.toArray(new String[0]); Arrays.sort(keys); return Arrays.asList(keys).iterator(); } public void shutdown() { } /** * Check to see if the currently running shell command is being * redirected to a file. * * @return true if the shell is redirecting to a file, else false */ public boolean isRedirected() { return this.isRedirected; } /** * Set the page size for data paging. * * @param size Number of rows to include in a page of data -- if * 0, then unlimited rows will be used. */ public void setPageSize(int size) { if (size == 0 || size < -1) { throw new IllegalArgumentException("Page size must be > 0 or -1"); } this.pageSize = size; } /** * Get the current page size used when paging data. * * @return the # of rows in the current page size. */ public int getPageSize() { return this.pageSize; } /** * Get the number of pages that the fetcher can fetch, given the * settings as specified by the control and the # of total entites * the fetcher can fetch * * @param control Control which dictates the page size * @param list Last pageList queried via the control */ private int getNumPages(PageControl control, PageList list) { int pageSize = control.getPagesize(); int totalElems; totalElems = list.getTotalSize(); if (pageSize == PageControl.SIZE_UNLIMITED) { return 1; } else if (pageSize == 0) { return 0; } if ((totalElems % pageSize) == 0) { return totalElems / pageSize; } return (totalElems / pageSize) + 1; } /** * Print a page of data * * @param out Stream to print to * @param data List containing the data to print * @param lineNo Line number of the first element of data * @param printLineNumbers If true, prefix lines with their numbers * * @return the number of lines printed */ private void printPage(PrintStream out, PageList data, int lineNo, boolean printLineNumbers) { for (Iterator i=data.iterator(); i.hasNext(); ) { if (printLineNumbers) { out.print(lineNo++ + ": "); } out.println((String)i.next()); } } public PageControl getDefaultPageControl() { PageControl res; res = new PageControl(0, getPageSize() == -1 ? PageControl.SIZE_UNLIMITED : getPageSize()); return res; } public void performPaging(PageFetcher fetcher) throws PageFetchException { performPaging(fetcher, getDefaultPageControl()); } public void performPaging(PageFetcher fetcher, PageControl control) throws PageFetchException { PrintStream out; PageList data; boolean lineNumberMode; // Don't know how to handle this case if (control.getPagesize() == 0) { return; } lineNumberMode = false; out = getOutStream(); if (isRedirected()) { control.setPagesize(PageControl.SIZE_UNLIMITED); } data = fetcher.getPage((PageControl)control.clone()); printPage(out, data, control.getPageEntityIndex() + 1, lineNumberMode); if (control.getPagesize() == PageControl.SIZE_UNLIMITED || data.size() < control.getPagesize()) { return; } while (true) { boolean printPage = false; String cmd; int totalPages; totalPages = getNumPages(control, data); try { cmd = getInput("--More-- (Page " + (control.getPagenum() + 1) + " of " + totalPages + ")", false); } catch(IOException exc) { out.println(); break; } if (cmd == null || (cmd = cmd.trim()).length() == 0) { printPage = true; control.setPagenum(control.getPagenum() + 1); } else if (cmd.equals("q")) { break; } else if (cmd.equals("b")) { printPage = true; if (control.getPagenum() > 0) { control.setPagenum(control.getPagenum() - 1); } } else if (cmd.equals("l")) { lineNumberMode = !lineNumberMode; printPage = true; } else if (cmd.equals("?")) { out.println(" 'b' - Scroll back one page"); out.println(" 'l' - Toggle line number mode"); out.println(" 'q' - Quit paging"); out.println(" '' - Jump to the specified page #"); out.println(" '' - Scroll forward one page"); } else { int newPageNo; try { newPageNo = Integer.parseInt(cmd); } catch(NumberFormatException exc) { out.println("Unknown command '" + cmd + "' " + " type '?' for paging help"); continue; } if (newPageNo < 1 || newPageNo > totalPages) { out.println(newPageNo + " out of range (must be " + "1 to " + totalPages + ")"); } else { control.setPagenum(newPageNo - 1); printPage = true; } } if (printPage) { data = fetcher.getPage((PageControl)control.clone()); printPage(out, data, control.getPageEntityIndex() + 1, lineNumberMode); // Check to see if we printed the last of the data if (data.size() < control.getPagesize()) { break; } } } } private static String[] explodeQuoted(String arg) { ArrayList res = new ArrayList(); StringTokenizer quoteTok; boolean inQuote = false; arg = arg.trim(); quoteTok = new StringTokenizer(arg, "\"", true); while (quoteTok.hasMoreTokens()) { String elem = (String)quoteTok.nextElement(); if (elem.equals("\"")) { inQuote = !inQuote; continue; } if (inQuote) { res.add(elem); } else { StringTokenizer spaceTok = new StringTokenizer(elem.trim()); while (spaceTok.hasMoreTokens()) { res.add(spaceTok.nextToken()); } } } if (inQuote) { throw new IllegalArgumentException("Unbalanced quotation marks"); } return (String[]) res.toArray(new String[0]); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommandBase.java000066400000000000000000000037631210132627500311760ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.io.PrintStream; public class ShellCommandBase implements ShellCommandHandler { protected String itsCommandName = null; protected ShellBase itsShell = null; private PrintStream out = null; public String getCommandName() { return itsCommandName; } public ShellBase getShell() { return itsShell; } public PrintStream getOutStream() { return this.getShell().getOutStream(); } public PrintStream getErrStream() { return this.getShell().getErrStream(); } public void init(String commandName, ShellBase shell) throws ShellCommandInitException { itsCommandName = commandName; itsShell = shell; } public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { out.println("ShellCommandBase: not implemented: " + itsCommandName); /* if (args != null && args.trim().length() > 0) { out.println("args were: " + args); } */ } public String getSyntax() { return "Syntax: " + this.getCommandName() + " " + this.getSyntaxArgs(); } public String getSyntaxArgs() { return ""; } public String getUsageShort() { return ""; } public String getUsageHelp(String[] args) { return "Help not available for command " + itsCommandName; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommandExecException.java000066400000000000000000000014621210132627500330610ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; public class ShellCommandExecException extends Exception { public ShellCommandExecException() {} public ShellCommandExecException(String s) { super(s); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommandHandler.java000066400000000000000000000040231210132627500316670ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; public interface ShellCommandHandler { /** * Initialize this command handler. * @param commandName The name of the command. * @param shell The shell. This is useful for command * that need to be able to interpret other commands, like the "help" * command, and for commands that need to get additional user input, * for example a login command that presents a password prompt. */ public void init(String commandName, ShellBase shell) throws ShellCommandInitException; /** * Handle a command. * @param args The args to the command. * @exception ShellCommandUsageException If the args are malformed. * @exception ShellCommandExecException If an error occurred * executing the command. */ public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException; /** * Get some info on how to invoke this command. * @return Some usage information on how this command is * expected to be invoked. */ public String getUsageHelp(String[] args); /** * Get a very brief (40 character) description of the command * @return A description of the command. */ public String getUsageShort(); /** * Get a description of the syntax for how a command should be invoked. * @return A description of the syntax */ public String getSyntax(); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommandInitException.java000066400000000000000000000014621210132627500331000ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; public class ShellCommandInitException extends Exception { public ShellCommandInitException() {} public ShellCommandInitException(String s) { super(s); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommandMapper.java000066400000000000000000000016471210132627500315470ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.util.Iterator; public interface ShellCommandMapper { /** * Get the command handler for a command. */ public ShellCommandHandler getHandler(String command); /** * Get an iterator for the command names. */ public Iterator getCommandNameIterator(); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommandUsageException.java000066400000000000000000000014651210132627500332440ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; public class ShellCommandUsageException extends Exception { public ShellCommandUsageException() {} public ShellCommandUsageException(String s) { super(s); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommand_alias.java000066400000000000000000000042751210132627500315530ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.util.HashMap; import java.util.Iterator; public class ShellCommand_alias extends ShellCommandBase { private static HashMap aliases = new HashMap(); public static String[] getAlias(String alias) { return (String[])aliases.get(alias); } public static Iterator getAliases() { return aliases.keySet().iterator(); } public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { if (args.length < 2) { throw new ShellCommandUsageException(this.getSyntax()); } int aliasArgsLen = args.length - 1; String[] aliasArgs = new String[ aliasArgsLen ]; System.arraycopy(args, 1, aliasArgs, 0, aliasArgsLen); aliases.put(args[0], aliasArgs); } public String getSyntaxArgs() { return " "; } public String getUsageShort() { return "Create alias command"; } public String getUsageHelp(String[] args) { if (aliases.size() == 0) { return "No aliases defined"; } StringBuffer sb = new StringBuffer(); sb.append("Defined aliases:\n"); for (Iterator it=aliases.keySet().iterator(); it.hasNext(); ) { String key = (String)it.next(); String[] cmd = getAlias(key); sb.append(key).append(" => "); for (int i=0; i [key2] ..."; } public String getUsageShort(){ return "Get system properties"; } public String getUsageHelp(String[] args) { return " " + getUsageShort() + "."; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommand_help.java000066400000000000000000000103511210132627500314020ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import org.hyperic.sigar.util.PrintfFormat; public class ShellCommand_help extends ShellCommandBase { public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { ShellCommandHandler handler; PrintStream out = this.getOutStream(); int useArgs; if (args.length == 0) { PrintfFormat fmt = new PrintfFormat("\t%-14s - %s"); Object[] fArgs = new Object[2]; ArrayList cmdNamesList = new ArrayList(); String[] cmdNames; Iterator i; i = itsShell.getCommandNameIterator(); while (i.hasNext()) { cmdNamesList.add(i.next()); } cmdNames = (String[])cmdNamesList.toArray(new String[0]); Arrays.sort(cmdNames); out.println("Available commands:"); for (int j=0; j [command arguments]"; } public String getUsageShort() { return "Gives help on shell commands"; } public String getUsageHelp(String[] args) { return " Displays help about the given command name. If the \n" + " command has arguments they may be entered for more " + "specific\n help"; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommand_quit.java000066400000000000000000000020341210132627500314330ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; public class ShellCommand_quit extends ShellCommandBase { public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { throw new NormalQuitCommandException(); } public String getUsageShort() { return "Terminate the shell"; } public String getUsageHelp(String[] args) { return " Terminate the shell."; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommand_set.java000066400000000000000000000057121210132627500312520ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.util.HashMap; import java.util.Iterator; public class ShellCommand_set extends ShellCommandBase { private HashMap keyDescriptions = new HashMap(); public ShellCommand_set() { this.keyDescriptions = new HashMap(); this.keyDescriptions.put(ShellBase.PROP_PAGE_SIZE, "The maximum size of a shell page"); } public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { if (args.length < 1 || args.length > 2) { throw new ShellCommandUsageException(this.getSyntax()); } if (args.length == 1) { System.getProperties().remove(args[0]); } else { if (args[0].equalsIgnoreCase(ShellBase.PROP_PAGE_SIZE)) { int newSize; try { newSize = Integer.parseInt(args[1]); if (newSize == 0 || newSize < -1) { throw new NumberFormatException(); } } catch(NumberFormatException exc) { throw new ShellCommandUsageException(args[0] + " must be "+ "an integer > 0 or " + "-1"); } this.getShell().setPageSize(newSize); } System.setProperty(args[0], args[1]); } } public void addSetKey(String key, String description) { this.keyDescriptions.put(key, description); } public String getSyntaxArgs() { return " [value]"; } public String getUsageShort() { return "Set system properties"; } public String getUsageHelp(String[] args) { String res = " " + this.getUsageShort() + ". If no value is provided, " + "the key will be\n deleted."; if (this.keyDescriptions.size() != 0) { res += "\n\n Common keys include:"; } for (Iterator i=this.keyDescriptions.keySet().iterator(); i.hasNext();) { String key = (String)i.next(); String value = (String)this.keyDescriptions.get(key); res += "\n " + key + ": " + value; } return res; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommand_sleep.java000066400000000000000000000031571210132627500315700ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; public class ShellCommand_sleep extends ShellCommandBase { public ShellCommand_sleep() {} public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { if (args.length != 1) { throw new ShellCommandUsageException(getSyntax()); } try { Thread.sleep(Integer.parseInt(args[0]) * 1000); } catch(NumberFormatException exc) { throw new ShellCommandExecException("Invalid time '" + args[0] + "' -- must be an integer"); } catch(InterruptedException exc) { throw new ShellCommandExecException("Sleep interrupted"); } } public String getSyntaxArgs() { return ""; } public String getUsageShort() { return "Delay execution for the a number of seconds "; } public String getUsageHelp(String[] args) { return " " + getUsageShort() + "."; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellCommand_source.java000066400000000000000000000043301210132627500317520ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.io.File; import java.io.IOException; import org.hyperic.sigar.util.GetlineCompleter; public class ShellCommand_source extends ShellCommandBase implements GetlineCompleter { public String complete(String line) { return new FileCompleter(getShell()).complete(line); } public void processCommand(String[] args) throws ShellCommandUsageException, ShellCommandExecException { File rcFile; if(args.length != 1){ throw new ShellCommandUsageException("Syntax: " + this.getCommandName() + " "); } rcFile = new File(FileCompleter.expand(args[0])); if(rcFile.isFile() == false){ throw new ShellCommandExecException("File '" + rcFile + "' not found"); } try { this.getShell().readRCFile(rcFile, true); } catch(IOException exc){ throw new ShellCommandExecException("Error reading file '" + rcFile + ": " + exc.getMessage()); } } public String getSyntaxArgs(){ return ""; } public String getUsageShort(){ return "Read a file, executing the contents"; } public String getUsageHelp(String[] args) { return " " + this.getUsageShort() + ". The file must contain " + "commands\n which are executable by the shell."; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/shell/ShellIntHandler.java000066400000000000000000000033371210132627500310520ustar00rootroot00000000000000/* * Copyright (c) 2006 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.shell; import java.util.Stack; import sun.misc.Signal; import sun.misc.SignalHandler; public class ShellIntHandler implements SignalHandler { private static ShellBase handlerShell; private static Stack handlers; public static void register(ShellBase shell) { handlerShell = shell; handlers = new Stack(); Signal signal; try { signal = new Signal("INT"); } catch (IllegalArgumentException e) { return; //e.g NetWare } try { Signal.handle(signal, new ShellIntHandler()); } catch(Exception e) { //java -Xrs for example will throw IllegalArgumentException } } public void handle(Signal signal) { if (handlers.empty()) { handlerShell.shutdown(); Runtime.getRuntime().halt(0); } else { SIGINT handler = (SIGINT)handlers.peek(); handler.handleSIGINT(); } } public static void push(SIGINT handler) { handlers.push(handler); } public static void pop() { handlers.pop(); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/test/000077500000000000000000000000001210132627500250315ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/test/GetPass.java000066400000000000000000000017741210132627500272530ustar00rootroot00000000000000/* * Copyright (c) 2006 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.io.IOException; import org.hyperic.sigar.Sigar; public class GetPass { public static void main(String[] args) throws Exception { try { String password = Sigar.getPassword("Enter password: "); System.out.println("You entered: ->" + password + "<-"); } catch (IOException e) { e.printStackTrace(); } } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/test/Proxy.java000066400000000000000000000357121210132627500270250ustar00rootroot00000000000000/* * Copyright (c) 2006 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.io.File; import java.io.FileFilter; import java.io.PrintStream; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarInvoker; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxyCache; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Proxy { private static final String HOME = System.getProperty("user.home"); private static boolean sameArg = true; //set false if using leaktest to also stress test private boolean pause = false; private boolean verbose = true; private boolean leakVerbose = false; private boolean fukksor = false; //compare SigarProxyCache to straightup reflection private boolean useReflection = false; private PrintStream out = System.out; private String ourPid; private Sigar sigar; private SigarProxy proxy; private long lastChange = 0, startSize = 0, currentSize = 0; private PidList pids; private NetifList netif; private FsList fs; private DirList dirs; private FileList files; public Proxy(Sigar sigar, SigarProxy proxy) { this.sigar = sigar; this.proxy = proxy; this.pids = new PidList(sigar); this.netif = new NetifList(sigar); this.fs = new FsList(sigar); this.dirs = new DirList(HOME); this.files = new FileList(HOME); } public void setOutputStream(PrintStream out) { this.out = out; } public void setVerbose(boolean value) { this.verbose = value; } public void setLeakVerbose(boolean value) { this.leakVerbose = value; } private void output() { this.out.println(); } private void output(String s) { String name = Thread.currentThread().getName(); this.out.println("[" + name + "] " + s); } private long getSize() throws SigarException { return sigar.getProcMem(ourPid).getResident(); } private boolean memstat(long i) throws SigarException { long size = getSize(); String changed = ""; if (currentSize != size) { long diff = size - currentSize; long iters = i - lastChange; changed = " (change=" + diff + ", iters=" + iters + ")"; output(i + ") size=" + size + changed); currentSize = size; lastChange = i; return true; } return false; } private void trace(String msg) { if (verbose) { output(msg); } } private boolean isNonStringArg(Method method) { Class[] paramTypes = method.getParameterTypes(); if ((paramTypes.length >= 1) && (paramTypes[0] != String.class)) { return true; } return false; } private String argsToString(Object[] args) { if ((args == null) || (args.length == 0)) { return ""; } StringBuffer sb = new StringBuffer(); sb.append('(').append(args[0].toString()); for (int i=1; i 0) { if (type.startsWith("Proc")) { arg = this.pids.getName(iter); switch (parms.length) { case 1: objArgs = new Object[] { arg }; break; case 2: if (type.equals("ProcEnv")) { objArgs = new Object[] { arg, "SHELL" }; } else if (type.equals("ProcPort")) { objArgs = new Object[] { "tcp", "80" }; } break; } } else { trace("SKIPPING: " + type); continue; } } Object obj; if (useReflection) { obj = method.invoke((Object)sigar, objArgs); } else { obj = invoke(new SigarInvoker(proxy, type), objArgs, null); } if (iter > 0) { if (memstat(iter)) { this.out.print(type); if (arg != null) { this.out.print(" " + arg); } output(); } } String value; if (obj instanceof Object[]) { value = argsToString((Object[])obj); } else { value = String.valueOf(obj); } trace(type + argsToString(objArgs) + "=" + value); continue; } Method[] attrs = attrClass.getMethods(); for (int j=0; j 0) { if (type.startsWith("Proc")) { arg = this.pids.getName(iter); } else if (type.startsWith("Net")) { arg = this.netif.getName(iter); } else if (type.startsWith("MultiProc")) { arg = "State.Name.eq=java"; } else if (type.equals("FileSystemUsage") || type.equals("MountedFileSystemUsage")) { arg = this.fs.getName(iter); } else if (type.equals("FileInfo") || type.equals("LinkInfo")) { arg = this.files.getName(iter); } else if (type.equals("DirStat")) { arg = this.dirs.getName(iter); } else { trace("SKIPPING: " + type); continue; } objArgs = new Object[] { arg }; } if (isNonStringArg(method)) { continue; } Object obj; if (useReflection) { Object typeObject = method.invoke((Object)sigar, objArgs); obj = getter.invoke(typeObject, new Object[0]); } else { obj = invoke(new SigarInvoker(proxy, type), objArgs, attrName); } if (iter > 0) { if (memstat(iter)) { this.out.print(type); if (arg != null) { this.out.print(" " + arg); } output(); } } trace(type + argsToString(objArgs) + "." + attrName + "=" + obj); if (pause) { //test cache expire pause(); } } } } private void pause() { output("hit enter to continue"); try { System.in.read(); } catch (Exception e) {} } private Object invoke(SigarInvoker invoker, Object[] args, String attr) { String type = invoker.getType(); if (fukksor) { //make args bogus to test exception handling/messages if (args.length != 0) { if (args[0] instanceof String) { if (type.startsWith("Proc")) { args[0] = new String("666666"); } else { args[0] = new String("bogus"); } } } } if (args.length == 0) { args = null; } try { return invoker.invoke(args, attr); } catch (SigarException e) { String msg = type + " failed: " + e.getMessage(); System.err.println(msg); return null; } } public static void main(String[] args) throws Exception { int expire = 30 * 1000; Sigar sigar = new Sigar(); SigarProxy proxy = SigarProxyCache.newInstance(sigar, expire); new Proxy(sigar, proxy).run(args); } public void run(String[] args) throws SigarException { ourPid = String.valueOf(sigar.getPid()); output("ourPid=" + ourPid); if (args.length >= 2) { String type = args[0], attr = args[args.length - 1]; if (type.equals("leaktest")) { int num = Integer.parseInt(args[1]); verbose = leakVerbose; startSize = currentSize = getSize(); long startTime = System.currentTimeMillis(); for (int i=0; i max) { break; } } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (Exception e) {} } } } private static void scanDir() { for (int i=0; i= 0; private static PrintStream out = System.out; public SigarTestCase(String name) { super(name); File f = new File(System.getProperty("user.home"), ".sigar.properties"); if (f.exists()) { FileInputStream is = null; try { is = new FileInputStream(f); this.props.load(is); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } public Sigar getSigar() { if (sigar == null) { sigar = new Sigar(); if (getVerbose()) { sigar.enableLogging(true); } } return sigar; } public static void closeSigar() { if (sigar != null) { sigar.close(); sigar = null; } ProcessQueryFactory.getInstance().clear(); Humidor.getInstance().close(); } public Properties getProperties() { return this.props; } public String getProperty(String key, String val) { return getProperties().getProperty(key, val); } public String getProperty(String key) { return getProperty(key, null); } public static void setVerbose(boolean value) { verbose = value; } public static boolean getVerbose() { return verbose; } public static void setWriter(PrintStream value) { out = value; } public static PrintStream getWriter() { return out; } public long getInvalidPid() { return 666666; } public void traceln(String msg) { if (getVerbose()) { getWriter().println(msg); } } public void trace(String msg) { if (getVerbose()) { getWriter().print(msg); } } public void assertTrueTrace(String msg, String value) { traceln(msg + "=" + value); assertTrue(msg, value != null); } public void assertLengthTrace(String msg, String value) { assertTrueTrace(msg, value); assertTrue(msg, value.length() > 0); } public void assertIndexOfTrace(String msg, String value, String substr) { assertTrueTrace(msg, value); assertTrue(msg, value.indexOf(substr) != -1); } public void assertGtZeroTrace(String msg, long value) { traceln(msg + "=" + value); assertTrue(msg, value > 0); } public void assertGtEqZeroTrace(String msg, long value) { traceln(msg + "=" + value); assertTrue(msg, value >= 0); } public void assertValidFieldTrace(String msg, long value) { if (value != Sigar.FIELD_NOTIMPL) { assertGtEqZeroTrace(msg, value); } } public void assertEqualsTrace(String msg, long expected, long actual) { traceln(msg + "=" + actual + "/" + expected); assertEquals(msg, expected, actual); } public void traceMethods(Object obj) throws Exception { Class cls = obj.getClass(); Method[] methods = cls.getDeclaredMethods(); traceln(""); for (int i=0; i printer.maxNameLen) { printer.maxNameLen = len; } suite.addTestSuite(test); } private static Class findTest(Class[] tests, String name) { String tname = "Test" + name; for (int i=0; i 0) { Properties props = new Properties(); for (int i=0; i= 0); traceln("Sys...." + cpu.getSys()); assertTrue(cpu.getSys() >= 0); traceln("Idle..." + cpu.getIdle()); assertTrue(cpu.getIdle() >= 0); traceln("Wait..." + cpu.getWait()); assertTrue(cpu.getWait() >= 0); traceln("Irq..." + cpu.getIrq()); assertTrue(cpu.getIrq() >= 0); traceln("SIrq.." + cpu.getSoftIrq()); assertTrue(cpu.getSoftIrq() >= 0); traceln("Stl..." + cpu.getStolen()); assertTrue(cpu.getStolen() >= 0); traceln("Total.." + cpu.getTotal()); assertTrue(cpu.getTotal() > 0); try { long current = getSigar().getProcState("$$").getProcessor(); traceln("last run cpu=" + current); } catch (SigarException e) { e.printStackTrace(); } } public void testCreate() throws Exception { Sigar sigar = getSigar(); Cpu cpu = sigar.getCpu(); traceln("getCpu:"); checkCpu(cpu); try { Cpu[] cpuList = sigar.getCpuList(); for (int i=0; i 0) { interval = Integer.parseInt(args[0]); } int sleep = 1000 * 60 * interval; Sigar sigar = new Sigar(); while (true) { System.out.println(HEADER); printCpu(" ", sigar.getCpuPerc()); CpuPerc[] cpuList = sigar.getCpuPercList(); for (int i=0; i 0; /* if (!validFQDN) { //wont get a valid fqdn on laptop at home //allow to fake with ant -Dsigar.fqdn=foo.bar String pfake = getProperty("sigar.fqdn"); String fake = System.getProperty("sigar.fqdn", pfake); if ("".equals(fake)) { fake = pfake; } if (fake != null) { traceln("fake='" + fake + "'"); validFQDN = fake.indexOf(".") > 0; } } */ assertTrue(validFQDN); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/test/TestFileInfo.java000066400000000000000000000117011210132627500302270ustar00rootroot00000000000000/* * Copyright (c) 2006 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.io.IOException; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.DirStat; import org.hyperic.sigar.FileInfo; public class TestFileInfo extends SigarTestCase { public TestFileInfo(String name) { super(name); } private void getFileInfo(Sigar sigar, String file) throws SigarException { traceln("Entry=" + file); FileInfo info = sigar.getFileInfo(file); assertGtEqZeroTrace("Permisions", info.getPermissions()); assertTrueTrace("Permissions", info.getPermissionsString()); assertGtEqZeroTrace("Mode", info.getMode()); assertTrueTrace("Type", info.getTypeString()); assertGtEqZeroTrace("Size", info.getSize()); assertGtEqZeroTrace("Uid", info.getUid()); assertGtEqZeroTrace("Gid", info.getUid()); assertGtEqZeroTrace("Inode", info.getInode()); traceln("Device=" + info.getDevice()); assertGtEqZeroTrace("Nlink", info.getNlink()); assertGtEqZeroTrace("Atime", info.getAtime()); traceln(new Date(info.getAtime()).toString()); assertGtZeroTrace("Mtime", info.getMtime()); traceln(new Date(info.getMtime()).toString()); assertGtZeroTrace("Ctime", info.getCtime()); traceln(new Date(info.getCtime()).toString()); if (info.getType() == FileInfo.TYPE_DIR) { try { DirStat stats = sigar.getDirStat(file); assertEqualsTrace("Total", new File(file).list().length, stats.getTotal()); assertGtEqZeroTrace("Files", stats.getFiles()); assertGtEqZeroTrace("Subdirs", stats.getSubdirs()); } catch (SigarNotImplementedException e) { //XXX win32 } } else { try { sigar.getDirStat(file); assertTrue(false); } catch (SigarException e) { assertTrue(true); } } sigar.getLinkInfo(file); } public void testCreate() throws Exception { Sigar sigar = getSigar(); String file; File dir = new File(System.getProperty("user.dir")); String[] entries = dir.list(); for (int i=0; i 0); for (int i=0; i Service.Name "Service.Name.eq=NOSUCHSERVICE", "Service.Name.ct=Oracle", "Service.DisplayName.re=DHCP|DNS", "Service.Path.ct=svchost", "Service.Exe.Ieq=inetinfo.exe", OTHER_JAVA_PROCESS, //all java procs cept this one "Cpu.Percent.ge=0.2", "State.Name.sw=java,Args.*.eq=org.jboss.Main", //jboss JAVA_PROCESS + ",Args.*.eq=com.ibm.ws.runtime.WsServer", //websphere JAVA_PROCESS + ",Args.-1.eq=weblogic.Server", //weblogic "State.Name.eq=perl,Args.*.eq=v", //testing w/ exp/fork.pl }; //XXX current required 1.4+ private static final String[] OK_RE_QUERIES = { "Args.-1.eq=weblogic.Server,Env.WEBLOGIC_CLASSPATH.re=.*weblogic.jar.*", //weblogic "State.Name.re=https?d.*|[Aa]pache2?$,State.Name.Pne=$1", //apache "State.Name.re=post(master|gres),State.Name.Pne=$1,Args.0.re=.*post(master|gres)$", //postgresql "State.Name.re=cfmx7|java,State.Name.Pne=$1,Args.*.ct=jrun.jar", //coldfusion }; private static final String[] MALFORMED_QUERIES = { "foo", "State.Name", "State.Name.eq", "State.Namex.eq=foo", "Statex.Name.eq=foo", "State.Name.eqx=foo", "State.Name.Xeq=foo", "State.Name.eq=foo,Args.*.eq=$3", "State.Name.eq=$1", "State.State.eq=read", "Args.x.eq=foo", "Time.Sys.gt=x", "Pid.Pid.eq=foo", "Cpu.Percent.ge=x", "Port.foo.eq=8080", "Port.tcp.gt=8080", "Port.tcp.eq=http", "Cpu.Sys.ew=lots", "Service.Invalid.ew=.exe", "", null, }; public TestPTQL(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); this.qf = new ProcessQueryFactory(); } protected void tearDown() throws Exception { super.tearDown(); this.qf.clear(); } private int runQuery(Sigar sigar, String qs) throws MalformedQueryException, SigarException { ProcessQuery query; try { query = this.qf.getQuery(qs); } catch (MalformedQueryException e) { traceln("parse error: " + qs); throw e; } try { long[] pids = query.find(sigar); traceln(pids.length + " processes match: " + qs); if (qs.indexOf(OTHER_PROCESS) != -1) { long pid = sigar.getPid(); for (int i=0; i= 0); } } public void testValidRegexQueries() throws Exception { for (int i=0; i= 0); } } public void testMalformedQueries() throws Exception { for (int i=0; i" + args[j] + "<=="); } } catch (SigarException e) { traceln(pidTrace + ": " + e.getMessage()); } } } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/test/TestProcEnv.java000066400000000000000000000043101210132627500301060ustar00rootroot00000000000000/* * Copyright (c) 2006, 2008 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.io.File; import java.util.Map; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarNotImplementedException; import org.hyperic.sigar.SigarPermissionDeniedException; public class TestProcEnv extends SigarTestCase { public TestProcEnv(String name) { super(name); } public void testCreate() throws Exception { Sigar sigar = getSigar(); try { sigar.getProcEnv(getInvalidPid()); } catch (SigarException e) { } long pid = sigar.getPid(); try { Map env = sigar.getProcEnv(pid); traceln(env.toString()); String key = "JAVA_HOME"; String val = (String)env.get(key); String single = sigar.getProcEnv(pid, key); if (val != null) { assertTrue(new File(val, "bin").exists()); assertTrue(val.equals(single)); traceln(key + "==>" + single); } key = "dOeSnOtExIsT"; val = (String)env.get(key); assertTrue(val == null); val = sigar.getProcEnv(pid, key); assertTrue(val == null); } catch (SigarNotImplementedException e) { //ok } catch (SigarPermissionDeniedException e) { //ok } long[] pids = sigar.getProcList(); for (int i=0; i 0) { assertTrue(new File(cwd).isDirectory()); } traceln("exe='" + exe.getName() + "'"); if (exe.getName().length() > 0) { assertTrue(exeFile.exists()); //win32 has .exe assertTrue(exeFile.getName().startsWith("java")); } } catch (SigarNotImplementedException e) { //ok } long[] pids = sigar.getProcList(); //go through all just to make sure no crashes for (int i=0; i 1); long pid = sigar.getPid(); boolean foundPid = false; //find our pid in the process list for (int i=0; i 1); traceln(stat.toString()); SigarProxy proxy = SigarProxyCache.newInstance(getSigar()); traceln(CurrentProcessSummary.get(proxy).toString()); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/test/TestProcState.java000066400000000000000000000033711210132627500304440ustar00rootroot00000000000000/* * Copyright (c) 2006 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 org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.ProcState; public class TestProcState extends SigarTestCase { public TestProcState(String name) { super(name); } private void traceState(Sigar sigar, long pid) { try { ProcState procState = sigar.getProcState(pid); traceln("[pid=" + pid + "] " + procState); } catch (SigarException e) { traceln("pid " + pid + ": " + e.getMessage()); } } public void testCreate() throws Exception { Sigar sigar = getSigar(); try { sigar.getProcState(getInvalidPid()); } catch (SigarException e) { } ProcState procState = sigar.getProcState(sigar.getPid()); traceState(sigar, sigar.getPid()); char state = procState.getState(); assertTrue((state == 'R') || (state == 'S')); assertTrue(procState.getName().indexOf("java") != -1); long[] pids = sigar.getProcList(); for (int i=0; i= size) { return false; } this.curr = (Iterator)this.iterators.get(this.ix); //recurse in the event that this.curr is empty return hasNext(); } public Object next() { return this.curr.next(); } public void remove() { throw new UnsupportedOperationException(); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/util/PrintfFormat.java000066400000000000000000002776751210132627500303350ustar00rootroot00000000000000// // (c) 2000 Sun Microsystems, Inc. // ALL RIGHTS RESERVED // // License Grant- // // // Permission to use, copy, modify, and distribute this Software and its // documentation for NON-COMMERCIAL or COMMERCIAL purposes and without fee is // hereby granted. // // This Software is provided "AS IS". All express warranties, including any // implied warranty of merchantability, satisfactory quality, fitness for a // particular purpose, or non-infringement, are disclaimed, except to the extent // that such disclaimers are held to be legally invalid. // // You acknowledge that Software is not designed, licensed or intended for use in // the design, construction, operation or maintenance of any nuclear facility // ("High Risk Activities"). Sun disclaims any express or implied warranty of // fitness for such uses. // // Please refer to the file http://www.sun.com/policies/trademarks/ for further // important trademark information and to // http://java.sun.com/nav/business/index.html for further important licensing // information for the Java Technology. // package org.hyperic.sigar.util; import java.util.Enumeration; import java.util.Vector; import java.util.Locale; import java.text.DecimalFormatSymbols; /** * PrintfFormat allows the formatting of an array of * objects embedded within a string. Primitive types * must be passed using wrapper types. The formatting * is controlled by a control string. *

* A control string is a Java string that contains a * control specification. The control specification * starts at the first percent sign (%) in the string, * provided that this percent sign *

    *
  1. is not escaped protected by a matching % or is * not an escape % character, *
  2. is not at the end of the format string, and *
  3. precedes a sequence of characters that parses as * a valid control specification. *
*

* A control specification usually takes the form: *

 % ['-+ #0]* [0..9]* { . [0..9]* }+
 *                { [hlL] }+ [idfgGoxXeEcs]
 *
* There are variants of this basic form that are * discussed below.

*

* The format is composed of zero or more directives * defined as follows: *

    *
  • ordinary characters, which are simply copied to * the output stream; *
  • escape sequences, which represent non-graphic * characters; and *
  • conversion specifications, each of which * results in the fetching of zero or more arguments. *

*

* The results are undefined if there are insufficient * arguments for the format. Usually an unchecked * exception will be thrown. If the format is * exhausted while arguments remain, the excess * arguments are evaluated but are otherwise ignored. * In format strings containing the % form of * conversion specifications, each argument in the * argument list is used exactly once.

*

* Conversions can be applied to the nth * argument after the format in the argument list, * rather than to the next unused argument. In this * case, the conversion characer % is replaced by the * sequence %n$, where n is * a decimal integer giving the position of the * argument in the argument list.

*

* In format strings containing the %n$ * form of conversion specifications, each argument * in the argument list is used exactly once.

* *

Escape Sequences

*

* The following table lists escape sequences and * associated actions on display devices capable of * the action. * * * * * * * * * * * * *
SequenceNameDescription
\\backlashNone. *
\aalertAttempts to alert * the user through audible or visible * notification. *
\bbackspaceMoves the * printing position to one column before * the current position, unless the * current position is the start of a line. *
\fform-feedMoves the * printing position to the initial * printing position of the next logical * page. *
\nnewlineMoves the * printing position to the start of the * next line. *
\rcarriage-returnMoves * the printing position to the start of * the current line. *
\ttabMoves the printing * position to the next implementation- * defined horizontal tab position. *
\vvertical-tabMoves the * printing position to the start of the * next implementation-defined vertical * tab position. *

*

Conversion Specifications

*

* Each conversion specification is introduced by * the percent sign character (%). After the character * %, the following appear in sequence:

*

* Zero or more flags (in any order), which modify the * meaning of the conversion specification.

*

* An optional minimum field width. If the converted * value has fewer characters than the field width, it * will be padded with spaces by default on the left; * t will be padded on the right, if the left- * adjustment flag (-), described below, is given to * the field width. The field width takes the form * of a decimal integer. If the conversion character * is s, the field width is the the minimum number of * characters to be printed.

*

* An optional precision that gives the minumum number * of digits to appear for the d, i, o, x or X * conversions (the field is padded with leading * zeros); the number of digits to appear after the * radix character for the e, E, and f conversions, * the maximum number of significant digits for the g * and G conversions; or the maximum number of * characters to be written from a string is s and S * conversions. The precision takes the form of an * optional decimal digit string, where a null digit * string is treated as 0. If a precision appears * with a c conversion character the precision is * ignored. *

*

* An optional h specifies that a following d, i, o, * x, or X conversion character applies to a type * short argument (the argument will be promoted * according to the integral promotions and its value * converted to type short before printing).

*

* An optional l (ell) specifies that a following * d, i, o, x, or X conversion character applies to a * type long argument.

*

* A field width or precision may be indicated by an * asterisk (*) instead of a digit string. In this * case, an integer argument supplised the field width * precision. The argument that is actually converted * is not fetched until the conversion letter is seen, * so the the arguments specifying field width or * precision must appear before the argument (if any) * to be converted. If the precision argument is * negative, it will be changed to zero. A negative * field width argument is taken as a - flag, followed * by a positive field width.

*

* In format strings containing the %n$ * form of a conversion specification, a field width * or precision may be indicated by the sequence * *m$, where m is a decimal integer * giving the position in the argument list (after the * format argument) of an integer argument containing * the field width or precision.

*

* The format can contain either numbered argument * specifications (that is, %n$ and * *m$), or unnumbered argument * specifications (that is % and *), but normally not * both. The only exception to this is that %% can * be mixed with the %n$ form. The * results of mixing numbered and unnumbered argument * specifications in a format string are undefined.

* *

Flag Characters

*

* The flags and their meanings are:

*
*
'
integer portion of the result of a * decimal conversion (%i, %d, %f, %g, or %G) will * be formatted with thousands' grouping * characters. For other conversions the flag * is ignored. The non-monetary grouping * character is used. *
-
result of the conversion is left-justified * within the field. (It will be right-justified * if this flag is not specified). *
+
result of a signed conversion always * begins with a sign (+ or -). (It will begin * with a sign only when a negative value is * converted if this flag is not specified.) *
<space>
If the first character of a * signed conversion is not a sign, a space * character will be placed before the result. * This means that if the space character and + * flags both appear, the space flag will be * ignored. *
#
value is to be converted to an alternative * form. For c, d, i, and s conversions, the flag * has no effect. For o conversion, it increases * the precision to force the first digit of the * result to be a zero. For x or X conversion, a * non-zero result has 0x or 0X prefixed to it, * respectively. For e, E, f, g, and G * conversions, the result always contains a radix * character, even if no digits follow the radix * character (normally, a decimal point appears in * the result of these conversions only if a digit * follows it). For g and G conversions, trailing * zeros will not be removed from the result as * they normally are. *
0
d, i, o, x, X, e, E, f, g, and G * conversions, leading zeros (following any * indication of sign or base) are used to pad to * the field width; no space padding is * performed. If the 0 and - flags both appear, * the 0 flag is ignored. For d, i, o, x, and X * conversions, if a precision is specified, the * 0 flag will be ignored. For c conversions, * the flag is ignored. *
* *

Conversion Characters

*

* Each conversion character results in fetching zero * or more arguments. The results are undefined if * there are insufficient arguments for the format. * Usually, an unchecked exception will be thrown. * If the format is exhausted while arguments remain, * the excess arguments are ignored.

* *

* The conversion characters and their meanings are: *

*
*
d,i
The int argument is converted to a * signed decimal in the style [-]dddd. The * precision specifies the minimum number of * digits to appear; if the value being * converted can be represented in fewer * digits, it will be expanded with leading * zeros. The default precision is 1. The * result of converting 0 with an explicit * precision of 0 is no characters. *
o
The int argument is converted to unsigned * octal format in the style ddddd. The * precision specifies the minimum number of * digits to appear; if the value being * converted can be represented in fewer * digits, it will be expanded with leading * zeros. The default precision is 1. The * result of converting 0 with an explicit * precision of 0 is no characters. *
x
The int argument is converted to unsigned * hexadecimal format in the style dddd; the * letters abcdef are used. The precision * specifies the minimum numberof digits to * appear; if the value being converted can be * represented in fewer digits, it will be * expanded with leading zeros. The default * precision is 1. The result of converting 0 * with an explicit precision of 0 is no * characters. *
X
Behaves the same as the x conversion * character except that letters ABCDEF are * used instead of abcdef. *
f
The floating point number argument is * written in decimal notation in the style * [-]ddd.ddd, where the number of digits after * the radix character (shown here as a decimal * point) is equal to the precision * specification. A Locale is used to determine * the radix character to use in this format. * If the precision is omitted from the * argument, six digits are written after the * radix character; if the precision is * explicitly 0 and the # flag is not specified, * no radix character appears. If a radix * character appears, at least 1 digit appears * before it. The value is rounded to the * appropriate number of digits. *
e,E
The floating point number argument is * written in the style [-]d.ddde{+-}dd * (the symbols {+-} indicate either a plus or * minus sign), where there is one digit before * the radix character (shown here as a decimal * point) and the number of digits after it is * equal to the precision. A Locale is used to * determine the radix character to use in this * format. When the precision is missing, six * digits are written after the radix character; * if the precision is 0 and the # flag is not * specified, no radix character appears. The * E conversion will produce a number with E * instead of e introducing the exponent. The * exponent always contains at least two digits. * However, if the value to be written requires * an exponent greater than two digits, * additional exponent digits are written as * necessary. The value is rounded to the * appropriate number of digits. *
g,G
The floating point number argument is * written in style f or e (or in sytle E in the * case of a G conversion character), with the * precision specifying the number of * significant digits. If the precision is * zero, it is taken as one. The style used * depends on the value converted: style e * (or E) will be used only if the exponent * resulting from the conversion is less than * -4 or greater than or equal to the precision. * Trailing zeros are removed from the result. * A radix character appears only if it is * followed by a digit. *
c,C
The integer argument is converted to a * char and the result is written. * *
s,S
The argument is taken to be a string and * bytes from the string are written until the * end of the string or the number of bytes * indicated by the precision specification of * the argument is reached. If the precision * is omitted from the argument, it is taken to * be infinite, so all characters up to the end * of the string are written. *
%
Write a % character; no argument is * converted. *
*

* If a conversion specification does not match one of * the above forms, an IllegalArgumentException is * thrown and the instance of PrintfFormat is not * created.

*

* If a floating point value is the internal * representation for infinity, the output is * [+]Infinity, where Infinity is either Infinity or * Inf, depending on the desired output string length. * Printing of the sign follows the rules described * above.

*

* If a floating point value is the internal * representation for "not-a-number," the output is * [+]NaN. Printing of the sign follows the rules * described above.

*

* In no case does a non-existent or small field width * cause truncation of a field; if the result of a * conversion is wider than the field width, the field * is simply expanded to contain the conversion result. *

*

* The behavior is like printf. One exception is that * the minimum number of exponent digits is 3 instead * of 2 for e and E formats when the optional L is used * before the e, E, g, or G conversion character. The * optional L does not imply conversion to a long long * double.

*

* The biggest divergence from the C printf * specification is in the use of 16 bit characters. * This allows the handling of characters beyond the * small ASCII character set and allows the utility to * interoperate correctly with the rest of the Java * runtime environment.

*

* Omissions from the C printf specification are * numerous. All the known omissions are present * because Java never uses bytes to represent * characters and does not have pointers:

*
    *
  • %c is the same as %C. *
  • %s is the same as %S. *
  • u, p, and n conversion characters. *
  • %ws format. *
  • h modifier applied to an n conversion character. *
  • l (ell) modifier applied to the c, n, or s * conversion characters. *
  • ll (ell ell) modifier to d, i, o, u, x, or X * conversion characters. *
  • ll (ell ell) modifier to an n conversion * character. *
  • c, C, d,i,o,u,x, and X conversion characters * apply to Byte, Character, Short, Integer, Long * types. *
  • f, e, E, g, and G conversion characters apply * to Float and Double types. *
  • s and S conversion characters apply to String * types. *
  • All other reference types can be formatted * using the s or S conversion characters only. *
*

* Most of this specification is quoted from the Unix * man page for the sprintf utility.

* (c) 2000 Sun Microsystems, Inc. * @author Allan Jacobs * @version 1 * Release 1: Initial release. * Release 2: Asterisk field widths and precisions * %n$ and *m$ * Bug fixes * g format fix (2 digits in e form corrupt) * rounding in f format implemented * round up when digit not printed is 5 * formatting of -0.0f * round up/down when last digits are 50000... */ public class PrintfFormat { /** * Constructs an array of control specifications * possibly preceded, separated, or followed by * ordinary strings. Control strings begin with * unpaired percent signs. A pair of successive * percent signs designates a single percent sign in * the format. * @param fmtArg Control string. * @exception IllegalArgumentException if the control * string is null, zero length, or otherwise * malformed. */ public PrintfFormat(String fmtArg) throws IllegalArgumentException { this(Locale.getDefault(),fmtArg); } /** * Constructs an array of control specifications * possibly preceded, separated, or followed by * ordinary strings. Control strings begin with * unpaired percent signs. A pair of successive * percent signs designates a single percent sign in * the format. * @param fmtArg Control string. * @exception IllegalArgumentException if the control * string is null, zero length, or otherwise * malformed. */ public PrintfFormat(Locale locale,String fmtArg) throws IllegalArgumentException { dfs = new DecimalFormatSymbols(locale); int ePos=0; ConversionSpecification sFmt=null; String unCS = this.nonControl(fmtArg,0); if (unCS!=null) { sFmt = new ConversionSpecification(); sFmt.setLiteral(unCS); vFmt.addElement(sFmt); } while(cPos!=-1 && cPosstart and ending at either the end * of the String s, the next unpaired * percent sign, or at the end of the String if the * last character is a percent sign. * @param s Control string. * @param start Position in the string * s to begin looking for the start * of a control string. * @return the substring from the start position * to the beginning of the control string. */ private String nonControl(String s,int start) { cPos=s.indexOf("%",start); if (cPos==-1) cPos=s.length(); return s.substring(start,cPos); } /** * Format an array of objects. Byte, Short, * Integer, Long, Float, Double, and Character * arguments are treated as wrappers for primitive * types. * @param o The array of objects to format. * @return The formatted String. */ public String sprintf(Object[] o) { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; int i=0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); else { if (cs.isPositionalSpecification()) { i=cs.getArgumentPosition()-1; if (cs.isPositionalFieldWidth()) { int ifw=cs.getArgumentPositionForFieldWidth()-1; cs.setFieldWidthWithArg(((Integer)o[ifw]).intValue()); } if (cs.isPositionalPrecision()) { int ipr=cs.getArgumentPositionForPrecision()-1; cs.setPrecisionWithArg(((Integer)o[ipr]).intValue()); } } else { if (cs.isVariableFieldWidth()) { cs.setFieldWidthWithArg(((Integer)o[i]).intValue()); i++; } if (cs.isVariablePrecision()) { cs.setPrecisionWithArg(((Integer)o[i]).intValue()); i++; } } if (o[i] instanceof Byte) sb.append(cs.internalsprintf( ((Byte)o[i]).byteValue())); else if (o[i] instanceof Short) sb.append(cs.internalsprintf( ((Short)o[i]).shortValue())); else if (o[i] instanceof Integer) sb.append(cs.internalsprintf( ((Integer)o[i]).intValue())); else if (o[i] instanceof Long) sb.append(cs.internalsprintf( ((Long)o[i]).longValue())); else if (o[i] instanceof Float) sb.append(cs.internalsprintf( ((Float)o[i]).floatValue())); else if (o[i] instanceof Double) sb.append(cs.internalsprintf( ((Double)o[i]).doubleValue())); else if (o[i] instanceof Character) sb.append(cs.internalsprintf( ((Character)o[i]).charValue())); else if (o[i] instanceof String) sb.append(cs.internalsprintf( (String)o[i])); else sb.append(cs.internalsprintf( o[i])); if (!cs.isPositionalSpecification()) i++; } } return sb.toString(); } /** * Format nothing. Just use the control string. * @return the formatted String. */ public String sprintf() { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); } return sb.toString(); } /** * Format an int. * @param x The int to format. * @return The formatted String. * @exception IllegalArgumentException if the * conversion character is f, e, E, g, G, s, * or S. */ public String sprintf(int x) throws IllegalArgumentException { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); else sb.append(cs.internalsprintf(x)); } return sb.toString(); } /** * Format an long. * @param x The long to format. * @return The formatted String. * @exception IllegalArgumentException if the * conversion character is f, e, E, g, G, s, * or S. */ public String sprintf(long x) throws IllegalArgumentException { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); else sb.append(cs.internalsprintf(x)); } return sb.toString(); } /** * Format a double. * @param x The double to format. * @return The formatted String. * @exception IllegalArgumentException if the * conversion character is c, C, s, S, * d, d, x, X, or o. */ public String sprintf(double x) throws IllegalArgumentException { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); else sb.append(cs.internalsprintf(x)); } return sb.toString(); } /** * Format a String. * @param x The String to format. * @return The formatted String. * @exception IllegalArgumentException if the * conversion character is neither s nor S. */ public String sprintf(String x) throws IllegalArgumentException { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); else sb.append(cs.internalsprintf(x)); } return sb.toString(); } /** * Format an Object. Convert wrapper types to * their primitive equivalents and call the * appropriate internal formatting method. Convert * Strings using an internal formatting method for * Strings. Otherwise use the default formatter * (use toString). * @param x the Object to format. * @return the formatted String. * @exception IllegalArgumentException if the * conversion character is inappropriate for * formatting an unwrapped value. */ public String sprintf(Object x) throws IllegalArgumentException { Enumeration e = vFmt.elements(); ConversionSpecification cs = null; char c = 0; StringBuffer sb=new StringBuffer(); while (e.hasMoreElements()) { cs = (ConversionSpecification) e.nextElement(); c = cs.getConversionCharacter(); if (c=='\0') sb.append(cs.getLiteral()); else if (c=='%') sb.append("%"); else { if (x instanceof Byte) sb.append(cs.internalsprintf( ((Byte)x).byteValue())); else if (x instanceof Short) sb.append(cs.internalsprintf( ((Short)x).shortValue())); else if (x instanceof Integer) sb.append(cs.internalsprintf( ((Integer)x).intValue())); else if (x instanceof Long) sb.append(cs.internalsprintf( ((Long)x).longValue())); else if (x instanceof Float) sb.append(cs.internalsprintf( ((Float)x).floatValue())); else if (x instanceof Double) sb.append(cs.internalsprintf( ((Double)x).doubleValue())); else if (x instanceof Character) sb.append(cs.internalsprintf( ((Character)x).charValue())); else if (x instanceof String) sb.append(cs.internalsprintf( (String)x)); else sb.append(cs.internalsprintf(x)); } } return sb.toString(); } /** *

* ConversionSpecification allows the formatting of * a single primitive or object embedded within a * string. The formatting is controlled by a * format string. Only one Java primitive or * object can be formatted at a time. *

* A format string is a Java string that contains * a control string. The control string starts at * the first percent sign (%) in the string, * provided that this percent sign *

    *
  1. is not escaped protected by a matching % or * is not an escape % character, *
  2. is not at the end of the format string, and *
  3. precedes a sequence of characters that parses * as a valid control string. *
*

* A control string takes the form: *

 % ['-+ #0]* [0..9]* { . [0..9]* }+
   *                { [hlL] }+ [idfgGoxXeEcs]
   *
*

* The behavior is like printf. One (hopefully the * only) exception is that the minimum number of * exponent digits is 3 instead of 2 for e and E * formats when the optional L is used before the * e, E, g, or G conversion character. The * optional L does not imply conversion to a long * long double. */ private class ConversionSpecification { /** * Constructor. Used to prepare an instance * to hold a literal, not a control string. */ ConversionSpecification() { } /** * Constructor for a conversion specification. * The argument must begin with a % and end * with the conversion character for the * conversion specification. * @param fmtArg String specifying the * conversion specification. * @exception IllegalArgumentException if the * input string is null, zero length, or * otherwise malformed. */ ConversionSpecification(String fmtArg) throws IllegalArgumentException { if (fmtArg==null) throw new NullPointerException(); if (fmtArg.length()==0) throw new IllegalArgumentException( "Control strings must have positive"+ " lengths."); if (fmtArg.charAt(0)=='%') { fmt = fmtArg; pos=1; setArgPosition(); setFlagCharacters(); setFieldWidth(); setPrecision(); setOptionalHL(); if (setConversionCharacter()) { if (pos==fmtArg.length()) { if(leadingZeros&&leftJustify) leadingZeros=false; if(precisionSet&&leadingZeros){ if(conversionCharacter=='d' ||conversionCharacter=='i' ||conversionCharacter=='o' ||conversionCharacter=='x') { leadingZeros=false; } } } else throw new IllegalArgumentException( "Malformed conversion specification="+ fmtArg); } else throw new IllegalArgumentException( "Malformed conversion specification="+ fmtArg); } else throw new IllegalArgumentException( "Control strings must begin with %."); } /** * Set the String for this instance. * @param s the String to store. */ void setLiteral(String s) { fmt = s; } /** * Get the String for this instance. Translate * any escape sequences. * * @return s the stored String. */ String getLiteral() { StringBuffer sb=new StringBuffer(); int i=0; while (itrue if the conversion * uses an * field width; otherwise * false. */ boolean isVariableFieldWidth() { return variableFieldWidth; } /** * Set the field width with an argument. A * negative field width is taken as a - flag * followed by a positive field width. * @param fw the field width. */ void setFieldWidthWithArg(int fw) { if (fw<0) leftJustify = true; fieldWidthSet = true; fieldWidth = Math.abs(fw); } /** * Check whether the specifier has a variable * precision that is going to be set by an * argument. * @return true if the conversion * uses an * precision; otherwise * false. */ boolean isVariablePrecision() { return variablePrecision; } /** * Set the precision with an argument. A * negative precision will be changed to zero. * @param pr the precision. */ void setPrecisionWithArg(int pr) { precisionSet = true; precision = Math.max(pr,0); } /** * Format an int argument using this conversion * specification. * @param s the int to format. * @return the formatted String. * @exception IllegalArgumentException if the * conversion character is f, e, E, g, or G. */ String internalsprintf(int s) throws IllegalArgumentException { String s2 = ""; switch(conversionCharacter) { case 'd': case 'i': if (optionalh) s2 = printDFormat((short)s); else if (optionall) s2 = printDFormat((long)s); else s2 = printDFormat(s); break; case 'x': case 'X': if (optionalh) s2 = printXFormat((short)s); else if (optionall) s2 = printXFormat((long)s); else s2 = printXFormat(s); break; case 'o': if (optionalh) s2 = printOFormat((short)s); else if (optionall) s2 = printOFormat((long)s); else s2 = printOFormat(s); break; case 'c': case 'C': s2 = printCFormat((char)s); break; default: throw new IllegalArgumentException( "Cannot format a int with a format using a "+ conversionCharacter+ " conversion character."); } return s2; } /** * Format a long argument using this conversion * specification. * @param s the long to format. * @return the formatted String. * @exception IllegalArgumentException if the * conversion character is f, e, E, g, or G. */ String internalsprintf(long s) throws IllegalArgumentException { String s2 = ""; switch(conversionCharacter) { case 'd': case 'i': if (optionalh) s2 = printDFormat((short)s); else if (optionall) s2 = printDFormat(s); else s2 = printDFormat((int)s); break; case 'x': case 'X': if (optionalh) s2 = printXFormat((short)s); else if (optionall) s2 = printXFormat(s); else s2 = printXFormat((int)s); break; case 'o': if (optionalh) s2 = printOFormat((short)s); else if (optionall) s2 = printOFormat(s); else s2 = printOFormat((int)s); break; case 'c': case 'C': s2 = printCFormat((char)s); break; default: throw new IllegalArgumentException( "Cannot format a long with a format using a "+ conversionCharacter+" conversion character."); } return s2; } /** * Format a double argument using this conversion * specification. * @param s the double to format. * @return the formatted String. * @exception IllegalArgumentException if the * conversion character is c, C, s, S, i, d, * x, X, or o. */ String internalsprintf(double s) throws IllegalArgumentException { String s2 = ""; switch(conversionCharacter) { case 'f': s2 = printFFormat(s); break; case 'E': case 'e': s2 = printEFormat(s); break; case 'G': case 'g': s2 = printGFormat(s); break; default: throw new IllegalArgumentException("Cannot "+ "format a double with a format using a "+ conversionCharacter+" conversion character."); } return s2; } /** * Format a String argument using this conversion * specification. * @param s the String to format. * @return the formatted String. * @exception IllegalArgumentException if the * conversion character is neither s nor S. */ String internalsprintf(String s) throws IllegalArgumentException { String s2 = ""; if(conversionCharacter=='s' || conversionCharacter=='S') s2 = printSFormat(s); else throw new IllegalArgumentException("Cannot "+ "format a String with a format using a "+ conversionCharacter+" conversion character."); return s2; } /** * Format an Object argument using this conversion * specification. * @param s the Object to format. * @return the formatted String. * @exception IllegalArgumentException if the * conversion character is neither s nor S. */ String internalsprintf(Object s) { if (s == null) { return ""; } String s2 = ""; if(conversionCharacter=='s' || conversionCharacter=='S') s2 = printSFormat(s.toString()); else throw new IllegalArgumentException( "Cannot format a String with a format using"+ " a "+conversionCharacter+ " conversion character."); return s2; } /** * For f format, the flag character '-', means that * the output should be left justified within the * field. The default is to pad with blanks on the * left. '+' character means that the conversion * will always begin with a sign (+ or -). The * blank flag character means that a non-negative * input will be preceded with a blank. If both * a '+' and a ' ' are specified, the blank flag * is ignored. The '0' flag character implies that * padding to the field width will be done with * zeros instead of blanks. * * The field width is treated as the minimum number * of characters to be printed. The default is to * add no padding. Padding is with blanks by * default. * * The precision, if set, is the number of digits * to appear after the radix character. Padding is * with trailing 0s. */ private char[] fFormatDigits(double x) { // int defaultDigits=6; String sx; int i,j,k; int n1In,n2In; int expon=0; boolean minusSign=false; if (x>0.0) sx = Double.toString(x); else if (x<0.0) { sx = Double.toString(-x); minusSign=true; } else { sx = Double.toString(x); if (sx.charAt(0)=='-') { minusSign=true; sx=sx.substring(1); } } int ePos = sx.indexOf('E'); int rPos = sx.indexOf('.'); if (rPos!=-1) n1In=rPos; else if (ePos!=-1) n1In=ePos; else n1In=sx.length(); if (rPos!=-1) { if (ePos!=-1) n2In = ePos-rPos-1; else n2In = sx.length()-rPos-1; } else n2In = 0; if (ePos!=-1) { int ie=ePos+1; expon=0; if (sx.charAt(ie)=='-') { for (++ie; ie0) { ca6 = new char[ca5.length+nThousands+lead]; ca6[0]=ca5[0]; for (i=lead,k=lead; i0 && (dp-i)%3==0) { // ca6[k]=','; ca6[k]=dfs.getGroupingSeparator(); ca6[k+1]=ca5[i]; k+=2; } else { ca6[k]=ca5[i]; k++; } } for (; i0.0) sx = Double.toString(x); else if (x<0.0) { sx = Double.toString(-x); minusSign=true; } else { sx = Double.toString(x); if (sx.charAt(0)=='-') { minusSign=true; sx=sx.substring(1); } } ePos = sx.indexOf('E'); if (ePos==-1) ePos = sx.indexOf('e'); rPos = sx.indexOf('.'); if (rPos!=-1) n1In=rPos; else if (ePos!=-1) n1In=ePos; else n1In=sx.length(); if (rPos!=-1) { if (ePos!=-1) n2In = ePos-rPos-1; else n2In = sx.length()-rPos-1; } else n2In = 0; if (ePos!=-1) { int ie=ePos+1; expon=0; if (sx.charAt(ie)=='-') { for (++ie; ie=100) { switch(expon/100) { case 1: ca2[i]='1'; break; case 2: ca2[i]='2'; break; case 3: ca2[i]='3'; break; case 4: ca2[i]='4'; break; case 5: ca2[i]='5'; break; case 6: ca2[i]='6'; break; case 7: ca2[i]='7'; break; case 8: ca2[i]='8'; break; case 9: ca2[i]='9'; break; } i++; } switch((expon%100)/10) { case 0: ca2[i]='0'; break; case 1: ca2[i]='1'; break; case 2: ca2[i]='2'; break; case 3: ca2[i]='3'; break; case 4: ca2[i]='4'; break; case 5: ca2[i]='5'; break; case 6: ca2[i]='6'; break; case 7: ca2[i]='7'; break; case 8: ca2[i]='8'; break; case 9: ca2[i]='9'; break; } i++; switch(expon%10) { case 0: ca2[i]='0'; break; case 1: ca2[i]='1'; break; case 2: ca2[i]='2'; break; case 3: ca2[i]='3'; break; case 4: ca2[i]='4'; break; case 5: ca2[i]='5'; break; case 6: ca2[i]='6'; break; case 7: ca2[i]='7'; break; case 8: ca2[i]='8'; break; case 9: ca2[i]='9'; break; } int nZeros=0; if (!leftJustify && leadingZeros) { int xThousands=0; if (thousands) { int xlead=0; if (ca2[0]=='+'||ca2[0]=='-'||ca2[0]==' ') xlead=1; int xdp=xlead; for (; xdp0) { ca4 = new char[ca3.length+nThousands+lead]; ca4[0]=ca3[0]; for (i=lead,k=lead; i0 && (dp-i)%3==0) { // ca4[k]=','; ca4[k]=dfs.getGroupingSeparator(); ca4[k+1]=ca3[i]; k+=2; } else { ca4[k]=ca3[i]; k++; } } for (; itrue if the truncation forces * a round that will change the print */ private boolean checkForCarry(char[] ca1,int icarry) { boolean carry=false; if (icarry0) { carry=(ca1[icarry-1]=='1'||ca1[icarry-1]=='3' ||ca1[icarry-1]=='5'||ca1[icarry-1]=='7' ||ca1[icarry-1]=='9'); } } } return carry; } /** * Start the symbolic carry process. The process * is not quite finished because the symbolic * carry may change the length of the string and * change the exponent (in e format). * @param cLast index of the last digit changed * by the round * @param cFirst index of the first digit allowed * to be changed by this phase of the round * @return true if the carry forces * a round that will change the print still * more */ private boolean startSymbolicCarry( char[] ca,int cLast,int cFirst) { boolean carry=true; for (int i=cLast; carry && i>=cFirst; i--) { carry = false; switch(ca[i]) { case '0': ca[i]='1'; break; case '1': ca[i]='2'; break; case '2': ca[i]='3'; break; case '3': ca[i]='4'; break; case '4': ca[i]='5'; break; case '5': ca[i]='6'; break; case '6': ca[i]='7'; break; case '7': ca[i]='8'; break; case '8': ca[i]='9'; break; case '9': ca[i]='0'; carry=true; break; } } return carry; } /** * An intermediate routine on the way to creating * an e format String. The method decides whether * the input double value is an infinity, * not-a-number, or a finite double and formats * each type of input appropriately. * @param x the double value to be formatted. * @param eChar an 'e' or 'E' to use in the * converted double value. * @return the converted double value. */ private String eFormatString(double x,char eChar) { boolean noDigits=false; char[] ca4,ca5; if (Double.isInfinite(x)) { if (x==Double.POSITIVE_INFINITY) { if (leadingSign) ca4 = "+Inf".toCharArray(); else if (leadingSpace) ca4 = " Inf".toCharArray(); else ca4 = "Inf".toCharArray(); } else ca4 = "-Inf".toCharArray(); noDigits = true; } else if (Double.isNaN(x)) { if (leadingSign) ca4 = "+NaN".toCharArray(); else if (leadingSpace) ca4 = " NaN".toCharArray(); else ca4 = "NaN".toCharArray(); noDigits = true; } else ca4 = eFormatDigits(x,eChar); ca5 = applyFloatPadding(ca4,false); return new String(ca5); } /** * Apply zero or blank, left or right padding. * @param ca4 array of characters before padding is * finished * @param noDigits NaN or signed Inf * @return a padded array of characters */ private char[] applyFloatPadding( char[] ca4,boolean noDigits) { char[] ca5 = ca4; if (fieldWidthSet) { int i,j,nBlanks; if (leftJustify) { nBlanks = fieldWidth-ca4.length; if (nBlanks > 0) { ca5 = new char[ca4.length+nBlanks]; for (i=0; i 0) { ca5 = new char[ca4.length+nBlanks]; for (i=0; i 0) { ca5 = new char[ca4.length+nBlanks]; i=0; j=0; if (ca4[0]=='-') { ca5[0]='-'; i++; j++; } for (int k=0; k=-4 && expon=0; i--) if (sy.charAt(i)!='0') break; if (i>=0 && sy.charAt(i)=='.') i--; if (i==-1) sz="0"; else if (!Character.isDigit(sy.charAt(i))) sz=sy.substring(0,i+1)+"0"; else sz=sy.substring(0,i+1); if (expon>=-4 && expon=-4 && expon=0) ret = " "+ret; ca4 = ret.toCharArray(); } // Pad with blanks or zeros. ca5 = applyFloatPadding(ca4,false); precision=savePrecision; return new String(ca5); } /** * Format method for the d conversion specifer and * short argument. * * For d format, the flag character '-', means that * the output should be left justified within the * field. The default is to pad with blanks on the * left. A '+' character means that the conversion * will always begin with a sign (+ or -). The * blank flag character means that a non-negative * input will be preceded with a blank. If both a * '+' and a ' ' are specified, the blank flag is * ignored. The '0' flag character implies that * padding to the field width will be done with * zeros instead of blanks. * * The field width is treated as the minimum number * of characters to be printed. The default is to * add no padding. Padding is with blanks by * default. * * The precision, if set, is the minimum number of * digits to appear. Padding is with leading 0s. * @param x the short to format. * @return the formatted String. */ private String printDFormat(short x) { return printDFormat(Short.toString(x)); } /** * Format method for the d conversion character and * long argument. * * For d format, the flag character '-', means that * the output should be left justified within the * field. The default is to pad with blanks on the * left. A '+' character means that the conversion * will always begin with a sign (+ or -). The * blank flag character means that a non-negative * input will be preceded with a blank. If both a * '+' and a ' ' are specified, the blank flag is * ignored. The '0' flag character implies that * padding to the field width will be done with * zeros instead of blanks. * * The field width is treated as the minimum number * of characters to be printed. The default is to * add no padding. Padding is with blanks by * default. * * The precision, if set, is the minimum number of * digits to appear. Padding is with leading 0s. * @param x the long to format. * @return the formatted String. */ private String printDFormat(long x) { return printDFormat(Long.toString(x)); } /** * Format method for the d conversion character and * int argument. * * For d format, the flag character '-', means that * the output should be left justified within the * field. The default is to pad with blanks on the * left. A '+' character means that the conversion * will always begin with a sign (+ or -). The * blank flag character means that a non-negative * input will be preceded with a blank. If both a * '+' and a ' ' are specified, the blank flag is * ignored. The '0' flag character implies that * padding to the field width will be done with * zeros instead of blanks. * * The field width is treated as the minimum number * of characters to be printed. The default is to * add no padding. Padding is with blanks by * default. * * The precision, if set, is the minimum number of * digits to appear. Padding is with leading 0s. * @param x the int to format. * @return the formatted String. */ private String printDFormat(int x) { return printDFormat(Integer.toString(x)); } /** * Utility method for formatting using the d * conversion character. * @param sx the String to format, the result of * converting a short, int, or long to a * String. * @return the formatted String. */ private String printDFormat(String sx) { int nLeadingZeros=0; int nBlanks=0,n=0; int i=0,jFirst=0; boolean neg = sx.charAt(0)=='-'; if (sx.equals("0")&&precisionSet&&precision==0) sx=""; if (!neg) { if (precisionSet && sx.length() < precision) nLeadingZeros = precision-sx.length(); } else { if (precisionSet&&(sx.length()-1)precision) nPrint=precision; if (!fieldWidthSet) width = nPrint; int n=0; if (width>nPrint) n+=width-nPrint; if (nPrint>=x.length()) n+= x.length(); else n+= nPrint; char[] ca = new char[n]; int i=0; if (leftJustify) { if (nPrint>=x.length()) { char[] csx = x.toCharArray(); for (i=0; i=x.length()) { char[] csx = x.toCharArray(); for (int j=0; jtrue if the conversion * character is there, and * false otherwise. */ private boolean setConversionCharacter() { /* idfgGoxXeEcs */ boolean ret = false; conversionCharacter='\0'; if (pos < fmt.length()) { char c = fmt.charAt(pos); if (c=='i'||c=='d'||c=='f'||c=='g'||c=='G' || c=='o' || c=='x' || c=='X' || c=='e' || c=='E' || c=='c' || c=='s' || c=='%') { conversionCharacter = c; pos++; ret = true; } } return ret; } /** * Check for an h, l, or L in a format. An L is * used to control the minimum number of digits * in an exponent when using floating point * formats. An l or h is used to control * conversion of the input to a long or short, * respectively, before formatting. If any of * these is present, store them. */ private void setOptionalHL() { optionalh=false; optionall=false; optionalL=false; if (pos < fmt.length()) { char c = fmt.charAt(pos); if (c=='h') { optionalh=true; pos++; } else if (c=='l') { optionall=true; pos++; } else if (c=='L') { optionalL=true; pos++; } } } /** * Set the precision. */ private void setPrecision() { int firstPos = pos; precisionSet = false; if (pos firstPos+1) { String sz = fmt.substring(firstPos+1,pos); precision = Integer.parseInt(sz); precisionSet = true; } } } } /** * Set the field width. */ private void setFieldWidth() { int firstPos = pos; fieldWidth = 0; fieldWidthSet = false; if ((pos < fmt.length()) && (fmt.charAt(pos)=='*')) { pos++; if (!setFieldWidthArgPosition()) { variableFieldWidth = true; fieldWidthSet = true; } } else { while (pos < fmt.length()) { char c = fmt.charAt(pos); if (Character.isDigit(c)) pos++; else break; } if (firstPosn in %n$ forms. */ private void setArgPosition() { int xPos; for (xPos=pos; xPospos && xPosn in *n$ forms. */ private boolean setFieldWidthArgPosition() { boolean ret=false; int xPos; for (xPos=pos; xPospos && xPosn in *n$ forms. */ private boolean setPrecisionArgPosition() { boolean ret=false; int xPos; for (xPos=pos; xPospos && xPos curEvent) { handleEvents(log, curEvent, lastEvent); } curEvent = lastEvent; try { Thread.sleep(this.interval); } catch (InterruptedException e) { } } } catch (Win32Exception e) { logger.error("Unable to monitor event log: ", e); } finally { try { log.close(); } catch (Win32Exception e) {} } } public void die() { this.shouldDie = true; } public static void main(String[] args) { if (args.length == 0) { args = new String[] { EventLog.SYSTEM, EventLog.APPLICATION, EventLog.SECURITY }; } EventLogNotification watcher = new EventLogNotification() { public boolean matches(EventLogRecord record) { return true; } public void handleNotification(EventLogRecord record) { System.out.println(record); } }; for (int i=0; i> 10; } public int getSubLangId() { return getSubLangId(this.id); } public static boolean isEnglish() { int id = getSystemDefaultLCID(); return getPrimaryLangId(id) == LANG_ENGLISH; } public String getPerflibLangId() { String id = Integer.toHexString(getPrimaryLangId()).toUpperCase(); //length always == 3 int pad = 3 - id.length(); StringBuffer fid = new StringBuffer(3); while (pad-- > 0) { fid.append("0"); } fid.append(id); return fid.toString(); } public String getAttribute(int attr) { return getAttribute(this.id, attr); } public String getEnglishLanguageName() { return getAttribute(LOCALE_SENGLANGUAGE); } public String getEnglishCountryName() { return getAttribute(LOCALE_SENGCOUNTRY); } public String toString() { return getId() + ":" + getEnglishLanguageName() + " (" + getEnglishCountryName() + ")"; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/win32/MetaBase.java000066400000000000000000000150421210132627500273420ustar00rootroot00000000000000/* * Copyright (c) 2006 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.win32; import java.util.Collection; import java.util.Vector; public class MetaBase extends Win32 { private static int IIS_MD_SERVER_BASE = 1000; private static int IIS_MD_HTTP_BASE = 2000; /* NOTE: This is only a partial list of the information that can * get from the metabase. * * These properties are applicable to both HTTP and FTP virtual * servers */ public static int MD_SERVER_COMMAND = IIS_MD_SERVER_BASE+12; public static int MD_CONNECTION_TIMEOUT = IIS_MD_SERVER_BASE+13; public static int MD_MAX_CONNECTIONS = IIS_MD_SERVER_BASE+14; public static int MD_SERVER_COMMENT = IIS_MD_SERVER_BASE+15; public static int MD_SERVER_STATE = IIS_MD_SERVER_BASE+16; public static int MD_SERVER_AUTOSTART = IIS_MD_SERVER_BASE+17; public static int MD_SERVER_SIZE = IIS_MD_SERVER_BASE+18; public static int MD_SERVER_LISTEN_BACKLOG = IIS_MD_SERVER_BASE+19; public static int MD_SERVER_LISTEN_TIMEOUT = IIS_MD_SERVER_BASE+20; public static int MD_DOWNLEVEL_ADMIN_INSTANCE = IIS_MD_SERVER_BASE+21; public static int MD_LEVELS_TO_SCAN = IIS_MD_SERVER_BASE+22; public static int MD_SERVER_BINDINGS = IIS_MD_SERVER_BASE+23; public static int MD_MAX_ENDPOINT_CONNECTIONS = IIS_MD_SERVER_BASE+24; public static int MD_SERVER_CONFIGURATION_INFO = IIS_MD_SERVER_BASE+27; public static int MD_IISADMIN_EXTENSIONS = IIS_MD_SERVER_BASE+28; public static int MD_LOGFILEDIRECTORY = 4001; // These properties are specific to HTTP and belong to the website public static int MD_SECURE_BINDINGS = IIS_MD_HTTP_BASE+21; private int m_handle; private long pIMeta; public MetaBase() { pIMeta = MetaBaseInit(); } public void close() { MetaBaseClose(); MetaBaseRelease(); } public void OpenSubKey(String subkey) { if (subkey.startsWith("/")) { MetaBaseOpenSubKeyAbs(subkey); } else { MetaBaseOpenSubKey(subkey); } } public int getIntValue(int datakey) throws Win32Exception { int iResult = 0; try { iResult = MetaBaseGetIntValue(datakey); } catch(Throwable t) { throw new Win32Exception("Error getting int value"); //W32Service.throwLastErrorException(); } return iResult; } public int getIntValue(int datakey, int defaultValue) { int iResult; try { iResult = this.getIntValue(datakey); } catch(Win32Exception e) { iResult = defaultValue; } return iResult; } public String getStringValue(int datakey) throws Win32Exception { String strResult = MetaBaseGetStringValue(datakey); if(strResult == null) //W32Service.throwLastErrorException(); throw new Win32Exception("Error getting string value"); return strResult; } public String getStringValue(int datakey, String defaultValue) { String strResult; try { strResult = this.getStringValue(datakey); } catch(Win32Exception e) { strResult = defaultValue; } return strResult; } public String[] getMultiStringValue(int datakey) throws Win32Exception { String[] strResult = MetaBaseGetMultiStringValue(datakey); return strResult; } public String[] getSubKeyNames() { Collection coll = new Vector(); String strName; for(int i = 0;(strName = MetaBaseEnumKey(i)) != null;i ++) coll.add(strName); return (String[])coll.toArray(new String[coll.size()]); } private final native long MetaBaseInit(); private final native void MetaBaseClose(); private final native void MetaBaseRelease(); private final native String MetaBaseEnumKey(int index); private final native void MetaBaseOpenSubKey(String subkey); private final native void MetaBaseOpenSubKeyAbs(String subkey); private final native int MetaBaseGetIntValue(int datakey); private final native String MetaBaseGetStringValue(int datakey); private final native String[] MetaBaseGetMultiStringValue(int datakey); public static void main(String args[]) { String key = "/LM/W3SVC"; try { MetaBase mb = new MetaBase(); mb.OpenSubKey(key); String logdir = mb.getStringValue(MD_LOGFILEDIRECTORY); System.out.println("Logdir: " + logdir); String keys[] = mb.getSubKeyNames(); System.out.println("Listing IIS Web Sites"); for (int i = 0; i < keys.length; i++) { int serverNum; try { serverNum = Integer.parseInt(keys[i]); } catch (NumberFormatException e) { continue; } MetaBase vhost = new MetaBase(); vhost.OpenSubKey(key + "/" + serverNum); String[] bindings = vhost.getMultiStringValue(MD_SERVER_BINDINGS); String hostname = vhost.getStringValue(MD_SERVER_COMMENT); System.out.println(""); System.out.println("Host: " + hostname); for (int j = 0; j < bindings.length; j++) { System.out.println("Bindings: " + bindings[j]); } vhost.close(); } mb.close(); } catch (Win32Exception e) { System.out.println("Unable to query MetaBase for IIS Web Sites"); } } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/win32/Pdh.java000066400000000000000000000477671210132627500264170ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.win32; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.hyperic.sigar.SigarLoader; public class Pdh extends Win32 { //PDH_CSTATUS_* from pdhmsg.h /** * The returned data is valid. */ public static final int VALID_DATA = 0x00000000; /** * The specified instance is not present. */ public static final int NO_INSTANCE = 0x800007D1; /** * The specified counter could not be found. */ public static final int NO_COUNTER = 0xC0000BB9; /** * The specified object is not found on the system. */ public static final int NO_OBJECT = 0xC0000BB8; /** * Unable to connect to specified machine or machine is off line. */ public static final int NO_MACHINE = 0x800007D0; /** * Unable to parse the counter path. */ public static final int BAD_COUNTERNAME = 0xC0000BC0; public static final String PERFLIB_KEY = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib"; //see winperf.h public static final long PERF_TYPE_NUMBER = 0x00000000; // a number (not a counter) public static final long PERF_TYPE_COUNTER = 0x00000400; // an increasing numeric value public static final long PERF_TYPE_TEXT = 0x00000800; // a text field public static final long PERF_TYPE_ZERO = 0x00000C00; // displays a zero private long query = -1l; // Handle to the query private String hostname = null; private static Map counters = null; static { final String prop = "sigar.pdh.enableTranslation"; if (SigarLoader.IS_WIN32 && !"false".equals(System.getProperty(prop))) { try { enableTranslation(); } catch (Exception e) { System.err.println(prop + ": " + e.getMessage()); } } } public Pdh() throws Win32Exception { this.query = pdhOpenQuery(); } public Pdh(String hostName) throws Win32Exception { this(); this.hostname = hostName; } protected void finalize() throws Throwable { try { this.close(); } finally { super.finalize(); } } public synchronized void close() throws Win32Exception { if (this.query != -1l) { pdhCloseQuery(this.query); this.query = -1l; } } public static void enableTranslation() throws Win32Exception { if (counters != null) { return; } if (LocaleInfo.isEnglish()) { return; } counters = getEnglishPerflibCounterMap(); } private static class PerflibCounterMap extends ArrayList { private Map map = new HashMap(); private String index = null; //called by RegistryKey.getMultiStringValue //format description see: http://support.microsoft.com/kb/q287159/ public boolean add(Object o) { if (index == null) { index = (String)o; return true; } String name = ((String)o).trim().toLowerCase(); int[] ix = (int[])this.map.get(name); if (ix == null) { ix = new int[1]; } else { int[] cur = ix; ix = new int[cur.length + 1]; System.arraycopy(cur, 0, ix, 1, cur.length); } ix[0] = Integer.parseInt(index); //name -> index this.map.put(name, ix); index = null; //reset return true; } } public static Map getEnglishPerflibCounterMap() throws Win32Exception { LocaleInfo locale = new LocaleInfo(LocaleInfo.LANG_ENGLISH); return getPerflibCounterMap(locale); } public static Map getPerflibCounterMap(LocaleInfo locale) throws Win32Exception { String path = PERFLIB_KEY + "\\" + locale.getPerflibLangId(); RegistryKey key = RegistryKey.LocalMachine.openSubKey(path); PerflibCounterMap counters = new PerflibCounterMap(); try { key.getMultiStringValue("Counter", counters); } finally { key.close(); } return counters.map; } public static String getCounterName(int index) throws Win32Exception { String name = pdhLookupPerfName(index).trim(); return name; } /** * @deprecated * @see #getRawValue(String path) */ public double getSingleValue(String path) throws Win32Exception { return getRawValue(path); } public double getRawValue(String path) throws Win32Exception { return getValue(path, false); } public double getFormattedValue(String path) throws Win32Exception { return getValue(path, true); } private static final String DELIM = "\\"; private static int[] getCounterIndex(String englishName) { if (counters == null) { return null; } return (int[])counters.get(englishName.toLowerCase()); } private static String getCounterName(String englishName) throws Win32Exception { int[] ix = getCounterIndex(englishName); if (ix == null) { return englishName; } String name = getCounterName(ix[0]); return name; } public static String translate(String path) throws Win32Exception { if (counters == null) { return path; } StringBuffer trans = new StringBuffer(); StringTokenizer tok = new StringTokenizer(path, DELIM); int num = tok.countTokens(); if (num == 3) { String hostname = tok.nextToken(); trans.append(DELIM).append(DELIM).append(hostname); } String object = tok.nextToken(); String instance = null; int ix = object.indexOf('('); if (ix != -1) { instance = object.substring(ix); object = object.substring(0, ix); } trans.append(DELIM).append(getCounterName(object)); if (instance != null) { trans.append(instance); } String counter = tok.nextToken(); trans.append(DELIM); int[] cix = getCounterIndex(counter); if (cix != null) { if (cix.length == 1) { counter = getCounterName(cix[0]); } else { //handle duplicate counter names for (int i=0; i 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-h") || args[i].equals("-help") || args[i].equals("--help")) { System.out.println("Usage: Pdh [OPTION]"); System.out.println("Show information from the Windows " + "PDH"); System.out.println(""); System.out.println(" --object=NAME " + "only print info on this object"); System.out.println(" --contains=NAME " + "only print info on objects that"); System.out.println(" " + "contain this substring"); System.out.println("-i, --instance " + "show instances [default=no]"); System.out.println("-k, --keys " + "show keys [default=no]"); System.out.println("-v, --values " + "include key values [default=no]"); System.out.println("-h, --help " + "display help and exit"); return; } else if (args[i].equals("-v") || args[i].equals("--values")) { showKeys = true; // Assume -k when -v is used. showValues = true; } else if (args[i].equals("-i") || args[i].equals("--instances")) { showInstances = true; } else if (args[i].equals("-k") || args[i].equals("--keys")) { showKeys = true; } else if (args[i].startsWith("--contains=")) { int idx = args[i].indexOf("="); partialName = args[i].substring(idx + 1); } else if (args[i].startsWith("--object=")) { int idx = args[i].indexOf("="); objectName = args[i].substring(idx + 1); } else { System.out.println("Unknown option: " + args[i]); System.out.println("Use --help for usage information"); return; } } } try { pdh = new Pdh(); String[] objects; // The list of objects to inspect. if (partialName != null) { // Check list of object names for a user defined // substring. (e.g. --contains=PLUMTREE for example) List matching = new ArrayList(); String[] allObjects = Pdh.getObjects(); for (int i = 0; i < allObjects.length; i++) { if (allObjects[i].toUpperCase(). indexOf(partialName.toUpperCase()) != -1) { matching.add(allObjects[i]); } } objects = (String[])matching.toArray(new String[0]); } else if (objectName != null) { // Query for a single object objects = new String[] { objectName }; } else { objects = Pdh.getObjects(); } for (int o = 0; o < objects.length; o++) { System.out.println(objects[o]); // Get the query keys for this object String[] keys; try { keys = Pdh.getKeys(objects[o]); } catch (Win32Exception e) { System.err.println("Unable to get keys for object=" + objects[o] + " Reason: " + e.getMessage()); continue; } int pad = getLongestKey(keys); // Get the instances for this object String[] instances = Pdh.getInstances(objects[o]); if (instances.length == 0) { // No instances, dump the keys and values for the // top level object if (showKeys == false) continue; for (int k = 0; k < keys.length; k++) { if (showValues) { String query = "\\" + objects[o] + "\\" + keys[k]; double val; try { val = pdh.getRawValue(query); } catch (Win32Exception e) { System.err.println("Unable to get value for " + " key=" + query + " Reason: " + e.getMessage()); continue; } String out = pad(keys[k], pad, ' '); System.out.println(" " + out + " = " + val); } else { System.out.println(" " + keys[k]); } } } else { // Only show instance level info if asked. if (showInstances == false) continue; // For each instance, print it along with the keys for (int i = 0; i < instances.length; i++) { System.out.println(" " + instances[i]); // Dump the keys for this instance if (showKeys == false) continue; for (int k = 0; k < keys.length; k++) { if (showValues) { String query = "\\" + objects[o] + "(" + instances[i] + ")" + "\\" + keys[k]; double val; try { val = pdh.getRawValue(query); } catch (Win32Exception e) { System.err.println("Unable to get value " + "for key=" + query + " Reason: " + e.getMessage()); continue; } String out = pad(keys[k], pad, ' '); System.out.println(" " + out + " = " + val); } else { System.out.println(" " + keys[k]); } } } } } pdh.close(); } catch (Win32Exception e) { // Should never happen System.err.println("Unable to dump PDH data: " + e.getMessage()); return; } } /** * String padder yanked from java-util's StringUtil.java */ private static String pad(String value, int length, char ch) { StringBuffer padder = new StringBuffer(value); if (value.length() < length) { for (int i=0; i < (length - value.length()); i++) { padder.append(ch); } } return padder.toString(); } /** * Returns the length of the longest string in an array */ private static int getLongestKey(String[] keys) { int longest = 0; for (int i = 0; i < keys.length; i++) { int len = keys[i].length(); if (len > longest) longest = len; } return longest; } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/win32/RegistryKey.java000066400000000000000000000212211210132627500301360ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hyperic.sigar.win32; import java.util.Collection; import java.util.List; import java.util.Vector; public class RegistryKey extends Win32 { private static final int HKEY_CLASSES_ROOT = 0x80000000; private static final int HKEY_CURRENT_USER = 0x80000001; private static final int HKEY_LOCAL_MACHINE = 0x80000002; private static final int HKEY_USERS = 0x80000003; private static final int HKEY_PERFORMANCE_DATA = 0x80000004; private static final int HKEY_CURRENT_CONFIG = 0x80000005; private static final int HKEY_DYN_DATA = 0x80000006; /** * HKEY_CLASSES_ROOT */ public static final RegistryKey ClassesRoot = new RegistryKey(RegistryKey.HKEY_CLASSES_ROOT); /** * HKEY_CURRENT_USER */ public static final RegistryKey CurrentUser = new RegistryKey(RegistryKey.HKEY_CURRENT_USER); /** * HKEY_LOCAL_MACHINE */ public static final RegistryKey LocalMachine = new RegistryKey(RegistryKey.HKEY_LOCAL_MACHINE); private long m_hkey; private String subkey; private RegistryKey() { } private RegistryKey(long hkey) { this.m_hkey = hkey; } public synchronized void close() { if (this.m_hkey != 0) { RegCloseKey(this.m_hkey); this.m_hkey = 0; } } public RegistryKey createSubKey(String subkey) { return new RegistryKey(RegCreateKey(this.m_hkey, subkey)); } public String getSubKeyName() { return this.subkey; } public RegistryKey createSubKey(String subkey, String value) throws Win32Exception { RegistryKey keyResult = null; long hkey = RegCreateKey(this.m_hkey, subkey); if(hkey != 0) { keyResult = new RegistryKey(hkey); if(keyResult != null) keyResult.setStringValue(null, value); } else //W32Service.throwLastErrorException(); throw new Win32Exception("Error creating subkey"); return keyResult; } public RegistryKey createSubKey(String subkey, int value) throws Win32Exception { RegistryKey keyResult = null; long hkey = RegCreateKey(this.m_hkey, subkey); if(hkey != 0) { keyResult = new RegistryKey(hkey); if(keyResult != null) keyResult.setIntValue(null, value); } else //W32Service.throwLastErrorException(); throw new Win32Exception("Error creating subkey"); return keyResult; } public void deleteSubKey(String subkey) { RegDeleteKey(this.m_hkey, subkey); } public void deleteSubKeyTree(String subkey) { } public void deleteValue(String name) { RegDeleteValue(this.m_hkey, name); } public void flush() { RegFlushKey(this.m_hkey); } public int getIntValue(String name) throws Win32Exception { int iResult = 0; try { iResult = RegQueryIntValue(this.m_hkey, name); } catch(Throwable t) { //W32Service.throwLastErrorException(); throw new Win32Exception("Error getting int value"); } return iResult; } public int getIntValue(String name, int defaultValue) { int iResult; try { iResult = this.getIntValue(name); } catch(Win32Exception e) { iResult = defaultValue; } return iResult; } public String getStringValue(String name) throws Win32Exception { String strResult = RegQueryStringValue(this.m_hkey, name); if(strResult == null) // W32Service.throwLastErrorException(); throw new Win32Exception("Error getting string value"); return strResult; } public void getMultiStringValue(String name, List values) throws Win32Exception { RegQueryMultiStringValue(this.m_hkey, name, values); } public String getStringValue(String name, String defaultValue) { String strResult; try { strResult = this.getStringValue(name); } catch(Win32Exception e) { strResult = defaultValue; } return strResult; } public String[] getSubKeyNames() { Collection coll = new Vector(); String strName; for(int i = 0; (strName = RegEnumKey(this.m_hkey, i)) != null; i++) coll.add(strName); return (String[])coll.toArray(new String[coll.size()]); } public String[] getValueNames() { Collection coll = new Vector(); String strName; for(int i = 0; (strName = RegEnumValueName(this.m_hkey, i)) != null; i ++) coll.add(strName); return (String[])coll.toArray(new String[coll.size()]); } public RegistryKey openSubKey(String subkey) throws Win32Exception { long hkey = RegOpenKey(this.m_hkey, subkey); if(hkey == 0) //W32Service.throwLastErrorException(); throw new Win32Exception("Error opening subkey"); RegistryKey key = new RegistryKey(hkey); key.subkey = subkey; return key; } public void setIntValue(String name, int value) throws Win32Exception { int iResult = RegSetIntValue(this.m_hkey, name, value); if(iResult != 0) //W32Service.throwLastErrorException(); throw new Win32Exception("Error setting int value"); } public void setStringValue(String name, String value) throws Win32Exception { int iResult = RegSetStringValue(this.m_hkey, name, value); if(iResult != 0) //W32Service.throwLastErrorException(); throw new Win32Exception("Error setting string value"); } protected void finalize() { close(); } private static native int RegCloseKey(long hkey); private static native long RegCreateKey(long hkey, String subkey); private static native int RegDeleteKey(long hkey, String subkey); private static native int RegDeleteValue(long hkey, String valueName); private static native String RegEnumKey(long hkey, int index); private static native String RegEnumValueName(long hkey, int index); private static native int RegFlushKey(long hkey); private static native int RegLoadKey(long hkey, String subkey, String filename); private static native long RegOpenKey(long hkey, String subkey); private static native byte[] RegQueryBufferValue(long hkey, String valueName); private static native int RegQueryIntValue(long hkey, String valueName); private static native String RegQueryStringValue(long hkey, String valueName); private static native void RegQueryMultiStringValue(long hkey, String valueName, List values); private static native int RegSetIntValue(long hkey, String valueName, int value); private static native int RegSetStringValue(long hkey, String valueName, String value); } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/win32/Service.java000066400000000000000000000332461210132627500272670ustar00rootroot00000000000000/* * Copyright (c) 2006-2008 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.win32; import java.io.PrintStream; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import org.hyperic.sigar.Sigar; public class Service extends Win32 { // Service State public static final int SERVICE_STOPPED = 0x00000001; public static final int SERVICE_START_PENDING = 0x00000002; public static final int SERVICE_STOP_PENDING = 0x00000003; public static final int SERVICE_RUNNING = 0x00000004; public static final int SERVICE_CONTINUE_PENDING = 0x00000005; public static final int SERVICE_PAUSE_PENDING = 0x00000006; public static final int SERVICE_PAUSED = 0x00000007; private static final String[] STATUS = { "Unknown", "Stopped", "Start Pending", "Stop Pending", "Running", "Continue Pending", "Pause Pending", "Paused" }; // Service Controls private static final int CONTROL_START = 0x00000000; private static final int CONTROL_STOP = 0x00000001; private static final int CONTROL_PAUSE = 0x00000002; private static final int CONTROL_RESUME = 0x00000003; // Service Control Manager object specific access types private static final int STANDARD_RIGHTS_REQUIRED = (int)0x000F0000L; private static final int SC_MANAGER_CONNECT = 0x0001; private static final int SC_MANAGER_CREATE_SERVICE = 0x0002; private static final int SC_MANAGER_ENUMERATE_SERVICE = 0x0004; private static final int SC_MANAGER_LOCK = 0x0008; private static final int SC_MANAGER_QUERY_LOCK_STATUS = 0x0010; private static final int SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020; private static final int SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG); // Service object specific access type private static final int SERVICE_QUERY_CONFIG = 0x0001; private static final int SERVICE_CHANGE_CONFIG = 0x0002; private static final int SERVICE_QUERY_STATUS = 0x0004; private static final int SERVICE_ENUMERATE_DEPENDENTS = 0x0008; private static final int SERVICE_START = 0x0010; private static final int SERVICE_STOP = 0x0020; private static final int SERVICE_PAUSE_CONTINUE = 0x0040; private static final int SERVICE_INTERROGATE = 0x0080; private static final int SERVICE_USER_DEFINED_CONTROL = 0x0100; private static final int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL); private long manager; private long service; private String name; private Service() throws Win32Exception { this.manager = OpenSCManager("", SC_MANAGER_ALL_ACCESS); } public static native List getServiceNames(Sigar sigar, String ptql) throws Win32Exception; public static List getServiceNames() throws Win32Exception { return getServiceNames(null, null); } public static List getServiceConfigs(Sigar sigar, String exe) throws Win32Exception { List services = new ArrayList(); List names = Service.getServiceNames(sigar, "Service.Exe.Ieq=" + exe); for (int i=0; i" + trans); } traceln(path + " validate: " + Pdh.validate(path)); getValue(path); } } public void testCounterMap() throws Exception { Map counters = Pdh.getEnglishPerflibCounterMap(); assertGtZeroTrace("counters", counters.size()); int dups = 0; for (Iterator it=counters.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); String name = (String)entry.getKey(); int[] ix = (int[])entry.getValue(); if (ix.length > 1) { dups++; //traceln(name + " has dups: " + ix.length); } } traceln(dups + " names have dups"); String[] keys = { "System", "System Up Time" }; int last = -1; for (int i=0; i" + Integer.toHexString(status).toUpperCase() + " != " + Integer.toHexString(expect).toUpperCase()); } assertTrue(expectedResult); } } public void testPdh() throws Exception { String[] iface = Pdh.getKeys("Thread"); assertTrue(iface.length > 0); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/win32/test/TestRegistryKey.java000066400000000000000000000106211210132627500317570ustar00rootroot00000000000000/* * Copyright (c) 2006, 2008 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.win32.test; import java.util.ArrayList; import org.hyperic.sigar.test.SigarTestCase; import org.hyperic.sigar.win32.RegistryKey; public class TestRegistryKey extends SigarTestCase { private static final boolean TEST_WRITE = false; public TestRegistryKey(String name) { super(name); } public void testRegistryRead() throws Exception { RegistryKey software = RegistryKey.LocalMachine.openSubKey("SOFTWARE"); String[] keys = software.getSubKeyNames(); assertTrue(keys.length > 0); software.close(); } public void testHardwareValues() throws Exception { RegistryKey hw = RegistryKey.LocalMachine.openSubKey("HARDWARE\\DESCRIPTION\\System"); try { ArrayList values = new ArrayList(); hw.getMultiStringValue("SystemBiosVersion", values); assertGtZeroTrace("SystemBiosVersion.size()", values.size()); traceln("SystemBiosVersion=" + values); } catch (Exception e) {} RegistryKey cpu0 = hw.openSubKey("CentralProcessor\\0"); String cpu = cpu0.getStringValue("ProcessorNameString"); assertLengthTrace("cpu0", cpu); cpu0.close(); hw.close(); } public void testSoftwareValues() throws Exception { RegistryKey ms = RegistryKey.LocalMachine.openSubKey("SOFTWARE\\Microsoft"); RegistryKey msmq = null; try { msmq = ms.openSubKey("MSMQ\\Parameters"); } catch (Exception e) { /*not installed - ok*/ } if (msmq != null) { traceln("MSMQ..."); if (msmq.getSubKeyNames().length > 0) { try { String build = msmq.getStringValue("CurrentBuild"); assertLengthTrace("CurrentBuild", build); int id = msmq.getIntValue("SeqID"); assertGtZeroTrace("SeqID", id); } catch (Exception e) {} } msmq.close(); } RegistryKey sql = null; try { sql = ms.openSubKey("Microsoft SQL Server\\MSSQL.1\\Setup"); } catch (Exception e) { /*not installed - ok*/ } if (sql != null) { traceln("MsSQL..."); try { String edition = sql.getStringValue("Edition"); assertLengthTrace("Edition", edition); } catch (Exception e) {} sql.close(); } ms.close(); final String TC = "SOFTWARE\\Apache Software Foundation\\Procrun 2.0\\Tomcat6\\Parameters\\Java"; try { RegistryKey tc = RegistryKey.LocalMachine.openSubKey(TC); traceln("Tomcat6..."); ArrayList values = new ArrayList(); tc.getMultiStringValue("Options", values); assertGtZeroTrace("Options.size()", values.size()); traceln("Options=" + values); tc.close(); } catch (Exception e) {} } //dont want to be writing to the registry public void testRegistryWrite() throws Exception { if (!TEST_WRITE) { return; } RegistryKey key = RegistryKey.LocalMachine. createSubKey("SOFTWARE\\Hyperic\\Test", "Hyperic Test"); key.setStringValue("TestString", "Hello World"); key.setIntValue("Test Int", 100); String[] astrNames = key.getValueNames(); String strValue = key.getStringValue(astrNames[0]); //assertTrue(strValue.equals("Covalent Test")); int iValue = key.getIntValue(astrNames[1]); //assertTrue(iValue == 100); key = RegistryKey.LocalMachine.openSubKey("SOFTWARE\\Hyperic"); astrNames = key.getSubKeyNames(); // Clean up key.deleteSubKey("Test"); } } hyperic-sigar-1.6.4+dfsg/bindings/java/src/org/hyperic/sigar/win32/test/TestService.java000066400000000000000000000067371210132627500311130ustar00rootroot00000000000000/* * Copyright (c) 2006, 2008 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.win32.test; import java.util.List; import org.hyperic.sigar.test.SigarTestCase; import org.hyperic.sigar.win32.Service; import org.hyperic.sigar.win32.ServiceConfig; import org.hyperic.sigar.win32.Win32Exception; public class TestService extends SigarTestCase { private static final String TEST_NAME = "MyTestService"; private static final String PREFIX = "sigar.test.service."; private static final boolean TEST_CREATE = "true".equals(System.getProperty(PREFIX + "create")); private static final boolean TEST_DELETE = "true".equals(System.getProperty(PREFIX + "delete")); public TestService(String name) { super(name); } public void testServiceOpen() throws Exception { Service service = new Service("Eventlog"); service.getConfig(); service.close(); String dummyName = "DOESNOTEXIST"; try { new Service(dummyName); assertTrue(false); } catch (Win32Exception e) { traceln(dummyName + ": " + e.getMessage()); assertTrue(true); } } public void testServiceNames() throws Exception { List services = Service.getServiceNames(); assertGtZeroTrace("getServiceNames", services.size()); final String[] ptql = { "Service.Name.ct=Ev", "Service.Path.ew=.exe", }; for (int i=0; i '.'); my $archname = SigarWrapper::archname(); my $libname = 'sigar'; if ($archname) { $libname .= '-' . $archname; } my $ccname = $Config{ccname}; my $define = { gcc => '-Wall -Werror', cc_r => '-qhalt=w', }->{$ccname} || ''; WriteMakefile( 'NAME' => 'Sigar', 'VERSION_FROM' => 'Sigar.pm', 'LIBS' => ["-L$installdir/lib -l$libname"], 'INC' => "-I$installdir/include", 'DEFINE' => $define, 'depend' => { 'Sigar.c' => 'Sigar_generated.xs' }, ); hyperic-sigar-1.6.4+dfsg/bindings/perl/Sigar.pm000066400000000000000000000015741210132627500213570ustar00rootroot00000000000000# # Copyright (c) 2004, 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package Sigar; use 5.003; use strict; use vars qw($VERSION @ISA); $VERSION = '0.01'; eval { require XSLoader; }; if ($@) { #$] < 5.6 require DynaLoader; @ISA = qw(DynaLoader); __PACKAGE__->bootstrap($VERSION); } else { XSLoader::load(__PACKAGE__, $VERSION); } 1; __END__ hyperic-sigar-1.6.4+dfsg/bindings/perl/Sigar.xs000066400000000000000000000263101210132627500213700ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 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. */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "sigar.h" #include "sigar_fileinfo.h" #include "sigar_format.h" typedef sigar_t * Sigar; typedef sigar_net_address_t Sigar__NetAddress; /* generated list */ typedef sigar_uptime_t * Sigar__Uptime; typedef sigar_mem_t * Sigar__Mem; typedef sigar_proc_cred_t * Sigar__ProcCred; typedef sigar_proc_fd_t * Sigar__ProcFd; typedef sigar_dir_stat_t * Sigar__DirStat; typedef sigar_proc_cred_name_t * Sigar__ProcCredName; typedef sigar_file_attrs_t * Sigar__FileAttrs; typedef sigar_cpu_t * Sigar__Cpu; typedef sigar_cpu_info_t * Sigar__CpuInfo; typedef sigar_cpu_perc_t * Sigar__CpuPerc; typedef sigar_net_interface_config_t * Sigar__NetInterfaceConfig; typedef sigar_swap_t * Sigar__Swap; typedef sigar_proc_state_t * Sigar__ProcState; typedef sigar_net_connection_t * Sigar__NetConnection; typedef sigar_proc_exe_t * Sigar__ProcExe; typedef sigar_proc_time_t * Sigar__ProcTime; typedef sigar_proc_cpu_t * Sigar__ProcCpu; typedef sigar_proc_mem_t * Sigar__ProcMem; typedef sigar_file_system_t * Sigar__FileSystem; typedef sigar_file_system_usage_t * Sigar__FileSystemUsage; typedef sigar_disk_usage_t * Sigar__DiskUsage; typedef sigar_proc_stat_t * Sigar__ProcStat; typedef sigar_net_route_t * Sigar__NetRoute; typedef sigar_net_interface_stat_t * Sigar__NetInterfaceStat; typedef sigar_who_t * Sigar__Who; typedef sigar_thread_cpu_t * Sigar__ThreadCpu; typedef sigar_resource_limit_t * Sigar__ResourceLimit; typedef sigar_net_info_t * Sigar__NetInfo; typedef sigar_dir_usage_t * Sigar__DirUsage; typedef sigar_sys_info_t * Sigar__SysInfo; typedef sigar_net_stat_t * Sigar__NetStat; typedef sigar_tcp_t * Sigar__Tcp; typedef sigar_nfs_client_v2_t * Sigar__NfsClientV2; typedef sigar_nfs_server_v2_t * Sigar__NfsServerV2; typedef sigar_nfs_client_v3_t * Sigar__NfsClientV3; typedef sigar_nfs_server_v3_t * Sigar__NfsServerV3; /* Perl < 5.6 */ #ifndef aTHX_ #define aTHX_ #endif #define SIGAR_CROAK(sigar, msg) \ Perl_croak(aTHX_ msg " %s", sigar_strerror(sigar, status)) static SV *convert_2svav(char *data, unsigned long number, int size, const char *classname) { AV *av = newAV(); unsigned long i; for (i=0; iklen == klen) && (strEQ(get->key, key))) { get->val = newSVpv(val, vlen); return !SIGAR_OK; /* foundit; stop iterating */ } return SIGAR_OK; } #define XS_SIGAR_CONST_IV(name) \ (void)newCONSTSUB(stash, #name, newSViv(SIGAR_##name)) #define XS_SIGAR_CONST_PV(name) \ (void)newCONSTSUB(stash, #name, newSVpv(SIGAR_##name, 0)) static void boot_Sigar_constants(pTHX) { HV *stash = gv_stashpv("Sigar", TRUE); XS_SIGAR_CONST_IV(IFF_UP); XS_SIGAR_CONST_IV(IFF_BROADCAST); XS_SIGAR_CONST_IV(IFF_DEBUG); XS_SIGAR_CONST_IV(IFF_LOOPBACK); XS_SIGAR_CONST_IV(IFF_POINTOPOINT); XS_SIGAR_CONST_IV(IFF_NOTRAILERS); XS_SIGAR_CONST_IV(IFF_RUNNING); XS_SIGAR_CONST_IV(IFF_NOARP); XS_SIGAR_CONST_IV(IFF_PROMISC); XS_SIGAR_CONST_IV(IFF_ALLMULTI); XS_SIGAR_CONST_IV(IFF_MULTICAST); XS_SIGAR_CONST_IV(NETCONN_CLIENT); XS_SIGAR_CONST_IV(NETCONN_SERVER); XS_SIGAR_CONST_IV(NETCONN_TCP); XS_SIGAR_CONST_IV(NETCONN_UDP); XS_SIGAR_CONST_IV(NETCONN_RAW); XS_SIGAR_CONST_IV(NETCONN_UNIX); XS_SIGAR_CONST_IV(TCP_ESTABLISHED); XS_SIGAR_CONST_IV(TCP_SYN_SENT); XS_SIGAR_CONST_IV(TCP_SYN_RECV); XS_SIGAR_CONST_IV(TCP_FIN_WAIT1); XS_SIGAR_CONST_IV(TCP_FIN_WAIT2); XS_SIGAR_CONST_IV(TCP_TIME_WAIT); XS_SIGAR_CONST_IV(TCP_CLOSE); XS_SIGAR_CONST_IV(TCP_CLOSE_WAIT); XS_SIGAR_CONST_IV(TCP_LAST_ACK); XS_SIGAR_CONST_IV(TCP_LISTEN); XS_SIGAR_CONST_IV(TCP_CLOSING); XS_SIGAR_CONST_IV(TCP_IDLE); XS_SIGAR_CONST_IV(TCP_BOUND); XS_SIGAR_CONST_IV(TCP_UNKNOWN); XS_SIGAR_CONST_PV(NULL_HWADDR); } MODULE = Sigar PACKAGE = Sigar PROTOTYPES: disable INCLUDE: Sigar_generated.xs BOOT: boot_Sigar_constants(aTHX); MODULE = Sigar PACKAGE = Sigar PREFIX = sigar_ Sigar new(classname) char *classname PREINIT: int status; CODE: if ((status = sigar_open(&RETVAL)) != SIGAR_OK) { classname = classname; /* -Wall */ SIGAR_CROAK(RETVAL, "open"); } OUTPUT: RETVAL void DESTROY(sigar) Sigar sigar CODE: (void)sigar_close(sigar); char * format_size(size) UV size PREINIT: char buffer[56]; CODE: RETVAL = sigar_format_size(size, buffer); OUTPUT: RETVAL char * net_interface_flags_string(size) UV size PREINIT: char buffer[1024]; CODE: RETVAL = sigar_net_interface_flags_to_string(size, buffer); OUTPUT: RETVAL char * sigar_fqdn(sigar) Sigar sigar PREINIT: char fqdn[SIGAR_FQDN_LEN]; CODE: sigar_fqdn_get(sigar, fqdn, sizeof(fqdn)); RETVAL = fqdn; OUTPUT: RETVAL SV * loadavg(sigar) Sigar sigar PREINIT: sigar_loadavg_t loadavg; int status; unsigned long i; AV *av; CODE: status = sigar_loadavg_get(sigar, &loadavg); if (status != SIGAR_OK) { SIGAR_CROAK(sigar, "loadavg"); } av = newAV(); av_extend(av, 2); for (i=0; i<3; i++) { av_push(av, newSVnv(loadavg.loadavg[i])); } RETVAL = newRV_noinc((SV*)av); OUTPUT: RETVAL SV * file_system_list(sigar) Sigar sigar PREINIT: sigar_file_system_list_t fslist; int status; CODE: status = sigar_file_system_list_get(sigar, &fslist); if (status != SIGAR_OK) { SIGAR_CROAK(sigar, "fslist"); } RETVAL = convert_2svav((char *)&fslist.data[0], fslist.number, sizeof(*fslist.data), "Sigar::FileSystem"); sigar_file_system_list_destroy(sigar, &fslist); OUTPUT: RETVAL SV * cpu_info_list(sigar) Sigar sigar PREINIT: sigar_cpu_info_list_t cpu_infos; int status; CODE: status = sigar_cpu_info_list_get(sigar, &cpu_infos); if (status != SIGAR_OK) { SIGAR_CROAK(sigar, "cpu_infos"); } RETVAL = convert_2svav((char *)&cpu_infos.data[0], cpu_infos.number, sizeof(*cpu_infos.data), "Sigar::CpuInfo"); sigar_cpu_info_list_destroy(sigar, &cpu_infos); OUTPUT: RETVAL SV * cpu_list(sigar) Sigar sigar PREINIT: sigar_cpu_list_t cpus; int status; CODE: status = sigar_cpu_list_get(sigar, &cpus); if (status != SIGAR_OK) { SIGAR_CROAK(sigar, "cpu_list"); } RETVAL = convert_2svav((char *)&cpus.data[0], cpus.number, sizeof(*cpus.data), "Sigar::Cpu"); sigar_cpu_list_destroy(sigar, &cpus); OUTPUT: RETVAL SV * proc_list(sigar) Sigar sigar PREINIT: sigar_proc_list_t proclist; int status; unsigned long i; AV *av; CODE: status = sigar_proc_list_get(sigar, &proclist); if (status != SIGAR_OK) { SIGAR_CROAK(sigar, "proc_list"); } av = newAV(); av_extend(av, proclist.number - 1); for (i=0; icpu_info_list; my $num = scalar @$infos; print "$num total CPUs..\n"; for my $info (@$infos) { print "Vendor........" . $info->vendor . "\n"; print "Model........." . $info->model . "\n"; print "Mhz..........." . $info->mhz . "\n"; print "Cache size...." . $info->cache_size . "\n"; } hyperic-sigar-1.6.4+dfsg/bindings/perl/examples/df.pl000066400000000000000000000030711210132627500225120ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (c) 2004 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. # use strict; use Sigar; my $sigar = new Sigar; my $fslist = $sigar->file_system_list; print "Filesystem\tSize\tUsed\tAvail\tUse%\tMounted on\tType\n"; for my $fs (@$fslist) { my $dirname = $fs->dir_name; my $usage; #e.g. on win32 D:\ fails with "Device not ready" #if there is no cd in the drive. eval { $usage = $sigar->file_system_usage($dirname); } or next; my $total = $usage->total; my $used = $total - $usage->free; my $avail = $usage->avail; my $pct = $usage->use_percent * 100; my $usePct; if ($pct == 0) { $usePct = "-" } else { $usePct = $pct . '%'; } print $fs->dev_name . "\t" . format_size($total) . "\t" . format_size($used) . "\t" . format_size($avail) . "\t" . $usePct . "\t" . $dirname . "\t" . $fs->sys_type_name . "/" . $fs->type_name . "\n"; } sub format_size { my($size) = @_; return Sigar::format_size($size * 1024); } hyperic-sigar-1.6.4+dfsg/bindings/perl/examples/free.pl000066400000000000000000000020001210132627500230310ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (c) 2004 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. # use strict; use Sigar; my $sigar = new Sigar; my $mem = $sigar->mem; my $swap = $sigar->swap; print "\tTotal\tUsed\tFree\n"; print "Mem: " . ($mem->total / 1024) . "\t" . ($mem->used / 1024) . "\t" . ($mem->free / 1024) . "\n"; print "Swap: " . ($swap->total / 1024) . "\t" . ($swap->used / 1024) . "\t" . ($swap->free / 1024) . "\n"; print "RAM: " . $mem->ram . "MB\n"; hyperic-sigar-1.6.4+dfsg/bindings/perl/examples/ifconfig.pl000066400000000000000000000047141210132627500237120ustar00rootroot00000000000000#!/usr/bin/perl # # Copyright (c) 2004-2005 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. # use strict; use Sigar; my $sigar = new Sigar; my $iflist = $sigar->net_interface_list; for my $ifname (@$iflist) { my $ifconfig = $sigar->net_interface_config($ifname); my $flags = $ifconfig->flags; my $encap = $ifconfig->type; my $hwaddr = $ifconfig->hwaddr; if ($hwaddr eq Sigar::NULL_HWADDR) { $hwaddr = ""; } else { $hwaddr = " HWaddr " . $hwaddr; } print $ifname . "\t" . "Link encap:" . $encap . $hwaddr . "\n"; my $ptp = ""; if ($flags & Sigar::IFF_POINTOPOINT) { $ptp = " P-t-P:" . $ifconfig->destination; } my $bcast = ""; if ($flags & Sigar::IFF_BROADCAST) { $bcast = " Bcast:" . $ifconfig->broadcast; } print "\t" . "inet addr:" . $ifconfig->address . $ptp . $bcast . " Mask:" . $ifconfig->netmask . "\n"; print "\t" . Sigar::net_interface_flags_string($flags) . " MTU:" . $ifconfig->mtu . " Metric:" . $ifconfig->metric . "\n"; my $ifstat; eval { $ifstat = $sigar->net_interface_stat($ifname); } or next; print "\t" . "RX packets:" . $ifstat->rx_packets . " errors:" . $ifstat->rx_errors . " dropped:" . $ifstat->rx_dropped . " overruns:" . $ifstat->rx_overruns . " frame:" . $ifstat->rx_frame . "\n"; print "\t" . "TX packets:" . $ifstat->tx_packets . " errors:" . $ifstat->tx_errors . " dropped:" . $ifstat->tx_dropped . " overruns:" . $ifstat->tx_overruns . " carrier:" . $ifstat->tx_carrier . "\n"; print "\t" . "collisions:" . $ifstat->tx_collisions . "\n"; my $rx_bytes = $ifstat->rx_bytes; my $tx_bytes = $ifstat->tx_bytes; print "\t" . "RX bytes:" . $rx_bytes . " (" . Sigar::format_size($rx_bytes) . ")" . " " . "TX bytes:" . $tx_bytes . " (" . Sigar::format_size($tx_bytes) . ")" . "\n\n"; } hyperic-sigar-1.6.4+dfsg/bindings/perl/typemap000066400000000000000000000022471210132627500213540ustar00rootroot00000000000000Sigar T_PTROBJ sigar_pid_t T_UV sigar_uint64_t T_UV const char * T_PV Sigar::NetAddress T_NETADDR #generated list Sigar::Uptime T_PTROBJ Sigar::Mem T_PTROBJ Sigar::ProcCred T_PTROBJ Sigar::ProcFd T_PTROBJ Sigar::DirStat T_PTROBJ Sigar::ProcCredName T_PTROBJ Sigar::FileAttrs T_PTROBJ Sigar::Cpu T_PTROBJ Sigar::CpuInfo T_PTROBJ Sigar::CpuPerc T_PTROBJ Sigar::NetInterfaceConfig T_PTROBJ Sigar::Swap T_PTROBJ Sigar::ProcState T_PTROBJ Sigar::NetConnection T_PTROBJ Sigar::ProcExe T_PTROBJ Sigar::ProcTime T_PTROBJ Sigar::ProcCpu T_PTROBJ Sigar::ProcMem T_PTROBJ Sigar::FileSystem T_PTROBJ Sigar::FileSystemUsage T_PTROBJ Sigar::DiskUsage T_PTROBJ Sigar::ProcStat T_PTROBJ Sigar::NetRoute T_PTROBJ Sigar::NetInterfaceStat T_PTROBJ Sigar::Who T_PTROBJ Sigar::ThreadCpu T_PTROBJ Sigar::ResourceLimit T_PTROBJ Sigar::NetInfo T_PTROBJ Sigar::DirUsage T_PTROBJ Sigar::SysInfo T_PTROBJ Sigar::NetStat T_PTROBJ Sigar::Tcp T_PTROBJ Sigar::NfsClientV2 T_PTROBJ Sigar::NfsServerV2 T_PTROBJ Sigar::NfsClientV3 T_PTROBJ Sigar::NfsServerV3 T_PTROBJ OUTPUT T_NETADDR { char addr_str[INET6_ADDRSTRLEN]; sigar_net_address_to_string(NULL, &$var, addr_str); sv_setpv($arg, addr_str); } hyperic-sigar-1.6.4+dfsg/bindings/php/000077500000000000000000000000001210132627500175725ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/php/config.m4000066400000000000000000000011011210132627500212720ustar00rootroot00000000000000PHP_ARG_ENABLE(sigar, whether to enable Sigar support, [ --enable-sigar Enable Sigar support]) if test "$PHP_SIGAR" = "yes"; then AC_DEFINE(HAVE_SIGAR, 1, [Whether you have Sigar]) dnl hardwired for the moment SIGAR_LIBNAME=sigar-universal-macosx SIGAR_INSTALLDIR=../java/sigar-bin SIGAR_LIB_DIR=$SIGAR_INSTALLDIR/lib SIGAR_INC_DIR=$SIGAR_INSTALLDIR/include PHP_ADD_LIBRARY_WITH_PATH($SIGAR_LIBNAME, $SIGAR_LIB_DIR, SIGAR_SHARED_LIBADD) PHP_ADD_INCLUDE($SIGAR_INC_DIR) PHP_NEW_EXTENSION(sigar, php_sigar.c, $ext_shared) PHP_SUBST(SIGAR_SHARED_LIBADD) fi hyperic-sigar-1.6.4+dfsg/bindings/php/examples/000077500000000000000000000000001210132627500214105ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/php/examples/free.php000066400000000000000000000006331210132627500230440ustar00rootroot00000000000000mem(); $swap = $sigar->swap(); echo "\tTotal\tUsed\tFree\n"; echo "Mem: " . ($mem->total() / 1024) . "\t" . ($mem->used() / 1024) . "\t" . ($mem->free() / 1024) . "\n"; echo "Swap: " . ($swap->total() / 1024) . "\t" . ($swap->used() / 1024) . "\t" . ($swap->free() / 1024) . "\n"; echo "RAM: " . $mem->ram() . "MB\n"; hyperic-sigar-1.6.4+dfsg/bindings/php/php_sigar.c000066400000000000000000000110231210132627500217070ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_sigar.h" #include "sigar.h" #include "sigar_fileinfo.h" #include "sigar_format.h" #define PHP_SIGAR_RETURN_STRING(s) \ RETURN_STRING(s, 1) static char *php_sigar_net_address_to_string(sigar_net_address_t address) { char addr_str[SIGAR_INET6_ADDRSTRLEN]; sigar_net_address_to_string(NULL, &address, addr_str); return estrdup(addr_str); } #define PHP_SIGAR_RETURN_NETADDR(a) \ RETURN_STRING(php_sigar_net_address_to_string(a), 0) #define zSIGAR_PARSE_PID \ zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pid) #define zSIGAR_PARSE_NAME \ zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) #define zSIGAR_OBJ \ (((php_sigar_obj_t *)zend_object_store_get_object(getThis() TSRMLS_CC))->ptr) #define zSIGAR \ sigar_t *sigar = (sigar_t *)zSIGAR_OBJ typedef struct { zend_object std; void *ptr; } php_sigar_obj_t; static void php_sigar_obj_dtor(void *object TSRMLS_DC) { php_sigar_obj_t *intern = (php_sigar_obj_t *)object; zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->ptr) { efree(intern->ptr); } efree(intern); } static zend_object_value php_sigar_ctor(zend_objects_free_object_storage_t dtor, zend_object_handlers *handlers, php_sigar_obj_t **obj, zend_class_entry *class_type) { php_sigar_obj_t *intern = emalloc(sizeof(*intern)); zend_object_value retval; memset(intern, 0, sizeof(*intern)); if (obj) { *obj = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); retval.handle = zend_objects_store_put(intern, NULL, dtor, NULL TSRMLS_CC); retval.handlers = handlers; return retval; } static void php_sigar_close(void *object TSRMLS_DC) { php_sigar_obj_t *intern = (php_sigar_obj_t *)object; if (!intern) { return; } if (intern->ptr) { sigar_close((sigar_t *)intern->ptr); intern->ptr = NULL; } php_sigar_obj_dtor(object); } static zend_object_handlers php_sigar_object_handlers; static zend_object_value php_sigar_new(zend_class_entry *class_type TSRMLS_DC) { php_sigar_obj_t *intern; zend_object_value retval = php_sigar_ctor(php_sigar_close, &php_sigar_object_handlers, &intern, class_type); sigar_open(&((sigar_t *)intern->ptr)); return retval; } static php_sigar_obj_t *php_sigar_obj_new(char *name, zval *object TSRMLS_DC) { zend_class_entry **ce; zend_lookup_class(name, strlen(name), &ce TSRMLS_CC); Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, *ce); object->refcount = 1; object->is_ref = 0; return (php_sigar_obj_t *)zend_object_store_get_object(object TSRMLS_CC); } #define PHP_SIGAR_INIT_HANDLERS(handlers) \ memcpy(&handlers, zend_get_std_object_handlers(), sizeof(handlers)); \ handlers.clone_obj = NULL #include "php_sigar_generated.c" static zend_function_entry php_sigar_class_functions[] = { PHP_SIGAR_FUNCTIONS {NULL, NULL, NULL} }; static PHP_MINIT_FUNCTION(sigar) { zend_class_entry ce; PHP_SIGAR_INIT_HANDLERS(php_sigar_object_handlers); INIT_CLASS_ENTRY(ce, "Sigar", php_sigar_class_functions); ce.create_object = php_sigar_new; zend_register_internal_class(&ce TSRMLS_CC); PHP_SIGAR_INIT; return SUCCESS; } zend_function_entry php_sigar_functions[] = { {NULL, NULL, NULL} }; zend_module_entry sigar_module_entry = { STANDARD_MODULE_HEADER, "sigar", php_sigar_functions, PHP_MINIT(sigar), NULL, NULL, NULL, NULL, "0.1", STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_SIGAR ZEND_GET_MODULE(sigar) #endif hyperic-sigar-1.6.4+dfsg/bindings/php/php_sigar.h000066400000000000000000000012721210132627500217210ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PHP_SIGAR_H #define PHP_SIGAR_H 1 extern zend_module_entry sigar_module_entry; #endif hyperic-sigar-1.6.4+dfsg/bindings/python/000077500000000000000000000000001210132627500203245ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/python/_sigar.c000066400000000000000000000203051210132627500217340ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include "sigar.h" #include "sigar_fileinfo.h" #include "sigar_format.h" #define PySigarString_FromNetAddr(a) pysigar_net_address_to_string(&a) #define PySigarInt_FromChar(c) PyInt_FromLong((int)c) #define PySigar_ParsePID \ if (!PyArg_ParseTuple(args, "i", &pid)) return NULL #define PySigar_ParseName \ if (!PyArg_ParseTuple(args, "s", &name, &name_len)) return NULL #define PySIGAR_OBJ ((PySigarObject *)self) #define PySIGAR ((sigar_t *)PySIGAR_OBJ->ptr) #define PySigar_new(t) PyType_GenericAlloc(&t, 0) #define PySigar_TPFLAGS Py_TPFLAGS_DEFAULT #define PySigar_AddType(name, t) \ if (PyType_Ready(&t) == 0) { \ Py_INCREF(&t); \ PyModule_AddObject(module, name, (PyObject *)&t); \ } #define PySigar_Croak() PyErr_SetString(PyExc_ValueError, sigar_strerror(sigar, status)) typedef struct { PyObject_HEAD void *ptr; } PySigarObject; static PyTypeObject pysigar_PySigarType; static void pysigar_free(PyObject *self) { if (PySIGAR_OBJ->ptr) { if (self->ob_type == &pysigar_PySigarType) { sigar_close(PySIGAR); } else { free(PySIGAR_OBJ->ptr); } PySIGAR_OBJ->ptr = NULL; } self->ob_type->tp_free((PyObject *)self); } static PyObject *pysigar_net_address_to_string(sigar_net_address_t *address) { char addr_str[SIGAR_INET6_ADDRSTRLEN]; sigar_net_address_to_string(NULL, address, addr_str); return PyString_FromString(addr_str); } #include "_sigar_generated.c" static PyObject *pysigar_open(PyObject *pyself, PyObject *args) { PyObject *self = PySigar_new(pysigar_PySigarType); sigar_open((sigar_t **)&PySIGAR_OBJ->ptr); return self; } static PyObject *pysigar_close(PyObject *self, PyObject *args) { if (PySIGAR_OBJ->ptr) { sigar_close(PySIGAR); PySIGAR_OBJ->ptr = NULL; } Py_INCREF(Py_None); return Py_None; } static int pysigar_parse_uint64(PyObject *args, sigar_uint64_t *val) { PyObject *obj; if (!PyArg_ParseTuple(args, "O", &obj)) { return !SIGAR_OK; } if (PyInt_Check(obj)) { *val = PyInt_AsUnsignedLongLongMask(obj); } else if (PyLong_Check(obj)) { *val = PyLong_AsUnsignedLongLong(obj); } else { return !SIGAR_OK; } return SIGAR_OK; } static PyObject *pysigar_new_strlist(char **data, unsigned long number) { unsigned long i; PyObject *av; if (!(av = PyTuple_New(number))) { return NULL; } for (i=0; iptr = ent; PyTuple_SET_ITEM(av, i, self); } return av; } static PyObject *pysigar_file_system_list(PyObject *self, PyObject *args) { int status; sigar_t *sigar = PySIGAR; sigar_file_system_list_t fslist; PyObject *RETVAL; status = sigar_file_system_list_get(sigar, &fslist); if (status != SIGAR_OK) { PySigar_Croak(); return NULL; } RETVAL = pysigar_new_list((char *)&fslist.data[0], fslist.number, sizeof(*fslist.data), &pysigar_PySigarFileSystemType); sigar_file_system_list_destroy(sigar, &fslist); return RETVAL; } static PyObject *pysigar_net_interface_list(PyObject *self, PyObject *args) { int status; sigar_t *sigar = PySIGAR; sigar_net_interface_list_t iflist; PyObject *RETVAL; status = sigar_net_interface_list_get(sigar, &iflist); if (status != SIGAR_OK) { PySigar_Croak(); return NULL; } RETVAL = pysigar_new_strlist(iflist.data, iflist.number); sigar_net_interface_list_destroy(sigar, &iflist); return RETVAL; } static PyObject *pysigar_format_size(PyObject *self, PyObject *args) { char buffer[56]; sigar_uint64_t size; if (pysigar_parse_uint64(args, &size) == SIGAR_OK) { return PyString_FromString(sigar_format_size(size, buffer)); } else { return NULL; } } static PyMethodDef pysigar_methods[] = { { "close", pysigar_close, METH_NOARGS, NULL }, { "net_interface_list", pysigar_net_interface_list, METH_NOARGS, NULL }, { "file_system_list", pysigar_file_system_list, METH_NOARGS, NULL }, PY_SIGAR_METHODS {NULL} }; static PyTypeObject pysigar_PySigarType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "Sigar", /*tp_name*/ sizeof(PySigarObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ pysigar_free, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ PySigar_TPFLAGS, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ pysigar_methods, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0 /*tp_new*/ }; static PyMethodDef pysigar_module_methods[] = { { "open", pysigar_open, METH_NOARGS, NULL }, { "format_size", pysigar_format_size, METH_VARARGS, NULL }, {NULL} }; #define PY_SIGAR_CONST_INT(name) \ PyDict_SetItemString(dict, #name, o=PyInt_FromLong(SIGAR_##name)); Py_DECREF(o) #define PY_SIGAR_CONST_STR(name) \ PyDict_SetItemString(dict, #name, o=PyString_FromString(SIGAR_##name)); Py_DECREF(o) static void init_pysigar_constants(PyObject *dict) { PyObject *o; PY_SIGAR_CONST_INT(FIELD_NOTIMPL); PY_SIGAR_CONST_INT(IFF_UP); PY_SIGAR_CONST_INT(IFF_BROADCAST); PY_SIGAR_CONST_INT(IFF_DEBUG); PY_SIGAR_CONST_INT(IFF_LOOPBACK); PY_SIGAR_CONST_INT(IFF_POINTOPOINT); PY_SIGAR_CONST_INT(IFF_NOTRAILERS); PY_SIGAR_CONST_INT(IFF_RUNNING); PY_SIGAR_CONST_INT(IFF_NOARP); PY_SIGAR_CONST_INT(IFF_PROMISC); PY_SIGAR_CONST_INT(IFF_ALLMULTI); PY_SIGAR_CONST_INT(IFF_MULTICAST); PY_SIGAR_CONST_STR(NULL_HWADDR); } PyMODINIT_FUNC init_sigar(void) { PyObject *module = Py_InitModule("_sigar", pysigar_module_methods); PySigar_AddType("Sigar", pysigar_PySigarType); PY_SIGAR_ADD_TYPES; init_pysigar_constants(PyModule_GetDict(module)); } hyperic-sigar-1.6.4+dfsg/bindings/python/examples/000077500000000000000000000000001210132627500221425ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/python/examples/df.py000066400000000000000000000022371210132627500231110ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os, sigar; sg = sigar.open() fslist = sg.file_system_list() def format_size(size): return sigar.format_size(size * 1024) print 'Filesystem\tSize\tUsed\tAvail\tUse%\tMounted on\tType\n' for fs in fslist: dir_name = fs.dir_name() usage = sg.file_system_usage(dir_name) total = usage.total() used = total - usage.free() avail = usage.avail() pct = usage.use_percent() * 100 if pct == 0.0: pct = '-' print fs.dev_name(), format_size(total), format_size(used), format_size(avail),\ pct, dir_name, fs.sys_type_name(), '/', fs.type_name() hyperic-sigar-1.6.4+dfsg/bindings/python/examples/free.py000066400000000000000000000016401210132627500234360ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os, sigar; sg = sigar.open() mem = sg.mem() swap = sg.swap() sg.close() print "\tTotal\tUsed\tFree" print "Mem:\t",\ (mem.total() / 1024), \ (mem.used() / 1024), \ (mem.free() / 1024) print "Swap:\t", \ (swap.total() / 1024), \ (swap.used() / 1024), \ (swap.free() / 1024) print "RAM:\t", mem.ram(), "MB" hyperic-sigar-1.6.4+dfsg/bindings/python/setup.py000066400000000000000000000020201210132627500220300ustar00rootroot00000000000000#!/usr/bin/env python # # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from distutils.core import setup, Extension _sigar = Extension( "_sigar", ["_sigar.c"], include_dirs = ['../java/sigar-bin/include'], extra_compile_args = ['-Wall'], libraries=['sigar-universal-macosx'], library_dirs=['../java/sigar-bin/lib'], extra_link_args=[], define_macros=[], undef_macros=[]) setup(name="pysigar", version="0.1", py_modules = ['sigar'], ext_modules=[_sigar]) hyperic-sigar-1.6.4+dfsg/bindings/python/sigar.py000066400000000000000000000011371210132627500220050ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from _sigar import * hyperic-sigar-1.6.4+dfsg/bindings/ruby/000077500000000000000000000000001210132627500177645ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/000077500000000000000000000000001210132627500216025ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/cpu_info.rb000066400000000000000000000016051210132627500237330ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' sigar = Sigar.new infos = sigar.cpu_info_list num = infos.length puts num.to_s + " total CPUs.." infos.each do |info| puts "Vendor........" + info.vendor puts "Model........." + info.model puts "Mhz..........." + info.mhz.to_s puts "Cache size...." + info.cache_size.to_s end hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/df.rb000066400000000000000000000023011210132627500225140ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' def format_size(size) return Sigar.format_size(size * 1024) end sigar = Sigar.new fslist = sigar.file_system_list puts "Filesystem\tSize\tUsed\tAvail\tUse%\tMounted on\tType\n" fslist.each do |fs| dir_name = fs.dir_name usage = sigar.file_system_usage(dir_name) total = usage.total used = total - usage.free avail = usage.avail pct = usage.use_percent * 100 puts fs.dev_name + "\t" + format_size(total) + "\t" + format_size(used) + "\t" + format_size(avail) + "\t" + (pct == 0.0 ? '-' : pct.to_s) + "\t" + dir_name + "\t" + fs.sys_type_name + "/" + fs.type_name end hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/free.rb000066400000000000000000000017121210132627500230510ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' sigar = Sigar.new mem = sigar.mem swap = sigar.swap puts "\tTotal\tUsed\tFree" puts "Mem: " + (mem.total / 1024).to_s + "\t" + (mem.used / 1024).to_s + "\t" + (mem.free/ 1024).to_s puts "Swap: " + (swap.total / 1024).to_s + "\t" + (swap.used / 1024).to_s + "\t" + (swap.free/ 1024).to_s puts "RAM: " + mem.ram.to_s + "MB"; hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/ifconfig.rb000066400000000000000000000043101210132627500237110ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' sigar = Sigar.new iflist = sigar.net_interface_list iflist.each do |ifname| ifconfig = sigar.net_interface_config(ifname) flags = ifconfig.flags encap = ifconfig.type hwaddr = ifconfig.hwaddr if hwaddr == Sigar::NULL_HWADDR hwaddr = "" else hwaddr = " HWaddr " + hwaddr end puts ifname + "\t" + "Link encap:" + encap + hwaddr if (flags & Sigar::IFF_POINTOPOINT) != 0 ptp = " P-t-P:" + ifconfig.destination else ptp = "" end if (flags & Sigar::IFF_BROADCAST) != 0 bcast = " Bcast:" + ifconfig.broadcast else bcast = "" end puts "\t" + "inet addr:" + ifconfig.address + ptp + bcast + " Mask:" + ifconfig.netmask puts "\t" + Sigar.net_interface_flags_to_s(flags) + " MTU:" + ifconfig.mtu.to_s + " Metric:" + ifconfig.metric.to_s ifstat = sigar.net_interface_stat(ifname) puts "\t" + "RX packets:" + ifstat.rx_packets.to_s + " errors:" + ifstat.rx_errors.to_s + " dropped:" + ifstat.rx_dropped.to_s + " overruns:" + ifstat.rx_overruns.to_s + " frame:" + ifstat.rx_frame.to_s puts "\t" + "TX packets:" + ifstat.tx_packets.to_s + " errors:" + ifstat.tx_errors.to_s + " dropped:" + ifstat.tx_dropped.to_s + " overruns:" + ifstat.tx_overruns.to_s + " carrier:" + ifstat.tx_carrier.to_s puts "\t" + "collisions:" + ifstat.tx_collisions.to_s rx_bytes = ifstat.rx_bytes tx_bytes = ifstat.tx_bytes print "\t" + "RX bytes:" + rx_bytes.to_s + " (" + Sigar.format_size(rx_bytes) + ")" + " " + "TX bytes:" + tx_bytes.to_s + " (" + Sigar.format_size(tx_bytes) + ")" + "\n"; end hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/netstat.rb000066400000000000000000000036221210132627500236140ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' require 'socket' #XXX this example is incomplete wrt: #../../java/src/org/hyperic/sigar/cmd/Netstat.java is_numeric = false flags = Sigar::NETCONN_CLIENT|Sigar::NETCONN_SERVER flags |= Sigar::NETCONN_TCP def format_port(sigar, proto, port, is_numeric) if port == 0 return "*" end if !is_numeric service = sigar.net_services_name(proto, port) if service != nil return service end end port.to_s end def format_address(sigar, proto, ip, portnum, is_numeric) port = format_port(sigar, proto, portnum, is_numeric) address = "" if ip == "0.0.0.0" || ip == "::" address = "*" elsif is_numeric address = ip.to_s else begin name = Socket.gethostbyname(ip) address = name[0] rescue SocketError address = ip.to_s end end return address + ":" + port end sigar = Sigar.new connections = sigar.net_connection_list(flags) puts "Proto\tLocal Address\tForeign Address\tState" connections.each do |conn| proto = Sigar.net_connection_type_to_s(conn.type) state = Sigar.net_connection_state_to_s(conn.state) local = format_address(sigar, conn.type, conn.local_address, conn.local_port, is_numeric) remote = format_address(sigar, conn.type, conn.remote_address, conn.remote_port, is_numeric) puts proto + "\t" + local + "\t" + remote + "\t" + state end hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/pargs.rb000066400000000000000000000015501210132627500232440ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' def output(sigar, pid) args = sigar.proc_args(pid) exe = sigar.proc_exe(pid); puts "exe=" + exe.name puts "cwd=" + exe.cwd args.each do |arg| puts " " + "=>" + arg + "<=" end end sigar = Sigar.new ARGV.each do |pid| output(sigar, pid.to_i) end hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/penv.rb000066400000000000000000000014211210132627500230750ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' def output(sigar, pid) env = sigar.proc_env(pid) env.each do |key, val| puts key + "=" + val end end sigar = Sigar.new ARGV.each do |pid| output(sigar, pid.to_i) end hyperic-sigar-1.6.4+dfsg/bindings/ruby/examples/who.rb000066400000000000000000000014641210132627500227310ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbsigar' def format_time(who) return Time.at(who.time).strftime("%b %e %H:%M") end sigar = Sigar.new whos = sigar.who_list whos.each do |who| puts who.user + "\t" + who.device + "\t" + format_time(who) + who.host end hyperic-sigar-1.6.4+dfsg/bindings/ruby/extconf.rb000066400000000000000000000016651210132627500217670ustar00rootroot00000000000000# # Copyright (c) 2007 Hyperic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'mkmf' extension_name = 'rbsigar' installdir = '../java/sigar-bin' #XXX hardwired for the moment libname = 'sigar-universal-macosx' $CPPFLAGS += ' -I' + installdir + '/include' $LOCAL_LIBS += '-L' + installdir + '/lib -l' + libname dir_config(extension_name) system('perl -Mlib=.. -MSigarWrapper -e generate Ruby .') create_makefile(extension_name) hyperic-sigar-1.6.4+dfsg/bindings/ruby/rbsigar.c000066400000000000000000000307411210132627500215660ustar00rootroot00000000000000/* * Copyright (c) 2007-2008 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. */ #include #include #include "sigar.h" #include "sigar_fileinfo.h" #include "sigar_format.h" #define RB_SIGAR_CROAK rb_raise(rb_eArgError, "%s", sigar_strerror(sigar, status)) #define NUM2PID NUM2UINT static sigar_t *rb_sigar_get(VALUE obj) { sigar_t *sigar; Data_Get_Struct(obj, sigar_t, sigar); return sigar; } static void rb_sigar_free(void *obj) { free(obj); } static void rb_sigar_close(void *obj) { sigar_close((sigar_t *)obj); } static VALUE rb_sigar_new(VALUE module) { sigar_t *sigar; sigar_open(&sigar); return Data_Wrap_Struct(module, 0, rb_sigar_close, sigar); } static VALUE rb_sigar_format_size(VALUE rclass, VALUE size) { char buffer[56]; return rb_str_new2(sigar_format_size(NUM2LL(size), buffer)); } static VALUE rb_sigar_net_interface_flags_to_s(VALUE rclass, VALUE flags) { char buffer[1024]; return rb_str_new2(sigar_net_interface_flags_to_string(NUM2LL(flags), buffer)); } static VALUE rb_sigar_net_connection_type_to_s(VALUE rclass, VALUE type) { return rb_str_new2(sigar_net_connection_type_get(NUM2INT(type))); } static VALUE rb_sigar_net_connection_state_to_s(VALUE rclass, VALUE state) { return rb_str_new2(sigar_net_connection_state_get(NUM2INT(state))); } static VALUE rb_sigar_net_address_to_string(sigar_net_address_t *address) { char addr_str[SIGAR_INET6_ADDRSTRLEN]; sigar_net_address_to_string(NULL, address, addr_str); return rb_str_new2(addr_str); } #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, int size, VALUE rclass) { unsigned long i; VALUE av = rb_ary_new2(number); for (i=0; ilen; switch (len) { case 4: address->family = SIGAR_AF_INET; break; case 4*4: address->family = SIGAR_AF_INET6; break; default: return EINVAL; } memcpy(RSTRING(bytes)->ptr, &address->addr.in6, len); return SIGAR_OK; } static VALUE rb_cSigarNetStat; static VALUE rb_sigar_net_stat_get(VALUE obj, VALUE flags, VALUE bytes, int port) { int status; int has_port = (port != -1); sigar_t *sigar = rb_sigar_get(obj); sigar_net_stat_t *RETVAL = malloc(sizeof(*RETVAL)); sigar_net_address_t address; if (has_port) { status = rb_sigar_str2net_address(bytes, &address); if (status == SIGAR_OK) { status = sigar_net_stat_port_get(sigar, RETVAL, NUM2INT(flags), &address, port); } } else { status = sigar_net_stat_get(sigar, RETVAL, NUM2INT(flags)); } if (status != SIGAR_OK) { free(RETVAL); RB_SIGAR_CROAK; } return Data_Wrap_Struct(rb_cSigarNetStat, 0, rb_sigar_free, RETVAL); } static VALUE rb_sigar_net_stat(VALUE obj, VALUE flags) { return rb_sigar_net_stat_get(obj, flags, Qnil, -1); } static VALUE rb_sigar_net_stat_port(VALUE obj, VALUE flags, VALUE address, VALUE port) { return rb_sigar_net_stat_get(obj, flags, address, NUM2INT(port)); } static VALUE rb_sigar_NetStat_tcp_states(VALUE self) { sigar_net_stat_t *net_stat; Data_Get_Struct(self, sigar_net_stat_t, net_stat); return rb_sigar_new_intlist(&net_stat->tcp_states[0], SIGAR_TCP_UNKNOWN); } static VALUE rb_cSigarNetConnection; static VALUE rb_sigar_net_connection_list(VALUE obj, VALUE flags) { int status; unsigned int i; sigar_t *sigar = rb_sigar_get(obj); sigar_net_connection_list_t connlist; VALUE RETVAL; status = sigar_net_connection_list_get(sigar, &connlist, NUM2UINT(flags)); if (status != SIGAR_OK) { RB_SIGAR_CROAK; } RETVAL = rb_sigar_new_list((char *)&connlist.data[0], connlist.number, sizeof(*connlist.data), rb_cSigarNetConnection); sigar_net_connection_list_destroy(sigar, &connlist); return RETVAL; } static VALUE rb_sigar_net_services_name(VALUE obj, VALUE protocol, VALUE port) { sigar_t *sigar = rb_sigar_get(obj); char *name; if ((name = sigar_net_services_name_get(sigar, NUM2UINT(protocol), NUM2UINT(port)))) { return rb_str_new2(name); } else { return Qnil; } } static VALUE rb_cSigarCpuInfo; static VALUE rb_sigar_cpu_info_list(VALUE obj) { int status; sigar_t *sigar = rb_sigar_get(obj); sigar_cpu_info_list_t cpu_infos; VALUE RETVAL; status = sigar_cpu_info_list_get(sigar, &cpu_infos); if (status != SIGAR_OK) { RB_SIGAR_CROAK; } RETVAL = rb_sigar_new_list((char *)&cpu_infos.data[0], cpu_infos.number, sizeof(*cpu_infos.data), rb_cSigarCpuInfo); sigar_cpu_info_list_destroy(sigar, &cpu_infos); return RETVAL; } static VALUE rb_cSigarCpuPerc; static VALUE rb_cSigarFileSystem; static VALUE rb_sigar_file_system_list(VALUE obj) { int status; sigar_t *sigar = rb_sigar_get(obj); sigar_file_system_list_t fslist; VALUE RETVAL; status = sigar_file_system_list_get(sigar, &fslist); if (status != SIGAR_OK) { RB_SIGAR_CROAK; } RETVAL = rb_sigar_new_list((char *)&fslist.data[0], fslist.number, sizeof(*fslist.data), rb_cSigarFileSystem); sigar_file_system_list_destroy(sigar, &fslist); return RETVAL; } static VALUE rb_cSigarWho; static VALUE rb_sigar_who_list(VALUE obj) { int status; sigar_t *sigar = rb_sigar_get(obj); sigar_who_list_t list; VALUE RETVAL; status = sigar_who_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_cSigarWho); sigar_who_list_destroy(sigar, &list); return RETVAL; } static VALUE rb_cSigarNetRoute; static VALUE rb_sigar_net_route_list(VALUE obj) { int status; sigar_t *sigar = rb_sigar_get(obj); sigar_net_route_list_t list; VALUE RETVAL; status = sigar_net_route_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_cSigarNetRoute); sigar_net_route_list_destroy(sigar, &list); return RETVAL; } static VALUE rb_sigar_proc_args(VALUE obj, VALUE pid) { int status; sigar_t *sigar = rb_sigar_get(obj); sigar_proc_args_t args; VALUE RETVAL; status = sigar_proc_args_get(sigar, NUM2PID(pid), &args); if (status != SIGAR_OK) { RB_SIGAR_CROAK; } RETVAL = rb_sigar_new_strlist(args.data, args.number); sigar_proc_args_destroy(sigar, &args); return RETVAL; } static int rb_sigar_env_getall(void *data, const char *key, int klen, char *val, int vlen) { rb_hash_aset(*((VALUE*)data), rb_str_new(key, klen), rb_str_new(val, vlen)); return SIGAR_OK; } static VALUE rb_sigar_proc_env(VALUE obj, VALUE pid) { int status; sigar_t *sigar = rb_sigar_get(obj); sigar_proc_env_t procenv; VALUE RETVAL = rb_hash_new(); procenv.type = SIGAR_PROC_ENV_ALL; procenv.env_getter = rb_sigar_env_getall; procenv.data = &RETVAL; status = sigar_proc_env_get(sigar, NUM2PID(pid), &procenv); if (status != SIGAR_OK) { RB_SIGAR_CROAK; } return RETVAL; } #include "./rbsigar_generated.rx" #define RB_SIGAR_CONST_INT(name) \ rb_define_const(rclass, #name, INT2FIX(SIGAR_##name)) #define RB_SIGAR_CONST_STR(name) \ rb_define_const(rclass, #name, rb_obj_freeze(rb_str_new2(SIGAR_##name))) static void Init_rbsigar_constants(VALUE rclass) { RB_SIGAR_CONST_INT(IFF_UP); RB_SIGAR_CONST_INT(IFF_BROADCAST); RB_SIGAR_CONST_INT(IFF_DEBUG); RB_SIGAR_CONST_INT(IFF_LOOPBACK); RB_SIGAR_CONST_INT(IFF_POINTOPOINT); RB_SIGAR_CONST_INT(IFF_NOTRAILERS); RB_SIGAR_CONST_INT(IFF_RUNNING); RB_SIGAR_CONST_INT(IFF_NOARP); RB_SIGAR_CONST_INT(IFF_PROMISC); RB_SIGAR_CONST_INT(IFF_ALLMULTI); RB_SIGAR_CONST_INT(IFF_MULTICAST); RB_SIGAR_CONST_INT(NETCONN_CLIENT); RB_SIGAR_CONST_INT(NETCONN_SERVER); RB_SIGAR_CONST_INT(NETCONN_TCP); RB_SIGAR_CONST_INT(NETCONN_UDP); RB_SIGAR_CONST_INT(NETCONN_RAW); RB_SIGAR_CONST_INT(NETCONN_UNIX); RB_SIGAR_CONST_INT(TCP_ESTABLISHED); RB_SIGAR_CONST_INT(TCP_SYN_SENT); RB_SIGAR_CONST_INT(TCP_SYN_RECV); RB_SIGAR_CONST_INT(TCP_FIN_WAIT1); RB_SIGAR_CONST_INT(TCP_FIN_WAIT2); RB_SIGAR_CONST_INT(TCP_TIME_WAIT); RB_SIGAR_CONST_INT(TCP_CLOSE); RB_SIGAR_CONST_INT(TCP_CLOSE_WAIT); RB_SIGAR_CONST_INT(TCP_LAST_ACK); RB_SIGAR_CONST_INT(TCP_LISTEN); RB_SIGAR_CONST_INT(TCP_CLOSING); RB_SIGAR_CONST_INT(TCP_IDLE); RB_SIGAR_CONST_INT(TCP_BOUND); RB_SIGAR_CONST_INT(TCP_UNKNOWN); RB_SIGAR_CONST_STR(NULL_HWADDR); } void Init_rbsigar(void) { VALUE rclass = rb_define_class("Sigar", rb_cObject); rb_define_method(rclass, "cpu_info_list", rb_sigar_cpu_info_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_interface_list", rb_sigar_net_interface_list, 0); rb_define_method(rclass, "net_services_name", rb_sigar_net_services_name, 2); 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_route_list", rb_sigar_net_route_list, 0); rb_define_method(rclass, "who_list", rb_sigar_who_list, 0); rb_define_method(rclass, "proc_args", rb_sigar_proc_args, 1); rb_define_method(rclass, "proc_env", rb_sigar_proc_env, 1); 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, "net_interface_flags_to_s", rb_sigar_net_interface_flags_to_s, 1); rb_define_singleton_method(rclass, "net_connection_type_to_s", rb_sigar_net_connection_type_to_s, 1); rb_define_singleton_method(rclass, "net_connection_state_to_s", rb_sigar_net_connection_state_to_s, 1); Init_rbsigar_constants(rclass); /* generated */ rb_sigar_define_module_methods(rclass); rb_define_method(rb_cSigarNetStat, "tcp_states", rb_sigar_NetStat_tcp_states, 0); } hyperic-sigar-1.6.4+dfsg/docs/000077500000000000000000000000001210132627500161365ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/000077500000000000000000000000001210132627500175455ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/allclasses-frame.html000066400000000000000000000502251210132627500236550ustar00rootroot00000000000000 All Classes (Sigar API) All Classes
CollectionCompleter
ConnectParams
Cpu
CpuInfo
CpuInfo
CpuPerc
CpuTimer
CurrentProcessSummary
Df
DirStat
DirUsage
DiskUsage
Du
EventLog
EventLogNotification
EventLogRecord
EventLogTail
EventLogThread
FileAttrs
FileCompleter
FileInfo
FileSystem
FileSystemMap
FileSystemUsage
FileTail
FileVersion
FileVersionInfo
FileWatcher
FileWatcherThread
Free
Getline
GetlineCompleter
Humidor
Ifconfig
Iostat
IteratorIterator
Kill
LocaleInfo
Ls
MalformedQueryException
Mem
MemWatch
MetaBase
MultiProcCpu
MultiProcMem
MultiPs
MultiwordShellCommand
NetConnection
NetFlags
NetInfo
NetInfo
NetInterfaceConfig
NetInterfaceStat
NetRoute
NetServices
Netstat
NetStat
NfsClientV2
NfsClientV3
NfsFileSystem
NfsServerV2
NfsServerV3
Nfsstat
NfsUnreachableException
NormalQuitCommandException
OperatingSystem
Pdh
Pidof
PrintfFormat
ProcCpu
ProcCred
ProcCredName
ProcessFinder
ProcessQuery
ProcessQueryCompleter
ProcessQueryFactory
ProcExe
ProcFd
ProcFileInfo
ProcFileMirror
ProcInfo
ProcMem
ProcModuleInfo
ProcStat
ProcState
ProcTime
ProcUtil
Ps
QueryLoadException
ReferenceMap
ReferenceMap.MapReference
ReferenceMap.SoftValue
ReferenceMap.WeakValue
RegistryKey
ResourceLimit
Route
RPC
Runner
Service
ServiceConfig
Shell
ShellBase
ShellCommand_alias
ShellCommand_get
ShellCommand_help
ShellCommand_quit
ShellCommand_set
ShellCommand_sleep
ShellCommand_source
ShellCommandBase
ShellCommandExecException
ShellCommandHandler
ShellCommandInitException
ShellCommandMapper
ShellCommandUsageException
ShellIntHandler
ShowArgs
ShowEnv
Sigar
SigarCommandBase
SigarException
SigarFileNotFoundException
SigarInvoker
SigarLoader
SigarLog
SigarNotImplementedException
SigarPermissionDeniedException
SigarProcessQuery
SigarProxy
SigarProxyCache
SIGINT
StringPattern
SudoFileInputStream
Swap
SysInfo
SysInfo
Tail
Tcp
ThreadCpu
Time
Top
Ulimit
Uptime
Uptime
Version
VM
VMControlLibrary
VMwareException
VMwareServer
Watch
WeakReferenceMap
Who
Who
Win32
Win32Exception
Win32Service
hyperic-sigar-1.6.4+dfsg/docs/javadoc/allclasses-noframe.html000066400000000000000000000421451210132627500242140ustar00rootroot00000000000000 All Classes (Sigar API) All Classes
CollectionCompleter
ConnectParams
Cpu
CpuInfo
CpuInfo
CpuPerc
CpuTimer
CurrentProcessSummary
Df
DirStat
DirUsage
DiskUsage
Du
EventLog
EventLogNotification
EventLogRecord
EventLogTail
EventLogThread
FileAttrs
FileCompleter
FileInfo
FileSystem
FileSystemMap
FileSystemUsage
FileTail
FileVersion
FileVersionInfo
FileWatcher
FileWatcherThread
Free
Getline
GetlineCompleter
Humidor
Ifconfig
Iostat
IteratorIterator
Kill
LocaleInfo
Ls
MalformedQueryException
Mem
MemWatch
MetaBase
MultiProcCpu
MultiProcMem
MultiPs
MultiwordShellCommand
NetConnection
NetFlags
NetInfo
NetInfo
NetInterfaceConfig
NetInterfaceStat
NetRoute
NetServices
Netstat
NetStat
NfsClientV2
NfsClientV3
NfsFileSystem
NfsServerV2
NfsServerV3
Nfsstat
NfsUnreachableException
NormalQuitCommandException
OperatingSystem
Pdh
Pidof
PrintfFormat
ProcCpu
ProcCred
ProcCredName
ProcessFinder
ProcessQuery
ProcessQueryCompleter
ProcessQueryFactory
ProcExe
ProcFd
ProcFileInfo
ProcFileMirror
ProcInfo
ProcMem
ProcModuleInfo
ProcStat
ProcState
ProcTime
ProcUtil
Ps
QueryLoadException
ReferenceMap
ReferenceMap.MapReference
ReferenceMap.SoftValue
ReferenceMap.WeakValue
RegistryKey
ResourceLimit
Route
RPC
Runner
Service
ServiceConfig
Shell
ShellBase
ShellCommand_alias
ShellCommand_get
ShellCommand_help
ShellCommand_quit
ShellCommand_set
ShellCommand_sleep
ShellCommand_source
ShellCommandBase
ShellCommandExecException
ShellCommandHandler
ShellCommandInitException
ShellCommandMapper
ShellCommandUsageException
ShellIntHandler
ShowArgs
ShowEnv
Sigar
SigarCommandBase
SigarException
SigarFileNotFoundException
SigarInvoker
SigarLoader
SigarLog
SigarNotImplementedException
SigarPermissionDeniedException
SigarProcessQuery
SigarProxy
SigarProxyCache
SIGINT
StringPattern
SudoFileInputStream
Swap
SysInfo
SysInfo
Tail
Tcp
ThreadCpu
Time
Top
Ulimit
Uptime
Uptime
Version
VM
VMControlLibrary
VMwareException
VMwareServer
Watch
WeakReferenceMap
Who
Who
Win32
Win32Exception
Win32Service
hyperic-sigar-1.6.4+dfsg/docs/javadoc/constant-values.html000066400000000000000000002250631210132627500235710ustar00rootroot00000000000000 Constant Field Values (Sigar API)



Constant Field Values


Contents
org.hyperic.*

org.hyperic.sigar.FileInfo
public static final int MODE_GEXECUTE 16
public static final int MODE_GREAD 64
public static final int MODE_GWRITE 32
public static final int MODE_UEXECUTE 256
public static final int MODE_UREAD 1024
public static final int MODE_UWRITE 512
public static final int MODE_WEXECUTE 1
public static final int MODE_WREAD 4
public static final int MODE_WWRITE 2
public static final int TYPE_BLK 4
public static final int TYPE_CHR 3
public static final int TYPE_DIR 2
public static final int TYPE_LNK 6
public static final int TYPE_NOFILE 0
public static final int TYPE_PIPE 5
public static final int TYPE_REG 1
public static final int TYPE_SOCK 7
public static final int TYPE_UNKFILE 8

org.hyperic.sigar.FileSystem
public static final int TYPE_CDROM 5
public static final int TYPE_LOCAL_DISK 2
public static final int TYPE_NETWORK 3
public static final int TYPE_NONE 1
public static final int TYPE_RAM_DISK 4
public static final int TYPE_SWAP 6
public static final int TYPE_UNKNOWN 0

org.hyperic.sigar.FileTail
public static final java.lang.String PROP_USE_SUDO "sigar.tail.sudo"

org.hyperic.sigar.FileWatcherThread
public static final int DEFAULT_INTERVAL 300000

org.hyperic.sigar.NetFlags
public static final java.lang.String ANY_ADDR "0.0.0.0"
public static final java.lang.String ANY_ADDR_V6 "::"
public static final int CONN_CLIENT 1
public static final int CONN_PROTOCOLS 240
public static final int CONN_RAW 64
public static final int CONN_SERVER 2
public static final int CONN_TCP 16
public static final int CONN_UDP 32
public static final int CONN_UNIX 128
public static final int IFF_ALLMULTI 512
public static final int IFF_BROADCAST 2
public static final int IFF_DEBUG 4
public static final int IFF_LOOPBACK 8
public static final int IFF_MULTICAST 2048
public static final int IFF_NOARP 128
public static final int IFF_NOTRAILERS 32
public static final int IFF_POINTOPOINT 16
public static final int IFF_PROMISC 256
public static final int IFF_RUNNING 64
public static final int IFF_SLAVE 4096
public static final int IFF_UP 1
public static final java.lang.String LOOPBACK_ADDRESS "127.0.0.1"
public static final java.lang.String LOOPBACK_ADDRESS_V6 "::1"
public static final java.lang.String LOOPBACK_HOSTNAME "localhost"
public static final java.lang.String NULL_HWADDR "00:00:00:00:00:00"
public static final int RTF_GATEWAY 2
public static final int RTF_HOST 4
public static final int RTF_UP 1
public static final int TCP_BOUND 13
public static final int TCP_CLOSE 7
public static final int TCP_CLOSE_WAIT 8
public static final int TCP_CLOSING 11
public static final int TCP_ESTABLISHED 1
public static final int TCP_FIN_WAIT1 4
public static final int TCP_FIN_WAIT2 5
public static final int TCP_IDLE 12
public static final int TCP_LAST_ACK 9
public static final int TCP_LISTEN 10
public static final int TCP_SYN_RECV 3
public static final int TCP_SYN_SENT 2
public static final int TCP_TIME_WAIT 6
public static final int TCP_UNKNOWN 14

org.hyperic.sigar.OperatingSystem
public static final java.lang.String NAME_AIX "AIX"
public static final java.lang.String NAME_FREEBSD "FreeBSD"
public static final java.lang.String NAME_HPUX "HPUX"
public static final java.lang.String NAME_LINUX "Linux"
public static final java.lang.String NAME_MACOSX "MacOSX"
public static final java.lang.String NAME_NETBSD "NetBSD"
public static final java.lang.String NAME_NETWARE "NetWare"
public static final java.lang.String NAME_OPENBSD "OpenBSD"
public static final java.lang.String NAME_SOLARIS "Solaris"
public static final java.lang.String NAME_WIN32 "Win32"

org.hyperic.sigar.ProcState
public static final char IDLE 68
public static final char RUN 82
public static final char SLEEP 83
public static final char STOP 84
public static final char ZOMBIE 90

org.hyperic.sigar.RPC
public static final int TCP 16
public static final int UDP 32

org.hyperic.sigar.Sigar
public static final java.lang.String BUILD_DATE "04/28/2010 04:59 PM"
public static final long FIELD_NOTIMPL -1L
public static final java.lang.String SCM_REVISION "4b67f57"
public static final java.lang.String VERSION_STRING "1.6.4.0"

org.hyperic.sigar.SigarLoader
public static final java.lang.String PROP_SIGAR_JAR_NAME "sigar.jar.name"

org.hyperic.sigar.SigarProxyCache
public static final int EXPIRE_DEFAULT 30000

org.hyperic.sigar.cmd.Shell
public static final java.lang.String RCFILE_NAME ".sigar_shellrc"

org.hyperic.sigar.shell.ShellBase
public static final java.lang.String PROP_PAGE_SIZE "page.size"

org.hyperic.sigar.vmware.VM
public static final java.lang.String ESX "ESX"
public static final int EXECUTION_STATE_OFF 2
public static final int EXECUTION_STATE_ON 1
public static final int EXECUTION_STATE_STUCK 4
public static final int EXECUTION_STATE_SUSPENDED 3
public static final int EXECUTION_STATE_UNKNOWN 5
public static final java.lang.String GSX "GSX"
public static final int PERM_EXECUTE 1
public static final int PERM_READ 4
public static final int PERM_WRITE 2
public static final int PLATFORM_LINUX 2
public static final int PLATFORM_UNKNOWN 4
public static final int PLATFORM_VMNIX 3
public static final int PLATFORM_WINDOWS 1
public static final int POWEROP_MODE_HARD 1
public static final int POWEROP_MODE_SOFT 2
public static final int POWEROP_MODE_TRYSOFT 3
public static final int PRODINFO_BUILD 3
public static final int PRODINFO_PLATFORM 2
public static final int PRODINFO_PRODUCT 1
public static final int PRODINFO_VERSION_MAJOR 4
public static final int PRODINFO_VERSION_MINOR 5
public static final int PRODINFO_VERSION_REVISION 6
public static final int PRODUCT_ESX 3
public static final int PRODUCT_GSX 2
public static final int PRODUCT_SERVER 4
public static final int PRODUCT_UNKNOWN 5
public static final int PRODUCT_WS 1
public static final java.lang.String SERVER "Server"

org.hyperic.sigar.vmware.VMControlLibrary
public static final java.lang.String PROP_VMCONTROL_SHLIB "vmcontrol.shlib"
public static final java.lang.String REGISTRY_ROOT "SOFTWARE\\VMware, Inc."

org.hyperic.sigar.win32.EventLog
public static final java.lang.String APPLICATION "Application"
public static final int EVENTLOG_AUDIT_FAILURE 16
public static final int EVENTLOG_AUDIT_SUCCESS 8
public static final int EVENTLOG_ERROR_TYPE 1
public static final int EVENTLOG_INFORMATION_TYPE 4
public static final int EVENTLOG_SUCCESS 0
public static final int EVENTLOG_WAIT_INFINITE -1
public static final int EVENTLOG_WARNING_TYPE 2
public static final java.lang.String SECURITY "Security"
public static final java.lang.String SYSTEM "System"

org.hyperic.sigar.win32.EventLogThread
public static final int DEFAULT_INTERVAL 60000

org.hyperic.sigar.win32.LocaleInfo
public static final int LANG_ENGLISH 9
public static final int LOCALE_SENGCOUNTRY 4098
public static final int LOCALE_SENGLANGUAGE 4097

org.hyperic.sigar.win32.Pdh
public static final int BAD_COUNTERNAME -1073738816
public static final int NO_COUNTER -1073738823
public static final int NO_INSTANCE -2147481647
public static final int NO_MACHINE -2147481648
public static final int NO_OBJECT -1073738824
public static final long PERF_TYPE_COUNTER 1024L
public static final long PERF_TYPE_NUMBER 0L
public static final long PERF_TYPE_TEXT 2048L
public static final long PERF_TYPE_ZERO 3072L
public static final java.lang.String PERFLIB_KEY "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib"
public static final int VALID_DATA 0

org.hyperic.sigar.win32.Service
public static final int SERVICE_CONTINUE_PENDING 5
public static final int SERVICE_PAUSE_PENDING 6
public static final int SERVICE_PAUSED 7
public static final int SERVICE_RUNNING 4
public static final int SERVICE_START_PENDING 2
public static final int SERVICE_STOP_PENDING 3
public static final int SERVICE_STOPPED 1

org.hyperic.sigar.win32.ServiceConfig
public static final int ERROR_CRITICAL 3
public static final int ERROR_IGNORE 0
public static final int ERROR_NORMAL 1
public static final int ERROR_SEVERE 2
public static final int START_AUTO 2
public static final int START_BOOT 0
public static final int START_DISABLED 4
public static final int START_MANUAL 3
public static final int START_SYSTEM 1
public static final int TYPE_ADAPTER 4
public static final int TYPE_FILE_SYSTEM_DRIVER 2
public static final int TYPE_INTERACTIVE_PROCESS 256
public static final int TYPE_KERNEL_DRIVER 1
public static final int TYPE_RECOGNIZER_DRIVER 8
public static final int TYPE_WIN32_OWN_PROCESS 16
public static final int TYPE_WIN32_SHARE_PROCESS 32

org.hyperic.sigar.win32.Win32
public static final java.lang.String EXE_EXT ".exe"



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/deprecated-list.html000066400000000000000000000242131210132627500235060ustar00rootroot00000000000000 Deprecated List (Sigar API)

Deprecated API


Contents
Deprecated Classes
org.hyperic.sigar.CurrentProcessSummary
            
org.hyperic.sigar.NetServices
            
 

Deprecated Exceptions
org.hyperic.sigar.ptql.QueryLoadException
            
 

Deprecated Methods
org.hyperic.sigar.CpuPerc.calculate(Cpu, Cpu)
            
org.hyperic.sigar.win32.EventLogThread.getInstance()
            
org.hyperic.sigar.ptql.ProcessQueryFactory.getInstance(String)
            
org.hyperic.sigar.ProcMem.getRss()
            
org.hyperic.sigar.win32.Service.getServiceConfigs(String)
            
org.hyperic.sigar.win32.Pdh.getSingleValue(String)
            
org.hyperic.sigar.win32.EventLogRecord.getStringData()
            
org.hyperic.sigar.ProcMem.getVsize()
            
org.hyperic.sigar.SigarProxyCache.setExpire(SigarProxy, String, int)
            
org.hyperic.sigar.win32.Service.status()
            
org.hyperic.sigar.win32.Service.stopAndWait(long)
            
 

Deprecated Constructors
org.hyperic.sigar.ptql.ProcessFinder(SigarProxy)
            
 



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/help-doc.html000066400000000000000000000216241210132627500221330ustar00rootroot00000000000000 API Help (Sigar API)

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Enums
  • Exceptions
  • Errors
  • Annotation Types

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Annotation Type

Each annotation type has its own separate page with the following sections:

  • Annotation Type declaration
  • Annotation Type description
  • Required Element Summary
  • Optional Element Summary
  • Element Detail

Enum

Each enum has its own separate page with the following sections:

  • Enum declaration
  • Enum description
  • Enum Constant Summary
  • Enum Constant Detail

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.

Constant Field Values

The Constant Field Values page lists the static final fields and their values.

This help file applies to API documentation generated using the standard doclet.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/index-all.html000066400000000000000000017042471210132627500223270ustar00rootroot00000000000000 Index (Sigar API)
A B C D E F G H I J K L M N O P Q R S T U V W Z

A

accept(File, String) - Method in class org.hyperic.sigar.shell.FileCompleter
 
add(CpuTimer) - Method in class org.hyperic.sigar.CpuTimer
 
add(String) - Method in class org.hyperic.sigar.FileTail
 
add(File) - Method in class org.hyperic.sigar.FileWatcher
 
add(String) - Method in class org.hyperic.sigar.FileWatcher
 
add(File[]) - Method in class org.hyperic.sigar.FileWatcher
 
add(String[]) - Method in class org.hyperic.sigar.FileWatcher
 
add(FileWatcher) - Method in class org.hyperic.sigar.FileWatcherThread
 
add(String) - Method in class org.hyperic.sigar.ProcFileMirror
 
add(Iterator) - Method in class org.hyperic.sigar.util.IteratorIterator
 
add(EventLogNotification) - Method in class org.hyperic.sigar.win32.EventLogThread
 
addSetKey(String, String) - Method in class org.hyperic.sigar.shell.ShellCommand_set
 
addToHistory(String) - Method in class org.hyperic.sigar.util.Getline
 
allInboundTotal - Variable in class org.hyperic.sigar.NetStat
 
allOutboundTotal - Variable in class org.hyperic.sigar.NetStat
 
ANY_ADDR - Static variable in class org.hyperic.sigar.NetFlags
 
ANY_ADDR_V6 - Static variable in class org.hyperic.sigar.NetFlags
 
APPLICATION - Static variable in class org.hyperic.sigar.win32.EventLog
 
available() - Method in class org.hyperic.sigar.SudoFileInputStream
 

B

BAD_COUNTERNAME - Static variable in class org.hyperic.sigar.win32.Pdh
Unable to parse the counter path.
BUILD_DATE - Static variable in class org.hyperic.sigar.Sigar
The date on which sigar.jar was built.

C

calculate(Cpu, Cpu) - Static method in class org.hyperic.sigar.CpuPerc
Deprecated.  
canExecute() - Method in class org.hyperic.sigar.vmware.VM
 
canRead() - Method in class org.hyperic.sigar.vmware.VM
 
canWrite() - Method in class org.hyperic.sigar.vmware.VM
 
changed() - Method in class org.hyperic.sigar.FileInfo
 
changed(FileInfo) - Method in class org.hyperic.sigar.FileTail
 
changed(FileInfo) - Method in class org.hyperic.sigar.FileWatcher
 
changed(FileInfo) - Method in class org.hyperic.sigar.ProcFileMirror
 
check() - Method in class org.hyperic.sigar.FileWatcher
 
check() - Method in class org.hyperic.sigar.FileWatcherThread
 
ClassesRoot - Static variable in class org.hyperic.sigar.win32.RegistryKey
HKEY_CLASSES_ROOT
clear() - Method in class org.hyperic.sigar.CpuTimer
 
clear() - Method in class org.hyperic.sigar.FileWatcher
 
clear() - Method in class org.hyperic.sigar.ptql.ProcessQueryFactory
 
clear(Object) - Static method in class org.hyperic.sigar.SigarProxyCache
 
clear() - Method in class org.hyperic.sigar.util.ReferenceMap
 
clearScreen() - Static method in class org.hyperic.sigar.cmd.Shell
 
close() - Method in class org.hyperic.sigar.Humidor
 
close() - Method in class org.hyperic.sigar.Sigar
Release any native resources associated with this sigar instance.
close() - Method in class org.hyperic.sigar.SudoFileInputStream
 
close() - Method in class org.hyperic.sigar.win32.EventLog
Close the event log.
close() - Method in class org.hyperic.sigar.win32.MetaBase
 
close() - Method in class org.hyperic.sigar.win32.Pdh
 
close() - Method in class org.hyperic.sigar.win32.RegistryKey
 
close() - Method in class org.hyperic.sigar.win32.Service
 
closeInstances() - Static method in class org.hyperic.sigar.win32.EventLogThread
 
CollectionCompleter - Class in org.hyperic.sigar.shell
GetlineCompleter implementation looks for possible completions using an Iterator.
CollectionCompleter() - Constructor for class org.hyperic.sigar.shell.CollectionCompleter
 
CollectionCompleter(ShellBase) - Constructor for class org.hyperic.sigar.shell.CollectionCompleter
 
CollectionCompleter(ShellBase, Collection) - Constructor for class org.hyperic.sigar.shell.CollectionCompleter
 
complete(String) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
complete(String) - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
complete(String) - Method in class org.hyperic.sigar.shell.FileCompleter
 
complete(String) - Method in class org.hyperic.sigar.shell.ProcessQueryCompleter
 
complete(ShellCommandHandler, String) - Method in class org.hyperic.sigar.shell.ShellBase
 
complete(String) - Method in class org.hyperic.sigar.shell.ShellBase
 
complete(String) - Method in class org.hyperic.sigar.shell.ShellCommand_source
 
complete(String) - Method in interface org.hyperic.sigar.util.GetlineCompleter
 
completePid(String) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
CONN_CLIENT - Static variable in class org.hyperic.sigar.NetFlags
 
CONN_PROTOCOLS - Static variable in class org.hyperic.sigar.NetFlags
 
CONN_RAW - Static variable in class org.hyperic.sigar.NetFlags
 
CONN_SERVER - Static variable in class org.hyperic.sigar.NetFlags
 
CONN_TCP - Static variable in class org.hyperic.sigar.NetFlags
 
CONN_UDP - Static variable in class org.hyperic.sigar.NetFlags
 
CONN_UNIX - Static variable in class org.hyperic.sigar.NetFlags
 
connect(ConnectParams, String, boolean) - Method in class org.hyperic.sigar.vmware.VM
 
connect(ConnectParams, String) - Method in class org.hyperic.sigar.vmware.VM
 
connect(ConnectParams) - Method in class org.hyperic.sigar.vmware.VMwareServer
 
ConnectParams - Class in org.hyperic.sigar.vmware
 
ConnectParams() - Constructor for class org.hyperic.sigar.vmware.ConnectParams
 
ConnectParams(String, int, String, String) - Constructor for class org.hyperic.sigar.vmware.ConnectParams
 
Cpu - Class in org.hyperic.sigar
Cpu sigar class.
Cpu() - Constructor for class org.hyperic.sigar.Cpu
 
CpuInfo - Class in org.hyperic.sigar.cmd
Display cpu information for each cpu found on the system.
CpuInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.CpuInfo
 
CpuInfo() - Constructor for class org.hyperic.sigar.cmd.CpuInfo
 
CpuInfo - Class in org.hyperic.sigar
CpuInfo sigar class.
CpuInfo() - Constructor for class org.hyperic.sigar.CpuInfo
 
CpuPerc - Class in org.hyperic.sigar
CPU percentage usage
CpuTimer - Class in org.hyperic.sigar
 
CpuTimer() - Constructor for class org.hyperic.sigar.CpuTimer
 
CpuTimer(Sigar) - Constructor for class org.hyperic.sigar.CpuTimer
 
create(ServiceConfig) - Static method in class org.hyperic.sigar.win32.Service
 
createSnapshot(String, String, boolean, boolean) - Method in class org.hyperic.sigar.vmware.VM
 
createSubKey(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
createSubKey(String, String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
createSubKey(String, int) - Method in class org.hyperic.sigar.win32.RegistryKey
 
CurrentProcessSummary - Class in org.hyperic.sigar
Deprecated.  
CurrentProcessSummary() - Constructor for class org.hyperic.sigar.CurrentProcessSummary
Deprecated.  
CurrentUser - Static variable in class org.hyperic.sigar.win32.RegistryKey
HKEY_CURRENT_USER

D

DEFAULT_INTERVAL - Static variable in class org.hyperic.sigar.FileWatcherThread
 
DEFAULT_INTERVAL - Static variable in class org.hyperic.sigar.win32.EventLogThread
 
delete() - Method in class org.hyperic.sigar.win32.Service
 
deleteSubKey(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
deleteSubKeyTree(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
deleteValue(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
deviceConnect(String) - Method in class org.hyperic.sigar.vmware.VM
 
deviceDisconnect(String) - Method in class org.hyperic.sigar.vmware.VM
 
deviceIsConnected(String) - Method in class org.hyperic.sigar.vmware.VM
 
Df - Class in org.hyperic.sigar.cmd
Report filesytem disk space usage.
Df(Shell) - Constructor for class org.hyperic.sigar.cmd.Df
 
Df() - Constructor for class org.hyperic.sigar.cmd.Df
 
die() - Method in class org.hyperic.sigar.FileWatcherThread
 
die() - Method in class org.hyperic.sigar.win32.EventLogThread
 
diff() - Method in class org.hyperic.sigar.FileInfo
 
diff(DirStat) - Method in class org.hyperic.sigar.FileInfo
 
diff(FileInfo) - Method in class org.hyperic.sigar.FileInfo
 
DirStat - Class in org.hyperic.sigar
DirStat sigar class.
DirStat() - Constructor for class org.hyperic.sigar.DirStat
 
DirUsage - Class in org.hyperic.sigar
DirUsage sigar class.
DirUsage() - Constructor for class org.hyperic.sigar.DirUsage
 
disable(Sigar) - Static method in class org.hyperic.sigar.SigarLog
 
disconnect() - Method in class org.hyperic.sigar.vmware.VM
 
disconnect() - Method in class org.hyperic.sigar.vmware.VMwareServer
 
DiskUsage - Class in org.hyperic.sigar
DiskUsage sigar class.
DiskUsage() - Constructor for class org.hyperic.sigar.DiskUsage
 
displayPossible(List) - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
displayPossible(String[]) - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
displayTimes - Variable in class org.hyperic.sigar.cmd.CpuInfo
 
doStart() - Method in class org.hyperic.sigar.FileWatcherThread
 
doStart() - Method in class org.hyperic.sigar.win32.EventLogThread
 
doStop() - Method in class org.hyperic.sigar.FileWatcherThread
 
doStop() - Method in class org.hyperic.sigar.win32.EventLogThread
 
Du - Class in org.hyperic.sigar.cmd
Display usage for a directory recursively
Du(Shell) - Constructor for class org.hyperic.sigar.cmd.Du
 
Du() - Constructor for class org.hyperic.sigar.cmd.Du
 

E

enable(Sigar) - Static method in class org.hyperic.sigar.SigarLog
 
enableDirStat(boolean) - Method in class org.hyperic.sigar.FileInfo
 
enableLogging(boolean) - Method in class org.hyperic.sigar.Sigar
Enabling logging in the native Sigar code.
enableTranslation() - Static method in class org.hyperic.sigar.win32.Pdh
 
entrySet() - Method in class org.hyperic.sigar.util.ReferenceMap
 
equals(Object) - Method in class org.hyperic.sigar.FileInfo
 
equals(Object) - Method in class org.hyperic.sigar.MultiProcCpu
 
err - Variable in class org.hyperic.sigar.cmd.SigarCommandBase
 
err - Variable in class org.hyperic.sigar.shell.ShellBase
 
ERROR_CRITICAL - Static variable in class org.hyperic.sigar.win32.ServiceConfig
The startup program logs the error, if possible.
ERROR_IGNORE - Static variable in class org.hyperic.sigar.win32.ServiceConfig
The startup (boot) program logs the error but continues the startup operation.
ERROR_NORMAL - Static variable in class org.hyperic.sigar.win32.ServiceConfig
The startup program logs the error and displays a message box pop-up but continues the startup operation.
ERROR_SEVERE - Static variable in class org.hyperic.sigar.win32.ServiceConfig
The startup program logs the error.
ESX - Static variable in class org.hyperic.sigar.vmware.VM
 
EventLog - Class in org.hyperic.sigar.win32
 
EventLog() - Constructor for class org.hyperic.sigar.win32.EventLog
Create an event log.
EVENTLOG_AUDIT_FAILURE - Static variable in class org.hyperic.sigar.win32.EventLog
 
EVENTLOG_AUDIT_SUCCESS - Static variable in class org.hyperic.sigar.win32.EventLog
 
EVENTLOG_ERROR_TYPE - Static variable in class org.hyperic.sigar.win32.EventLog
 
EVENTLOG_INFORMATION_TYPE - Static variable in class org.hyperic.sigar.win32.EventLog
 
EVENTLOG_SUCCESS - Static variable in class org.hyperic.sigar.win32.EventLog
 
EVENTLOG_WAIT_INFINITE - Static variable in class org.hyperic.sigar.win32.EventLog
 
EVENTLOG_WARNING_TYPE - Static variable in class org.hyperic.sigar.win32.EventLog
 
EventLogNotification - Interface in org.hyperic.sigar.win32
Register for event log notifications.
EventLogRecord - Class in org.hyperic.sigar.win32
Class to represent event log records
EventLogTail - Class in org.hyperic.sigar.cmd
 
EventLogTail() - Constructor for class org.hyperic.sigar.cmd.EventLogTail
 
EventLogThread - Class in org.hyperic.sigar.win32
A simple thread that runs forever monitoring the event log.
EventLogThread() - Constructor for class org.hyperic.sigar.win32.EventLogThread
 
EXE_EXT - Static variable in class org.hyperic.sigar.win32.Win32
 
exec(String) - Method in class org.hyperic.sigar.vmware.VMwareServer
 
EXECUTION_STATE_OFF - Static variable in class org.hyperic.sigar.vmware.VM
 
EXECUTION_STATE_ON - Static variable in class org.hyperic.sigar.vmware.VM
 
EXECUTION_STATE_STUCK - Static variable in class org.hyperic.sigar.vmware.VM
 
EXECUTION_STATE_SUSPENDED - Static variable in class org.hyperic.sigar.vmware.VM
 
EXECUTION_STATE_UNKNOWN - Static variable in class org.hyperic.sigar.vmware.VM
 
EXECUTION_STATES - Static variable in class org.hyperic.sigar.vmware.VM
 
expand(String) - Static method in class org.hyperic.sigar.shell.FileCompleter
 
EXPIRE_DEFAULT - Static variable in class org.hyperic.sigar.SigarProxyCache
 

F

FIELD_NOTIMPL - Static variable in class org.hyperic.sigar.Sigar
 
FileAttrs - Class in org.hyperic.sigar
FileAttrs sigar class.
FileAttrs() - Constructor for class org.hyperic.sigar.FileAttrs
 
FileCompleter - Class in org.hyperic.sigar.shell
 
FileCompleter() - Constructor for class org.hyperic.sigar.shell.FileCompleter
 
FileCompleter(ShellBase) - Constructor for class org.hyperic.sigar.shell.FileCompleter
 
FileInfo - Class in org.hyperic.sigar
 
FileInfo() - Constructor for class org.hyperic.sigar.FileInfo
 
files - Variable in class org.hyperic.sigar.cmd.Tail
 
FileSystem - Class in org.hyperic.sigar
FileSystem sigar class.
FileSystem() - Constructor for class org.hyperic.sigar.FileSystem
 
FileSystemMap - Class in org.hyperic.sigar
Helper class to build a map of mounted file systems.
FileSystemMap() - Constructor for class org.hyperic.sigar.FileSystemMap
 
FileSystemUsage - Class in org.hyperic.sigar
FileSystemUsage sigar class.
FileSystemUsage() - Constructor for class org.hyperic.sigar.FileSystemUsage
 
FileTail - Class in org.hyperic.sigar
 
FileTail(Sigar) - Constructor for class org.hyperic.sigar.FileTail
 
FileVersion - Class in org.hyperic.sigar.win32
 
FileVersionInfo - Class in org.hyperic.sigar.cmd
Display process file information.
FileVersionInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.FileVersionInfo
 
FileVersionInfo() - Constructor for class org.hyperic.sigar.cmd.FileVersionInfo
 
FileWatcher - Class in org.hyperic.sigar
 
FileWatcher(Sigar) - Constructor for class org.hyperic.sigar.FileWatcher
 
FileWatcherThread - Class in org.hyperic.sigar
 
FileWatcherThread() - Constructor for class org.hyperic.sigar.FileWatcherThread
 
finalize() - Method in class org.hyperic.sigar.NetServices
Deprecated.  
finalize() - Method in class org.hyperic.sigar.ptql.SigarProcessQuery
 
finalize() - Method in class org.hyperic.sigar.Sigar
 
finalize() - Method in class org.hyperic.sigar.win32.Pdh
 
finalize() - Method in class org.hyperic.sigar.win32.RegistryKey
 
finalize() - Method in class org.hyperic.sigar.win32.Service
 
find(Sigar, String) - Static method in class org.hyperic.sigar.ptql.ProcessFinder
 
find(SigarProxy, String) - Static method in class org.hyperic.sigar.ptql.ProcessFinder
 
find(String) - Method in class org.hyperic.sigar.ptql.ProcessFinder
 
find(ProcessQuery) - Method in class org.hyperic.sigar.ptql.ProcessFinder
 
find(Sigar) - Method in interface org.hyperic.sigar.ptql.ProcessQuery
 
find(Sigar) - Method in class org.hyperic.sigar.ptql.SigarProcessQuery
 
findExecutable(String) - Static method in class org.hyperic.sigar.win32.Win32
 
findPids(String[]) - Method in class org.hyperic.sigar.cmd.Shell
 
findPids(String) - Method in class org.hyperic.sigar.cmd.Shell
 
findProcess(Sigar) - Method in interface org.hyperic.sigar.ptql.ProcessQuery
 
findProcess(Sigar) - Method in class org.hyperic.sigar.ptql.SigarProcessQuery
 
findScriptExecutable(String) - Static method in class org.hyperic.sigar.win32.Win32
 
findSingleProcess(String) - Method in class org.hyperic.sigar.ptql.ProcessFinder
 
findSingleProcess(ProcessQuery) - Method in class org.hyperic.sigar.ptql.ProcessFinder
 
flush() - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
flush() - Method in class org.hyperic.sigar.win32.RegistryKey
 
follow - Variable in class org.hyperic.sigar.cmd.Tail
 
format(double) - Static method in class org.hyperic.sigar.CpuPerc
 
format(long) - Method in class org.hyperic.sigar.CpuTimer
 
formatSize(long) - Static method in class org.hyperic.sigar.Sigar
Format size in bytes to a human readable string.
Free - Class in org.hyperic.sigar.cmd
Display amount of free and used memory in the system.
Free(Shell) - Constructor for class org.hyperic.sigar.cmd.Free
 
Free() - Constructor for class org.hyperic.sigar.cmd.Free
 

G

gather(Sigar) - Method in class org.hyperic.sigar.Cpu
 
gather(Sigar) - Method in class org.hyperic.sigar.CpuInfo
 
gather(Sigar, String) - Method in class org.hyperic.sigar.DirStat
 
gather(Sigar, String) - Method in class org.hyperic.sigar.DirUsage
 
gather(Sigar, String) - Method in class org.hyperic.sigar.DiskUsage
 
gather(Sigar, String) - Method in class org.hyperic.sigar.FileAttrs
 
gather(Sigar) - Method in class org.hyperic.sigar.FileSystem
 
gather(Sigar, String) - Method in class org.hyperic.sigar.FileSystemUsage
 
gather(Sigar) - Method in class org.hyperic.sigar.Mem
 
gather(Sigar) - Method in class org.hyperic.sigar.NetConnection
 
gather(Sigar) - Method in class org.hyperic.sigar.NetInfo
 
gather(Sigar, String) - Method in class org.hyperic.sigar.NetInterfaceConfig
 
gather(Sigar, String) - Method in class org.hyperic.sigar.NetInterfaceStat
 
gather(Sigar) - Method in class org.hyperic.sigar.NetRoute
 
gather(Sigar) - Method in class org.hyperic.sigar.NfsClientV2
 
gather(Sigar) - Method in class org.hyperic.sigar.NfsClientV3
 
gather(Sigar) - Method in class org.hyperic.sigar.NfsServerV2
 
gather(Sigar) - Method in class org.hyperic.sigar.NfsServerV3
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcCpu
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcCred
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcCredName
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcExe
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcFd
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcMem
 
gather(Sigar) - Method in class org.hyperic.sigar.ProcStat
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcState
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ProcTime
 
gather(Sigar) - Method in class org.hyperic.sigar.ResourceLimit
 
gather(Sigar) - Method in class org.hyperic.sigar.Swap
 
gather(Sigar) - Method in class org.hyperic.sigar.SysInfo
 
gather(Sigar) - Method in class org.hyperic.sigar.Tcp
 
gather(Sigar, long) - Method in class org.hyperic.sigar.ThreadCpu
 
gather(Sigar) - Method in class org.hyperic.sigar.Uptime
 
gather(Sigar) - Method in class org.hyperic.sigar.Who
 
get(SigarProxy) - Static method in class org.hyperic.sigar.CurrentProcessSummary
Deprecated.  
get(Object) - Method in class org.hyperic.sigar.util.ReferenceMap
 
getAccess() - Method in class org.hyperic.sigar.NfsClientV3
Get the access.
getAccess() - Method in class org.hyperic.sigar.NfsServerV3
Get the access.
getActiveOpens() - Method in class org.hyperic.sigar.Tcp
Get the active_opens.
getActualFree() - Method in class org.hyperic.sigar.Mem
Get the Actual total free system memory.
getActualUsed() - Method in class org.hyperic.sigar.Mem
Get the Actual total used system memory (e.g.
getAddress() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the address.
getAlias(String) - Static method in class org.hyperic.sigar.shell.ShellCommand_alias
 
getAliases() - Static method in class org.hyperic.sigar.shell.ShellCommand_alias
 
getAllInboundTotal() - Method in class org.hyperic.sigar.NetStat
 
getAllOutboundTotal() - Method in class org.hyperic.sigar.NetStat
 
getArch() - Method in class org.hyperic.sigar.SysInfo
Get the arch.
getArchLibName() - Method in class org.hyperic.sigar.SigarLoader
 
getArgv() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getAtime() - Method in class org.hyperic.sigar.FileAttrs
Get the atime.
getAttemptFails() - Method in class org.hyperic.sigar.Tcp
Get the attempt_fails.
getAttribute(int) - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getAvail() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Total free Kbytes on filesystem available to caller.
getBlkdevs() - Method in class org.hyperic.sigar.DirStat
Get the blkdevs.
getBlkdevs() - Method in class org.hyperic.sigar.DirUsage
Get the blkdevs.
getBroadcast() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the broadcast.
getCacheSize() - Method in class org.hyperic.sigar.CpuInfo
Get the CPU cache size.
getCategory() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the category for this event.
getCategoryString() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the formatted string for the category.
getChrdevs() - Method in class org.hyperic.sigar.DirStat
Get the chrdevs.
getChrdevs() - Method in class org.hyperic.sigar.DirUsage
Get the chrdevs.
getCollection() - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
getCombined() - Method in class org.hyperic.sigar.CpuPerc
 
getCommandName() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getCommandNameIterator() - Method in class org.hyperic.sigar.shell.ShellBase
 
getCommandNameIterator() - Method in interface org.hyperic.sigar.shell.ShellCommandMapper
Get an iterator for the command names.
getCommit() - Method in class org.hyperic.sigar.NfsClientV3
Get the commit.
getCommit() - Method in class org.hyperic.sigar.NfsServerV3
Get the commit.
getCompleter() - Method in class org.hyperic.sigar.cmd.Df
 
getCompleter() - Method in class org.hyperic.sigar.cmd.Iostat
 
getCompleter() - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
getCompletions() - Method in class org.hyperic.sigar.cmd.Ifconfig
 
getCompletions() - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
getCompletions() - Method in class org.hyperic.sigar.cmd.Win32Service
 
getComputerName() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the machine name where the event was generated
getConfig(String) - Method in class org.hyperic.sigar.vmware.VM
 
getConfig() - Method in class org.hyperic.sigar.win32.Service
 
getConnectionProtocol(String) - Static method in class org.hyperic.sigar.NetFlags
 
getCoreCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the core_cur.
getCoreMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the core_max.
getCoresPerSocket() - Method in class org.hyperic.sigar.CpuInfo
Get the Number of CPU cores per CPU socket.
getCounterName(int) - Static method in class org.hyperic.sigar.win32.Pdh
 
getCounterType(String) - Method in class org.hyperic.sigar.win32.Pdh
 
getCpu() - Method in class org.hyperic.sigar.Sigar
Get system cpu info.
getCpu() - Method in interface org.hyperic.sigar.SigarProxy
 
getCpuCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the cpu_cur.
getCpuEndian() - Method in class org.hyperic.sigar.OperatingSystem
 
getCpuInfoList() - Method in class org.hyperic.sigar.Sigar
Get list of cpu infomation.
getCpuInfoList() - Method in interface org.hyperic.sigar.SigarProxy
 
getCpuList() - Method in class org.hyperic.sigar.Sigar
Get list of per-cpu metrics.
getCpuList() - Method in interface org.hyperic.sigar.SigarProxy
 
getCpuMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the cpu_max.
getCpuPerc() - Method in class org.hyperic.sigar.Sigar
Get system CPU info in percentage format.
getCpuPerc() - Method in interface org.hyperic.sigar.SigarProxy
 
getCpuPercList() - Method in class org.hyperic.sigar.Sigar
Get system per-CPU info in percentage format.
getCpuPercList() - Method in interface org.hyperic.sigar.SigarProxy
 
getCpuSys() - Method in class org.hyperic.sigar.CpuTimer
 
getCpuTime(long) - Static method in class org.hyperic.sigar.cmd.Ps
 
getCpuTime(ProcTime) - Static method in class org.hyperic.sigar.cmd.Ps
 
getCpuTotal() - Method in class org.hyperic.sigar.CpuTimer
 
getCpuUsage() - Method in class org.hyperic.sigar.CpuTimer
 
getCpuUser() - Method in class org.hyperic.sigar.CpuTimer
 
getCreate() - Method in class org.hyperic.sigar.NfsClientV2
Get the create.
getCreate() - Method in class org.hyperic.sigar.NfsClientV3
Get the create.
getCreate() - Method in class org.hyperic.sigar.NfsServerV2
Get the create.
getCreate() - Method in class org.hyperic.sigar.NfsServerV3
Get the create.
getCtime() - Method in class org.hyperic.sigar.FileAttrs
Get the ctime.
getCurrEstab() - Method in class org.hyperic.sigar.Tcp
Get the curr_estab.
getCwd() - Method in class org.hyperic.sigar.ProcExe
Get the Name of process current working directory.
getDataCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the data_cur.
getDataMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the data_max.
getDataModel() - Method in class org.hyperic.sigar.OperatingSystem
 
getDefaultGateway() - Method in class org.hyperic.sigar.NetInfo
Get the default_gateway.
getDefaultLibName() - Method in class org.hyperic.sigar.SigarLoader
 
getDefaultPageControl() - Method in class org.hyperic.sigar.shell.ShellBase
 
getDependencies() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getDescription() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the description.
getDescription(SigarProxy, long) - Static method in class org.hyperic.sigar.ProcUtil
 
getDescription() - Method in class org.hyperic.sigar.SysInfo
Get the description.
getDescription(String) - Method in class org.hyperic.sigar.win32.Pdh
 
getDescription() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getDestination() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the destination.
getDestination() - Method in class org.hyperic.sigar.NetRoute
Get the destination.
getDevice() - Method in class org.hyperic.sigar.FileAttrs
Get the device.
getDevice() - Method in class org.hyperic.sigar.Who
Get the device.
getDevName() - Method in class org.hyperic.sigar.FileSystem
Get the Device name.
getDiff() - Method in class org.hyperic.sigar.CpuTimer
 
getDiff(Sigar) - Method in class org.hyperic.sigar.CpuTimer
 
getDirName() - Method in class org.hyperic.sigar.FileSystem
Get the Directory name.
getDirStat(String) - Method in class org.hyperic.sigar.Sigar
 
getDirStat(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getDirUsage(String) - Method in class org.hyperic.sigar.Sigar
 
getDirUsage(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getDiskQueue() - Method in class org.hyperic.sigar.FileSystemUsage
Get the disk_queue.
getDiskReadBytes() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Number of physical disk bytes read.
getDiskReads() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Number of physical disk reads.
getDiskServiceTime() - Method in class org.hyperic.sigar.FileSystemUsage
Get the disk_service_time.
getDiskUsage() - Method in class org.hyperic.sigar.DirStat
Get the disk_usage.
getDiskUsage() - Method in class org.hyperic.sigar.DirUsage
Get the disk_usage.
getDiskUsage(String) - Method in class org.hyperic.sigar.Sigar
Get disk usage.
getDiskUsage(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getDiskWriteBytes() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Number of physical disk bytes written.
getDiskWrites() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Number of physical disk writes.
getDisplayName() - Method in class org.hyperic.sigar.vmware.VM
 
getDisplayName() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getDomainName() - Method in class org.hyperic.sigar.NetInfo
Get the domain_name.
getEgid() - Method in class org.hyperic.sigar.ProcCred
Get the Process effective group id.
getEnglishCountryName() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getEnglishLanguageName() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getEnglishPerflibCounterMap() - Static method in class org.hyperic.sigar.win32.Pdh
 
getErrorCode() - Method in exception org.hyperic.sigar.win32.Win32Exception
 
getErrorControl() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getErrorControlString() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getErrStream() - Method in class org.hyperic.sigar.shell.ShellBase
 
getErrStream() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getEstabResets() - Method in class org.hyperic.sigar.Tcp
Get the estab_resets.
getEuid() - Method in class org.hyperic.sigar.ProcCred
Get the Process effective user id.
getEventId() - Method in class org.hyperic.sigar.win32.EventLogRecord
Event identifier.
getEventType() - Method in class org.hyperic.sigar.win32.EventLogRecord
Return the event type.
getEventTypeString() - Method in class org.hyperic.sigar.win32.EventLogRecord
 
getExe() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getExecutionState() - Method in class org.hyperic.sigar.vmware.VM
 
getExpireMillis() - Method in class org.hyperic.sigar.ProcFileMirror
 
getFileBuild() - Method in class org.hyperic.sigar.win32.FileVersion
 
getFileInfo(String) - Method in class org.hyperic.sigar.Sigar
 
getFileInfo(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getFileMajor() - Method in class org.hyperic.sigar.win32.FileVersion
 
getFileMinor() - Method in class org.hyperic.sigar.win32.FileVersion
 
getFileRevision() - Method in class org.hyperic.sigar.win32.FileVersion
 
getFiles() - Method in class org.hyperic.sigar.DirStat
Get the files.
getFiles() - Method in class org.hyperic.sigar.DirUsage
Get the files.
getFiles() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Total number of file nodes on the filesystem.
getFiles() - Method in class org.hyperic.sigar.FileWatcher
 
getFileSizeCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the file_size_cur.
getFileSizeMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the file_size_max.
getFileSystem(String) - Method in class org.hyperic.sigar.FileSystemMap
 
getFileSystemList() - Method in class org.hyperic.sigar.Sigar
Get list of file systems.
getFileSystemList() - Method in interface org.hyperic.sigar.SigarProxy
 
getFileSystemMap() - Method in class org.hyperic.sigar.Sigar
 
getFileSystemMap() - Method in interface org.hyperic.sigar.SigarProxy
 
getFileSystemUsage(String) - Method in class org.hyperic.sigar.Sigar
Get file system usage.
getFileSystemUsage(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getFileVersion() - Method in class org.hyperic.sigar.win32.FileVersion
 
getFileVersion(String) - Static method in class org.hyperic.sigar.win32.Win32
 
getFlags(String[], int) - Static method in class org.hyperic.sigar.cmd.Netstat
 
getFlags() - Method in class org.hyperic.sigar.FileSystem
Get the File system flags.
getFlags() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the flags.
getFlags() - Method in class org.hyperic.sigar.NetRoute
Get the flags.
getFormattedValue(String) - Method in class org.hyperic.sigar.win32.Pdh
 
getFormatter() - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
getFQDN() - Method in class org.hyperic.sigar.Sigar
Reliably retrieve the FQDN for a machine
getFQDN() - Method in interface org.hyperic.sigar.SigarProxy
 
getFree() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Total free Kbytes on filesystem.
getFree() - Method in class org.hyperic.sigar.Mem
Get the Total free system memory (e.g.
getFree() - Method in class org.hyperic.sigar.Swap
Get the Total free system swap.
getFreeFiles() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Number of free file nodes on the filesystem.
getFreePercent() - Method in class org.hyperic.sigar.Mem
Get the Percent total free system memory.
getFsinfo() - Method in class org.hyperic.sigar.NfsClientV3
Get the fsinfo.
getFsinfo() - Method in class org.hyperic.sigar.NfsServerV3
Get the fsinfo.
getFsstat() - Method in class org.hyperic.sigar.NfsClientV2
Get the fsstat.
getFsstat() - Method in class org.hyperic.sigar.NfsClientV3
Get the fsstat.
getFsstat() - Method in class org.hyperic.sigar.NfsServerV2
Get the fsstat.
getFsstat() - Method in class org.hyperic.sigar.NfsServerV3
Get the fsstat.
getFullVersion() - Method in class org.hyperic.sigar.vmware.VM
 
getGateway() - Method in class org.hyperic.sigar.NetRoute
Get the gateway.
getGetattr() - Method in class org.hyperic.sigar.NfsClientV2
Get the getattr.
getGetattr() - Method in class org.hyperic.sigar.NfsClientV3
Get the getattr.
getGetattr() - Method in class org.hyperic.sigar.NfsServerV2
Get the getattr.
getGetattr() - Method in class org.hyperic.sigar.NfsServerV3
Get the getattr.
getGetline() - Method in class org.hyperic.sigar.shell.ShellBase
 
getGid() - Method in class org.hyperic.sigar.FileAttrs
Get the gid.
getGid() - Method in class org.hyperic.sigar.ProcCred
Get the Process group id.
getGroup() - Method in class org.hyperic.sigar.ProcCredName
Get the Process owner group name.
getGuestInfo(String) - Method in class org.hyperic.sigar.vmware.VM
 
getGuestOS() - Method in class org.hyperic.sigar.vmware.VM
 
getHandler(String) - Method in class org.hyperic.sigar.shell.ShellBase
 
getHandler(String) - Method in interface org.hyperic.sigar.shell.ShellCommandMapper
Get the command handler for a command.
getHandlerNames() - Method in class org.hyperic.sigar.shell.MultiwordShellCommand
 
getHeartbeat() - Method in class org.hyperic.sigar.vmware.VM
 
getHiddenInput(String) - Method in class org.hyperic.sigar.shell.ShellBase
If a command needs additional input via the console, they can get it this way.
getHost() - Method in class org.hyperic.sigar.Who
Get the host.
getHostName() - Method in class org.hyperic.sigar.NetInfo
Get the host_name.
getHostname() - Method in class org.hyperic.sigar.NfsFileSystem
 
getHwaddr() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the hwaddr.
getId() - Method in class org.hyperic.sigar.vmware.VM
 
getId() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getIdle() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu idle time.
getIdle() - Method in class org.hyperic.sigar.CpuPerc
 
getIdle() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of processes in idle state.
getIfFlagsString(long) - Static method in class org.hyperic.sigar.NetFlags
 
getIfname() - Method in class org.hyperic.sigar.NetRoute
Get the ifname.
getInErrs() - Method in class org.hyperic.sigar.Tcp
Get the in_errs.
getInfo(SigarProxy, long) - Static method in class org.hyperic.sigar.cmd.Ps
 
getInfo(SigarProxy) - Static method in class org.hyperic.sigar.cmd.Uptime
 
getInfo() - Method in class org.hyperic.sigar.win32.FileVersion
 
getInode() - Method in class org.hyperic.sigar.FileAttrs
Get the inode.
getInput(String) - Method in class org.hyperic.sigar.shell.ShellBase
If a command needs additional input via the console, they can get it this way.
getInput(String, boolean) - Method in class org.hyperic.sigar.shell.ShellBase
If a command needs additional input via the console, they can get it this way.
getInSegs() - Method in class org.hyperic.sigar.Tcp
Get the in_segs.
getInstance(String) - Static method in class org.hyperic.sigar.CpuTimer
 
getInstance() - Static method in class org.hyperic.sigar.FileWatcherThread
 
getInstance() - Static method in class org.hyperic.sigar.Humidor
 
getInstance() - Static method in class org.hyperic.sigar.OperatingSystem
 
getInstance() - Static method in class org.hyperic.sigar.ptql.ProcessQueryFactory
 
getInstance(String) - Static method in class org.hyperic.sigar.ptql.ProcessQueryFactory
Deprecated.  
getInstance() - Static method in class org.hyperic.sigar.win32.EventLogThread
Deprecated.  
getInstance(String) - Static method in class org.hyperic.sigar.win32.EventLogThread
 
getInstances(String) - Static method in class org.hyperic.sigar.win32.Pdh
 
getInterval() - Method in class org.hyperic.sigar.FileWatcher
 
getInterval() - Method in class org.hyperic.sigar.FileWatcherThread
 
getIntValue(int) - Method in class org.hyperic.sigar.win32.MetaBase
 
getIntValue(int, int) - Method in class org.hyperic.sigar.win32.MetaBase
 
getIntValue(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
getIntValue(String, int) - Method in class org.hyperic.sigar.win32.RegistryKey
 
getIrq() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu time servicing interrupts.
getIrq() - Method in class org.hyperic.sigar.CpuPerc
 
getIrtt() - Method in class org.hyperic.sigar.NetRoute
Get the irtt.
getIterator() - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
getIterator() - Method in class org.hyperic.sigar.shell.FileCompleter
 
getJarName() - Method in class org.hyperic.sigar.SigarLoader
 
getJavaMainClass(SigarProxy, long) - Static method in class org.hyperic.sigar.ProcUtil
Try to determina classname for java programs
getKey() - Method in interface org.hyperic.sigar.util.ReferenceMap.MapReference
 
getKey() - Method in class org.hyperic.sigar.util.ReferenceMap.SoftValue
 
getKey() - Method in class org.hyperic.sigar.util.ReferenceMap.WeakValue
 
getKeys(String) - Static method in class org.hyperic.sigar.win32.Pdh
 
getLastSampleTime() - Method in class org.hyperic.sigar.CpuTimer
 
getLastTime() - Method in class org.hyperic.sigar.ProcCpu
Get the last_time.
getLibJars(String) - Static method in class org.hyperic.sigar.cmd.Runner
 
Getline - Class in org.hyperic.sigar.util
This class provides Emacs style key bindings, history and tab completion for command shell applications.
Getline() - Constructor for class org.hyperic.sigar.util.Getline
 
Getline(String) - Constructor for class org.hyperic.sigar.util.Getline
 
getLine() - Method in class org.hyperic.sigar.util.Getline
 
getLine(String) - Method in class org.hyperic.sigar.util.Getline
 
getLine(String, boolean) - Method in class org.hyperic.sigar.util.Getline
 
GetlineCompleter - Interface in org.hyperic.sigar.util
 
getLink() - Method in class org.hyperic.sigar.NfsClientV2
Get the link.
getLink() - Method in class org.hyperic.sigar.NfsClientV3
Get the link.
getLink() - Method in class org.hyperic.sigar.NfsServerV2
Get the link.
getLink() - Method in class org.hyperic.sigar.NfsServerV3
Get the link.
getLinkInfo(String) - Method in class org.hyperic.sigar.Sigar
 
getLinkInfo(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getLoadAverage() - Method in class org.hyperic.sigar.Sigar
Get system load average.
getLoadAverage() - Method in interface org.hyperic.sigar.SigarProxy
 
getLoadOrderGroup() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getLocalAddress() - Method in class org.hyperic.sigar.NetConnection
Get the local_address.
getLocalPort() - Method in class org.hyperic.sigar.NetConnection
Get the local_port.
getLocation() - Static method in class org.hyperic.sigar.SigarLoader
Returns the path where sigar.jar is located.
getLogger(String) - Static method in class org.hyperic.sigar.SigarLog
 
getLogName() - Method in class org.hyperic.sigar.win32.EventLogRecord
 
getLogNames() - Static method in class org.hyperic.sigar.win32.EventLog
Eventlog names are store in the registry under: SYSTEM\CurrentControlSet\Services\Eventlog This method returns the list of these entries.
getLookup() - Method in class org.hyperic.sigar.NfsClientV2
Get the lookup.
getLookup() - Method in class org.hyperic.sigar.NfsClientV3
Get the lookup.
getLookup() - Method in class org.hyperic.sigar.NfsServerV2
Get the lookup.
getLookup() - Method in class org.hyperic.sigar.NfsServerV3
Get the lookup.
getMachine() - Method in class org.hyperic.sigar.SysInfo
Get the machine.
getMajorFaults() - Method in class org.hyperic.sigar.ProcMem
Get the i/o page faults.
getMask() - Method in class org.hyperic.sigar.NetRoute
Get the mask.
getMem() - Method in class org.hyperic.sigar.Sigar
Get system memory info.
getMem() - Method in interface org.hyperic.sigar.SigarProxy
 
getMemoryCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the memory_cur.
getMemoryMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the memory_max.
getMemSize() - Method in class org.hyperic.sigar.vmware.VM
 
getMessage() - Method in exception org.hyperic.sigar.SigarException
 
getMessage() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the message for the event.
getMethodOpNames(Method) - Static method in class org.hyperic.sigar.shell.ProcessQueryCompleter
 
getMethods() - Static method in class org.hyperic.sigar.shell.ProcessQueryCompleter
 
getMetric() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the metric.
getMetric() - Method in class org.hyperic.sigar.NetRoute
Get the metric.
getMhz() - Method in class org.hyperic.sigar.CpuInfo
Get the CPU speed.
getMinorFaults() - Method in class org.hyperic.sigar.ProcMem
Get the non i/o page faults.
getMkdir() - Method in class org.hyperic.sigar.NfsClientV2
Get the mkdir.
getMkdir() - Method in class org.hyperic.sigar.NfsClientV3
Get the mkdir.
getMkdir() - Method in class org.hyperic.sigar.NfsServerV2
Get the mkdir.
getMkdir() - Method in class org.hyperic.sigar.NfsServerV3
Get the mkdir.
getMknod() - Method in class org.hyperic.sigar.NfsClientV3
Get the mknod.
getMknod() - Method in class org.hyperic.sigar.NfsServerV3
Get the mknod.
getMode() - Method in class org.hyperic.sigar.FileInfo
Convert permissions bit mask to human readable number.
getModel() - Method in class org.hyperic.sigar.CpuInfo
Get the CPU model.
getMountedFileSystemUsage(String) - Method in class org.hyperic.sigar.Sigar
Get file system usage of a mounted directory.
getMountedFileSystemUsage(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getMountPoint(String) - Method in class org.hyperic.sigar.FileSystemMap
Find the file system the given file or directory is within.
getMtime() - Method in class org.hyperic.sigar.FileAttrs
Get the mtime.
getMtu() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the mtu.
getMtu() - Method in class org.hyperic.sigar.NetRoute
Get the mtu.
getMultiProcCpu(String) - Method in class org.hyperic.sigar.Sigar
 
getMultiProcCpu(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getMultiProcMem(String) - Method in class org.hyperic.sigar.Sigar
 
getMultiProcMem(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getMultiStringValue(int) - Method in class org.hyperic.sigar.win32.MetaBase
 
getMultiStringValue(String, List) - Method in class org.hyperic.sigar.win32.RegistryKey
 
getName() - Method in class org.hyperic.sigar.FileInfo
 
getName() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the name.
getName(String, long) - Static method in class org.hyperic.sigar.NetServices
Deprecated.  
getName() - Method in class org.hyperic.sigar.ProcExe
Get the Name of process executable.
getName() - Method in class org.hyperic.sigar.ProcState
Get the Name of the process program.
getName() - Method in class org.hyperic.sigar.SysInfo
Get the name.
getName() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getNativeLibrary() - Method in class org.hyperic.sigar.Sigar
 
getNativeLibraryName() - Static method in class org.hyperic.sigar.SigarLoader
Returns the name of the native sigar library.
getNetConnectionList(int) - Method in class org.hyperic.sigar.Sigar
Get list of network connections.
getNetConnectionList(int) - Method in interface org.hyperic.sigar.SigarProxy
 
getNetInfo() - Method in class org.hyperic.sigar.Sigar
Get general network info.
getNetInfo() - Method in interface org.hyperic.sigar.SigarProxy
 
getNetInterfaceConfig(String) - Method in class org.hyperic.sigar.Sigar
Get network interface configuration info.
getNetInterfaceConfig() - Method in class org.hyperic.sigar.Sigar
Get default network interface configuration info.
getNetInterfaceConfig(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getNetInterfaceConfig() - Method in interface org.hyperic.sigar.SigarProxy
 
getNetInterfaceList() - Method in class org.hyperic.sigar.Sigar
Get the list of configured network interface names.
getNetInterfaceList() - Method in interface org.hyperic.sigar.SigarProxy
 
getNetInterfaceStat(String) - Method in class org.hyperic.sigar.Sigar
Get network interface stats.
getNetInterfaceStat(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getNetListenAddress(long) - Method in class org.hyperic.sigar.Sigar
Get the TCP listen address for the given port.
getNetListenAddress(String) - Method in class org.hyperic.sigar.Sigar
 
getNetListenAddress(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getNetListenAddress(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getNetmask() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the netmask.
getNetRouteList() - Method in class org.hyperic.sigar.Sigar
Get list of network routes.
getNetRouteList() - Method in interface org.hyperic.sigar.SigarProxy
 
getNetServicesName(int, long) - Method in class org.hyperic.sigar.Sigar
 
getNetServicesName(int, long) - Method in interface org.hyperic.sigar.SigarProxy
 
getNetStat() - Method in class org.hyperic.sigar.Sigar
 
getNetStat(byte[], long) - Method in class org.hyperic.sigar.Sigar
 
getNetStat() - Method in interface org.hyperic.sigar.SigarProxy
 
getNewestRecord() - Method in class org.hyperic.sigar.win32.EventLog
Get the newest event log record.
getNfsClientV2() - Method in class org.hyperic.sigar.Sigar
 
getNfsClientV2() - Method in interface org.hyperic.sigar.SigarProxy
 
getNfsClientV3() - Method in class org.hyperic.sigar.Sigar
 
getNfsClientV3() - Method in interface org.hyperic.sigar.SigarProxy
 
getNfsServerV2() - Method in class org.hyperic.sigar.Sigar
 
getNfsServerV2() - Method in interface org.hyperic.sigar.SigarProxy
 
getNfsServerV3() - Method in class org.hyperic.sigar.Sigar
 
getNfsServerV3() - Method in interface org.hyperic.sigar.SigarProxy
 
getNice() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu nice time.
getNice() - Method in class org.hyperic.sigar.CpuPerc
 
getNice() - Method in class org.hyperic.sigar.ProcState
Get the Nice value of process.
getNlink() - Method in class org.hyperic.sigar.FileAttrs
Get the nlink.
getNull() - Method in class org.hyperic.sigar.NfsClientV2
Get the null.
getNull() - Method in class org.hyperic.sigar.NfsClientV3
Get the null.
getNull() - Method in class org.hyperic.sigar.NfsServerV2
Get the null.
getNull() - Method in class org.hyperic.sigar.NfsServerV3
Get the null.
getNumberOfRecords() - Method in class org.hyperic.sigar.win32.EventLog
Get the number of records for this event log
getObjects() - Static method in class org.hyperic.sigar.win32.Pdh
 
getOldestRecord() - Method in class org.hyperic.sigar.win32.EventLog
Get the oldest event log record
getOpenFilesCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the open_files_cur.
getOpenFilesMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the open_files_max.
getOptions() - Method in class org.hyperic.sigar.FileSystem
Get the File system mount options.
getOutRsts() - Method in class org.hyperic.sigar.Tcp
Get the out_rsts.
getOutSegs() - Method in class org.hyperic.sigar.Tcp
Get the out_segs.
getOutStream() - Method in class org.hyperic.sigar.shell.ShellBase
 
getOutStream() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getPageFaults() - Method in class org.hyperic.sigar.ProcMem
Get the Total number of page faults.
getPageIn() - Method in class org.hyperic.sigar.Swap
Get the Pages in.
getPageOut() - Method in class org.hyperic.sigar.Swap
Get the Pages out.
getPageSize() - Method in class org.hyperic.sigar.shell.ShellBase
Get the current page size used when paging data.
getPartialCompletion(String[]) - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
getPassiveOpens() - Method in class org.hyperic.sigar.Tcp
Get the passive_opens.
getPassword(String) - Static method in class org.hyperic.sigar.Sigar
Prompt for a password, disabling terminal echo during user input if possible.
getPassword() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getPatchLevel() - Method in class org.hyperic.sigar.SysInfo
Get the patch_level.
getPath() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getPathconf() - Method in class org.hyperic.sigar.NfsClientV3
Get the pathconf.
getPathconf() - Method in class org.hyperic.sigar.NfsServerV3
Get the pathconf.
getPercent() - Method in class org.hyperic.sigar.MultiProcCpu
 
getPercent() - Method in class org.hyperic.sigar.ProcCpu
Get the Process cpu usage.
getPerflibCounterMap(LocaleInfo) - Static method in class org.hyperic.sigar.win32.Pdh
 
getPerflibLangId() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getPermissions() - Method in class org.hyperic.sigar.FileAttrs
Get the permissions.
getPermissions() - Method in class org.hyperic.sigar.vmware.VM
 
getPermissionsString() - Method in class org.hyperic.sigar.FileInfo
 
getPermissionsString() - Method in class org.hyperic.sigar.vmware.VM
 
getPid() - Method in class org.hyperic.sigar.Sigar
Get pid of the current process.
getPid() - Method in interface org.hyperic.sigar.SigarProxy
 
getPid() - Method in class org.hyperic.sigar.vmware.VM
 
getPids(SigarProxy, String[]) - Static method in class org.hyperic.sigar.cmd.Shell
 
getPipeSizeCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the pipe_size_cur.
getPipeSizeMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the pipe_size_max.
getPpid() - Method in class org.hyperic.sigar.ProcState
Get the Process parent process id.
getPreviousInfo() - Method in class org.hyperic.sigar.FileInfo
 
getPrimaryDns() - Method in class org.hyperic.sigar.NetInfo
Get the primary_dns.
getPrimaryLangId() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getPriority() - Method in class org.hyperic.sigar.ProcState
Get the Kernel scheduling priority of process.
getProcArgs(long) - Method in class org.hyperic.sigar.Sigar
Get process arguments.
getProcArgs(String) - Method in class org.hyperic.sigar.Sigar
 
getProcArgs(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcArgs(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcCpu(long) - Method in class org.hyperic.sigar.Sigar
Get process cpu info.
getProcCpu(String) - Method in class org.hyperic.sigar.Sigar
 
getProcCpu(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcCpu(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcCred(long) - Method in class org.hyperic.sigar.Sigar
Get process credential info.
getProcCred(String) - Method in class org.hyperic.sigar.Sigar
 
getProcCred(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcCred(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcCredName(long) - Method in class org.hyperic.sigar.Sigar
Get process credential names.
getProcCredName(String) - Method in class org.hyperic.sigar.Sigar
 
getProcCredName(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcCredName(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcEnv(long) - Method in class org.hyperic.sigar.Sigar
Get process environment.
getProcEnv(String) - Method in class org.hyperic.sigar.Sigar
 
getProcEnv(long, String) - Method in class org.hyperic.sigar.Sigar
Get process environment variable value.
getProcEnv(String, String) - Method in class org.hyperic.sigar.Sigar
 
getProcEnv(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcEnv(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcEnv(long, String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcEnv(String, String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcesses() - Method in class org.hyperic.sigar.MultiProcCpu
 
getProcessesCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the processes_cur.
getProcessesMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the processes_max.
getProcessor() - Method in class org.hyperic.sigar.ProcState
Get the Processor number last run on.
getProcExe(long) - Method in class org.hyperic.sigar.Sigar
Get process current working directory.
getProcExe(String) - Method in class org.hyperic.sigar.Sigar
 
getProcExe(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcExe(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcFd(long) - Method in class org.hyperic.sigar.Sigar
Get process file descriptor info.
getProcFd(String) - Method in class org.hyperic.sigar.Sigar
 
getProcFd(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcFd(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcFile(File) - Method in class org.hyperic.sigar.ProcFileMirror
 
getProcFile(String) - Method in class org.hyperic.sigar.ProcFileMirror
 
getProcList() - Method in class org.hyperic.sigar.Sigar
Get system process list.
getProcList() - Method in interface org.hyperic.sigar.SigarProxy
 
getProcMem(long) - Method in class org.hyperic.sigar.Sigar
Get process memory info.
getProcMem(String) - Method in class org.hyperic.sigar.Sigar
 
getProcMem(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcMem(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcModules(long) - Method in class org.hyperic.sigar.Sigar
 
getProcModules(String) - Method in class org.hyperic.sigar.Sigar
 
getProcModules(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcModules(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcPort(int, long) - Method in class org.hyperic.sigar.Sigar
Find the pid of the process which is listening on the given port.
getProcPort(String, String) - Method in class org.hyperic.sigar.Sigar
 
getProcPort(int, long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcPort(String, String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcStat() - Method in class org.hyperic.sigar.Sigar
Get system process stats.
getProcStat() - Method in interface org.hyperic.sigar.SigarProxy
 
getProcState(long) - Method in class org.hyperic.sigar.Sigar
Get process state info.
getProcState(String) - Method in class org.hyperic.sigar.Sigar
 
getProcState(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcState(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcTime(long) - Method in class org.hyperic.sigar.Sigar
Get process time info.
getProcTime(String) - Method in class org.hyperic.sigar.Sigar
 
getProcTime(long) - Method in interface org.hyperic.sigar.SigarProxy
 
getProcTime(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getProductBuild() - Method in class org.hyperic.sigar.win32.FileVersion
 
getProductInfo(int) - Method in class org.hyperic.sigar.vmware.VM
 
getProductMajor() - Method in class org.hyperic.sigar.win32.FileVersion
 
getProductMinor() - Method in class org.hyperic.sigar.win32.FileVersion
 
getProductName() - Method in class org.hyperic.sigar.vmware.VM
 
getProductPlatform() - Method in class org.hyperic.sigar.vmware.VM
 
getProductRevision() - Method in class org.hyperic.sigar.win32.FileVersion
 
getProductVersion() - Method in class org.hyperic.sigar.win32.FileVersion
 
getProgram(String) - Static method in class org.hyperic.sigar.RPC
 
getQuery(String) - Method in class org.hyperic.sigar.ptql.ProcessQueryFactory
 
getQueue() - Method in class org.hyperic.sigar.DiskUsage
Get the queue.
getRam() - Method in class org.hyperic.sigar.Mem
Get the System Random Access Memory (in MB).
getRawValue(String) - Method in class org.hyperic.sigar.win32.Pdh
 
getRead() - Method in class org.hyperic.sigar.NfsClientV2
Get the read.
getRead() - Method in class org.hyperic.sigar.NfsClientV3
Get the read.
getRead() - Method in class org.hyperic.sigar.NfsServerV2
Get the read.
getRead() - Method in class org.hyperic.sigar.NfsServerV3
Get the read.
getReadBytes() - Method in class org.hyperic.sigar.DiskUsage
Get the Number of physical disk bytes read.
getReaddir() - Method in class org.hyperic.sigar.NfsClientV2
Get the readdir.
getReaddir() - Method in class org.hyperic.sigar.NfsClientV3
Get the readdir.
getReaddir() - Method in class org.hyperic.sigar.NfsServerV2
Get the readdir.
getReaddir() - Method in class org.hyperic.sigar.NfsServerV3
Get the readdir.
getReaddirplus() - Method in class org.hyperic.sigar.NfsClientV3
Get the readdirplus.
getReaddirplus() - Method in class org.hyperic.sigar.NfsServerV3
Get the readdirplus.
getReadlink() - Method in class org.hyperic.sigar.NfsClientV2
Get the readlink.
getReadlink() - Method in class org.hyperic.sigar.NfsClientV3
Get the readlink.
getReadlink() - Method in class org.hyperic.sigar.NfsServerV2
Get the readlink.
getReadlink() - Method in class org.hyperic.sigar.NfsServerV3
Get the readlink.
getReads() - Method in class org.hyperic.sigar.DiskUsage
Get the Number of physical disk reads.
getReceiveQueue() - Method in class org.hyperic.sigar.NetConnection
Get the receive_queue.
getRecordNumber() - Method in class org.hyperic.sigar.win32.EventLogRecord
 
getRefcnt() - Method in class org.hyperic.sigar.NetRoute
Get the refcnt.
getRegisteredVmNames() - Method in class org.hyperic.sigar.vmware.VMwareServer
 
getRemoteAddress() - Method in class org.hyperic.sigar.NetConnection
Get the remote_address.
getRemoteConnections() - Method in class org.hyperic.sigar.vmware.VM
 
getRemotePort() - Method in class org.hyperic.sigar.NetConnection
Get the remote_port.
getRemove() - Method in class org.hyperic.sigar.NfsClientV2
Get the remove.
getRemove() - Method in class org.hyperic.sigar.NfsClientV3
Get the remove.
getRemove() - Method in class org.hyperic.sigar.NfsServerV2
Get the remove.
getRemove() - Method in class org.hyperic.sigar.NfsServerV3
Get the remove.
getRename() - Method in class org.hyperic.sigar.NfsClientV2
Get the rename.
getRename() - Method in class org.hyperic.sigar.NfsClientV3
Get the rename.
getRename() - Method in class org.hyperic.sigar.NfsServerV2
Get the rename.
getRename() - Method in class org.hyperic.sigar.NfsServerV3
Get the rename.
getResident() - Method in class org.hyperic.sigar.ProcMem
Get the Total process resident memory.
getResource(String) - Method in class org.hyperic.sigar.vmware.VM
 
getResource(String) - Method in class org.hyperic.sigar.vmware.VMwareServer
 
getResourceLimit() - Method in class org.hyperic.sigar.Sigar
Get system resource limits.
getResourceLimit() - Method in interface org.hyperic.sigar.SigarProxy
 
getRetransSegs() - Method in class org.hyperic.sigar.Tcp
Get the retrans_segs.
getRmdir() - Method in class org.hyperic.sigar.NfsClientV2
Get the rmdir.
getRmdir() - Method in class org.hyperic.sigar.NfsClientV3
Get the rmdir.
getRmdir() - Method in class org.hyperic.sigar.NfsServerV2
Get the rmdir.
getRmdir() - Method in class org.hyperic.sigar.NfsServerV3
Get the rmdir.
getRoot() - Method in class org.hyperic.sigar.NfsClientV2
Get the root.
getRoot() - Method in class org.hyperic.sigar.NfsServerV2
Get the root.
getRss() - Method in class org.hyperic.sigar.ProcMem
Deprecated.  
getRunAsUser() - Method in class org.hyperic.sigar.vmware.VM
 
getRunning() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of processes in run state.
getRxBytes() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the rx_bytes.
getRxDropped() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the rx_dropped.
getRxErrors() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the rx_errors.
getRxFrame() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the rx_frame.
getRxOverruns() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the rx_overruns.
getRxPackets() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the rx_packets.
getSecondaryDns() - Method in class org.hyperic.sigar.NetInfo
Get the secondary_dns.
getSendQueue() - Method in class org.hyperic.sigar.NetConnection
Get the send_queue.
getServiceConfigs(Sigar, String) - Static method in class org.hyperic.sigar.win32.Service
 
getServiceConfigs(String) - Static method in class org.hyperic.sigar.win32.Service
Deprecated.  
getServiceNames(Sigar, String) - Static method in class org.hyperic.sigar.win32.Service
 
getServiceNames() - Static method in class org.hyperic.sigar.win32.Service
 
getServicePid(String) - Method in class org.hyperic.sigar.Sigar
Get pid for the Windows service with the given name.
getServicePid(String) - Method in interface org.hyperic.sigar.SigarProxy
 
getServiceTime() - Method in class org.hyperic.sigar.DiskUsage
Get the service_time.
getSetattr() - Method in class org.hyperic.sigar.NfsClientV2
Get the setattr.
getSetattr() - Method in class org.hyperic.sigar.NfsClientV3
Get the setattr.
getSetattr() - Method in class org.hyperic.sigar.NfsServerV2
Get the setattr.
getSetattr() - Method in class org.hyperic.sigar.NfsServerV3
Get the setattr.
getShare() - Method in class org.hyperic.sigar.ProcMem
Get the Total process shared memory.
getSharedLibrary() - Static method in class org.hyperic.sigar.vmware.VMControlLibrary
 
getShell() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getSigar() - Method in class org.hyperic.sigar.cmd.Shell
 
getSigar() - Method in class org.hyperic.sigar.Humidor
 
getSigar(Object) - Static method in class org.hyperic.sigar.SigarProxyCache
 
getSigarJarName() - Static method in class org.hyperic.sigar.SigarLoader
 
getSigarProxy() - Method in class org.hyperic.sigar.cmd.Shell
 
getSigNum(String) - Static method in class org.hyperic.sigar.Sigar
 
getSingleValue(String) - Method in class org.hyperic.sigar.win32.Pdh
Deprecated.  
getSize() - Method in class org.hyperic.sigar.FileAttrs
Get the size.
getSize() - Method in class org.hyperic.sigar.ProcMem
Get the Total process virtual memory.
getSleeping() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of processes in sleep state.
getSockets() - Method in class org.hyperic.sigar.DirStat
Get the sockets.
getSockets() - Method in class org.hyperic.sigar.DirUsage
Get the sockets.
getSoftIrq() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu time servicing softirqs.
getSoftIrq() - Method in class org.hyperic.sigar.CpuPerc
 
getSource() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the application which triggered the event
getSpeed() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the speed.
getStackCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the stack_cur.
getStackMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the stack_max.
getStartName() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getStartTime() - Method in class org.hyperic.sigar.ProcCpu
Get the Time process was started in seconds.
getStartTime() - Method in class org.hyperic.sigar.ProcTime
Get the Time process was started in seconds.
getStartType() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getStartTypeString() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getState() - Method in class org.hyperic.sigar.NetConnection
Get the state.
getState() - Method in class org.hyperic.sigar.ProcState
Get the Process state (Running, Zombie, etc.).
getStateString(int) - Static method in class org.hyperic.sigar.NetConnection
 
getStateString() - Method in class org.hyperic.sigar.NetConnection
 
getStatus() - Method in class org.hyperic.sigar.win32.Service
 
getStatusString() - Method in class org.hyperic.sigar.win32.Service
 
getStolen() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu involuntary wait time.
getStolen() - Method in class org.hyperic.sigar.CpuPerc
 
getStopped() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of processes in stop state.
getStringData() - Method in class org.hyperic.sigar.win32.EventLogRecord
Deprecated.  
getStringValue(int) - Method in class org.hyperic.sigar.win32.MetaBase
 
getStringValue(int, String) - Method in class org.hyperic.sigar.win32.MetaBase
 
getStringValue(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
getStringValue(String, String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
getSubdirs() - Method in class org.hyperic.sigar.DirStat
Get the subdirs.
getSubdirs() - Method in class org.hyperic.sigar.DirUsage
Get the subdirs.
getSubHandler(String) - Method in class org.hyperic.sigar.shell.MultiwordShellCommand
 
getSubKeyName() - Method in class org.hyperic.sigar.win32.RegistryKey
 
getSubKeyNames() - Method in class org.hyperic.sigar.win32.MetaBase
 
getSubKeyNames() - Method in class org.hyperic.sigar.win32.RegistryKey
 
getSubLangId() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
getSwap() - Method in class org.hyperic.sigar.Sigar
Get system swap info.
getSwap() - Method in interface org.hyperic.sigar.SigarProxy
 
getSymlink() - Method in class org.hyperic.sigar.NfsClientV2
Get the symlink.
getSymlink() - Method in class org.hyperic.sigar.NfsClientV3
Get the symlink.
getSymlink() - Method in class org.hyperic.sigar.NfsServerV2
Get the symlink.
getSymlink() - Method in class org.hyperic.sigar.NfsServerV3
Get the symlink.
getSymlinks() - Method in class org.hyperic.sigar.DirStat
Get the symlinks.
getSymlinks() - Method in class org.hyperic.sigar.DirUsage
Get the symlinks.
getSyntax() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getSyntax() - Method in interface org.hyperic.sigar.shell.ShellCommandHandler
Get a description of the syntax for how a command should be invoked.
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Df
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Ifconfig
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Iostat
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Kill
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.MultiPs
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Pidof
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Ps
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Time
 
getSyntaxArgs() - Method in class org.hyperic.sigar.cmd.Win32Service
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.MultiwordShellCommand
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommand_alias
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommand_get
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommand_help
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommand_set
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommand_sleep
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommand_source
 
getSyntaxArgs() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getSys() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu kernel time.
getSys() - Method in class org.hyperic.sigar.CpuPerc
 
getSys() - Method in class org.hyperic.sigar.ProcCpu
Get the Process cpu kernel time.
getSys() - Method in class org.hyperic.sigar.ProcTime
Get the Process cpu kernel time.
getSys() - Method in class org.hyperic.sigar.ThreadCpu
Get the Thread cpu kernel time.
getSysTypeName() - Method in class org.hyperic.sigar.FileSystem
Get the File system os specific type name.
getTagId() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getTcp() - Method in class org.hyperic.sigar.Sigar
TCP-MIB stats
getTcp() - Method in interface org.hyperic.sigar.SigarProxy
 
getTcpBound() - Method in class org.hyperic.sigar.NetStat
 
getTcpClose() - Method in class org.hyperic.sigar.NetStat
 
getTcpCloseWait() - Method in class org.hyperic.sigar.NetStat
 
getTcpClosing() - Method in class org.hyperic.sigar.NetStat
 
getTcpEstablished() - Method in class org.hyperic.sigar.NetStat
 
getTcpFinWait1() - Method in class org.hyperic.sigar.NetStat
 
getTcpFinWait2() - Method in class org.hyperic.sigar.NetStat
 
getTcpIdle() - Method in class org.hyperic.sigar.NetStat
 
getTcpInboundTotal() - Method in class org.hyperic.sigar.NetStat
 
getTcpLastAck() - Method in class org.hyperic.sigar.NetStat
 
getTcpListen() - Method in class org.hyperic.sigar.NetStat
 
getTcpName(long) - Static method in class org.hyperic.sigar.NetServices
Deprecated.  
getTcpOutboundTotal() - Method in class org.hyperic.sigar.NetStat
 
getTcpStates() - Method in class org.hyperic.sigar.NetStat
 
getTcpSynRecv() - Method in class org.hyperic.sigar.NetStat
 
getTcpSynSent() - Method in class org.hyperic.sigar.NetStat
 
getTcpTimeWait() - Method in class org.hyperic.sigar.NetStat
 
getThreadCpu() - Method in class org.hyperic.sigar.Sigar
Get the cumulative cpu time for the calling thread.
getThreads() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of threads.
getThreads() - Method in class org.hyperic.sigar.ProcState
Get the Number of active threads.
getTime() - Method in class org.hyperic.sigar.Who
Get the time.
getTimeGenerated() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the time at which this entry was submitted.
getTimeWritten() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the time at which this entry was received by the service to be written to the logfile.
getToolsLastActive() - Method in class org.hyperic.sigar.vmware.VM
 
getTotal() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu time.
getTotal() - Method in class org.hyperic.sigar.DirStat
Get the total.
getTotal() - Method in class org.hyperic.sigar.DirUsage
Get the total.
getTotal() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Total Kbytes of filesystem.
getTotal() - Method in class org.hyperic.sigar.Mem
Get the Total system memory.
getTotal() - Method in class org.hyperic.sigar.ProcCpu
Get the Process cpu time (sum of User and Sys).
getTotal() - Method in class org.hyperic.sigar.ProcFd
Get the Total number of open file descriptors.
getTotal() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of processes.
getTotal() - Method in class org.hyperic.sigar.ProcTime
Get the Process cpu time (sum of User and Sys).
getTotal() - Method in class org.hyperic.sigar.Swap
Get the Total system swap.
getTotal() - Method in class org.hyperic.sigar.ThreadCpu
Get the Thread cpu time (sum of User and Sys).
getTotalCores() - Method in class org.hyperic.sigar.CpuInfo
Get the Total CPU cores (logical).
getTotalSockets() - Method in class org.hyperic.sigar.CpuInfo
Get the Total CPU sockets (physical).
getTotalTime() - Method in class org.hyperic.sigar.CpuTimer
 
getTty() - Method in class org.hyperic.sigar.ProcState
Get the Device number of rocess controling terminal.
getTxBytes() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the tx_bytes.
getTxCarrier() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the tx_carrier.
getTxCollisions() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the tx_collisions.
getTxDropped() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the tx_dropped.
getTxErrors() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the *.
getTxOverruns() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the tx_overruns.
getTxPackets() - Method in class org.hyperic.sigar.NetInterfaceStat
Get the tx_packets.
getType() - Method in class org.hyperic.sigar.FileAttrs
Get the type.
getType() - Method in class org.hyperic.sigar.FileSystem
Get the File system type.
getType() - Method in class org.hyperic.sigar.NetConnection
Get the type.
getType() - Method in class org.hyperic.sigar.NetInterfaceConfig
Get the type.
getType() - Method in class org.hyperic.sigar.SigarInvoker
The type of this instance, as passed to the constructor.
getType() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getTypeChar() - Method in class org.hyperic.sigar.FileInfo
 
getTypeList() - Method in class org.hyperic.sigar.win32.ServiceConfig
 
getTypeName() - Method in class org.hyperic.sigar.FileSystem
Get the File system generic type name.
getTypeString() - Method in class org.hyperic.sigar.FileInfo
 
getTypeString() - Method in class org.hyperic.sigar.NetConnection
 
getUdpName(long) - Static method in class org.hyperic.sigar.NetServices
Deprecated.  
getUid() - Method in class org.hyperic.sigar.FileAttrs
Get the uid.
getUid() - Method in class org.hyperic.sigar.ProcCred
Get the Process user id.
getUnreachableException() - Method in class org.hyperic.sigar.NfsFileSystem
 
getUnreachableMessage() - Method in class org.hyperic.sigar.NfsFileSystem
 
getUptime() - Method in class org.hyperic.sigar.Sigar
Get system uptime info.
getUptime() - Method in interface org.hyperic.sigar.SigarProxy
 
getUptime() - Method in class org.hyperic.sigar.Uptime
Get the Time since machine started in seconds.
getUptime() - Method in class org.hyperic.sigar.vmware.VM
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.MultiwordShellCommand
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_alias
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_get
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_help
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_quit
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_set
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_sleep
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_source
 
getUsageHelp(String[]) - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getUsageHelp(String[]) - Method in interface org.hyperic.sigar.shell.ShellCommandHandler
Get some info on how to invoke this command.
getUsageShort() - Method in class org.hyperic.sigar.cmd.CpuInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Df
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Du
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.FileVersionInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Free
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Ifconfig
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Iostat
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Kill
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Ls
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.MultiPs
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.NetInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Netstat
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Nfsstat
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Pidof
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.ProcFileInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.ProcInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.ProcModuleInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Ps
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Route
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.ShowArgs
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.ShowEnv
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.SysInfo
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Time
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Ulimit
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Uptime
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Version
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Who
 
getUsageShort() - Method in class org.hyperic.sigar.cmd.Win32Service
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_alias
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_get
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_help
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_quit
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_set
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_sleep
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommand_source
 
getUsageShort() - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
getUsageShort() - Method in interface org.hyperic.sigar.shell.ShellCommandHandler
Get a very brief (40 character) description of the command
getUse() - Method in class org.hyperic.sigar.NetRoute
Get the use.
getUsed() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Total used Kbytes on filesystem.
getUsed() - Method in class org.hyperic.sigar.Mem
Get the Total used system memory.
getUsed() - Method in class org.hyperic.sigar.Swap
Get the Total used system swap.
getUsedPercent() - Method in class org.hyperic.sigar.Mem
Get the Percent total used system memory.
getUsePercent() - Method in class org.hyperic.sigar.FileSystemUsage
Get the Percent of disk used.
getUser() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu user time.
getUser() - Method in class org.hyperic.sigar.CpuPerc
 
getUser() - Method in class org.hyperic.sigar.ProcCpu
Get the Process cpu user time.
getUser() - Method in class org.hyperic.sigar.ProcCredName
Get the Process owner user name.
getUser() - Method in class org.hyperic.sigar.ProcTime
Get the Process cpu user time.
getUser() - Method in class org.hyperic.sigar.ThreadCpu
Get the Thread cpu user time.
getUser() - Method in class org.hyperic.sigar.Who
Get the user.
getUser() - Method in class org.hyperic.sigar.win32.EventLogRecord
Get the user who generated the event.
getUserDeniedMessage(long) - Method in class org.hyperic.sigar.cmd.Shell
 
getUserDeniedMessage(SigarProxy, long) - Static method in exception org.hyperic.sigar.SigarPermissionDeniedException
 
getValueNames() - Method in class org.hyperic.sigar.win32.RegistryKey
 
getVendor() - Method in class org.hyperic.sigar.CpuInfo
Get the CPU vendor id.
getVendor() - Method in class org.hyperic.sigar.SysInfo
Get the vendor.
getVendorCodeName() - Method in class org.hyperic.sigar.SysInfo
Get the vendor_code_name.
getVendorName() - Method in class org.hyperic.sigar.SysInfo
Get the vendor_name.
getVendorVersion() - Method in class org.hyperic.sigar.SysInfo
Get the vendor_version.
getVersion() - Method in class org.hyperic.sigar.SysInfo
Get the version.
getVersion() - Method in class org.hyperic.sigar.vmware.VM
 
getVirtualMemoryCur() - Method in class org.hyperic.sigar.ResourceLimit
Get the virtual_memory_cur.
getVirtualMemoryMax() - Method in class org.hyperic.sigar.ResourceLimit
Get the virtual_memory_max.
getVsize() - Method in class org.hyperic.sigar.ProcMem
Deprecated.  
getWait() - Method in class org.hyperic.sigar.Cpu
Get the Total system cpu io wait time.
getWait() - Method in class org.hyperic.sigar.CpuPerc
 
getWhoList() - Method in class org.hyperic.sigar.Sigar
 
getWhoList() - Method in interface org.hyperic.sigar.SigarProxy
 
getWindow() - Method in class org.hyperic.sigar.NetRoute
Get the window.
getWrite() - Method in class org.hyperic.sigar.NfsClientV2
Get the write.
getWrite() - Method in class org.hyperic.sigar.NfsClientV3
Get the write.
getWrite() - Method in class org.hyperic.sigar.NfsServerV2
Get the write.
getWrite() - Method in class org.hyperic.sigar.NfsServerV3
Get the write.
getWriteBytes() - Method in class org.hyperic.sigar.DiskUsage
Get the Number of physical disk bytes written.
getWritecache() - Method in class org.hyperic.sigar.NfsClientV2
Get the writecache.
getWritecache() - Method in class org.hyperic.sigar.NfsServerV2
Get the writecache.
getWrites() - Method in class org.hyperic.sigar.DiskUsage
Get the Number of physical disk writes.
getZombie() - Method in class org.hyperic.sigar.ProcStat
Get the Total number of processes in zombie state.
gl - Variable in class org.hyperic.sigar.shell.ShellBase
 
GSX - Static variable in class org.hyperic.sigar.vmware.VM
 

H

handle(Signal) - Method in class org.hyperic.sigar.shell.ShellIntHandler
 
handleCommand(String) - Method in class org.hyperic.sigar.shell.ShellBase
 
handleCommand(String, String[]) - Method in class org.hyperic.sigar.shell.ShellBase
 
handleNotification(EventLogRecord) - Method in interface org.hyperic.sigar.win32.EventLogNotification
Called if matches() returns true
handlerIsHidden(String) - Method in class org.hyperic.sigar.shell.ShellBase
 
handleSIGINT() - Method in class org.hyperic.sigar.shell.ShellBase
 
handleSIGINT() - Method in interface org.hyperic.sigar.shell.SIGINT
 
hasCompleter(ShellCommandHandler) - Method in class org.hyperic.sigar.shell.ShellBase
 
hashCode() - Method in class org.hyperic.sigar.FileInfo
 
hashCode() - Method in class org.hyperic.sigar.MultiProcCpu
 
hasNext() - Method in class org.hyperic.sigar.util.IteratorIterator
 
hasSnapshot() - Method in class org.hyperic.sigar.vmware.VM
 
Humidor - Class in org.hyperic.sigar
The Humidor provides access to a single Sigar instance.
Humidor(Sigar) - Constructor for class org.hyperic.sigar.Humidor
 

I

IDLE - Static variable in class org.hyperic.sigar.ProcState
 
Ifconfig - Class in org.hyperic.sigar.cmd
Display network interface configuration and metrics.
Ifconfig(Shell) - Constructor for class org.hyperic.sigar.cmd.Ifconfig
 
Ifconfig() - Constructor for class org.hyperic.sigar.cmd.Ifconfig
 
IFF_ALLMULTI - Static variable in class org.hyperic.sigar.NetFlags
receive all multicast packets
IFF_BROADCAST - Static variable in class org.hyperic.sigar.NetFlags
broadcast address valid
IFF_DEBUG - Static variable in class org.hyperic.sigar.NetFlags
debugging is on
IFF_LOOPBACK - Static variable in class org.hyperic.sigar.NetFlags
is a loopback net
IFF_MULTICAST - Static variable in class org.hyperic.sigar.NetFlags
supports multicast
IFF_NOARP - Static variable in class org.hyperic.sigar.NetFlags
no ARP protocol
IFF_NOTRAILERS - Static variable in class org.hyperic.sigar.NetFlags
avoid use of trailers
IFF_POINTOPOINT - Static variable in class org.hyperic.sigar.NetFlags
interface has a point-to-point link
IFF_PROMISC - Static variable in class org.hyperic.sigar.NetFlags
receive all packets
IFF_RUNNING - Static variable in class org.hyperic.sigar.NetFlags
interface is running
IFF_SLAVE - Static variable in class org.hyperic.sigar.NetFlags
 
IFF_UP - Static variable in class org.hyperic.sigar.NetFlags
interface is up
INFINITY() - Static method in class org.hyperic.sigar.ResourceLimit
 
init(FileSystem[]) - Method in class org.hyperic.sigar.FileSystemMap
Populate the map.
init(String, PrintStream, PrintStream) - Method in class org.hyperic.sigar.shell.ShellBase
 
init(String, ShellBase) - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
init(String, ShellBase) - Method in interface org.hyperic.sigar.shell.ShellCommandHandler
Initialize this command handler.
initHistory() - Method in class org.hyperic.sigar.shell.ShellBase
 
initHistory(File) - Method in class org.hyperic.sigar.shell.ShellBase
 
initHistoryFile(File) - Method in class org.hyperic.sigar.util.Getline
 
INSTANCE - Static variable in exception org.hyperic.sigar.SigarNotImplementedException
 
invoke(Object, String) - Method in class org.hyperic.sigar.SigarInvoker
 
invoke(Object[], String) - Method in class org.hyperic.sigar.SigarInvoker
 
invoke(Object, Method, Object[]) - Method in class org.hyperic.sigar.SigarProxyCache
The java.lang.reflect.InvocationHandler used by the Proxy.
Iostat - Class in org.hyperic.sigar.cmd
Report filesytem disk space usage.
Iostat(Shell) - Constructor for class org.hyperic.sigar.cmd.Iostat
 
Iostat() - Constructor for class org.hyperic.sigar.cmd.Iostat
 
IS_WIN32 - Static variable in class org.hyperic.sigar.OperatingSystem
 
isAnyAddress(String) - Static method in class org.hyperic.sigar.NetFlags
 
isConnected() - Method in class org.hyperic.sigar.vmware.VM
 
isConnected() - Method in class org.hyperic.sigar.vmware.VMwareServer
 
isEnglish() - Static method in class org.hyperic.sigar.win32.LocaleInfo
 
isESX() - Method in class org.hyperic.sigar.vmware.VM
 
isGSX() - Method in class org.hyperic.sigar.vmware.VM
 
isInteractive() - Method in class org.hyperic.sigar.cmd.Shell
 
isLoaded() - Static method in class org.hyperic.sigar.vmware.VMControlLibrary
 
isLoopback(String) - Static method in class org.hyperic.sigar.NetFlags
 
isMounted(String) - Method in class org.hyperic.sigar.FileSystemMap
 
isOff() - Method in class org.hyperic.sigar.vmware.VM
 
isOn() - Method in class org.hyperic.sigar.vmware.VM
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.Kill
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.MultiPs
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.ProcFileInfo
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.ProcInfo
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.ProcModuleInfo
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.Ps
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.ShowArgs
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.ShowEnv
 
isPidCompleter() - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
isRedirected() - Method in class org.hyperic.sigar.shell.ShellBase
Check to see if the currently running shell command is being redirected to a file.
isRegistered(String) - Method in class org.hyperic.sigar.vmware.VMwareServer
 
isSigarClass(Class) - Static method in class org.hyperic.sigar.shell.ProcessQueryCompleter
 
isStuck() - Method in class org.hyperic.sigar.vmware.VM
 
isSupported(String) - Static method in class org.hyperic.sigar.OperatingSystem
 
isSuspended() - Method in class org.hyperic.sigar.vmware.VM
 
isTTY() - Static method in class org.hyperic.sigar.util.Getline
 
isWin32(String) - Static method in class org.hyperic.sigar.OperatingSystem
 
IteratorIterator - Class in org.hyperic.sigar.util
Iterator for multiple Iterators.
IteratorIterator() - Constructor for class org.hyperic.sigar.util.IteratorIterator
 
itsCommandName - Variable in class org.hyperic.sigar.shell.ShellCommandBase
 
itsShell - Variable in class org.hyperic.sigar.shell.ShellCommandBase
 

J

join(List) - Static method in class org.hyperic.sigar.cmd.Ps
 

K

Kill - Class in org.hyperic.sigar.cmd
Send a signal to a process.
Kill(Shell) - Constructor for class org.hyperic.sigar.cmd.Kill
 
Kill() - Constructor for class org.hyperic.sigar.cmd.Kill
 
kill(long, int) - Method in class org.hyperic.sigar.Sigar
Send a signal to a process.
kill(long, String) - Method in class org.hyperic.sigar.Sigar
Send a signal to a process.
kill(String, int) - Method in class org.hyperic.sigar.Sigar
Send a signal to a process.

L

LANG_ENGLISH - Static variable in class org.hyperic.sigar.win32.LocaleInfo
English primary language id
link() - Static method in class org.hyperic.sigar.vmware.VMControlLibrary
 
link(String) - Static method in class org.hyperic.sigar.vmware.VMControlLibrary
 
list(PrintStream) - Method in class org.hyperic.sigar.CpuTimer
 
list(PrintStream) - Method in class org.hyperic.sigar.win32.Service
 
list(PrintStream) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
load() - Static method in class org.hyperic.sigar.Sigar
 
LOCALE_SENGCOUNTRY - Static variable in class org.hyperic.sigar.win32.LocaleInfo
English name of country
LOCALE_SENGLANGUAGE - Static variable in class org.hyperic.sigar.win32.LocaleInfo
English name of language
LocaleInfo - Class in org.hyperic.sigar.win32
 
LocaleInfo() - Constructor for class org.hyperic.sigar.win32.LocaleInfo
 
LocaleInfo(Integer) - Constructor for class org.hyperic.sigar.win32.LocaleInfo
 
LocaleInfo(int) - Constructor for class org.hyperic.sigar.win32.LocaleInfo
 
LocaleInfo(int, int) - Constructor for class org.hyperic.sigar.win32.LocaleInfo
 
LocalMachine - Static variable in class org.hyperic.sigar.win32.RegistryKey
HKEY_LOCAL_MACHINE
LOOPBACK_ADDRESS - Static variable in class org.hyperic.sigar.NetFlags
 
LOOPBACK_ADDRESS_V6 - Static variable in class org.hyperic.sigar.NetFlags
 
LOOPBACK_HOSTNAME - Static variable in class org.hyperic.sigar.NetFlags
 
Ls - Class in org.hyperic.sigar.cmd
 
Ls(Shell) - Constructor for class org.hyperic.sigar.cmd.Ls
 
Ls() - Constructor for class org.hyperic.sigar.cmd.Ls
 

M

main(String[]) - Static method in class org.hyperic.sigar.cmd.CpuInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Df
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Du
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.EventLogTail
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.FileVersionInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Free
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Ifconfig
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Iostat
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Kill
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Ls
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.MemWatch
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.MultiPs
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.NetInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Netstat
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.ProcFileInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.ProcInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.ProcModuleInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Ps
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Route
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Runner
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Shell
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.ShowArgs
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.ShowEnv
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.SysInfo
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Tail
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Time
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Top
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Ulimit
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Uptime
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Version
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Watch
 
main(String[]) - Static method in class org.hyperic.sigar.cmd.Who
 
main(String[]) - Static method in class org.hyperic.sigar.NfsFileSystem
 
main(String[]) - Static method in class org.hyperic.sigar.OperatingSystem
 
main(String[]) - Static method in class org.hyperic.sigar.RPC
 
main(String[]) - Static method in class org.hyperic.sigar.shell.FileCompleter
 
main(String[]) - Static method in class org.hyperic.sigar.vmware.VMControlLibrary
 
main(String[]) - Static method in class org.hyperic.sigar.win32.EventLogThread
 
main(String[]) - Static method in class org.hyperic.sigar.win32.MetaBase
 
main(String[]) - Static method in class org.hyperic.sigar.win32.Pdh
Main method for dumping the entire PDH Usage: Pdh [OPTION] Show information from the Windows PDH -v, --values include key values [default=no] --object=NAME only print info on this object --contains=NAME only print info on objects that contain this substring -i, --instance show instances [default=no] -k, --keys show keys [default=no] -h, --help display help and exit
main(String[]) - Static method in class org.hyperic.sigar.win32.Service
 
main(String[]) - Static method in class org.hyperic.sigar.win32.Win32
 
makeLangId(int, int) - Static method in class org.hyperic.sigar.win32.LocaleInfo
 
MalformedQueryException - Exception in org.hyperic.sigar.ptql
Exception for malformed process queries which cannot be parsed.
MalformedQueryException() - Constructor for exception org.hyperic.sigar.ptql.MalformedQueryException
 
MalformedQueryException(String) - Constructor for exception org.hyperic.sigar.ptql.MalformedQueryException
 
map - Variable in class org.hyperic.sigar.util.ReferenceMap
 
mark(int) - Method in class org.hyperic.sigar.SudoFileInputStream
 
markSupported() - Method in class org.hyperic.sigar.SudoFileInputStream
 
match(Sigar, long) - Method in interface org.hyperic.sigar.ptql.ProcessQuery
 
match(Sigar, long) - Method in class org.hyperic.sigar.ptql.SigarProcessQuery
 
matches(String, String) - Static method in class org.hyperic.sigar.ptql.StringPattern
Wrapper around Pattern.compile(regex).matcher(source).find()
matches(EventLogRecord) - Method in interface org.hyperic.sigar.win32.EventLogNotification
Determine if we want to handle this event.
MD_CONNECTION_TIMEOUT - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_DOWNLEVEL_ADMIN_INSTANCE - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_IISADMIN_EXTENSIONS - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_LEVELS_TO_SCAN - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_LOGFILEDIRECTORY - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_MAX_CONNECTIONS - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_MAX_ENDPOINT_CONNECTIONS - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SECURE_BINDINGS - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_AUTOSTART - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_BINDINGS - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_COMMAND - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_COMMENT - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_CONFIGURATION_INFO - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_LISTEN_BACKLOG - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_LISTEN_TIMEOUT - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_SIZE - Static variable in class org.hyperic.sigar.win32.MetaBase
 
MD_SERVER_STATE - Static variable in class org.hyperic.sigar.win32.MetaBase
 
Mem - Class in org.hyperic.sigar
Mem sigar class.
Mem() - Constructor for class org.hyperic.sigar.Mem
 
MemWatch - Class in org.hyperic.sigar.cmd
Watch for changes in program memory usage.
MemWatch() - Constructor for class org.hyperic.sigar.cmd.MemWatch
 
MetaBase - Class in org.hyperic.sigar.win32
 
MetaBase() - Constructor for class org.hyperic.sigar.win32.MetaBase
 
MODE_GEXECUTE - Static variable in class org.hyperic.sigar.FileInfo
Executable by group.
MODE_GREAD - Static variable in class org.hyperic.sigar.FileInfo
Readable by group.
MODE_GWRITE - Static variable in class org.hyperic.sigar.FileInfo
Writable by group.
MODE_UEXECUTE - Static variable in class org.hyperic.sigar.FileInfo
Executable by user.
MODE_UREAD - Static variable in class org.hyperic.sigar.FileInfo
Readable by user.
MODE_UWRITE - Static variable in class org.hyperic.sigar.FileInfo
Writable by user.
MODE_WEXECUTE - Static variable in class org.hyperic.sigar.FileInfo
Executable by others.
MODE_WREAD - Static variable in class org.hyperic.sigar.FileInfo
Readable by others.
MODE_WWRITE - Static variable in class org.hyperic.sigar.FileInfo
Writable by others.
modified() - Method in class org.hyperic.sigar.FileInfo
 
MultiProcCpu - Class in org.hyperic.sigar
Provide multi process cpu metrics.
MultiProcCpu() - Constructor for class org.hyperic.sigar.MultiProcCpu
 
MultiProcMem - Class in org.hyperic.sigar
 
MultiProcMem() - Constructor for class org.hyperic.sigar.MultiProcMem
 
MultiPs - Class in org.hyperic.sigar.cmd
Show multi process status.
MultiPs(Shell) - Constructor for class org.hyperic.sigar.cmd.MultiPs
 
MultiPs() - Constructor for class org.hyperic.sigar.cmd.MultiPs
 
MultiwordShellCommand - Class in org.hyperic.sigar.shell
 
MultiwordShellCommand() - Constructor for class org.hyperic.sigar.shell.MultiwordShellCommand
 

N

NAME_AIX - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_FREEBSD - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_HPUX - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_LINUX - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_MACOSX - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_NETBSD - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_NETWARE - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_OPENBSD - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_SOLARIS - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAME_WIN32 - Static variable in class org.hyperic.sigar.OperatingSystem
 
NAMES - Static variable in class org.hyperic.sigar.OperatingSystem
 
NATIVE_BUILD_DATE - Static variable in class org.hyperic.sigar.Sigar
The date on which the sigar native binary was built.
NATIVE_SCM_REVISION - Static variable in class org.hyperic.sigar.Sigar
The scm (svn) revision from which the sigar native binary was built.
NATIVE_VERSION_STRING - Static variable in class org.hyperic.sigar.Sigar
The Sigar native version.
NetConnection - Class in org.hyperic.sigar
NetConnection sigar class.
NetConnection() - Constructor for class org.hyperic.sigar.NetConnection
 
NetFlags - Class in org.hyperic.sigar
Flag constants for network related ops.
NetInfo - Class in org.hyperic.sigar.cmd
Display network info.
NetInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.NetInfo
 
NetInfo() - Constructor for class org.hyperic.sigar.cmd.NetInfo
 
NetInfo - Class in org.hyperic.sigar
NetInfo sigar class.
NetInfo() - Constructor for class org.hyperic.sigar.NetInfo
 
NetInterfaceConfig - Class in org.hyperic.sigar
NetInterfaceConfig sigar class.
NetInterfaceConfig() - Constructor for class org.hyperic.sigar.NetInterfaceConfig
 
NetInterfaceStat - Class in org.hyperic.sigar
NetInterfaceStat sigar class.
NetInterfaceStat() - Constructor for class org.hyperic.sigar.NetInterfaceStat
 
NetRoute - Class in org.hyperic.sigar
NetRoute sigar class.
NetRoute() - Constructor for class org.hyperic.sigar.NetRoute
 
NetServices - Class in org.hyperic.sigar
Deprecated.  
Netstat - Class in org.hyperic.sigar.cmd
Display network connections.
Netstat(Shell) - Constructor for class org.hyperic.sigar.cmd.Netstat
 
Netstat() - Constructor for class org.hyperic.sigar.cmd.Netstat
 
NetStat - Class in org.hyperic.sigar
 
NetStat() - Constructor for class org.hyperic.sigar.NetStat
 
newInstance() - Static method in class org.hyperic.sigar.SigarProxyCache
 
newInstance(Sigar) - Static method in class org.hyperic.sigar.SigarProxyCache
 
newInstance(Sigar, int) - Static method in class org.hyperic.sigar.SigarProxyCache
 
newInstance() - Static method in class org.hyperic.sigar.util.ReferenceMap
 
newInstance(Map) - Static method in class org.hyperic.sigar.util.ReferenceMap
 
next() - Method in class org.hyperic.sigar.util.IteratorIterator
 
NfsClientV2 - Class in org.hyperic.sigar
NfsClientV2 sigar class.
NfsClientV2() - Constructor for class org.hyperic.sigar.NfsClientV2
 
NfsClientV3 - Class in org.hyperic.sigar
NfsClientV3 sigar class.
NfsClientV3() - Constructor for class org.hyperic.sigar.NfsClientV3
 
NfsFileSystem - Class in org.hyperic.sigar
 
NfsFileSystem() - Constructor for class org.hyperic.sigar.NfsFileSystem
 
NfsServerV2 - Class in org.hyperic.sigar
NfsServerV2 sigar class.
NfsServerV2() - Constructor for class org.hyperic.sigar.NfsServerV2
 
NfsServerV3 - Class in org.hyperic.sigar
NfsServerV3 sigar class.
NfsServerV3() - Constructor for class org.hyperic.sigar.NfsServerV3
 
Nfsstat - Class in org.hyperic.sigar.cmd
 
Nfsstat(Shell) - Constructor for class org.hyperic.sigar.cmd.Nfsstat
 
Nfsstat() - Constructor for class org.hyperic.sigar.cmd.Nfsstat
 
NfsUnreachableException - Exception in org.hyperic.sigar
 
NfsUnreachableException() - Constructor for exception org.hyperic.sigar.NfsUnreachableException
 
NfsUnreachableException(String) - Constructor for exception org.hyperic.sigar.NfsUnreachableException
 
NO_COUNTER - Static variable in class org.hyperic.sigar.win32.Pdh
The specified counter could not be found.
NO_INSTANCE - Static variable in class org.hyperic.sigar.win32.Pdh
The specified instance is not present.
NO_MACHINE - Static variable in class org.hyperic.sigar.win32.Pdh
Unable to connect to specified machine or machine is off line.
NO_OBJECT - Static variable in class org.hyperic.sigar.win32.Pdh
The specified object is not found on the system.
NormalQuitCommandException - Exception in org.hyperic.sigar.shell
This exception is thrown when a command wants to exit the shell completely.
NormalQuitCommandException() - Constructor for exception org.hyperic.sigar.shell.NormalQuitCommandException
 
NULL_HWADDR - Static variable in class org.hyperic.sigar.NetFlags
value of unknown or non-existent hardware address
number - Variable in class org.hyperic.sigar.cmd.Tail
 

O

onChange(FileInfo) - Method in class org.hyperic.sigar.FileTail
 
onChange(FileInfo) - Method in class org.hyperic.sigar.FileWatcher
 
onChange(FileInfo) - Method in class org.hyperic.sigar.ProcFileMirror
 
onException(FileInfo, SigarException) - Method in class org.hyperic.sigar.FileWatcher
 
onNotFound(FileInfo) - Method in class org.hyperic.sigar.FileWatcher
 
open(String) - Method in class org.hyperic.sigar.win32.EventLog
Open the event log.
openlog(String) - Method in class org.hyperic.sigar.win32.EventLog
 
OpenSubKey(String) - Method in class org.hyperic.sigar.win32.MetaBase
 
openSubKey(String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
OperatingSystem - Class in org.hyperic.sigar
 
org.hyperic.sigar - package org.hyperic.sigar
Sigar - System Information Gatherer And Reporter
org.hyperic.sigar.cmd - package org.hyperic.sigar.cmd
Example classes implementing familar unix tools in Java.
org.hyperic.sigar.ptql - package org.hyperic.sigar.ptql
Process Table Query Language
org.hyperic.sigar.shell - package org.hyperic.sigar.shell
Base package for implementing a command shell.
org.hyperic.sigar.util - package org.hyperic.sigar.util
Utility classes independent of Sigar.
org.hyperic.sigar.vmware - package org.hyperic.sigar.vmware
 
org.hyperic.sigar.win32 - package org.hyperic.sigar.win32
 
out - Variable in class org.hyperic.sigar.cmd.SigarCommandBase
 
out - Variable in class org.hyperic.sigar.shell.ShellBase
 
output(String[]) - Method in class org.hyperic.sigar.cmd.CpuInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Df
 
output(FileSystem) - Method in class org.hyperic.sigar.cmd.Df
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Du
 
output(String[]) - Method in class org.hyperic.sigar.cmd.FileVersionInfo
 
output(String) - Method in class org.hyperic.sigar.cmd.FileVersionInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Free
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Ifconfig
 
output(String) - Method in class org.hyperic.sigar.cmd.Ifconfig
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Iostat
 
output(FileSystem) - Method in class org.hyperic.sigar.cmd.Iostat
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Kill
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Ls
 
output(String[]) - Method in class org.hyperic.sigar.cmd.MultiPs
 
output(String[]) - Method in class org.hyperic.sigar.cmd.NetInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Netstat
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Nfsstat
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Pidof
 
output(String[]) - Method in class org.hyperic.sigar.cmd.ProcFileInfo
 
output(long) - Method in class org.hyperic.sigar.cmd.ProcFileInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.ProcInfo
 
output(String) - Method in class org.hyperic.sigar.cmd.ProcInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.ProcModuleInfo
 
output(long) - Method in class org.hyperic.sigar.cmd.ProcModuleInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Ps
 
output(long) - Method in class org.hyperic.sigar.cmd.Ps
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Route
 
output(String[]) - Method in class org.hyperic.sigar.cmd.ShowArgs
 
output(long) - Method in class org.hyperic.sigar.cmd.ShowArgs
 
output(String[]) - Method in class org.hyperic.sigar.cmd.ShowEnv
 
output(long) - Method in class org.hyperic.sigar.cmd.ShowEnv
 
output - Variable in class org.hyperic.sigar.cmd.SigarCommandBase
 
output(String[]) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
output(String[]) - Method in class org.hyperic.sigar.cmd.SysInfo
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Time
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Ulimit
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Uptime
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Version
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Who
 
output(String[]) - Method in class org.hyperic.sigar.cmd.Win32Service
 
outputDisk(String) - Method in class org.hyperic.sigar.cmd.Iostat
 
outputFileSystem(String) - Method in class org.hyperic.sigar.cmd.Iostat
 

P

parseArgs(String[]) - Method in class org.hyperic.sigar.cmd.Tail
 
pause() - Method in class org.hyperic.sigar.win32.Service
 
pause(long) - Method in class org.hyperic.sigar.win32.Service
 
Pdh - Class in org.hyperic.sigar.win32
 
Pdh() - Constructor for class org.hyperic.sigar.win32.Pdh
 
Pdh(String) - Constructor for class org.hyperic.sigar.win32.Pdh
 
PERF_TYPE_COUNTER - Static variable in class org.hyperic.sigar.win32.Pdh
 
PERF_TYPE_NUMBER - Static variable in class org.hyperic.sigar.win32.Pdh
 
PERF_TYPE_TEXT - Static variable in class org.hyperic.sigar.win32.Pdh
 
PERF_TYPE_ZERO - Static variable in class org.hyperic.sigar.win32.Pdh
 
PERFLIB_KEY - Static variable in class org.hyperic.sigar.win32.Pdh
 
performPaging(PageFetcher) - Method in class org.hyperic.sigar.shell.ShellBase
 
performPaging(PageFetcher, PageControl) - Method in class org.hyperic.sigar.shell.ShellBase
 
PERM_EXECUTE - Static variable in class org.hyperic.sigar.vmware.VM
 
PERM_READ - Static variable in class org.hyperic.sigar.vmware.VM
 
PERM_WRITE - Static variable in class org.hyperic.sigar.vmware.VM
 
Pidof - Class in org.hyperic.sigar.cmd
 
Pidof(Shell) - Constructor for class org.hyperic.sigar.cmd.Pidof
 
Pidof() - Constructor for class org.hyperic.sigar.cmd.Pidof
 
ping() - Method in class org.hyperic.sigar.NfsFileSystem
 
ping(String, int, long, long) - Static method in class org.hyperic.sigar.RPC
 
ping(String, int, String, long) - Static method in class org.hyperic.sigar.RPC
 
ping(String, long) - Static method in class org.hyperic.sigar.RPC
 
ping(String, String) - Static method in class org.hyperic.sigar.RPC
 
PLATFORM_LINUX - Static variable in class org.hyperic.sigar.vmware.VM
 
PLATFORM_UNKNOWN - Static variable in class org.hyperic.sigar.vmware.VM
 
PLATFORM_VMNIX - Static variable in class org.hyperic.sigar.vmware.VM
 
PLATFORM_WINDOWS - Static variable in class org.hyperic.sigar.vmware.VM
 
PLATFORMS - Static variable in class org.hyperic.sigar.vmware.VM
 
poll() - Method in class org.hyperic.sigar.util.ReferenceMap
 
pop() - Static method in class org.hyperic.sigar.shell.ShellIntHandler
 
POWEROP_MODE_HARD - Static variable in class org.hyperic.sigar.vmware.VM
 
POWEROP_MODE_SOFT - Static variable in class org.hyperic.sigar.vmware.VM
 
POWEROP_MODE_TRYSOFT - Static variable in class org.hyperic.sigar.vmware.VM
 
printf(String, Object[]) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
printf(Object[]) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
printf(List) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
PrintfFormat - Class in org.hyperic.sigar.util
PrintfFormat allows the formatting of an array of objects embedded within a string.
PrintfFormat(String) - Constructor for class org.hyperic.sigar.util.PrintfFormat
Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings.
PrintfFormat(Locale, String) - Constructor for class org.hyperic.sigar.util.PrintfFormat
Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings.
printHeader() - Method in class org.hyperic.sigar.cmd.Df
 
printHeader() - Method in class org.hyperic.sigar.cmd.Iostat
 
printInfo(PrintStream) - Static method in class org.hyperic.sigar.cmd.Version
 
println(String) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
ProcCpu - Class in org.hyperic.sigar
ProcCpu sigar class.
ProcCpu() - Constructor for class org.hyperic.sigar.ProcCpu
 
ProcCred - Class in org.hyperic.sigar
ProcCred sigar class.
ProcCred() - Constructor for class org.hyperic.sigar.ProcCred
 
ProcCredName - Class in org.hyperic.sigar
ProcCredName sigar class.
ProcCredName() - Constructor for class org.hyperic.sigar.ProcCredName
 
processCommand(ShellCommandHandler, String[]) - Method in class org.hyperic.sigar.cmd.Shell
 
processCommand(String[]) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.MultiwordShellCommand
 
processCommand(ShellCommandHandler, String[]) - Method in class org.hyperic.sigar.shell.ShellBase
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_alias
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_get
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_help
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_quit
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_set
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_sleep
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommand_source
 
processCommand(String[]) - Method in class org.hyperic.sigar.shell.ShellCommandBase
 
processCommand(String[]) - Method in interface org.hyperic.sigar.shell.ShellCommandHandler
Handle a command.
ProcessFinder - Class in org.hyperic.sigar.ptql
 
ProcessFinder(SigarProxy) - Constructor for class org.hyperic.sigar.ptql.ProcessFinder
Deprecated.  
ProcessFinder(Sigar) - Constructor for class org.hyperic.sigar.ptql.ProcessFinder
 
ProcessQuery - Interface in org.hyperic.sigar.ptql
 
ProcessQueryCompleter - Class in org.hyperic.sigar.shell
 
ProcessQueryCompleter(ShellBase) - Constructor for class org.hyperic.sigar.shell.ProcessQueryCompleter
 
ProcessQueryFactory - Class in org.hyperic.sigar.ptql
 
ProcessQueryFactory() - Constructor for class org.hyperic.sigar.ptql.ProcessQueryFactory
 
ProcExe - Class in org.hyperic.sigar
ProcExe sigar class.
ProcExe() - Constructor for class org.hyperic.sigar.ProcExe
 
ProcFd - Class in org.hyperic.sigar
ProcFd sigar class.
ProcFd() - Constructor for class org.hyperic.sigar.ProcFd
 
ProcFileInfo - Class in org.hyperic.sigar.cmd
Display process file information.
ProcFileInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.ProcFileInfo
 
ProcFileInfo() - Constructor for class org.hyperic.sigar.cmd.ProcFileInfo
 
ProcFileMirror - Class in org.hyperic.sigar
 
ProcFileMirror(Sigar, String) - Constructor for class org.hyperic.sigar.ProcFileMirror
 
ProcInfo - Class in org.hyperic.sigar.cmd
Display all process information.
ProcInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.ProcInfo
 
ProcInfo() - Constructor for class org.hyperic.sigar.cmd.ProcInfo
 
ProcMem - Class in org.hyperic.sigar
ProcMem sigar class.
ProcMem() - Constructor for class org.hyperic.sigar.ProcMem
 
ProcModuleInfo - Class in org.hyperic.sigar.cmd
Display process module info.
ProcModuleInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.ProcModuleInfo
 
ProcModuleInfo() - Constructor for class org.hyperic.sigar.cmd.ProcModuleInfo
 
ProcStat - Class in org.hyperic.sigar
ProcStat sigar class.
ProcStat() - Constructor for class org.hyperic.sigar.ProcStat
 
ProcState - Class in org.hyperic.sigar
ProcState sigar class.
ProcState() - Constructor for class org.hyperic.sigar.ProcState
 
ProcTime - Class in org.hyperic.sigar
ProcTime sigar class.
ProcTime() - Constructor for class org.hyperic.sigar.ProcTime
 
ProcUtil - Class in org.hyperic.sigar
 
ProcUtil() - Constructor for class org.hyperic.sigar.ProcUtil
 
PRODINFO_BUILD - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODINFO_PLATFORM - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODINFO_PRODUCT - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODINFO_VERSION_MAJOR - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODINFO_VERSION_MINOR - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODINFO_VERSION_REVISION - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODUCT_ESX - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODUCT_GSX - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODUCT_SERVER - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODUCT_UNKNOWN - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODUCT_WS - Static variable in class org.hyperic.sigar.vmware.VM
 
PRODUCTS - Static variable in class org.hyperic.sigar.vmware.VM
 
PROP_PAGE_SIZE - Static variable in class org.hyperic.sigar.shell.ShellBase
 
PROP_SIGAR_JAR_NAME - Static variable in class org.hyperic.sigar.SigarLoader
 
PROP_USE_SUDO - Static variable in class org.hyperic.sigar.FileTail
 
PROP_VMCONTROL_SHLIB - Static variable in class org.hyperic.sigar.vmware.VMControlLibrary
 
proxy - Variable in class org.hyperic.sigar.cmd.SigarCommandBase
 
Ps - Class in org.hyperic.sigar.cmd
Show process status.
Ps(Shell) - Constructor for class org.hyperic.sigar.cmd.Ps
 
Ps() - Constructor for class org.hyperic.sigar.cmd.Ps
 
push(SIGINT) - Static method in class org.hyperic.sigar.shell.ShellIntHandler
 
put(Object, Object) - Method in class org.hyperic.sigar.FileSystemMap
FileSystemMap is read-only, this method is unsupported.
put(Object, Object) - Method in class org.hyperic.sigar.util.ReferenceMap
 
put(Object, Object) - Method in class org.hyperic.sigar.util.WeakReferenceMap
 

Q

QueryLoadException - Exception in org.hyperic.sigar.ptql
Deprecated.  
QueryLoadException() - Constructor for exception org.hyperic.sigar.ptql.QueryLoadException
Deprecated.  
QueryLoadException(String) - Constructor for exception org.hyperic.sigar.ptql.QueryLoadException
Deprecated.  
queue - Variable in class org.hyperic.sigar.util.ReferenceMap
 

R

RCFILE_NAME - Static variable in class org.hyperic.sigar.cmd.Shell
 
read() - Method in class org.hyperic.sigar.SudoFileInputStream
 
read(byte[]) - Method in class org.hyperic.sigar.SudoFileInputStream
 
read(byte[], int, int) - Method in class org.hyperic.sigar.SudoFileInputStream
 
read(int) - Method in class org.hyperic.sigar.win32.EventLog
Read an event log record.
readCommandFile(String) - Method in class org.hyperic.sigar.cmd.Shell
 
readRCFile(File, boolean) - Method in class org.hyperic.sigar.shell.ShellBase
Read a .rc file into the shell, invoking everything in it (without saving the actions to history)
redraw() - Method in class org.hyperic.sigar.util.Getline
 
ReferenceMap - Class in org.hyperic.sigar.util
 
ReferenceMap() - Constructor for class org.hyperic.sigar.util.ReferenceMap
 
ReferenceMap(Map) - Constructor for class org.hyperic.sigar.util.ReferenceMap
 
ReferenceMap.MapReference - Interface in org.hyperic.sigar.util
 
ReferenceMap.SoftValue - Class in org.hyperic.sigar.util
 
ReferenceMap.WeakValue - Class in org.hyperic.sigar.util
 
ReferenceMap.WeakValue(Object, Object, ReferenceQueue) - Constructor for class org.hyperic.sigar.util.ReferenceMap.WeakValue
 
register(ShellBase) - Static method in class org.hyperic.sigar.shell.ShellIntHandler
 
registerCommandHandler(String, ShellCommandHandler) - Method in class org.hyperic.sigar.shell.ShellBase
Register a new command handler.
registerCommands() - Method in class org.hyperic.sigar.cmd.Shell
 
registerSigIntHandler() - Method in class org.hyperic.sigar.shell.ShellBase
 
registerSubHandler(String, ShellCommandHandler) - Method in class org.hyperic.sigar.shell.MultiwordShellCommand
 
REGISTRY_ROOT - Static variable in class org.hyperic.sigar.vmware.VMControlLibrary
 
RegistryKey - Class in org.hyperic.sigar.win32
 
remove(File) - Method in class org.hyperic.sigar.FileWatcher
 
remove(String) - Method in class org.hyperic.sigar.FileWatcher
 
remove(FileWatcher) - Method in class org.hyperic.sigar.FileWatcherThread
 
remove() - Method in class org.hyperic.sigar.util.IteratorIterator
 
remove(Object) - Method in class org.hyperic.sigar.util.ReferenceMap
 
remove(EventLogNotification) - Method in class org.hyperic.sigar.win32.EventLogThread
 
removeAllSnapshots() - Method in class org.hyperic.sigar.vmware.VM
 
reset() - Method in class org.hyperic.sigar.SudoFileInputStream
 
reset() - Method in class org.hyperic.sigar.util.Getline
 
reset(int) - Method in class org.hyperic.sigar.vmware.VM
 
reset() - Method in class org.hyperic.sigar.vmware.VM
 
ResourceLimit - Class in org.hyperic.sigar
ResourceLimit sigar class.
ResourceLimit() - Constructor for class org.hyperic.sigar.ResourceLimit
 
resume(int) - Method in class org.hyperic.sigar.vmware.VM
 
resume() - Method in class org.hyperic.sigar.vmware.VM
 
resume() - Method in class org.hyperic.sigar.win32.Service
 
revertToSnapshot() - Method in class org.hyperic.sigar.vmware.VM
 
Route - Class in org.hyperic.sigar.cmd
 
Route(Shell) - Constructor for class org.hyperic.sigar.cmd.Route
 
Route() - Constructor for class org.hyperic.sigar.cmd.Route
 
RPC - Class in org.hyperic.sigar
 
RPC() - Constructor for class org.hyperic.sigar.RPC
 
RTF_GATEWAY - Static variable in class org.hyperic.sigar.NetFlags
 
RTF_HOST - Static variable in class org.hyperic.sigar.NetFlags
 
RTF_UP - Static variable in class org.hyperic.sigar.NetFlags
 
run() - Method in class org.hyperic.sigar.FileWatcherThread
 
RUN - Static variable in class org.hyperic.sigar.ProcState
 
run() - Method in class org.hyperic.sigar.shell.ShellBase
 
run() - Method in class org.hyperic.sigar.win32.EventLogThread
 
Runner - Class in org.hyperic.sigar.cmd
 
Runner() - Constructor for class org.hyperic.sigar.cmd.Runner
 

S

saveScreenshot(String) - Method in class org.hyperic.sigar.vmware.VM
 
SCM_REVISION - Static variable in class org.hyperic.sigar.Sigar
The scm (svn) revision from which sigar.jar was built.
SECURITY - Static variable in class org.hyperic.sigar.win32.EventLog
 
sendToErrStream(String) - Method in class org.hyperic.sigar.shell.ShellBase
Write a string to this shell's output stream.
sendToOutStream(String) - Method in class org.hyperic.sigar.shell.ShellBase
Write a string to this shell's output stream.
SERVER - Static variable in class org.hyperic.sigar.vmware.VM
 
Service - Class in org.hyperic.sigar.win32
 
Service(String) - Constructor for class org.hyperic.sigar.win32.Service
 
SERVICE_CONTINUE_PENDING - Static variable in class org.hyperic.sigar.win32.Service
 
SERVICE_PAUSE_PENDING - Static variable in class org.hyperic.sigar.win32.Service
 
SERVICE_PAUSED - Static variable in class org.hyperic.sigar.win32.Service
 
SERVICE_RUNNING - Static variable in class org.hyperic.sigar.win32.Service
 
SERVICE_START_PENDING - Static variable in class org.hyperic.sigar.win32.Service
 
SERVICE_STOP_PENDING - Static variable in class org.hyperic.sigar.win32.Service
 
SERVICE_STOPPED - Static variable in class org.hyperic.sigar.win32.Service
 
ServiceConfig - Class in org.hyperic.sigar.win32
 
ServiceConfig(String) - Constructor for class org.hyperic.sigar.win32.ServiceConfig
 
setCollection(Collection) - Method in class org.hyperic.sigar.shell.CollectionCompleter
 
setCompleter(GetlineCompleter) - Static method in class org.hyperic.sigar.util.Getline
 
setDependencies(String[]) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setDescription(String) - Method in class org.hyperic.sigar.win32.Service
 
setDescription(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setDisplayName(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setErrorControl(int) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setExpire(long) - Method in class org.hyperic.sigar.ProcFileMirror
 
setExpire(SigarProxy, String, int) - Static method in class org.hyperic.sigar.SigarProxyCache
Deprecated.  
setExpireMillis(long) - Method in class org.hyperic.sigar.ProcFileMirror
 
setGuestInfo(String, String) - Method in class org.hyperic.sigar.vmware.VM
 
setHandlerHidden(String, boolean) - Method in class org.hyperic.sigar.shell.ShellBase
 
setId(int) - Method in class org.hyperic.sigar.win32.LocaleInfo
 
setInteractive(boolean) - Method in class org.hyperic.sigar.cmd.Shell
 
setInterval(long) - Method in class org.hyperic.sigar.FileWatcher
 
setInterval(long) - Method in class org.hyperic.sigar.FileWatcherThread
 
setInterval(long) - Method in class org.hyperic.sigar.win32.EventLogThread
 
setIntValue(String, int) - Method in class org.hyperic.sigar.win32.RegistryKey
 
setLevel(Sigar, int) - Static method in class org.hyperic.sigar.SigarLog
 
setLoadOrderGroup(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setLogName(String) - Method in class org.hyperic.sigar.win32.EventLogThread
 
setName(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setOutputFormat(String) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
setPageSize(int) - Method in class org.hyperic.sigar.shell.ShellBase
Set the page size for data paging.
setPassword(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setPath(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setPrompt(String) - Method in class org.hyperic.sigar.shell.ShellBase
Change the prompt
setProxy(SigarProxy) - Method in class org.hyperic.sigar.SigarInvoker
 
setSharedLibrary(String) - Static method in class org.hyperic.sigar.vmware.VMControlLibrary
 
setSigarJarName(String) - Static method in class org.hyperic.sigar.SigarLoader
 
setStartName(String) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setStartType(int) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setStringValue(String, String) - Method in class org.hyperic.sigar.win32.RegistryKey
 
setTagId(int) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
setType(String) - Method in class org.hyperic.sigar.SigarInvoker
 
setType(int) - Method in class org.hyperic.sigar.win32.ServiceConfig
 
Shell - Class in org.hyperic.sigar.cmd
The Sigar Shell provides a command shell for running the example commands and Sigar tests.
Shell() - Constructor for class org.hyperic.sigar.cmd.Shell
 
shell - Variable in class org.hyperic.sigar.cmd.SigarCommandBase
 
ShellBase - Class in org.hyperic.sigar.shell
 
ShellBase() - Constructor for class org.hyperic.sigar.shell.ShellBase
 
ShellCommand_alias - Class in org.hyperic.sigar.shell
 
ShellCommand_alias() - Constructor for class org.hyperic.sigar.shell.ShellCommand_alias
 
ShellCommand_get - Class in org.hyperic.sigar.shell
 
ShellCommand_get() - Constructor for class org.hyperic.sigar.shell.ShellCommand_get
 
ShellCommand_help - Class in org.hyperic.sigar.shell
 
ShellCommand_help() - Constructor for class org.hyperic.sigar.shell.ShellCommand_help
 
ShellCommand_quit - Class in org.hyperic.sigar.shell
 
ShellCommand_quit() - Constructor for class org.hyperic.sigar.shell.ShellCommand_quit
 
ShellCommand_set - Class in org.hyperic.sigar.shell
 
ShellCommand_set() - Constructor for class org.hyperic.sigar.shell.ShellCommand_set
 
ShellCommand_sleep - Class in org.hyperic.sigar.shell
 
ShellCommand_sleep() - Constructor for class org.hyperic.sigar.shell.ShellCommand_sleep
 
ShellCommand_source - Class in org.hyperic.sigar.shell
 
ShellCommand_source() - Constructor for class org.hyperic.sigar.shell.ShellCommand_source
 
ShellCommandBase - Class in org.hyperic.sigar.shell
 
ShellCommandBase() - Constructor for class org.hyperic.sigar.shell.ShellCommandBase
 
ShellCommandExecException - Exception in org.hyperic.sigar.shell
 
ShellCommandExecException() - Constructor for exception org.hyperic.sigar.shell.ShellCommandExecException
 
ShellCommandExecException(String) - Constructor for exception org.hyperic.sigar.shell.ShellCommandExecException
 
ShellCommandHandler - Interface in org.hyperic.sigar.shell
 
ShellCommandInitException - Exception in org.hyperic.sigar.shell
 
ShellCommandInitException() - Constructor for exception org.hyperic.sigar.shell.ShellCommandInitException
 
ShellCommandInitException(String) - Constructor for exception org.hyperic.sigar.shell.ShellCommandInitException
 
ShellCommandMapper - Interface in org.hyperic.sigar.shell
 
ShellCommandUsageException - Exception in org.hyperic.sigar.shell
 
ShellCommandUsageException() - Constructor for exception org.hyperic.sigar.shell.ShellCommandUsageException
 
ShellCommandUsageException(String) - Constructor for exception org.hyperic.sigar.shell.ShellCommandUsageException
 
ShellIntHandler - Class in org.hyperic.sigar.shell
 
ShellIntHandler() - Constructor for class org.hyperic.sigar.shell.ShellIntHandler
 
ShowArgs - Class in org.hyperic.sigar.cmd
Show process command line arguments.
ShowArgs(Shell) - Constructor for class org.hyperic.sigar.cmd.ShowArgs
 
ShowArgs() - Constructor for class org.hyperic.sigar.cmd.ShowArgs
 
ShowEnv - Class in org.hyperic.sigar.cmd
Show process environment.
ShowEnv(Shell) - Constructor for class org.hyperic.sigar.cmd.ShowEnv
 
ShowEnv() - Constructor for class org.hyperic.sigar.cmd.ShowEnv
 
shutdown() - Method in class org.hyperic.sigar.cmd.Shell
 
shutdown() - Method in class org.hyperic.sigar.shell.ShellBase
 
sigar - Variable in class org.hyperic.sigar.cmd.SigarCommandBase
 
Sigar - Class in org.hyperic.sigar
The Sigar class provides access to the sigar objects containing system information.
Sigar() - Constructor for class org.hyperic.sigar.Sigar
Allocate and initialize the native Sigar object.
SigarCommandBase - Class in org.hyperic.sigar.cmd
 
SigarCommandBase(Shell) - Constructor for class org.hyperic.sigar.cmd.SigarCommandBase
 
SigarCommandBase() - Constructor for class org.hyperic.sigar.cmd.SigarCommandBase
 
SigarException - Exception in org.hyperic.sigar
Sigar base exception class.
SigarException() - Constructor for exception org.hyperic.sigar.SigarException
 
SigarException(String) - Constructor for exception org.hyperic.sigar.SigarException
 
SigarFileNotFoundException - Exception in org.hyperic.sigar
 
SigarFileNotFoundException(String) - Constructor for exception org.hyperic.sigar.SigarFileNotFoundException
 
SigarInvoker - Class in org.hyperic.sigar
This class provides a string-ish interface to sigar.
SigarInvoker() - Constructor for class org.hyperic.sigar.SigarInvoker
 
SigarInvoker(SigarProxy, String) - Constructor for class org.hyperic.sigar.SigarInvoker
 
SigarLoader - Class in org.hyperic.sigar
 
SigarLoader(Class) - Constructor for class org.hyperic.sigar.SigarLoader
 
SigarLog - Class in org.hyperic.sigar
 
SigarLog() - Constructor for class org.hyperic.sigar.SigarLog
 
SigarNotImplementedException - Exception in org.hyperic.sigar
Sigar exception class, thrown for methods which are not implemented on a given platform.
SigarNotImplementedException() - Constructor for exception org.hyperic.sigar.SigarNotImplementedException
 
SigarNotImplementedException(String) - Constructor for exception org.hyperic.sigar.SigarNotImplementedException
 
SigarPermissionDeniedException - Exception in org.hyperic.sigar
 
SigarPermissionDeniedException(String) - Constructor for exception org.hyperic.sigar.SigarPermissionDeniedException
 
SigarPermissionDeniedException(SigarProxy, long) - Constructor for exception org.hyperic.sigar.SigarPermissionDeniedException
 
SigarProcessQuery - Class in org.hyperic.sigar.ptql
 
SigarProcessQuery() - Constructor for class org.hyperic.sigar.ptql.SigarProcessQuery
 
SigarProxy - Interface in org.hyperic.sigar
The proxyable interface for caching via SigarProxyCache.
SigarProxyCache - Class in org.hyperic.sigar
This class implements a caching mechanism to avoid system calls with heavy Sigar usage in a short period of time.
SigarProxyCache(Sigar, int) - Constructor for class org.hyperic.sigar.SigarProxyCache
 
SIGINT - Interface in org.hyperic.sigar.shell
 
size() - Method in class org.hyperic.sigar.util.ReferenceMap
 
skip(long) - Method in class org.hyperic.sigar.SudoFileInputStream
 
SLEEP - Static variable in class org.hyperic.sigar.ProcState
 
sprintf(String, Object[]) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
sprintf(Object[]) - Method in class org.hyperic.sigar.util.PrintfFormat
Format an array of objects.
sprintf() - Method in class org.hyperic.sigar.util.PrintfFormat
Format nothing.
sprintf(int) - Method in class org.hyperic.sigar.util.PrintfFormat
Format an int.
sprintf(long) - Method in class org.hyperic.sigar.util.PrintfFormat
Format an long.
sprintf(double) - Method in class org.hyperic.sigar.util.PrintfFormat
Format a double.
sprintf(String) - Method in class org.hyperic.sigar.util.PrintfFormat
Format a String.
sprintf(Object) - Method in class org.hyperic.sigar.util.PrintfFormat
Format an Object.
start() - Method in class org.hyperic.sigar.CpuTimer
 
start(Sigar) - Method in class org.hyperic.sigar.CpuTimer
 
start(int) - Method in class org.hyperic.sigar.vmware.VM
 
start() - Method in class org.hyperic.sigar.vmware.VM
 
start() - Method in class org.hyperic.sigar.win32.Service
 
start(long) - Method in class org.hyperic.sigar.win32.Service
 
START_AUTO - Static variable in class org.hyperic.sigar.win32.ServiceConfig
A service started automatically by the service control manager during system startup.
START_BOOT - Static variable in class org.hyperic.sigar.win32.ServiceConfig
A device driver started by the system loader.
START_DISABLED - Static variable in class org.hyperic.sigar.win32.ServiceConfig
A service that cannot be started.
START_MANUAL - Static variable in class org.hyperic.sigar.win32.ServiceConfig
A service started by the service control manager when a process calls the StartService function.
START_SYSTEM - Static variable in class org.hyperic.sigar.win32.ServiceConfig
A device driver started by the IoInitSystem function.
stat() - Method in class org.hyperic.sigar.FileInfo
 
stat(Sigar) - Method in class org.hyperic.sigar.NetStat
 
stat(Sigar, byte[], long) - Method in class org.hyperic.sigar.NetStat
 
status() - Method in class org.hyperic.sigar.win32.Service
Deprecated.  
stop() - Method in class org.hyperic.sigar.CpuTimer
 
stop(Sigar) - Method in class org.hyperic.sigar.CpuTimer
 
STOP - Static variable in class org.hyperic.sigar.ProcState
 
stop(int) - Method in class org.hyperic.sigar.vmware.VM
 
stop() - Method in class org.hyperic.sigar.vmware.VM
 
stop() - Method in class org.hyperic.sigar.win32.Service
 
stop(long) - Method in class org.hyperic.sigar.win32.Service
 
stopAndWait(long) - Method in class org.hyperic.sigar.win32.Service
Deprecated.  
strerror(int) - Static method in class org.hyperic.sigar.RPC
 
StringPattern - Class in org.hyperic.sigar.ptql
 
StringPattern() - Constructor for class org.hyperic.sigar.ptql.StringPattern
 
SudoFileInputStream - Class in org.hyperic.sigar
InputStream wrapper for 'sudo cat filename'
SudoFileInputStream(String) - Constructor for class org.hyperic.sigar.SudoFileInputStream
 
SudoFileInputStream(File) - Constructor for class org.hyperic.sigar.SudoFileInputStream
 
suspend(int) - Method in class org.hyperic.sigar.vmware.VM
 
suspend() - Method in class org.hyperic.sigar.vmware.VM
 
Swap - Class in org.hyperic.sigar
Swap sigar class.
Swap() - Constructor for class org.hyperic.sigar.Swap
 
synchronizedMap() - Static method in class org.hyperic.sigar.util.ReferenceMap
 
SysInfo - Class in org.hyperic.sigar.cmd
Display System Information
SysInfo(Shell) - Constructor for class org.hyperic.sigar.cmd.SysInfo
 
SysInfo() - Constructor for class org.hyperic.sigar.cmd.SysInfo
 
SysInfo - Class in org.hyperic.sigar
SysInfo sigar class.
SysInfo() - Constructor for class org.hyperic.sigar.SysInfo
 
SYSTEM - Static variable in class org.hyperic.sigar.win32.EventLog
 
systemLoad(String) - Method in class org.hyperic.sigar.SigarLoader
 
systemLoadLibrary(String) - Method in class org.hyperic.sigar.SigarLoader
 

T

Tail - Class in org.hyperic.sigar.cmd
Display the last part of files to the standard output.
Tail() - Constructor for class org.hyperic.sigar.cmd.Tail
 
tail(FileInfo, Reader) - Method in class org.hyperic.sigar.FileTail
 
TCP - Static variable in class org.hyperic.sigar.RPC
 
Tcp - Class in org.hyperic.sigar
Tcp sigar class.
Tcp() - Constructor for class org.hyperic.sigar.Tcp
 
TCP_BOUND - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_CLOSE - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_CLOSE_WAIT - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_CLOSING - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_ESTABLISHED - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_FIN_WAIT1 - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_FIN_WAIT2 - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_IDLE - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_LAST_ACK - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_LISTEN - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_SYN_RECV - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_SYN_SENT - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_TIME_WAIT - Static variable in class org.hyperic.sigar.NetFlags
 
TCP_UNKNOWN - Static variable in class org.hyperic.sigar.NetFlags
 
tcpInboundTotal - Variable in class org.hyperic.sigar.NetStat
 
tcpOutboundTotal - Variable in class org.hyperic.sigar.NetStat
 
tcpStates - Variable in class org.hyperic.sigar.NetStat
 
ThreadCpu - Class in org.hyperic.sigar
ThreadCpu sigar class.
ThreadCpu() - Constructor for class org.hyperic.sigar.ThreadCpu
 
Time - Class in org.hyperic.sigar.cmd
 
Time(Shell) - Constructor for class org.hyperic.sigar.cmd.Time
 
Time() - Constructor for class org.hyperic.sigar.cmd.Time
 
toMap() - Method in class org.hyperic.sigar.Cpu
 
toMap() - Method in class org.hyperic.sigar.CpuInfo
 
toMap() - Method in class org.hyperic.sigar.DirStat
 
toMap() - Method in class org.hyperic.sigar.DirUsage
 
toMap() - Method in class org.hyperic.sigar.DiskUsage
 
toMap() - Method in class org.hyperic.sigar.FileAttrs
 
toMap() - Method in class org.hyperic.sigar.FileSystem
 
toMap() - Method in class org.hyperic.sigar.FileSystemUsage
 
toMap() - Method in class org.hyperic.sigar.Mem
 
toMap() - Method in class org.hyperic.sigar.NetConnection
 
toMap() - Method in class org.hyperic.sigar.NetInfo
 
toMap() - Method in class org.hyperic.sigar.NetInterfaceConfig
 
toMap() - Method in class org.hyperic.sigar.NetInterfaceStat
 
toMap() - Method in class org.hyperic.sigar.NetRoute
 
toMap() - Method in class org.hyperic.sigar.NfsClientV2
 
toMap() - Method in class org.hyperic.sigar.NfsClientV3
 
toMap() - Method in class org.hyperic.sigar.NfsServerV2
 
toMap() - Method in class org.hyperic.sigar.NfsServerV3
 
toMap() - Method in class org.hyperic.sigar.ProcCpu
 
toMap() - Method in class org.hyperic.sigar.ProcCred
 
toMap() - Method in class org.hyperic.sigar.ProcCredName
 
toMap() - Method in class org.hyperic.sigar.ProcExe
 
toMap() - Method in class org.hyperic.sigar.ProcFd
 
toMap() - Method in class org.hyperic.sigar.ProcMem
 
toMap() - Method in class org.hyperic.sigar.ProcStat
 
toMap() - Method in class org.hyperic.sigar.ProcState
 
toMap() - Method in class org.hyperic.sigar.ProcTime
 
toMap() - Method in class org.hyperic.sigar.ResourceLimit
 
toMap() - Method in class org.hyperic.sigar.Swap
 
toMap() - Method in class org.hyperic.sigar.SysInfo
 
toMap() - Method in class org.hyperic.sigar.Tcp
 
toMap() - Method in class org.hyperic.sigar.ThreadCpu
 
toMap() - Method in class org.hyperic.sigar.Uptime
 
toMap() - Method in class org.hyperic.sigar.Who
 
Top - Class in org.hyperic.sigar.cmd
Display system resource utilization summaries and process information.
Top() - Constructor for class org.hyperic.sigar.cmd.Top
 
toString() - Method in class org.hyperic.sigar.Cpu
 
toString() - Method in class org.hyperic.sigar.CpuInfo
 
toString() - Method in class org.hyperic.sigar.CpuPerc
 
toString() - Method in class org.hyperic.sigar.DirStat
 
toString() - Method in class org.hyperic.sigar.DirUsage
 
toString() - Method in class org.hyperic.sigar.DiskUsage
 
toString() - Method in class org.hyperic.sigar.FileAttrs
 
toString() - Method in class org.hyperic.sigar.FileSystem
 
toString() - Method in class org.hyperic.sigar.FileSystemUsage
 
toString() - Method in class org.hyperic.sigar.Mem
 
toString() - Method in class org.hyperic.sigar.NetConnection
 
toString() - Method in class org.hyperic.sigar.NetInfo
 
toString() - Method in class org.hyperic.sigar.NetInterfaceConfig
 
toString() - Method in class org.hyperic.sigar.NetInterfaceStat
 
toString() - Method in class org.hyperic.sigar.NetRoute
 
toString() - Method in class org.hyperic.sigar.NfsClientV2
 
toString() - Method in class org.hyperic.sigar.NfsClientV3
 
toString() - Method in class org.hyperic.sigar.NfsServerV2
 
toString() - Method in class org.hyperic.sigar.NfsServerV3
 
toString() - Method in class org.hyperic.sigar.ProcCpu
 
toString() - Method in class org.hyperic.sigar.ProcCred
 
toString() - Method in class org.hyperic.sigar.ProcCredName
 
toString() - Method in class org.hyperic.sigar.ProcExe
 
toString() - Method in class org.hyperic.sigar.ProcFd
 
toString() - Method in class org.hyperic.sigar.ProcMem
 
toString() - Method in class org.hyperic.sigar.ProcStat
 
toString() - Method in class org.hyperic.sigar.ProcState
 
toString() - Method in class org.hyperic.sigar.ProcTime
 
toString() - Method in class org.hyperic.sigar.ResourceLimit
 
toString() - Method in class org.hyperic.sigar.Swap
 
toString() - Method in class org.hyperic.sigar.SysInfo
 
toString() - Method in class org.hyperic.sigar.Tcp
 
toString() - Method in class org.hyperic.sigar.ThreadCpu
 
toString() - Method in class org.hyperic.sigar.Uptime
 
toString() - Method in class org.hyperic.sigar.Who
 
toString() - Method in class org.hyperic.sigar.win32.EventLogRecord
For debugging
toString() - Method in class org.hyperic.sigar.win32.LocaleInfo
 
translate(String) - Static method in class org.hyperic.sigar.win32.Pdh
 
TYPE_ADAPTER - Static variable in class org.hyperic.sigar.win32.ServiceConfig
 
TYPE_BLK - Static variable in class org.hyperic.sigar.FileInfo
A block device.
TYPE_CDROM - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_CHR - Static variable in class org.hyperic.sigar.FileInfo
A character device.
TYPE_DIR - Static variable in class org.hyperic.sigar.FileInfo
A directory.
TYPE_FILE_SYSTEM_DRIVER - Static variable in class org.hyperic.sigar.win32.ServiceConfig
File system driver service.
TYPE_INTERACTIVE_PROCESS - Static variable in class org.hyperic.sigar.win32.ServiceConfig
The service can interact with the desktop.
TYPE_KERNEL_DRIVER - Static variable in class org.hyperic.sigar.win32.ServiceConfig
Driver service.
TYPE_LNK - Static variable in class org.hyperic.sigar.FileInfo
A symbolic link.
TYPE_LOCAL_DISK - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_NETWORK - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_NOFILE - Static variable in class org.hyperic.sigar.FileInfo
No file type determined.
TYPE_NONE - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_PIPE - Static variable in class org.hyperic.sigar.FileInfo
A FIFO / pipe.
TYPE_RAM_DISK - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_RECOGNIZER_DRIVER - Static variable in class org.hyperic.sigar.win32.ServiceConfig
 
TYPE_REG - Static variable in class org.hyperic.sigar.FileInfo
A regular file.
TYPE_SOCK - Static variable in class org.hyperic.sigar.FileInfo
A [unix domain] socket.
TYPE_SWAP - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_UNKFILE - Static variable in class org.hyperic.sigar.FileInfo
A file of unknown type.
TYPE_UNKNOWN - Static variable in class org.hyperic.sigar.FileSystem
 
TYPE_WIN32_OWN_PROCESS - Static variable in class org.hyperic.sigar.win32.ServiceConfig
Service that runs in its own process.
TYPE_WIN32_SHARE_PROCESS - Static variable in class org.hyperic.sigar.win32.ServiceConfig
Service that shares a process with other services.

U

UDP - Static variable in class org.hyperic.sigar.RPC
 
Ulimit - Class in org.hyperic.sigar.cmd
Display system resource limits.
Ulimit(Shell) - Constructor for class org.hyperic.sigar.cmd.Ulimit
 
Ulimit() - Constructor for class org.hyperic.sigar.cmd.Ulimit
 
UNIX_NAMES - Static variable in class org.hyperic.sigar.OperatingSystem
 
Uptime - Class in org.hyperic.sigar.cmd
Display how long the system has been running and the current load averages.
Uptime(Shell) - Constructor for class org.hyperic.sigar.cmd.Uptime
 
Uptime() - Constructor for class org.hyperic.sigar.cmd.Uptime
 
Uptime - Class in org.hyperic.sigar
Uptime sigar class.
Uptime() - Constructor for class org.hyperic.sigar.Uptime
 
useSudo(boolean) - Method in class org.hyperic.sigar.FileTail
 

V

VALID_DATA - Static variable in class org.hyperic.sigar.win32.Pdh
The returned data is valid.
validate(String) - Static method in class org.hyperic.sigar.win32.Pdh
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Df
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Du
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.FileVersionInfo
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Ifconfig
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Iostat
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Kill
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Ls
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.MultiPs
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Netstat
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Nfsstat
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Pidof
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.ProcFileInfo
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.ProcInfo
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.ProcModuleInfo
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Ps
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.ShowArgs
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.ShowEnv
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.SigarCommandBase
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Time
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Ulimit
 
validateArgs(String[]) - Method in class org.hyperic.sigar.cmd.Win32Service
 
Version - Class in org.hyperic.sigar.cmd
Display Sigar, java and system version information.
Version(Shell) - Constructor for class org.hyperic.sigar.cmd.Version
 
Version() - Constructor for class org.hyperic.sigar.cmd.Version
 
VERSION_STRING - Static variable in class org.hyperic.sigar.Sigar
The Sigar java version.
VM - Class in org.hyperic.sigar.vmware
 
VM() - Constructor for class org.hyperic.sigar.vmware.VM
 
VMControlLibrary - Class in org.hyperic.sigar.vmware
 
VMControlLibrary() - Constructor for class org.hyperic.sigar.vmware.VMControlLibrary
 
VMwareException - Exception in org.hyperic.sigar.vmware
 
VMwareException() - Constructor for exception org.hyperic.sigar.vmware.VMwareException
 
VMwareException(String) - Constructor for exception org.hyperic.sigar.vmware.VMwareException
 
VMwareServer - Class in org.hyperic.sigar.vmware
 
VMwareServer() - Constructor for class org.hyperic.sigar.vmware.VMwareServer
 

W

waitForChange(int) - Method in class org.hyperic.sigar.win32.EventLog
Wait for a change to the event log.
Watch - Class in org.hyperic.sigar.cmd
Watch a file or directory displaying attribute changes.
Watch() - Constructor for class org.hyperic.sigar.cmd.Watch
 
WeakReferenceMap - Class in org.hyperic.sigar.util
 
WeakReferenceMap() - Constructor for class org.hyperic.sigar.util.WeakReferenceMap
 
Who - Class in org.hyperic.sigar.cmd
 
Who(Shell) - Constructor for class org.hyperic.sigar.cmd.Who
 
Who() - Constructor for class org.hyperic.sigar.cmd.Who
 
Who - Class in org.hyperic.sigar
Who sigar class.
Who() - Constructor for class org.hyperic.sigar.Who
 
Win32 - Class in org.hyperic.sigar.win32
 
Win32() - Constructor for class org.hyperic.sigar.win32.Win32
 
WIN32_NAMES - Static variable in class org.hyperic.sigar.OperatingSystem
 
Win32Exception - Exception in org.hyperic.sigar.win32
 
Win32Exception(String) - Constructor for exception org.hyperic.sigar.win32.Win32Exception
 
Win32Exception(int, String) - Constructor for exception org.hyperic.sigar.win32.Win32Exception
 
Win32Service - Class in org.hyperic.sigar.cmd
 
Win32Service() - Constructor for class org.hyperic.sigar.cmd.Win32Service
 
Win32Service(Shell) - Constructor for class org.hyperic.sigar.cmd.Win32Service
 

Z

ZOMBIE - Static variable in class org.hyperic.sigar.ProcState
 

A B C D E F G H I J K L M N O P Q R S T U V W Z

Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/index.html000066400000000000000000000025561210132627500215520ustar00rootroot00000000000000 Sigar API <H2> Frame Alert</H2> <P> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. <BR> Link to<A HREF="overview-summary.html">Non-frame version.</A> hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/000077500000000000000000000000001210132627500203345ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/000077500000000000000000000000001210132627500217775ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/000077500000000000000000000000001210132627500231045ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Cpu.html000066400000000000000000000455121210132627500245300ustar00rootroot00000000000000 Cpu (Sigar API)

org.hyperic.sigar
Class Cpu

java.lang.Object
  extended by org.hyperic.sigar.Cpu
All Implemented Interfaces:
java.io.Serializable

public class Cpu
extends java.lang.Object
implements java.io.Serializable

Cpu sigar class.

See Also:
Serialized Form

Constructor Summary
Cpu()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getIdle()
          Get the Total system cpu idle time.
 long getIrq()
          Get the Total system cpu time servicing interrupts.
 long getNice()
          Get the Total system cpu nice time.
 long getSoftIrq()
          Get the Total system cpu time servicing softirqs.
 long getStolen()
          Get the Total system cpu involuntary wait time.
 long getSys()
          Get the Total system cpu kernel time.
 long getTotal()
          Get the Total system cpu time.
 long getUser()
          Get the Total system cpu user time.
 long getWait()
          Get the Total system cpu io wait time.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Cpu

public Cpu()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getUser

public long getUser()
Get the Total system cpu user time.

Supported Platforms: All.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu user time

getSys

public long getSys()
Get the Total system cpu kernel time.

Supported Platforms: All.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu kernel time

getNice

public long getNice()
Get the Total system cpu nice time.

Supported Platforms: Darwin, FreeBSD, HPUX, Linux.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu nice time

getIdle

public long getIdle()
Get the Total system cpu idle time.

Supported Platforms: All.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu idle time

getWait

public long getWait()
Get the Total system cpu io wait time.

Supported Platforms: AIX, Linux, HPUX, Solaris.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu io wait time

getIrq

public long getIrq()
Get the Total system cpu time servicing interrupts.

Supported Platforms: FreeBSD, Linux, HPUX, Win32.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu time servicing interrupts

getSoftIrq

public long getSoftIrq()
Get the Total system cpu time servicing softirqs.

Supported Platforms: Linux.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu time servicing softirqs

getStolen

public long getStolen()
Get the Total system cpu involuntary wait time.

Supported Platforms: Linux.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu involuntary wait time

getTotal

public long getTotal()
Get the Total system cpu time.

Supported Platforms: All.

System equivalent commands:

  • AIX: top
  • Darwin: top
  • FreeBSD: top
  • HPUX: top
  • Linux: top
  • Solaris: top
  • Win32: taskman

Returns:
Total system cpu time

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/CpuInfo.html000066400000000000000000000426701210132627500253460ustar00rootroot00000000000000 CpuInfo (Sigar API)

org.hyperic.sigar
Class CpuInfo

java.lang.Object
  extended by org.hyperic.sigar.CpuInfo
All Implemented Interfaces:
java.io.Serializable

public class CpuInfo
extends java.lang.Object
implements java.io.Serializable

CpuInfo sigar class.

See Also:
Serialized Form

Constructor Summary
CpuInfo()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getCacheSize()
          Get the CPU cache size.
 int getCoresPerSocket()
          Get the Number of CPU cores per CPU socket.
 int getMhz()
          Get the CPU speed.
 java.lang.String getModel()
          Get the CPU model.
 int getTotalCores()
          Get the Total CPU cores (logical).
 int getTotalSockets()
          Get the Total CPU sockets (physical).
 java.lang.String getVendor()
          Get the CPU vendor id.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

CpuInfo

public CpuInfo()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getVendor

public java.lang.String getVendor()
Get the CPU vendor id.

Supported Platforms: AIX, FreeBSD, Linux, HPUX, Solaris, Win32.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
CPU vendor id

getModel

public java.lang.String getModel()
Get the CPU model.

Supported Platforms: AIX, FreeBSD, Linux, HPUX, Solaris, Win32.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
CPU model

getMhz

public int getMhz()
Get the CPU speed.

Supported Platforms: AIX, FreeBSD, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
CPU speed

getCacheSize

public long getCacheSize()
Get the CPU cache size.

Supported Platforms: AIX, Linux.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
CPU cache size

getTotalCores

public int getTotalCores()
Get the Total CPU cores (logical).

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
Total CPU cores (logical)

getTotalSockets

public int getTotalSockets()
Get the Total CPU sockets (physical).

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
Total CPU sockets (physical)

getCoresPerSocket

public int getCoresPerSocket()
Get the Number of CPU cores per CPU socket.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: lsattr -El proc0
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/cpuinfo
  • Solaris: psrinfo -v
  • Win32:

Returns:
Number of CPU cores per CPU socket

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/CpuPerc.html000066400000000000000000000346601210132627500253440ustar00rootroot00000000000000 CpuPerc (Sigar API)

org.hyperic.sigar
Class CpuPerc

java.lang.Object
  extended by org.hyperic.sigar.CpuPerc
All Implemented Interfaces:
java.io.Serializable

public class CpuPerc
extends java.lang.Object
implements java.io.Serializable

CPU percentage usage

See Also:
Serialized Form

Method Summary
static CpuPerc calculate(Cpu oldCpu, Cpu curCpu)
          Deprecated.  
static java.lang.String format(double val)
           
 double getCombined()
           
 double getIdle()
           
 double getIrq()
           
 double getNice()
           
 double getSoftIrq()
           
 double getStolen()
           
 double getSys()
           
 double getUser()
           
 double getWait()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Method Detail

calculate

public static CpuPerc calculate(Cpu oldCpu,
                                Cpu curCpu)
Deprecated. 


getUser

public double getUser()

getSys

public double getSys()

getNice

public double getNice()

getIdle

public double getIdle()

getWait

public double getWait()

getIrq

public double getIrq()

getSoftIrq

public double getSoftIrq()

getStolen

public double getStolen()

getCombined

public double getCombined()
Returns:
Sum of User + Sys + Nice + Wait

format

public static java.lang.String format(double val)

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/CpuTimer.html000066400000000000000000000474001210132627500255270ustar00rootroot00000000000000 CpuTimer (Sigar API)

org.hyperic.sigar
Class CpuTimer

java.lang.Object
  extended by org.hyperic.sigar.CpuTimer
All Implemented Interfaces:
org.hyperic.sigar.jmx.CpuTimerMBean

public class CpuTimer
extends java.lang.Object
implements org.hyperic.sigar.jmx.CpuTimerMBean


Constructor Summary
CpuTimer()
           
CpuTimer(Sigar sigar)
           
 
Method Summary
 void add(CpuTimer timer)
           
 void clear()
           
 java.lang.String format(long elap)
           
 long getCpuSys()
           
 long getCpuTotal()
           
 double getCpuUsage()
           
 long getCpuUser()
           
 ThreadCpu getDiff()
           
 ThreadCpu getDiff(Sigar sigar)
           
static CpuTimer getInstance(java.lang.String name)
           
 long getLastSampleTime()
           
 long getTotalTime()
           
 void list(java.io.PrintStream out)
           
 void start()
           
 void start(Sigar sigar)
           
 void stop()
           
 void stop(Sigar sigar)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

CpuTimer

public CpuTimer()

CpuTimer

public CpuTimer(Sigar sigar)
Method Detail

clear

public void clear()

add

public void add(CpuTimer timer)

start

public void start()

start

public void start(Sigar sigar)

stop

public void stop()

stop

public void stop(Sigar sigar)

getDiff

public ThreadCpu getDiff()

getDiff

public ThreadCpu getDiff(Sigar sigar)

getTotalTime

public long getTotalTime()
Specified by:
getTotalTime in interface org.hyperic.sigar.jmx.CpuTimerMBean

getCpuTotal

public long getCpuTotal()
Specified by:
getCpuTotal in interface org.hyperic.sigar.jmx.CpuTimerMBean

getCpuUser

public long getCpuUser()
Specified by:
getCpuUser in interface org.hyperic.sigar.jmx.CpuTimerMBean

getCpuSys

public long getCpuSys()
Specified by:
getCpuSys in interface org.hyperic.sigar.jmx.CpuTimerMBean

getCpuUsage

public double getCpuUsage()
Specified by:
getCpuUsage in interface org.hyperic.sigar.jmx.CpuTimerMBean

getLastSampleTime

public long getLastSampleTime()
Specified by:
getLastSampleTime in interface org.hyperic.sigar.jmx.CpuTimerMBean

getInstance

public static CpuTimer getInstance(java.lang.String name)

format

public java.lang.String format(long elap)

list

public void list(java.io.PrintStream out)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/CurrentProcessSummary.html000066400000000000000000000300301210132627500303250ustar00rootroot00000000000000 CurrentProcessSummary (Sigar API)

org.hyperic.sigar
Class CurrentProcessSummary

java.lang.Object
  extended by org.hyperic.sigar.ProcStat
      extended by org.hyperic.sigar.CurrentProcessSummary
All Implemented Interfaces:
java.io.Serializable

Deprecated.

public class CurrentProcessSummary
extends ProcStat

See Also:
ProcStat, Serialized Form

Constructor Summary
CurrentProcessSummary()
          Deprecated.  
 
Method Summary
static CurrentProcessSummary get(SigarProxy sigar)
          Deprecated.  
 
Methods inherited from class org.hyperic.sigar.ProcStat
gather, getIdle, getRunning, getSleeping, getStopped, getThreads, getTotal, getZombie, toMap, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

CurrentProcessSummary

public CurrentProcessSummary()
Deprecated. 
Method Detail

get

public static CurrentProcessSummary get(SigarProxy sigar)
                                 throws SigarException
Deprecated. 
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/DirStat.html000066400000000000000000000372701210132627500253550ustar00rootroot00000000000000 DirStat (Sigar API)

org.hyperic.sigar
Class DirStat

java.lang.Object
  extended by org.hyperic.sigar.DirStat
All Implemented Interfaces:
java.io.Serializable

public class DirStat
extends java.lang.Object
implements java.io.Serializable

DirStat sigar class.

See Also:
Serialized Form

Constructor Summary
DirStat()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 long getBlkdevs()
          Get the blkdevs.
 long getChrdevs()
          Get the chrdevs.
 long getDiskUsage()
          Get the disk_usage.
 long getFiles()
          Get the files.
 long getSockets()
          Get the sockets.
 long getSubdirs()
          Get the subdirs.
 long getSymlinks()
          Get the symlinks.
 long getTotal()
          Get the total.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

DirStat

public DirStat()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the total.

Supported Platforms: Undocumented.

Returns:
total

getFiles

public long getFiles()
Get the files.

Supported Platforms: Undocumented.

Returns:
files

getSubdirs

public long getSubdirs()
Get the subdirs.

Supported Platforms: Undocumented.

Returns:
subdirs

getSymlinks

public long getSymlinks()
Get the symlinks.

Supported Platforms: Undocumented.

Returns:
symlinks

getChrdevs

public long getChrdevs()
Get the chrdevs.

Supported Platforms: Undocumented.

Returns:
chrdevs

getBlkdevs

public long getBlkdevs()
Get the blkdevs.

Supported Platforms: Undocumented.

Returns:
blkdevs

getSockets

public long getSockets()
Get the sockets.

Supported Platforms: Undocumented.

Returns:
sockets

getDiskUsage

public long getDiskUsage()
Get the disk_usage.

Supported Platforms: Undocumented.

Returns:
disk_usage

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/DirUsage.html000066400000000000000000000372721210132627500255100ustar00rootroot00000000000000 DirUsage (Sigar API)

org.hyperic.sigar
Class DirUsage

java.lang.Object
  extended by org.hyperic.sigar.DirUsage
All Implemented Interfaces:
java.io.Serializable

public class DirUsage
extends java.lang.Object
implements java.io.Serializable

DirUsage sigar class.

See Also:
Serialized Form

Constructor Summary
DirUsage()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 long getBlkdevs()
          Get the blkdevs.
 long getChrdevs()
          Get the chrdevs.
 long getDiskUsage()
          Get the disk_usage.
 long getFiles()
          Get the files.
 long getSockets()
          Get the sockets.
 long getSubdirs()
          Get the subdirs.
 long getSymlinks()
          Get the symlinks.
 long getTotal()
          Get the total.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

DirUsage

public DirUsage()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the total.

Supported Platforms: Undocumented.

Returns:
total

getFiles

public long getFiles()
Get the files.

Supported Platforms: Undocumented.

Returns:
files

getSubdirs

public long getSubdirs()
Get the subdirs.

Supported Platforms: Undocumented.

Returns:
subdirs

getSymlinks

public long getSymlinks()
Get the symlinks.

Supported Platforms: Undocumented.

Returns:
symlinks

getChrdevs

public long getChrdevs()
Get the chrdevs.

Supported Platforms: Undocumented.

Returns:
chrdevs

getBlkdevs

public long getBlkdevs()
Get the blkdevs.

Supported Platforms: Undocumented.

Returns:
blkdevs

getSockets

public long getSockets()
Get the sockets.

Supported Platforms: Undocumented.

Returns:
sockets

getDiskUsage

public long getDiskUsage()
Get the disk_usage.

Supported Platforms: Undocumented.

Returns:
disk_usage

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/DiskUsage.html000066400000000000000000000357041210132627500256620ustar00rootroot00000000000000 DiskUsage (Sigar API)

org.hyperic.sigar
Class DiskUsage

java.lang.Object
  extended by org.hyperic.sigar.DiskUsage
All Implemented Interfaces:
java.io.Serializable

public class DiskUsage
extends java.lang.Object
implements java.io.Serializable

DiskUsage sigar class.

See Also:
Serialized Form

Constructor Summary
DiskUsage()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 double getQueue()
          Get the queue.
 long getReadBytes()
          Get the Number of physical disk bytes read.
 long getReads()
          Get the Number of physical disk reads.
 double getServiceTime()
          Get the service_time.
 long getWriteBytes()
          Get the Number of physical disk bytes written.
 long getWrites()
          Get the Number of physical disk writes.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

DiskUsage

public DiskUsage()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getReads

public long getReads()
Get the Number of physical disk reads.

Supported Platforms: AIX, FreeBSD, HPUX, Linux, Solaris, Win32.

Returns:
Number of physical disk reads

getWrites

public long getWrites()
Get the Number of physical disk writes.

Supported Platforms: AIX, FreeBSD, HPUX, Linux, Solaris, Win32.

Returns:
Number of physical disk writes

getReadBytes

public long getReadBytes()
Get the Number of physical disk bytes read.

Supported Platforms: Undocumented.

Returns:
Number of physical disk bytes read

getWriteBytes

public long getWriteBytes()
Get the Number of physical disk bytes written.

Supported Platforms: Undocumented.

Returns:
Number of physical disk bytes written

getQueue

public double getQueue()
Get the queue.

Supported Platforms: Undocumented.

Returns:
queue

getServiceTime

public double getServiceTime()
Get the service_time.

Supported Platforms: Undocumented.

Returns:
service_time

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileAttrs.html000066400000000000000000000427151210132627500257000ustar00rootroot00000000000000 FileAttrs (Sigar API)

org.hyperic.sigar
Class FileAttrs

java.lang.Object
  extended by org.hyperic.sigar.FileAttrs
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
FileInfo

public class FileAttrs
extends java.lang.Object
implements java.io.Serializable

FileAttrs sigar class.

See Also:
Serialized Form

Constructor Summary
FileAttrs()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 long getAtime()
          Get the atime.
 long getCtime()
          Get the ctime.
 long getDevice()
          Get the device.
 long getGid()
          Get the gid.
 long getInode()
          Get the inode.
 long getMtime()
          Get the mtime.
 long getNlink()
          Get the nlink.
 long getPermissions()
          Get the permissions.
 long getSize()
          Get the size.
 int getType()
          Get the type.
 long getUid()
          Get the uid.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

FileAttrs

public FileAttrs()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getPermissions

public long getPermissions()
Get the permissions.

Supported Platforms: Undocumented.

Returns:
permissions

getType

public int getType()
Get the type.

Supported Platforms: Undocumented.

Returns:
type

getUid

public long getUid()
Get the uid.

Supported Platforms: Undocumented.

Returns:
uid

getGid

public long getGid()
Get the gid.

Supported Platforms: Undocumented.

Returns:
gid

getInode

public long getInode()
Get the inode.

Supported Platforms: Undocumented.

Returns:
inode

getDevice

public long getDevice()
Get the device.

Supported Platforms: Undocumented.

Returns:
device

getNlink

public long getNlink()
Get the nlink.

Supported Platforms: Undocumented.

Returns:
nlink

getSize

public long getSize()
Get the size.

Supported Platforms: Undocumented.

Returns:
size

getAtime

public long getAtime()
Get the atime.

Supported Platforms: Undocumented.

Returns:
atime

getCtime

public long getCtime()
Get the ctime.

Supported Platforms: Undocumented.

Returns:
ctime

getMtime

public long getMtime()
Get the mtime.

Supported Platforms: Undocumented.

Returns:
mtime

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileInfo.html000066400000000000000000001012051210132627500254640ustar00rootroot00000000000000 FileInfo (Sigar API)

org.hyperic.sigar
Class FileInfo

java.lang.Object
  extended by org.hyperic.sigar.FileAttrs
      extended by org.hyperic.sigar.FileInfo
All Implemented Interfaces:
java.io.Serializable

public class FileInfo
extends FileAttrs
implements java.io.Serializable

See Also:
Serialized Form

Field Summary
static int MODE_GEXECUTE
          Executable by group.
static int MODE_GREAD
          Readable by group.
static int MODE_GWRITE
          Writable by group.
static int MODE_UEXECUTE
          Executable by user.
static int MODE_UREAD
          Readable by user.
static int MODE_UWRITE
          Writable by user.
static int MODE_WEXECUTE
          Executable by others.
static int MODE_WREAD
          Readable by others.
static int MODE_WWRITE
          Writable by others.
static int TYPE_BLK
          A block device.
static int TYPE_CHR
          A character device.
static int TYPE_DIR
          A directory.
static int TYPE_LNK
          A symbolic link.
static int TYPE_NOFILE
          No file type determined.
static int TYPE_PIPE
          A FIFO / pipe.
static int TYPE_REG
          A regular file.
static int TYPE_SOCK
          A [unix domain] socket.
static int TYPE_UNKFILE
          A file of unknown type.
 
Constructor Summary
FileInfo()
           
 
Method Summary
 boolean changed()
           
 java.lang.String diff()
           
 java.lang.String diff(DirStat stat)
           
 java.lang.String diff(FileInfo info)
           
 void enableDirStat(boolean value)
           
 boolean equals(java.lang.Object o)
           
 int getMode()
          Convert permissions bit mask to human readable number.
 java.lang.String getName()
           
 java.lang.String getPermissionsString()
           
 FileInfo getPreviousInfo()
           
 char getTypeChar()
           
 java.lang.String getTypeString()
           
 int hashCode()
           
 boolean modified()
           
 void stat()
           
 
Methods inherited from class org.hyperic.sigar.FileAttrs
gather, getAtime, getCtime, getDevice, getGid, getInode, getMtime, getNlink, getPermissions, getSize, getType, getUid, toMap, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

TYPE_NOFILE

public static final int TYPE_NOFILE
No file type determined.

See Also:
Constant Field Values

TYPE_REG

public static final int TYPE_REG
A regular file.

See Also:
Constant Field Values

TYPE_DIR

public static final int TYPE_DIR
A directory.

See Also:
Constant Field Values

TYPE_CHR

public static final int TYPE_CHR
A character device.

See Also:
Constant Field Values

TYPE_BLK

public static final int TYPE_BLK
A block device.

See Also:
Constant Field Values

TYPE_PIPE

public static final int TYPE_PIPE
A FIFO / pipe.

See Also:
Constant Field Values

TYPE_LNK

public static final int TYPE_LNK
A symbolic link.

See Also:
Constant Field Values

TYPE_SOCK

public static final int TYPE_SOCK
A [unix domain] socket.

See Also:
Constant Field Values

TYPE_UNKFILE

public static final int TYPE_UNKFILE
A file of unknown type.

See Also:
Constant Field Values

MODE_UREAD

public static final int MODE_UREAD
Readable by user.

See Also:
Constant Field Values

MODE_UWRITE

public static final int MODE_UWRITE
Writable by user.

See Also:
Constant Field Values

MODE_UEXECUTE

public static final int MODE_UEXECUTE
Executable by user.

See Also:
Constant Field Values

MODE_GREAD

public static final int MODE_GREAD
Readable by group.

See Also:
Constant Field Values

MODE_GWRITE

public static final int MODE_GWRITE
Writable by group.

See Also:
Constant Field Values

MODE_GEXECUTE

public static final int MODE_GEXECUTE
Executable by group.

See Also:
Constant Field Values

MODE_WREAD

public static final int MODE_WREAD
Readable by others.

See Also:
Constant Field Values

MODE_WWRITE

public static final int MODE_WWRITE
Writable by others.

See Also:
Constant Field Values

MODE_WEXECUTE

public static final int MODE_WEXECUTE
Executable by others.

See Also:
Constant Field Values
Constructor Detail

FileInfo

public FileInfo()
Method Detail

getTypeString

public java.lang.String getTypeString()

getTypeChar

public char getTypeChar()

getName

public java.lang.String getName()

hashCode

public int hashCode()
Overrides:
hashCode in class java.lang.Object

equals

public boolean equals(java.lang.Object o)
Overrides:
equals in class java.lang.Object

getPermissionsString

public java.lang.String getPermissionsString()

getMode

public int getMode()
Convert permissions bit mask to human readable number. Example: MODE_UREAD|MODE_UWRITE|MODE_GREAD|MODE_WREAD converts to 644.

Returns:
The file permissions mode.

enableDirStat

public void enableDirStat(boolean value)

diff

public java.lang.String diff()

diff

public java.lang.String diff(DirStat stat)

diff

public java.lang.String diff(FileInfo info)

getPreviousInfo

public FileInfo getPreviousInfo()

modified

public boolean modified()
                 throws SigarException,
                        SigarFileNotFoundException
Throws:
SigarException
SigarFileNotFoundException

changed

public boolean changed()
                throws SigarException,
                       SigarFileNotFoundException
Throws:
SigarException
SigarFileNotFoundException

stat

public void stat()
          throws SigarException,
                 SigarFileNotFoundException
Throws:
SigarException
SigarFileNotFoundException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileSystem.html000066400000000000000000000506021210132627500260610ustar00rootroot00000000000000 FileSystem (Sigar API)

org.hyperic.sigar
Class FileSystem

java.lang.Object
  extended by org.hyperic.sigar.FileSystem
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
NfsFileSystem

public class FileSystem
extends java.lang.Object
implements java.io.Serializable

FileSystem sigar class.

See Also:
Serialized Form

Field Summary
static int TYPE_CDROM
           
static int TYPE_LOCAL_DISK
           
static int TYPE_NETWORK
           
static int TYPE_NONE
           
static int TYPE_RAM_DISK
           
static int TYPE_SWAP
           
static int TYPE_UNKNOWN
           
 
Constructor Summary
FileSystem()
           
 
Method Summary
 void gather(Sigar sigar)
           
 java.lang.String getDevName()
          Get the Device name.
 java.lang.String getDirName()
          Get the Directory name.
 long getFlags()
          Get the File system flags.
 java.lang.String getOptions()
          Get the File system mount options.
 java.lang.String getSysTypeName()
          Get the File system os specific type name.
 int getType()
          Get the File system type.
 java.lang.String getTypeName()
          Get the File system generic type name.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

TYPE_UNKNOWN

public static final int TYPE_UNKNOWN
See Also:
Constant Field Values

TYPE_NONE

public static final int TYPE_NONE
See Also:
Constant Field Values

TYPE_LOCAL_DISK

public static final int TYPE_LOCAL_DISK
See Also:
Constant Field Values

TYPE_NETWORK

public static final int TYPE_NETWORK
See Also:
Constant Field Values

TYPE_RAM_DISK

public static final int TYPE_RAM_DISK
See Also:
Constant Field Values

TYPE_CDROM

public static final int TYPE_CDROM
See Also:
Constant Field Values

TYPE_SWAP

public static final int TYPE_SWAP
See Also:
Constant Field Values
Constructor Detail

FileSystem

public FileSystem()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getDirName

public java.lang.String getDirName()
Get the Directory name.

Supported Platforms: All.

Returns:
Directory name

getDevName

public java.lang.String getDevName()
Get the Device name.

Supported Platforms: All.

Returns:
Device name

getTypeName

public java.lang.String getTypeName()
Get the File system generic type name.

Supported Platforms: All.

Returns:
File system generic type name

getSysTypeName

public java.lang.String getSysTypeName()
Get the File system os specific type name.

Supported Platforms: All.

Returns:
File system os specific type name

getOptions

public java.lang.String getOptions()
Get the File system mount options.

Supported Platforms: All.

Returns:
File system mount options

getType

public int getType()
Get the File system type.

Supported Platforms: All.

Returns:
File system type

getFlags

public long getFlags()
Get the File system flags.

Supported Platforms: All.

Returns:
File system flags

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object

toMap

public java.util.Map toMap()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileSystemMap.html000066400000000000000000000367761210132627500265370ustar00rootroot00000000000000 FileSystemMap (Sigar API)

org.hyperic.sigar
Class FileSystemMap

java.lang.Object
  extended by java.util.AbstractMap<K,V>
      extended by java.util.HashMap
          extended by org.hyperic.sigar.FileSystemMap
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, java.util.Map

public class FileSystemMap
extends java.util.HashMap

Helper class to build a map of mounted file systems.

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class java.util.AbstractMap
java.util.AbstractMap.SimpleEntry<K,V>, java.util.AbstractMap.SimpleImmutableEntry<K,V>
 
Constructor Summary
FileSystemMap()
           
 
Method Summary
 FileSystem getFileSystem(java.lang.String name)
           
 FileSystem getMountPoint(java.lang.String name)
          Find the file system the given file or directory is within.
 void init(FileSystem[] fslist)
          Populate the map.
 boolean isMounted(java.lang.String name)
           
 java.lang.Object put(java.lang.Object key, java.lang.Object value)
          FileSystemMap is read-only, this method is unsupported.
 
Methods inherited from class java.util.HashMap
clear, clone, containsKey, containsValue, entrySet, get, isEmpty, keySet, putAll, remove, size, values
 
Methods inherited from class java.util.AbstractMap
equals, hashCode, toString
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface java.util.Map
equals, hashCode
 

Constructor Detail

FileSystemMap

public FileSystemMap()
Method Detail

put

public java.lang.Object put(java.lang.Object key,
                            java.lang.Object value)
FileSystemMap is read-only, this method is unsupported.

Specified by:
put in interface java.util.Map
Overrides:
put in class java.util.HashMap
See Also:
init(org.hyperic.sigar.FileSystem[])

init

public void init(FileSystem[] fslist)
Populate the map. FileSystem.getDirName is used as the map key.


getFileSystem

public FileSystem getFileSystem(java.lang.String name)

isMounted

public boolean isMounted(java.lang.String name)

getMountPoint

public FileSystem getMountPoint(java.lang.String name)
Find the file system the given file or directory is within.

Returns:
FileSystem or null if file or directory name does not exist.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileSystemUsage.html000066400000000000000000000565751210132627500270650ustar00rootroot00000000000000 FileSystemUsage (Sigar API)

org.hyperic.sigar
Class FileSystemUsage

java.lang.Object
  extended by org.hyperic.sigar.FileSystemUsage
All Implemented Interfaces:
java.io.Serializable

public class FileSystemUsage
extends java.lang.Object
implements java.io.Serializable

FileSystemUsage sigar class.

See Also:
Serialized Form

Constructor Summary
FileSystemUsage()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 long getAvail()
          Get the Total free Kbytes on filesystem available to caller.
 double getDiskQueue()
          Get the disk_queue.
 long getDiskReadBytes()
          Get the Number of physical disk bytes read.
 long getDiskReads()
          Get the Number of physical disk reads.
 double getDiskServiceTime()
          Get the disk_service_time.
 long getDiskWriteBytes()
          Get the Number of physical disk bytes written.
 long getDiskWrites()
          Get the Number of physical disk writes.
 long getFiles()
          Get the Total number of file nodes on the filesystem.
 long getFree()
          Get the Total free Kbytes on filesystem.
 long getFreeFiles()
          Get the Number of free file nodes on the filesystem.
 long getTotal()
          Get the Total Kbytes of filesystem.
 long getUsed()
          Get the Total used Kbytes on filesystem.
 double getUsePercent()
          Get the Percent of disk used.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

FileSystemUsage

public FileSystemUsage()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the Total Kbytes of filesystem.

Supported Platforms: All.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Total Kbytes of filesystem

getFree

public long getFree()
Get the Total free Kbytes on filesystem.

Supported Platforms: All.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Total free Kbytes on filesystem

getUsed

public long getUsed()
Get the Total used Kbytes on filesystem.

Supported Platforms: All.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Total used Kbytes on filesystem

getAvail

public long getAvail()
Get the Total free Kbytes on filesystem available to caller.

Supported Platforms: All.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Total free Kbytes on filesystem available to caller

getFiles

public long getFiles()
Get the Total number of file nodes on the filesystem.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Total number of file nodes on the filesystem

getFreeFiles

public long getFreeFiles()
Get the Number of free file nodes on the filesystem.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Number of free file nodes on the filesystem

getDiskReads

public long getDiskReads()
Get the Number of physical disk reads.

Supported Platforms: AIX, FreeBSD, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Number of physical disk reads

getDiskWrites

public long getDiskWrites()
Get the Number of physical disk writes.

Supported Platforms: AIX, FreeBSD, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Number of physical disk writes

getDiskReadBytes

public long getDiskReadBytes()
Get the Number of physical disk bytes read.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Number of physical disk bytes read

getDiskWriteBytes

public long getDiskWriteBytes()
Get the Number of physical disk bytes written.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Number of physical disk bytes written

getDiskQueue

public double getDiskQueue()
Get the disk_queue.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
disk_queue

getDiskServiceTime

public double getDiskServiceTime()
Get the disk_service_time.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
disk_service_time

getUsePercent

public double getUsePercent()
Get the Percent of disk used.

Supported Platforms: All.

System equivalent commands:

  • AIX: df
  • Darwin: df
  • FreeBSD: df
  • HPUX: df
  • Linux: df
  • Solaris: df
  • Win32:

Returns:
Percent of disk used

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileTail.html000066400000000000000000000422401210132627500254650ustar00rootroot00000000000000 FileTail (Sigar API)

org.hyperic.sigar
Class FileTail

java.lang.Object
  extended by org.hyperic.sigar.FileWatcher
      extended by org.hyperic.sigar.FileTail

public abstract class FileTail
extends FileWatcher


Field Summary
static java.lang.String PROP_USE_SUDO
           
 
Constructor Summary
FileTail(Sigar sigar)
           
 
Method Summary
 FileInfo add(java.lang.String file)
           
protected  boolean changed(FileInfo info)
           
 void onChange(FileInfo info)
           
abstract  void tail(FileInfo info, java.io.Reader reader)
           
 void useSudo(boolean useSudo)
           
 
Methods inherited from class org.hyperic.sigar.FileWatcher
add, add, add, check, clear, getFiles, getInterval, onException, onNotFound, remove, remove, setInterval
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PROP_USE_SUDO

public static final java.lang.String PROP_USE_SUDO
See Also:
Constant Field Values
Constructor Detail

FileTail

public FileTail(Sigar sigar)
Method Detail

tail

public abstract void tail(FileInfo info,
                          java.io.Reader reader)

useSudo

public void useSudo(boolean useSudo)

onChange

public void onChange(FileInfo info)
Specified by:
onChange in class FileWatcher

add

public FileInfo add(java.lang.String file)
             throws SigarException
Overrides:
add in class FileWatcher
Throws:
SigarException

changed

protected boolean changed(FileInfo info)
                   throws SigarException,
                          SigarFileNotFoundException
Overrides:
changed in class FileWatcher
Throws:
SigarException
SigarFileNotFoundException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileWatcher.html000066400000000000000000000475011210132627500261760ustar00rootroot00000000000000 FileWatcher (Sigar API)

org.hyperic.sigar
Class FileWatcher

java.lang.Object
  extended by org.hyperic.sigar.FileWatcher
Direct Known Subclasses:
FileTail, ProcFileMirror

public abstract class FileWatcher
extends java.lang.Object


Constructor Summary
FileWatcher(Sigar sigar)
           
 
Method Summary
 FileInfo add(java.io.File file)
           
 void add(java.io.File[] files)
           
 FileInfo add(java.lang.String file)
           
 void add(java.lang.String[] files)
           
protected  boolean changed(FileInfo info)
           
 void check()
           
 void clear()
           
 java.util.Set getFiles()
           
 long getInterval()
           
abstract  void onChange(FileInfo info)
           
 void onException(FileInfo info, SigarException e)
           
 void onNotFound(FileInfo info)
           
 void remove(java.io.File file)
           
 void remove(java.lang.String file)
           
 void setInterval(long interval)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FileWatcher

public FileWatcher(Sigar sigar)
Method Detail

onChange

public abstract void onChange(FileInfo info)

onNotFound

public void onNotFound(FileInfo info)

onException

public void onException(FileInfo info,
                        SigarException e)

setInterval

public void setInterval(long interval)

getInterval

public long getInterval()

add

public FileInfo add(java.io.File file)
             throws SigarException
Throws:
SigarException

add

public FileInfo add(java.lang.String file)
             throws SigarException
Throws:
SigarException

add

public void add(java.io.File[] files)
         throws SigarException
Throws:
SigarException

add

public void add(java.lang.String[] files)
         throws SigarException
Throws:
SigarException

remove

public void remove(java.io.File file)

remove

public void remove(java.lang.String file)

clear

public void clear()

getFiles

public java.util.Set getFiles()

changed

protected boolean changed(FileInfo info)
                   throws SigarException,
                          SigarFileNotFoundException
Throws:
SigarException
SigarFileNotFoundException

check

public void check()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/FileWatcherThread.html000066400000000000000000000375221210132627500273300ustar00rootroot00000000000000 FileWatcherThread (Sigar API)

org.hyperic.sigar
Class FileWatcherThread

java.lang.Object
  extended by org.hyperic.sigar.FileWatcherThread
All Implemented Interfaces:
java.lang.Runnable

public class FileWatcherThread
extends java.lang.Object
implements java.lang.Runnable


Field Summary
static int DEFAULT_INTERVAL
           
 
Constructor Summary
FileWatcherThread()
           
 
Method Summary
 void add(FileWatcher watcher)
           
 void check()
           
 void die()
           
 void doStart()
           
 void doStop()
           
static FileWatcherThread getInstance()
           
 long getInterval()
           
 void remove(FileWatcher watcher)
           
 void run()
           
 void setInterval(long interval)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_INTERVAL

public static final int DEFAULT_INTERVAL
See Also:
Constant Field Values
Constructor Detail

FileWatcherThread

public FileWatcherThread()
Method Detail

getInstance

public static FileWatcherThread getInstance()

doStart

public void doStart()

doStop

public void doStop()

setInterval

public void setInterval(long interval)

getInterval

public long getInterval()

add

public void add(FileWatcher watcher)

remove

public void remove(FileWatcher watcher)

run

public void run()
Specified by:
run in interface java.lang.Runnable

die

public void die()

check

public void check()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Humidor.html000066400000000000000000000256411210132627500254110ustar00rootroot00000000000000 Humidor (Sigar API)

org.hyperic.sigar
Class Humidor

java.lang.Object
  extended by org.hyperic.sigar.Humidor

public class Humidor
extends java.lang.Object

The Humidor provides access to a single Sigar instance. Sigar has a high-cost setup/teardown and has a high amount of caching, used to determine things like the % of CPU used in-between calls. The Humidor also synchronizes access to all Sigar methods, so all calls will be serialized.


Constructor Summary
Humidor(Sigar sigar)
           
 
Method Summary
 void close()
           
static Humidor getInstance()
           
 SigarProxy getSigar()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Humidor

public Humidor(Sigar sigar)
Method Detail

getSigar

public SigarProxy getSigar()

getInstance

public static Humidor getInstance()

close

public void close()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Mem.html000066400000000000000000000442641210132627500245220ustar00rootroot00000000000000 Mem (Sigar API)

org.hyperic.sigar
Class Mem

java.lang.Object
  extended by org.hyperic.sigar.Mem
All Implemented Interfaces:
java.io.Serializable

public class Mem
extends java.lang.Object
implements java.io.Serializable

Mem sigar class.

See Also:
Serialized Form

Constructor Summary
Mem()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getActualFree()
          Get the Actual total free system memory.
 long getActualUsed()
          Get the Actual total used system memory (e.g.
 long getFree()
          Get the Total free system memory (e.g.
 double getFreePercent()
          Get the Percent total free system memory.
 long getRam()
          Get the System Random Access Memory (in MB).
 long getTotal()
          Get the Total system memory.
 long getUsed()
          Get the Total used system memory.
 double getUsedPercent()
          Get the Percent total used system memory.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Mem

public Mem()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the Total system memory.

Supported Platforms: All.

System equivalent commands:

  • AIX: lsattr -El sys0 -a realmem
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Total system memory

getRam

public long getRam()
Get the System Random Access Memory (in MB).

Supported Platforms: All.

System equivalent commands:

  • AIX: lsattr -El sys0 -a realmem
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: cat /proc/mtrr | head -1
  • Solaris:
  • Win32:

Returns:
System Random Access Memory (in MB)

getUsed

public long getUsed()
Get the Total used system memory.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Total used system memory

getFree

public long getFree()
Get the Total free system memory (e.g. Linux plus cached).

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Total free system memory (e.g. Linux plus cached)

getActualUsed

public long getActualUsed()
Get the Actual total used system memory (e.g. Linux minus buffers).

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Actual total used system memory (e.g. Linux minus buffers)

getActualFree

public long getActualFree()
Get the Actual total free system memory.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Actual total free system memory

getUsedPercent

public double getUsedPercent()
Get the Percent total used system memory.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Percent total used system memory

getFreePercent

public double getFreePercent()
Get the Percent total free system memory.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris:
  • Win32: taskman

Returns:
Percent total free system memory

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object

toMap

public java.util.Map toMap()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/MultiProcCpu.html000066400000000000000000000317531210132627500263710ustar00rootroot00000000000000 MultiProcCpu (Sigar API)

org.hyperic.sigar
Class MultiProcCpu

java.lang.Object
  extended by org.hyperic.sigar.ProcCpu
      extended by org.hyperic.sigar.MultiProcCpu
All Implemented Interfaces:
java.io.Serializable

public class MultiProcCpu
extends ProcCpu

Provide multi process cpu metrics.

See Also:
Serialized Form

Constructor Summary
MultiProcCpu()
           
 
Method Summary
 boolean equals(java.lang.Object cpu)
           
 double getPercent()
          Get the Process cpu usage.
 int getProcesses()
           
 int hashCode()
           
 
Methods inherited from class org.hyperic.sigar.ProcCpu
gather, getLastTime, getStartTime, getSys, getTotal, getUser, toMap, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MultiProcCpu

public MultiProcCpu()
Method Detail

getPercent

public double getPercent()
Description copied from class: ProcCpu
Get the Process cpu usage.

Supported Platforms: All.

Overrides:
getPercent in class ProcCpu
Returns:
Processes CPU usage percentage.

getProcesses

public int getProcesses()
Returns:
Number of processes matched by query.

hashCode

public int hashCode()
Overrides:
hashCode in class java.lang.Object
Returns:
Pid of the process.

equals

public boolean equals(java.lang.Object cpu)
Overrides:
equals in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/MultiProcMem.html000066400000000000000000000243421210132627500263540ustar00rootroot00000000000000 MultiProcMem (Sigar API)

org.hyperic.sigar
Class MultiProcMem

java.lang.Object
  extended by org.hyperic.sigar.ProcMem
      extended by org.hyperic.sigar.MultiProcMem
All Implemented Interfaces:
java.io.Serializable

public class MultiProcMem
extends ProcMem

See Also:
Serialized Form

Constructor Summary
MultiProcMem()
           
 
Method Summary
 
Methods inherited from class org.hyperic.sigar.ProcMem
gather, getMajorFaults, getMinorFaults, getPageFaults, getResident, getRss, getShare, getSize, getVsize, toMap, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MultiProcMem

public MultiProcMem()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetConnection.html000066400000000000000000000473541210132627500265550ustar00rootroot00000000000000 NetConnection (Sigar API)

org.hyperic.sigar
Class NetConnection

java.lang.Object
  extended by org.hyperic.sigar.NetConnection
All Implemented Interfaces:
java.io.Serializable

public class NetConnection
extends java.lang.Object
implements java.io.Serializable

NetConnection sigar class.

See Also:
Serialized Form

Constructor Summary
NetConnection()
           
 
Method Summary
 void gather(Sigar sigar)
           
 java.lang.String getLocalAddress()
          Get the local_address.
 long getLocalPort()
          Get the local_port.
 long getReceiveQueue()
          Get the receive_queue.
 java.lang.String getRemoteAddress()
          Get the remote_address.
 long getRemotePort()
          Get the remote_port.
 long getSendQueue()
          Get the send_queue.
 int getState()
          Get the state.
 java.lang.String getStateString()
           
static java.lang.String getStateString(int state)
           
 int getType()
          Get the type.
 java.lang.String getTypeString()
           
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NetConnection

public NetConnection()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getLocalPort

public long getLocalPort()
Get the local_port.

Supported Platforms: Linux, FreeBSD, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
local_port

getLocalAddress

public java.lang.String getLocalAddress()
Get the local_address.

Supported Platforms: Linux, FreeBSD, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
local_address

getRemotePort

public long getRemotePort()
Get the remote_port.

Supported Platforms: Linux, FreeBSD, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
remote_port

getRemoteAddress

public java.lang.String getRemoteAddress()
Get the remote_address.

Supported Platforms: Linux, FreeBSD, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
remote_address

getType

public int getType()
Get the type.

Supported Platforms: Linux, FreeBSD, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
type

getState

public int getState()
Get the state.

Supported Platforms: Linux, FreeBSD, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
state

getSendQueue

public long getSendQueue()
Get the send_queue.

Supported Platforms: Linux, FreeBSD, Solaris.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
send_queue

getReceiveQueue

public long getReceiveQueue()
Get the receive_queue.

Supported Platforms: Linux, FreeBSD, Solaris.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: netstat
  • Solaris:
  • Win32:

Returns:
receive_queue

getTypeString

public java.lang.String getTypeString()

getStateString

public static java.lang.String getStateString(int state)

getStateString

public java.lang.String getStateString()

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetFlags.html000066400000000000000000001107441210132627500255040ustar00rootroot00000000000000 NetFlags (Sigar API)

org.hyperic.sigar
Class NetFlags

java.lang.Object
  extended by org.hyperic.sigar.NetFlags

public class NetFlags
extends java.lang.Object

Flag constants for network related ops.


Field Summary
static java.lang.String ANY_ADDR
           
static java.lang.String ANY_ADDR_V6
           
static int CONN_CLIENT
           
static int CONN_PROTOCOLS
           
static int CONN_RAW
           
static int CONN_SERVER
           
static int CONN_TCP
           
static int CONN_UDP
           
static int CONN_UNIX
           
static int IFF_ALLMULTI
          receive all multicast packets
static int IFF_BROADCAST
          broadcast address valid
static int IFF_DEBUG
          debugging is on
static int IFF_LOOPBACK
          is a loopback net
static int IFF_MULTICAST
          supports multicast
static int IFF_NOARP
          no ARP protocol
static int IFF_NOTRAILERS
          avoid use of trailers
static int IFF_POINTOPOINT
          interface has a point-to-point link
static int IFF_PROMISC
          receive all packets
static int IFF_RUNNING
          interface is running
static int IFF_SLAVE
           
static int IFF_UP
          interface is up
static java.lang.String LOOPBACK_ADDRESS
           
static java.lang.String LOOPBACK_ADDRESS_V6
           
static java.lang.String LOOPBACK_HOSTNAME
           
static java.lang.String NULL_HWADDR
          value of unknown or non-existent hardware address
static int RTF_GATEWAY
           
static int RTF_HOST
           
static int RTF_UP
           
static int TCP_BOUND
           
static int TCP_CLOSE
           
static int TCP_CLOSE_WAIT
           
static int TCP_CLOSING
           
static int TCP_ESTABLISHED
           
static int TCP_FIN_WAIT1
           
static int TCP_FIN_WAIT2
           
static int TCP_IDLE
           
static int TCP_LAST_ACK
           
static int TCP_LISTEN
           
static int TCP_SYN_RECV
           
static int TCP_SYN_SENT
           
static int TCP_TIME_WAIT
           
static int TCP_UNKNOWN
           
 
Method Summary
static int getConnectionProtocol(java.lang.String protocol)
           
static java.lang.String getIfFlagsString(long flags)
           
static boolean isAnyAddress(java.lang.String address)
           
static boolean isLoopback(java.lang.String address)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NULL_HWADDR

public static final java.lang.String NULL_HWADDR
value of unknown or non-existent hardware address

See Also:
Constant Field Values

ANY_ADDR

public static final java.lang.String ANY_ADDR
See Also:
Constant Field Values

ANY_ADDR_V6

public static final java.lang.String ANY_ADDR_V6
See Also:
Constant Field Values

LOOPBACK_HOSTNAME

public static final java.lang.String LOOPBACK_HOSTNAME
See Also:
Constant Field Values

LOOPBACK_ADDRESS

public static final java.lang.String LOOPBACK_ADDRESS
See Also:
Constant Field Values

LOOPBACK_ADDRESS_V6

public static final java.lang.String LOOPBACK_ADDRESS_V6
See Also:
Constant Field Values

IFF_UP

public static final int IFF_UP
interface is up

See Also:
Constant Field Values

IFF_BROADCAST

public static final int IFF_BROADCAST
broadcast address valid

See Also:
Constant Field Values

IFF_DEBUG

public static final int IFF_DEBUG
debugging is on

See Also:
Constant Field Values

IFF_LOOPBACK

public static final int IFF_LOOPBACK
is a loopback net

See Also:
Constant Field Values

IFF_POINTOPOINT

public static final int IFF_POINTOPOINT
interface has a point-to-point link

See Also:
Constant Field Values

IFF_NOTRAILERS

public static final int IFF_NOTRAILERS
avoid use of trailers

See Also:
Constant Field Values

IFF_RUNNING

public static final int IFF_RUNNING
interface is running

See Also:
Constant Field Values

IFF_NOARP

public static final int IFF_NOARP
no ARP protocol

See Also:
Constant Field Values

IFF_PROMISC

public static final int IFF_PROMISC
receive all packets

See Also:
Constant Field Values

IFF_ALLMULTI

public static final int IFF_ALLMULTI
receive all multicast packets

See Also:
Constant Field Values

IFF_MULTICAST

public static final int IFF_MULTICAST
supports multicast

See Also:
Constant Field Values

IFF_SLAVE

public static final int IFF_SLAVE
See Also:
Constant Field Values

RTF_UP

public static final int RTF_UP
See Also:
Constant Field Values

RTF_GATEWAY

public static final int RTF_GATEWAY
See Also:
Constant Field Values

RTF_HOST

public static final int RTF_HOST
See Also:
Constant Field Values

CONN_CLIENT

public static final int CONN_CLIENT
See Also:
Constant Field Values

CONN_SERVER

public static final int CONN_SERVER
See Also:
Constant Field Values

CONN_TCP

public static final int CONN_TCP
See Also:
Constant Field Values

CONN_UDP

public static final int CONN_UDP
See Also:
Constant Field Values

CONN_RAW

public static final int CONN_RAW
See Also:
Constant Field Values

CONN_UNIX

public static final int CONN_UNIX
See Also:
Constant Field Values

CONN_PROTOCOLS

public static final int CONN_PROTOCOLS
See Also:
Constant Field Values

TCP_ESTABLISHED

public static final int TCP_ESTABLISHED
See Also:
Constant Field Values

TCP_SYN_SENT

public static final int TCP_SYN_SENT
See Also:
Constant Field Values

TCP_SYN_RECV

public static final int TCP_SYN_RECV
See Also:
Constant Field Values

TCP_FIN_WAIT1

public static final int TCP_FIN_WAIT1
See Also:
Constant Field Values

TCP_FIN_WAIT2

public static final int TCP_FIN_WAIT2
See Also:
Constant Field Values

TCP_TIME_WAIT

public static final int TCP_TIME_WAIT
See Also:
Constant Field Values

TCP_CLOSE

public static final int TCP_CLOSE
See Also:
Constant Field Values

TCP_CLOSE_WAIT

public static final int TCP_CLOSE_WAIT
See Also:
Constant Field Values

TCP_LAST_ACK

public static final int TCP_LAST_ACK
See Also:
Constant Field Values

TCP_LISTEN

public static final int TCP_LISTEN
See Also:
Constant Field Values

TCP_CLOSING

public static final int TCP_CLOSING
See Also:
Constant Field Values

TCP_IDLE

public static final int TCP_IDLE
See Also:
Constant Field Values

TCP_BOUND

public static final int TCP_BOUND
See Also:
Constant Field Values

TCP_UNKNOWN

public static final int TCP_UNKNOWN
See Also:
Constant Field Values
Method Detail

getConnectionProtocol

public static int getConnectionProtocol(java.lang.String protocol)
                                 throws SigarException
Throws:
SigarException

getIfFlagsString

public static java.lang.String getIfFlagsString(long flags)
Parameters:
flags - network interface flags.
Returns:
String representation of network interface flags.
See Also:
NetInterfaceConfig.getFlags()

isAnyAddress

public static boolean isAnyAddress(java.lang.String address)

isLoopback

public static boolean isLoopback(java.lang.String address)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetInfo.html000066400000000000000000000341471210132627500253450ustar00rootroot00000000000000 NetInfo (Sigar API)

org.hyperic.sigar
Class NetInfo

java.lang.Object
  extended by org.hyperic.sigar.NetInfo
All Implemented Interfaces:
java.io.Serializable

public class NetInfo
extends java.lang.Object
implements java.io.Serializable

NetInfo sigar class.

See Also:
Serialized Form

Constructor Summary
NetInfo()
           
 
Method Summary
 void gather(Sigar sigar)
           
 java.lang.String getDefaultGateway()
          Get the default_gateway.
 java.lang.String getDomainName()
          Get the domain_name.
 java.lang.String getHostName()
          Get the host_name.
 java.lang.String getPrimaryDns()
          Get the primary_dns.
 java.lang.String getSecondaryDns()
          Get the secondary_dns.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NetInfo

public NetInfo()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getDefaultGateway

public java.lang.String getDefaultGateway()
Get the default_gateway.

Supported Platforms: Undocumented.

Returns:
default_gateway

getHostName

public java.lang.String getHostName()
Get the host_name.

Supported Platforms: Undocumented.

Returns:
host_name

getDomainName

public java.lang.String getDomainName()
Get the domain_name.

Supported Platforms: Undocumented.

Returns:
domain_name

getPrimaryDns

public java.lang.String getPrimaryDns()
Get the primary_dns.

Supported Platforms: Undocumented.

Returns:
primary_dns

getSecondaryDns

public java.lang.String getSecondaryDns()
Get the secondary_dns.

Supported Platforms: Undocumented.

Returns:
secondary_dns

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetInterfaceConfig.html000066400000000000000000000515241210132627500274760ustar00rootroot00000000000000 NetInterfaceConfig (Sigar API)

org.hyperic.sigar
Class NetInterfaceConfig

java.lang.Object
  extended by org.hyperic.sigar.NetInterfaceConfig
All Implemented Interfaces:
java.io.Serializable

public class NetInterfaceConfig
extends java.lang.Object
implements java.io.Serializable

NetInterfaceConfig sigar class.

See Also:
Serialized Form

Constructor Summary
NetInterfaceConfig()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 java.lang.String getAddress()
          Get the address.
 java.lang.String getBroadcast()
          Get the broadcast.
 java.lang.String getDescription()
          Get the description.
 java.lang.String getDestination()
          Get the destination.
 long getFlags()
          Get the flags.
 java.lang.String getHwaddr()
          Get the hwaddr.
 long getMetric()
          Get the metric.
 long getMtu()
          Get the mtu.
 java.lang.String getName()
          Get the name.
 java.lang.String getNetmask()
          Get the netmask.
 java.lang.String getType()
          Get the type.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NetInterfaceConfig

public NetInterfaceConfig()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getName

public java.lang.String getName()
Get the name.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
name

getHwaddr

public java.lang.String getHwaddr()
Get the hwaddr.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
hwaddr

getType

public java.lang.String getType()
Get the type.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
type

getDescription

public java.lang.String getDescription()
Get the description.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
description

getAddress

public java.lang.String getAddress()
Get the address.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
address

getDestination

public java.lang.String getDestination()
Get the destination.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
destination

getBroadcast

public java.lang.String getBroadcast()
Get the broadcast.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
broadcast

getNetmask

public java.lang.String getNetmask()
Get the netmask.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
netmask

getFlags

public long getFlags()
Get the flags.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
flags

getMtu

public long getMtu()
Get the mtu.

Supported Platforms: Darwin, FreeBSD, Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
mtu

getMetric

public long getMetric()
Get the metric.

Supported Platforms: Darwin, FreeBSD, Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ifconfig
  • Solaris: ifconfig -a
  • Win32:

Returns:
metric

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetInterfaceStat.html000066400000000000000000000575471210132627500272170ustar00rootroot00000000000000 NetInterfaceStat (Sigar API)

org.hyperic.sigar
Class NetInterfaceStat

java.lang.Object
  extended by org.hyperic.sigar.NetInterfaceStat
All Implemented Interfaces:
java.io.Serializable

public class NetInterfaceStat
extends java.lang.Object
implements java.io.Serializable

NetInterfaceStat sigar class.

See Also:
Serialized Form

Constructor Summary
NetInterfaceStat()
           
 
Method Summary
 void gather(Sigar sigar, java.lang.String name)
           
 long getRxBytes()
          Get the rx_bytes.
 long getRxDropped()
          Get the rx_dropped.
 long getRxErrors()
          Get the rx_errors.
 long getRxFrame()
          Get the rx_frame.
 long getRxOverruns()
          Get the rx_overruns.
 long getRxPackets()
          Get the rx_packets.
 long getSpeed()
          Get the speed.
 long getTxBytes()
          Get the tx_bytes.
 long getTxCarrier()
          Get the tx_carrier.
 long getTxCollisions()
          Get the tx_collisions.
 long getTxDropped()
          Get the tx_dropped.
 long getTxErrors()
          Get the *.
 long getTxOverruns()
          Get the tx_overruns.
 long getTxPackets()
          Get the tx_packets.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NetInterfaceStat

public NetInterfaceStat()
Method Detail

gather

public void gather(Sigar sigar,
                   java.lang.String name)
            throws SigarException
Throws:
SigarException

getRxBytes

public long getRxBytes()
Get the rx_bytes.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
rx_bytes

getRxPackets

public long getRxPackets()
Get the rx_packets.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
rx_packets

getRxErrors

public long getRxErrors()
Get the rx_errors.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
rx_errors

getRxDropped

public long getRxDropped()
Get the rx_dropped.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
rx_dropped

getRxOverruns

public long getRxOverruns()
Get the rx_overruns.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
rx_overruns

getRxFrame

public long getRxFrame()
Get the rx_frame.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
rx_frame

getTxBytes

public long getTxBytes()
Get the tx_bytes.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
tx_bytes

getTxPackets

public long getTxPackets()
Get the tx_packets.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
tx_packets

getTxErrors

public long getTxErrors()
Get the *.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
*

getTxDropped

public long getTxDropped()
Get the tx_dropped.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
tx_dropped

getTxOverruns

public long getTxOverruns()
Get the tx_overruns.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
tx_overruns

getTxCollisions

public long getTxCollisions()
Get the tx_collisions.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
tx_collisions

getTxCarrier

public long getTxCarrier()
Get the tx_carrier.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
tx_carrier

getSpeed

public long getSpeed()
Get the speed.

Supported Platforms: Undocumented.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX: /usr/sbin/lanadmin -g mibstats 0, netstat -i
  • Linux: ifconfig
  • Solaris:
  • Win32:

Returns:
speed

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetRoute.html000066400000000000000000000502071210132627500255430ustar00rootroot00000000000000 NetRoute (Sigar API)

org.hyperic.sigar
Class NetRoute

java.lang.Object
  extended by org.hyperic.sigar.NetRoute
All Implemented Interfaces:
java.io.Serializable

public class NetRoute
extends java.lang.Object
implements java.io.Serializable

NetRoute sigar class.

See Also:
Serialized Form

Constructor Summary
NetRoute()
           
 
Method Summary
 void gather(Sigar sigar)
           
 java.lang.String getDestination()
          Get the destination.
 long getFlags()
          Get the flags.
 java.lang.String getGateway()
          Get the gateway.
 java.lang.String getIfname()
          Get the ifname.
 long getIrtt()
          Get the irtt.
 java.lang.String getMask()
          Get the mask.
 long getMetric()
          Get the metric.
 long getMtu()
          Get the mtu.
 long getRefcnt()
          Get the refcnt.
 long getUse()
          Get the use.
 long getWindow()
          Get the window.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NetRoute

public NetRoute()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getDestination

public java.lang.String getDestination()
Get the destination.

Supported Platforms: HPUX, Linux, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
destination

getGateway

public java.lang.String getGateway()
Get the gateway.

Supported Platforms: HPUX, Linux, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
gateway

getFlags

public long getFlags()
Get the flags.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
flags

getRefcnt

public long getRefcnt()
Get the refcnt.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
refcnt

getUse

public long getUse()
Get the use.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
use

getMetric

public long getMetric()
Get the metric.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
metric

getMask

public java.lang.String getMask()
Get the mask.

Supported Platforms: HPUX, Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
mask

getMtu

public long getMtu()
Get the mtu.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
mtu

getWindow

public long getWindow()
Get the window.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
window

getIrtt

public long getIrtt()
Get the irtt.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
irtt

getIfname

public java.lang.String getIfname()
Get the ifname.

Supported Platforms: Linux.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: route -n
  • Solaris:
  • Win32:

Returns:
ifname

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetServices.html000066400000000000000000000244051210132627500262310ustar00rootroot00000000000000 NetServices (Sigar API)

org.hyperic.sigar
Class NetServices

java.lang.Object
  extended by org.hyperic.sigar.NetServices

Deprecated.

public class NetServices
extends java.lang.Object

See Also:
Sigar.getNetServicesName(int, long)

Method Summary
protected  void finalize()
          Deprecated.  
static java.lang.String getName(java.lang.String protocol, long port)
          Deprecated.  
static java.lang.String getTcpName(long port)
          Deprecated.  
static java.lang.String getUdpName(long port)
          Deprecated.  
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

finalize

protected void finalize()
Deprecated. 
Overrides:
finalize in class java.lang.Object

getName

public static java.lang.String getName(java.lang.String protocol,
                                       long port)
Deprecated. 

getTcpName

public static java.lang.String getTcpName(long port)
Deprecated. 

getUdpName

public static java.lang.String getUdpName(long port)
Deprecated. 


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NetStat.html000066400000000000000000000555431210132627500253700ustar00rootroot00000000000000 NetStat (Sigar API)

org.hyperic.sigar
Class NetStat

java.lang.Object
  extended by org.hyperic.sigar.NetStat
All Implemented Interfaces:
java.io.Serializable

public class NetStat
extends java.lang.Object
implements java.io.Serializable

See Also:
Serialized Form

Field Summary
protected  int allInboundTotal
           
protected  int allOutboundTotal
           
protected  int tcpInboundTotal
           
protected  int tcpOutboundTotal
           
protected  int[] tcpStates
           
 
Constructor Summary
NetStat()
           
 
Method Summary
 int getAllInboundTotal()
           
 int getAllOutboundTotal()
           
 int getTcpBound()
           
 int getTcpClose()
           
 int getTcpCloseWait()
           
 int getTcpClosing()
           
 int getTcpEstablished()
           
 int getTcpFinWait1()
           
 int getTcpFinWait2()
           
 int getTcpIdle()
           
 int getTcpInboundTotal()
           
 int getTcpLastAck()
           
 int getTcpListen()
           
 int getTcpOutboundTotal()
           
 int[] getTcpStates()
           
 int getTcpSynRecv()
           
 int getTcpSynSent()
           
 int getTcpTimeWait()
           
 void stat(Sigar sigar)
           
 void stat(Sigar sigar, byte[] address, long port)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

tcpStates

protected int[] tcpStates

tcpInboundTotal

protected int tcpInboundTotal

tcpOutboundTotal

protected int tcpOutboundTotal

allInboundTotal

protected int allInboundTotal

allOutboundTotal

protected int allOutboundTotal
Constructor Detail

NetStat

public NetStat()
Method Detail

stat

public void stat(Sigar sigar)
          throws SigarException
Throws:
SigarException

stat

public void stat(Sigar sigar,
                 byte[] address,
                 long port)
          throws SigarException
Throws:
SigarException

getTcpInboundTotal

public int getTcpInboundTotal()

getTcpOutboundTotal

public int getTcpOutboundTotal()

getAllInboundTotal

public int getAllInboundTotal()

getAllOutboundTotal

public int getAllOutboundTotal()

getTcpStates

public int[] getTcpStates()

getTcpEstablished

public int getTcpEstablished()

getTcpSynSent

public int getTcpSynSent()

getTcpSynRecv

public int getTcpSynRecv()

getTcpFinWait1

public int getTcpFinWait1()

getTcpFinWait2

public int getTcpFinWait2()

getTcpTimeWait

public int getTcpTimeWait()

getTcpClose

public int getTcpClose()

getTcpCloseWait

public int getTcpCloseWait()

getTcpLastAck

public int getTcpLastAck()

getTcpListen

public int getTcpListen()

getTcpClosing

public int getTcpClosing()

getTcpIdle

public int getTcpIdle()

getTcpBound

public int getTcpBound()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NfsClientV2.html000066400000000000000000000525571210132627500261050ustar00rootroot00000000000000 NfsClientV2 (Sigar API)

org.hyperic.sigar
Class NfsClientV2

java.lang.Object
  extended by org.hyperic.sigar.NfsClientV2
All Implemented Interfaces:
java.io.Serializable

public class NfsClientV2
extends java.lang.Object
implements java.io.Serializable

NfsClientV2 sigar class.

See Also:
Serialized Form

Constructor Summary
NfsClientV2()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getCreate()
          Get the create.
 long getFsstat()
          Get the fsstat.
 long getGetattr()
          Get the getattr.
 long getLink()
          Get the link.
 long getLookup()
          Get the lookup.
 long getMkdir()
          Get the mkdir.
 long getNull()
          Get the null.
 long getRead()
          Get the read.
 long getReaddir()
          Get the readdir.
 long getReadlink()
          Get the readlink.
 long getRemove()
          Get the remove.
 long getRename()
          Get the rename.
 long getRmdir()
          Get the rmdir.
 long getRoot()
          Get the root.
 long getSetattr()
          Get the setattr.
 long getSymlink()
          Get the symlink.
 long getWrite()
          Get the write.
 long getWritecache()
          Get the writecache.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NfsClientV2

public NfsClientV2()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getNull

public long getNull()
Get the null.

Supported Platforms: Undocumented.

Returns:
null

getGetattr

public long getGetattr()
Get the getattr.

Supported Platforms: Undocumented.

Returns:
getattr

getSetattr

public long getSetattr()
Get the setattr.

Supported Platforms: Undocumented.

Returns:
setattr

getRoot

public long getRoot()
Get the root.

Supported Platforms: Undocumented.

Returns:
root

getLookup

public long getLookup()
Get the lookup.

Supported Platforms: Undocumented.

Returns:
lookup

getReadlink

public long getReadlink()
Get the readlink.

Supported Platforms: Undocumented.

Returns:
readlink

getRead

public long getRead()
Get the read.

Supported Platforms: Undocumented.

Returns:
read

getWritecache

public long getWritecache()
Get the writecache.

Supported Platforms: Undocumented.

Returns:
writecache

getWrite

public long getWrite()
Get the write.

Supported Platforms: Undocumented.

Returns:
write

getCreate

public long getCreate()
Get the create.

Supported Platforms: Undocumented.

Returns:
create

getRemove

public long getRemove()
Get the remove.

Supported Platforms: Undocumented.

Returns:
remove

getRename

public long getRename()
Get the rename.

Supported Platforms: Undocumented.

Returns:
rename

getLink

public long getLink()
Get the link.

Supported Platforms: Undocumented.

Returns:
link

getSymlink

public long getSymlink()
Get the symlink.

Supported Platforms: Undocumented.

Returns:
symlink

getMkdir

public long getMkdir()
Get the mkdir.

Supported Platforms: Undocumented.

Returns:
mkdir

getRmdir

public long getRmdir()
Get the rmdir.

Supported Platforms: Undocumented.

Returns:
rmdir

getReaddir

public long getReaddir()
Get the readdir.

Supported Platforms: Undocumented.

Returns:
readdir

getFsstat

public long getFsstat()
Get the fsstat.

Supported Platforms: Undocumented.

Returns:
fsstat

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NfsClientV3.html000066400000000000000000000573271210132627500261060ustar00rootroot00000000000000 NfsClientV3 (Sigar API)

org.hyperic.sigar
Class NfsClientV3

java.lang.Object
  extended by org.hyperic.sigar.NfsClientV3
All Implemented Interfaces:
java.io.Serializable

public class NfsClientV3
extends java.lang.Object
implements java.io.Serializable

NfsClientV3 sigar class.

See Also:
Serialized Form

Constructor Summary
NfsClientV3()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getAccess()
          Get the access.
 long getCommit()
          Get the commit.
 long getCreate()
          Get the create.
 long getFsinfo()
          Get the fsinfo.
 long getFsstat()
          Get the fsstat.
 long getGetattr()
          Get the getattr.
 long getLink()
          Get the link.
 long getLookup()
          Get the lookup.
 long getMkdir()
          Get the mkdir.
 long getMknod()
          Get the mknod.
 long getNull()
          Get the null.
 long getPathconf()
          Get the pathconf.
 long getRead()
          Get the read.
 long getReaddir()
          Get the readdir.
 long getReaddirplus()
          Get the readdirplus.
 long getReadlink()
          Get the readlink.
 long getRemove()
          Get the remove.
 long getRename()
          Get the rename.
 long getRmdir()
          Get the rmdir.
 long getSetattr()
          Get the setattr.
 long getSymlink()
          Get the symlink.
 long getWrite()
          Get the write.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NfsClientV3

public NfsClientV3()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getNull

public long getNull()
Get the null.

Supported Platforms: Undocumented.

Returns:
null

getGetattr

public long getGetattr()
Get the getattr.

Supported Platforms: Undocumented.

Returns:
getattr

getSetattr

public long getSetattr()
Get the setattr.

Supported Platforms: Undocumented.

Returns:
setattr

getLookup

public long getLookup()
Get the lookup.

Supported Platforms: Undocumented.

Returns:
lookup

getAccess

public long getAccess()
Get the access.

Supported Platforms: Undocumented.

Returns:
access

getReadlink

public long getReadlink()
Get the readlink.

Supported Platforms: Undocumented.

Returns:
readlink

getRead

public long getRead()
Get the read.

Supported Platforms: Undocumented.

Returns:
read

getWrite

public long getWrite()
Get the write.

Supported Platforms: Undocumented.

Returns:
write

getCreate

public long getCreate()
Get the create.

Supported Platforms: Undocumented.

Returns:
create

getMkdir

public long getMkdir()
Get the mkdir.

Supported Platforms: Undocumented.

Returns:
mkdir

getSymlink

public long getSymlink()
Get the symlink.

Supported Platforms: Undocumented.

Returns:
symlink

getMknod

public long getMknod()
Get the mknod.

Supported Platforms: Undocumented.

Returns:
mknod

getRemove

public long getRemove()
Get the remove.

Supported Platforms: Undocumented.

Returns:
remove

getRmdir

public long getRmdir()
Get the rmdir.

Supported Platforms: Undocumented.

Returns:
rmdir

getRename

public long getRename()
Get the rename.

Supported Platforms: Undocumented.

Returns:
rename

getLink

public long getLink()
Get the link.

Supported Platforms: Undocumented.

Returns:
link

getReaddir

public long getReaddir()
Get the readdir.

Supported Platforms: Undocumented.

Returns:
readdir

getReaddirplus

public long getReaddirplus()
Get the readdirplus.

Supported Platforms: Undocumented.

Returns:
readdirplus

getFsstat

public long getFsstat()
Get the fsstat.

Supported Platforms: Undocumented.

Returns:
fsstat

getFsinfo

public long getFsinfo()
Get the fsinfo.

Supported Platforms: Undocumented.

Returns:
fsinfo

getPathconf

public long getPathconf()
Get the pathconf.

Supported Platforms: Undocumented.

Returns:
pathconf

getCommit

public long getCommit()
Get the commit.

Supported Platforms: Undocumented.

Returns:
commit

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NfsFileSystem.html000066400000000000000000000356701210132627500265400ustar00rootroot00000000000000 NfsFileSystem (Sigar API)

org.hyperic.sigar
Class NfsFileSystem

java.lang.Object
  extended by org.hyperic.sigar.FileSystem
      extended by org.hyperic.sigar.NfsFileSystem
All Implemented Interfaces:
java.io.Serializable

public class NfsFileSystem
extends FileSystem
implements java.io.Serializable

See Also:
Serialized Form

Field Summary
 
Fields inherited from class org.hyperic.sigar.FileSystem
TYPE_CDROM, TYPE_LOCAL_DISK, TYPE_NETWORK, TYPE_NONE, TYPE_RAM_DISK, TYPE_SWAP, TYPE_UNKNOWN
 
Constructor Summary
NfsFileSystem()
           
 
Method Summary
 java.lang.String getHostname()
           
 NfsUnreachableException getUnreachableException()
           
 java.lang.String getUnreachableMessage()
           
static void main(java.lang.String[] args)
           
 boolean ping()
           
 
Methods inherited from class org.hyperic.sigar.FileSystem
gather, getDevName, getDirName, getFlags, getOptions, getSysTypeName, getType, getTypeName, toMap, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NfsFileSystem

public NfsFileSystem()
Method Detail

getHostname

public java.lang.String getHostname()

ping

public boolean ping()

getUnreachableMessage

public java.lang.String getUnreachableMessage()

getUnreachableException

public NfsUnreachableException getUnreachableException()

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NfsServerV2.html000066400000000000000000000525731210132627500261330ustar00rootroot00000000000000 NfsServerV2 (Sigar API)

org.hyperic.sigar
Class NfsServerV2

java.lang.Object
  extended by org.hyperic.sigar.NfsServerV2
All Implemented Interfaces:
java.io.Serializable

public class NfsServerV2
extends java.lang.Object
implements java.io.Serializable

NfsServerV2 sigar class.

See Also:
Serialized Form

Constructor Summary
NfsServerV2()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getCreate()
          Get the create.
 long getFsstat()
          Get the fsstat.
 long getGetattr()
          Get the getattr.
 long getLink()
          Get the link.
 long getLookup()
          Get the lookup.
 long getMkdir()
          Get the mkdir.
 long getNull()
          Get the null.
 long getRead()
          Get the read.
 long getReaddir()
          Get the readdir.
 long getReadlink()
          Get the readlink.
 long getRemove()
          Get the remove.
 long getRename()
          Get the rename.
 long getRmdir()
          Get the rmdir.
 long getRoot()
          Get the root.
 long getSetattr()
          Get the setattr.
 long getSymlink()
          Get the symlink.
 long getWrite()
          Get the write.
 long getWritecache()
          Get the writecache.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NfsServerV2

public NfsServerV2()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getNull

public long getNull()
Get the null.

Supported Platforms: Undocumented.

Returns:
null

getGetattr

public long getGetattr()
Get the getattr.

Supported Platforms: Undocumented.

Returns:
getattr

getSetattr

public long getSetattr()
Get the setattr.

Supported Platforms: Undocumented.

Returns:
setattr

getRoot

public long getRoot()
Get the root.

Supported Platforms: Undocumented.

Returns:
root

getLookup

public long getLookup()
Get the lookup.

Supported Platforms: Undocumented.

Returns:
lookup

getReadlink

public long getReadlink()
Get the readlink.

Supported Platforms: Undocumented.

Returns:
readlink

getRead

public long getRead()
Get the read.

Supported Platforms: Undocumented.

Returns:
read

getWritecache

public long getWritecache()
Get the writecache.

Supported Platforms: Undocumented.

Returns:
writecache

getWrite

public long getWrite()
Get the write.

Supported Platforms: Undocumented.

Returns:
write

getCreate

public long getCreate()
Get the create.

Supported Platforms: Undocumented.

Returns:
create

getRemove

public long getRemove()
Get the remove.

Supported Platforms: Undocumented.

Returns:
remove

getRename

public long getRename()
Get the rename.

Supported Platforms: Undocumented.

Returns:
rename

getLink

public long getLink()
Get the link.

Supported Platforms: Undocumented.

Returns:
link

getSymlink

public long getSymlink()
Get the symlink.

Supported Platforms: Undocumented.

Returns:
symlink

getMkdir

public long getMkdir()
Get the mkdir.

Supported Platforms: Undocumented.

Returns:
mkdir

getRmdir

public long getRmdir()
Get the rmdir.

Supported Platforms: Undocumented.

Returns:
rmdir

getReaddir

public long getReaddir()
Get the readdir.

Supported Platforms: Undocumented.

Returns:
readdir

getFsstat

public long getFsstat()
Get the fsstat.

Supported Platforms: Undocumented.

Returns:
fsstat

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NfsServerV3.html000066400000000000000000000573531210132627500261350ustar00rootroot00000000000000 NfsServerV3 (Sigar API)

org.hyperic.sigar
Class NfsServerV3

java.lang.Object
  extended by org.hyperic.sigar.NfsServerV3
All Implemented Interfaces:
java.io.Serializable

public class NfsServerV3
extends java.lang.Object
implements java.io.Serializable

NfsServerV3 sigar class.

See Also:
Serialized Form

Constructor Summary
NfsServerV3()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getAccess()
          Get the access.
 long getCommit()
          Get the commit.
 long getCreate()
          Get the create.
 long getFsinfo()
          Get the fsinfo.
 long getFsstat()
          Get the fsstat.
 long getGetattr()
          Get the getattr.
 long getLink()
          Get the link.
 long getLookup()
          Get the lookup.
 long getMkdir()
          Get the mkdir.
 long getMknod()
          Get the mknod.
 long getNull()
          Get the null.
 long getPathconf()
          Get the pathconf.
 long getRead()
          Get the read.
 long getReaddir()
          Get the readdir.
 long getReaddirplus()
          Get the readdirplus.
 long getReadlink()
          Get the readlink.
 long getRemove()
          Get the remove.
 long getRename()
          Get the rename.
 long getRmdir()
          Get the rmdir.
 long getSetattr()
          Get the setattr.
 long getSymlink()
          Get the symlink.
 long getWrite()
          Get the write.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NfsServerV3

public NfsServerV3()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getNull

public long getNull()
Get the null.

Supported Platforms: Undocumented.

Returns:
null

getGetattr

public long getGetattr()
Get the getattr.

Supported Platforms: Undocumented.

Returns:
getattr

getSetattr

public long getSetattr()
Get the setattr.

Supported Platforms: Undocumented.

Returns:
setattr

getLookup

public long getLookup()
Get the lookup.

Supported Platforms: Undocumented.

Returns:
lookup

getAccess

public long getAccess()
Get the access.

Supported Platforms: Undocumented.

Returns:
access

getReadlink

public long getReadlink()
Get the readlink.

Supported Platforms: Undocumented.

Returns:
readlink

getRead

public long getRead()
Get the read.

Supported Platforms: Undocumented.

Returns:
read

getWrite

public long getWrite()
Get the write.

Supported Platforms: Undocumented.

Returns:
write

getCreate

public long getCreate()
Get the create.

Supported Platforms: Undocumented.

Returns:
create

getMkdir

public long getMkdir()
Get the mkdir.

Supported Platforms: Undocumented.

Returns:
mkdir

getSymlink

public long getSymlink()
Get the symlink.

Supported Platforms: Undocumented.

Returns:
symlink

getMknod

public long getMknod()
Get the mknod.

Supported Platforms: Undocumented.

Returns:
mknod

getRemove

public long getRemove()
Get the remove.

Supported Platforms: Undocumented.

Returns:
remove

getRmdir

public long getRmdir()
Get the rmdir.

Supported Platforms: Undocumented.

Returns:
rmdir

getRename

public long getRename()
Get the rename.

Supported Platforms: Undocumented.

Returns:
rename

getLink

public long getLink()
Get the link.

Supported Platforms: Undocumented.

Returns:
link

getReaddir

public long getReaddir()
Get the readdir.

Supported Platforms: Undocumented.

Returns:
readdir

getReaddirplus

public long getReaddirplus()
Get the readdirplus.

Supported Platforms: Undocumented.

Returns:
readdirplus

getFsstat

public long getFsstat()
Get the fsstat.

Supported Platforms: Undocumented.

Returns:
fsstat

getFsinfo

public long getFsinfo()
Get the fsinfo.

Supported Platforms: Undocumented.

Returns:
fsinfo

getPathconf

public long getPathconf()
Get the pathconf.

Supported Platforms: Undocumented.

Returns:
pathconf

getCommit

public long getCommit()
Get the commit.

Supported Platforms: Undocumented.

Returns:
commit

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/NfsUnreachableException.html000066400000000000000000000255621210132627500305430ustar00rootroot00000000000000 NfsUnreachableException (Sigar API)

org.hyperic.sigar
Class NfsUnreachableException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.NfsUnreachableException
All Implemented Interfaces:
java.io.Serializable

public class NfsUnreachableException
extends SigarException

See Also:
Serialized Form

Constructor Summary
NfsUnreachableException()
           
NfsUnreachableException(java.lang.String s)
           
 
Method Summary
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NfsUnreachableException

public NfsUnreachableException()

NfsUnreachableException

public NfsUnreachableException(java.lang.String s)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/OperatingSystem.html000066400000000000000000000533731210132627500271420ustar00rootroot00000000000000 OperatingSystem (Sigar API)

org.hyperic.sigar
Class OperatingSystem

java.lang.Object
  extended by org.hyperic.sigar.SysInfo
      extended by org.hyperic.sigar.OperatingSystem
All Implemented Interfaces:
java.io.Serializable

public class OperatingSystem
extends SysInfo

See Also:
Serialized Form

Field Summary
static boolean IS_WIN32
           
static java.lang.String NAME_AIX
           
static java.lang.String NAME_FREEBSD
           
static java.lang.String NAME_HPUX
           
static java.lang.String NAME_LINUX
           
static java.lang.String NAME_MACOSX
           
static java.lang.String NAME_NETBSD
           
static java.lang.String NAME_NETWARE
           
static java.lang.String NAME_OPENBSD
           
static java.lang.String NAME_SOLARIS
           
static java.lang.String NAME_WIN32
           
static java.lang.String[] NAMES
           
static java.lang.String[] UNIX_NAMES
           
static java.lang.String[] WIN32_NAMES
           
 
Method Summary
 java.lang.String getCpuEndian()
           
 java.lang.String getDataModel()
           
static OperatingSystem getInstance()
           
static boolean isSupported(java.lang.String name)
           
static boolean isWin32(java.lang.String name)
           
static void main(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.SysInfo
gather, getArch, getDescription, getMachine, getName, getPatchLevel, getVendor, getVendorCodeName, getVendorName, getVendorVersion, getVersion, toMap, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

NAME_LINUX

public static final java.lang.String NAME_LINUX
See Also:
Constant Field Values

NAME_SOLARIS

public static final java.lang.String NAME_SOLARIS
See Also:
Constant Field Values

NAME_HPUX

public static final java.lang.String NAME_HPUX
See Also:
Constant Field Values

NAME_AIX

public static final java.lang.String NAME_AIX
See Also:
Constant Field Values

NAME_MACOSX

public static final java.lang.String NAME_MACOSX
See Also:
Constant Field Values

NAME_FREEBSD

public static final java.lang.String NAME_FREEBSD
See Also:
Constant Field Values

NAME_OPENBSD

public static final java.lang.String NAME_OPENBSD
See Also:
Constant Field Values

NAME_NETBSD

public static final java.lang.String NAME_NETBSD
See Also:
Constant Field Values

NAME_WIN32

public static final java.lang.String NAME_WIN32
See Also:
Constant Field Values

NAME_NETWARE

public static final java.lang.String NAME_NETWARE
See Also:
Constant Field Values

UNIX_NAMES

public static final java.lang.String[] UNIX_NAMES

WIN32_NAMES

public static final java.lang.String[] WIN32_NAMES

NAMES

public static final java.lang.String[] NAMES

IS_WIN32

public static final boolean IS_WIN32
Method Detail

isSupported

public static boolean isSupported(java.lang.String name)

isWin32

public static boolean isWin32(java.lang.String name)

getInstance

public static OperatingSystem getInstance()

getDataModel

public java.lang.String getDataModel()

getCpuEndian

public java.lang.String getCpuEndian()

main

public static void main(java.lang.String[] args)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcCpu.html000066400000000000000000000355331210132627500253560ustar00rootroot00000000000000 ProcCpu (Sigar API)

org.hyperic.sigar
Class ProcCpu

java.lang.Object
  extended by org.hyperic.sigar.ProcCpu
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
MultiProcCpu

public class ProcCpu
extends java.lang.Object
implements java.io.Serializable

ProcCpu sigar class.

See Also:
Serialized Form

Constructor Summary
ProcCpu()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 long getLastTime()
          Get the last_time.
 double getPercent()
          Get the Process cpu usage.
 long getStartTime()
          Get the Time process was started in seconds.
 long getSys()
          Get the Process cpu kernel time.
 long getTotal()
          Get the Process cpu time (sum of User and Sys).
 long getUser()
          Get the Process cpu user time.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcCpu

public ProcCpu()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getPercent

public double getPercent()
Get the Process cpu usage.

Supported Platforms: All.

Returns:
Process cpu usage

getLastTime

public long getLastTime()
Get the last_time.

Supported Platforms: All.

Returns:
last_time

getStartTime

public long getStartTime()
Get the Time process was started in seconds.

Supported Platforms: All.

Returns:
Time process was started in seconds

getUser

public long getUser()
Get the Process cpu user time.

Supported Platforms: All.

Returns:
Process cpu user time

getSys

public long getSys()
Get the Process cpu kernel time.

Supported Platforms: All.

Returns:
Process cpu kernel time

getTotal

public long getTotal()
Get the Process cpu time (sum of User and Sys).

Supported Platforms: All.

Returns:
Process cpu time (sum of User and Sys)

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcCred.html000066400000000000000000000353471210132627500255070ustar00rootroot00000000000000 ProcCred (Sigar API)

org.hyperic.sigar
Class ProcCred

java.lang.Object
  extended by org.hyperic.sigar.ProcCred
All Implemented Interfaces:
java.io.Serializable

public class ProcCred
extends java.lang.Object
implements java.io.Serializable

ProcCred sigar class.

See Also:
Serialized Form

Constructor Summary
ProcCred()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 long getEgid()
          Get the Process effective group id.
 long getEuid()
          Get the Process effective user id.
 long getGid()
          Get the Process group id.
 long getUid()
          Get the Process user id.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcCred

public ProcCred()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getUid

public long getUid()
Get the Process user id.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process user id

getGid

public long getGid()
Get the Process group id.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process group id

getEuid

public long getEuid()
Get the Process effective user id.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process effective user id

getEgid

public long getEgid()
Get the Process effective group id.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process effective group id

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcCredName.html000066400000000000000000000305231210132627500262770ustar00rootroot00000000000000 ProcCredName (Sigar API)

org.hyperic.sigar
Class ProcCredName

java.lang.Object
  extended by org.hyperic.sigar.ProcCredName
All Implemented Interfaces:
java.io.Serializable

public class ProcCredName
extends java.lang.Object
implements java.io.Serializable

ProcCredName sigar class.

See Also:
Serialized Form

Constructor Summary
ProcCredName()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 java.lang.String getGroup()
          Get the Process owner group name.
 java.lang.String getUser()
          Get the Process owner user name.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcCredName

public ProcCredName()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getUser

public java.lang.String getUser()
Get the Process owner user name.

Supported Platforms: All.

Returns:
Process owner user name

getGroup

public java.lang.String getGroup()
Get the Process owner group name.

Supported Platforms: All.

Returns:
Process owner group name

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcExe.html000066400000000000000000000315641210132627500253500ustar00rootroot00000000000000 ProcExe (Sigar API)

org.hyperic.sigar
Class ProcExe

java.lang.Object
  extended by org.hyperic.sigar.ProcExe
All Implemented Interfaces:
java.io.Serializable

public class ProcExe
extends java.lang.Object
implements java.io.Serializable

ProcExe sigar class.

See Also:
Serialized Form

Constructor Summary
ProcExe()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 java.lang.String getCwd()
          Get the Name of process current working directory.
 java.lang.String getName()
          Get the Name of process executable.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcExe

public ProcExe()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getName

public java.lang.String getName()
Get the Name of process executable.

Supported Platforms: FreeBSD, Linux, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ls -l /proc/$$/exe
  • Solaris:
  • Win32:

Returns:
Name of process executable

getCwd

public java.lang.String getCwd()
Get the Name of process current working directory.

Supported Platforms: Linux, Solaris, Win32.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: ls -l /proc/$$/cwd
  • Solaris:
  • Win32:

Returns:
Name of process current working directory

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcFd.html000066400000000000000000000276401210132627500251600ustar00rootroot00000000000000 ProcFd (Sigar API)

org.hyperic.sigar
Class ProcFd

java.lang.Object
  extended by org.hyperic.sigar.ProcFd
All Implemented Interfaces:
java.io.Serializable

public class ProcFd
extends java.lang.Object
implements java.io.Serializable

ProcFd sigar class.

See Also:
Serialized Form

Constructor Summary
ProcFd()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 long getTotal()
          Get the Total number of open file descriptors.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcFd

public ProcFd()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the Total number of open file descriptors.

Supported Platforms: AIX, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: lsof
  • Darwin: lsof
  • FreeBSD: lsof
  • HPUX: lsof
  • Linux: lsof
  • Solaris: lsof
  • Win32:

Returns:
Total number of open file descriptors

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcFileMirror.html000066400000000000000000000425431210132627500267000ustar00rootroot00000000000000 ProcFileMirror (Sigar API)

org.hyperic.sigar
Class ProcFileMirror

java.lang.Object
  extended by org.hyperic.sigar.FileWatcher
      extended by org.hyperic.sigar.ProcFileMirror

public class ProcFileMirror
extends FileWatcher


Constructor Summary
ProcFileMirror(Sigar sigar, java.lang.String proc)
           
 
Method Summary
 FileInfo add(java.lang.String name)
           
protected  boolean changed(FileInfo info)
           
 long getExpireMillis()
           
 java.lang.String getProcFile(java.io.File file)
           
 java.lang.String getProcFile(java.lang.String file)
           
 void onChange(FileInfo info)
           
 void setExpire(long seconds)
           
 void setExpireMillis(long millis)
           
 
Methods inherited from class org.hyperic.sigar.FileWatcher
add, add, add, check, clear, getFiles, getInterval, onException, onNotFound, remove, remove, setInterval
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcFileMirror

public ProcFileMirror(Sigar sigar,
                      java.lang.String proc)
Method Detail

getExpireMillis

public long getExpireMillis()

setExpire

public void setExpire(long seconds)

setExpireMillis

public void setExpireMillis(long millis)

getProcFile

public java.lang.String getProcFile(java.io.File file)

getProcFile

public java.lang.String getProcFile(java.lang.String file)

add

public FileInfo add(java.lang.String name)
             throws SigarException
Overrides:
add in class FileWatcher
Throws:
SigarException

onChange

public void onChange(FileInfo info)
Specified by:
onChange in class FileWatcher

changed

protected boolean changed(FileInfo info)
                   throws SigarException,
                          SigarFileNotFoundException
Overrides:
changed in class FileWatcher
Throws:
SigarException
SigarFileNotFoundException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcMem.html000066400000000000000000000441311210132627500253370ustar00rootroot00000000000000 ProcMem (Sigar API)

org.hyperic.sigar
Class ProcMem

java.lang.Object
  extended by org.hyperic.sigar.ProcMem
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
MultiProcMem

public class ProcMem
extends java.lang.Object
implements java.io.Serializable

ProcMem sigar class.

See Also:
Serialized Form

Constructor Summary
ProcMem()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 long getMajorFaults()
          Get the i/o page faults.
 long getMinorFaults()
          Get the non i/o page faults.
 long getPageFaults()
          Get the Total number of page faults.
 long getResident()
          Get the Total process resident memory.
 long getRss()
          Deprecated.  
 long getShare()
          Get the Total process shared memory.
 long getSize()
          Get the Total process virtual memory.
 long getVsize()
          Deprecated.  
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcMem

public ProcMem()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getSize

public long getSize()
Get the Total process virtual memory.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total process virtual memory

getResident

public long getResident()
Get the Total process resident memory.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total process resident memory

getShare

public long getShare()
Get the Total process shared memory.

Supported Platforms: AIX, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total process shared memory

getMinorFaults

public long getMinorFaults()
Get the non i/o page faults.

Supported Platforms: AIX, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
non i/o page faults

getMajorFaults

public long getMajorFaults()
Get the i/o page faults.

Supported Platforms: AIX, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
i/o page faults

getPageFaults

public long getPageFaults()
Get the Total number of page faults.

Supported Platforms: AIX, Darwin, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of page faults

getRss

public long getRss()
Deprecated. 

See Also:
getResident()

getVsize

public long getVsize()
Deprecated. 

See Also:
getSize()

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcStat.html000066400000000000000000000434121210132627500255350ustar00rootroot00000000000000 ProcStat (Sigar API)

org.hyperic.sigar
Class ProcStat

java.lang.Object
  extended by org.hyperic.sigar.ProcStat
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
CurrentProcessSummary

public class ProcStat
extends java.lang.Object
implements java.io.Serializable

ProcStat sigar class.

See Also:
Serialized Form

Constructor Summary
ProcStat()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getIdle()
          Get the Total number of processes in idle state.
 long getRunning()
          Get the Total number of processes in run state.
 long getSleeping()
          Get the Total number of processes in sleep state.
 long getStopped()
          Get the Total number of processes in stop state.
 long getThreads()
          Get the Total number of threads.
 long getTotal()
          Get the Total number of processes.
 long getZombie()
          Get the Total number of processes in zombie state.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcStat

public ProcStat()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the Total number of processes.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of processes

getIdle

public long getIdle()
Get the Total number of processes in idle state.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of processes in idle state

getRunning

public long getRunning()
Get the Total number of processes in run state.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of processes in run state

getSleeping

public long getSleeping()
Get the Total number of processes in sleep state.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of processes in sleep state

getStopped

public long getStopped()
Get the Total number of processes in stop state.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of processes in stop state

getZombie

public long getZombie()
Get the Total number of processes in zombie state.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of processes in zombie state

getThreads

public long getThreads()
Get the Total number of threads.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Total number of threads

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcState.html000066400000000000000000000541531210132627500257060ustar00rootroot00000000000000 ProcState (Sigar API)

org.hyperic.sigar
Class ProcState

java.lang.Object
  extended by org.hyperic.sigar.ProcState
All Implemented Interfaces:
java.io.Serializable

public class ProcState
extends java.lang.Object
implements java.io.Serializable

ProcState sigar class.

See Also:
Serialized Form

Field Summary
static char IDLE
           
static char RUN
           
static char SLEEP
           
static char STOP
           
static char ZOMBIE
           
 
Constructor Summary
ProcState()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 java.lang.String getName()
          Get the Name of the process program.
 int getNice()
          Get the Nice value of process.
 long getPpid()
          Get the Process parent process id.
 int getPriority()
          Get the Kernel scheduling priority of process.
 int getProcessor()
          Get the Processor number last run on.
 char getState()
          Get the Process state (Running, Zombie, etc.).
 long getThreads()
          Get the Number of active threads.
 int getTty()
          Get the Device number of rocess controling terminal.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

SLEEP

public static final char SLEEP
See Also:
Constant Field Values

RUN

public static final char RUN
See Also:
Constant Field Values

STOP

public static final char STOP
See Also:
Constant Field Values

ZOMBIE

public static final char ZOMBIE
See Also:
Constant Field Values

IDLE

public static final char IDLE
See Also:
Constant Field Values
Constructor Detail

ProcState

public ProcState()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getState

public char getState()
Get the Process state (Running, Zombie, etc.).

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process state (Running, Zombie, etc.)

getName

public java.lang.String getName()
Get the Name of the process program.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Name of the process program

getPpid

public long getPpid()
Get the Process parent process id.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process parent process id

getTty

public int getTty()
Get the Device number of rocess controling terminal.

Supported Platforms: AIX, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Device number of rocess controling terminal

getNice

public int getNice()
Get the Nice value of process.

Supported Platforms: AIX, Darwin, FreeBSD, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Nice value of process

getPriority

public int getPriority()
Get the Kernel scheduling priority of process.

Supported Platforms: Darwin, FreeBSD, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Kernel scheduling priority of process

getThreads

public long getThreads()
Get the Number of active threads.

Supported Platforms: AIX, Darwin, HPUX, Linux, Solaris, Win32.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Number of active threads

getProcessor

public int getProcessor()
Get the Processor number last run on.

Supported Platforms: AIX, HPUX, Linux, Solaris.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Processor number last run on

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcTime.html000066400000000000000000000353231210132627500255220ustar00rootroot00000000000000 ProcTime (Sigar API)

org.hyperic.sigar
Class ProcTime

java.lang.Object
  extended by org.hyperic.sigar.ProcTime
All Implemented Interfaces:
java.io.Serializable

public class ProcTime
extends java.lang.Object
implements java.io.Serializable

ProcTime sigar class.

See Also:
Serialized Form

Constructor Summary
ProcTime()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 long getStartTime()
          Get the Time process was started in seconds.
 long getSys()
          Get the Process cpu kernel time.
 long getTotal()
          Get the Process cpu time (sum of User and Sys).
 long getUser()
          Get the Process cpu user time.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProcTime

public ProcTime()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getStartTime

public long getStartTime()
Get the Time process was started in seconds.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Time process was started in seconds

getUser

public long getUser()
Get the Process cpu user time.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process cpu user time

getSys

public long getSys()
Get the Process cpu kernel time.

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process cpu kernel time

getTotal

public long getTotal()
Get the Process cpu time (sum of User and Sys).

Supported Platforms: All.

System equivalent commands:

  • AIX: top, ps
  • Darwin: top, ps
  • FreeBSD: top, ps
  • HPUX: top, ps
  • Linux: top, ps
  • Solaris: top, ps
  • Win32: taskman

Returns:
Process cpu time (sum of User and Sys)

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ProcUtil.html000066400000000000000000000262301210132627500255360ustar00rootroot00000000000000 ProcUtil (Sigar API)

org.hyperic.sigar
Class ProcUtil

java.lang.Object
  extended by org.hyperic.sigar.ProcUtil

public class ProcUtil
extends java.lang.Object


Constructor Summary
ProcUtil()
           
 
Method Summary
static java.lang.String getDescription(SigarProxy sigar, long pid)
           
static java.lang.String getJavaMainClass(SigarProxy sigar, long pid)
          Try to determina classname for java programs
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcUtil

public ProcUtil()
Method Detail

getJavaMainClass

public static java.lang.String getJavaMainClass(SigarProxy sigar,
                                                long pid)
                                         throws SigarException
Try to determina classname for java programs

Throws:
SigarException

getDescription

public static java.lang.String getDescription(SigarProxy sigar,
                                              long pid)
                                       throws SigarException
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/RPC.html000066400000000000000000000355661210132627500244350ustar00rootroot00000000000000 RPC (Sigar API)

org.hyperic.sigar
Class RPC

java.lang.Object
  extended by org.hyperic.sigar.RPC

public class RPC
extends java.lang.Object


Field Summary
static int TCP
           
static int UDP
           
 
Constructor Summary
RPC()
           
 
Method Summary
static long getProgram(java.lang.String program)
           
static void main(java.lang.String[] args)
           
static int ping(java.lang.String hostname, int protocol, long program, long version)
           
static int ping(java.lang.String hostname, int protocol, java.lang.String program, long version)
           
static int ping(java.lang.String hostname, long program)
           
static int ping(java.lang.String hostname, java.lang.String program)
           
static java.lang.String strerror(int status)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

UDP

public static final int UDP
See Also:
Constant Field Values

TCP

public static final int TCP
See Also:
Constant Field Values
Constructor Detail

RPC

public RPC()
Method Detail

ping

public static int ping(java.lang.String hostname,
                       int protocol,
                       long program,
                       long version)

strerror

public static java.lang.String strerror(int status)

ping

public static int ping(java.lang.String hostname,
                       int protocol,
                       java.lang.String program,
                       long version)

ping

public static int ping(java.lang.String hostname,
                       long program)

ping

public static int ping(java.lang.String hostname,
                       java.lang.String program)

getProgram

public static long getProgram(java.lang.String program)
Returns:
RPC program number as defined in /etc/rpc

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ResourceLimit.html000066400000000000000000000574111210132627500265700ustar00rootroot00000000000000 ResourceLimit (Sigar API)

org.hyperic.sigar
Class ResourceLimit

java.lang.Object
  extended by org.hyperic.sigar.ResourceLimit
All Implemented Interfaces:
java.io.Serializable

public class ResourceLimit
extends java.lang.Object
implements java.io.Serializable

ResourceLimit sigar class.

See Also:
Serialized Form

Constructor Summary
ResourceLimit()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getCoreCur()
          Get the core_cur.
 long getCoreMax()
          Get the core_max.
 long getCpuCur()
          Get the cpu_cur.
 long getCpuMax()
          Get the cpu_max.
 long getDataCur()
          Get the data_cur.
 long getDataMax()
          Get the data_max.
 long getFileSizeCur()
          Get the file_size_cur.
 long getFileSizeMax()
          Get the file_size_max.
 long getMemoryCur()
          Get the memory_cur.
 long getMemoryMax()
          Get the memory_max.
 long getOpenFilesCur()
          Get the open_files_cur.
 long getOpenFilesMax()
          Get the open_files_max.
 long getPipeSizeCur()
          Get the pipe_size_cur.
 long getPipeSizeMax()
          Get the pipe_size_max.
 long getProcessesCur()
          Get the processes_cur.
 long getProcessesMax()
          Get the processes_max.
 long getStackCur()
          Get the stack_cur.
 long getStackMax()
          Get the stack_max.
 long getVirtualMemoryCur()
          Get the virtual_memory_cur.
 long getVirtualMemoryMax()
          Get the virtual_memory_max.
static long INFINITY()
           
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ResourceLimit

public ResourceLimit()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getCpuCur

public long getCpuCur()
Get the cpu_cur.

Supported Platforms: Undocumented.

Returns:
cpu_cur

getCpuMax

public long getCpuMax()
Get the cpu_max.

Supported Platforms: Undocumented.

Returns:
cpu_max

getFileSizeCur

public long getFileSizeCur()
Get the file_size_cur.

Supported Platforms: Undocumented.

Returns:
file_size_cur

getFileSizeMax

public long getFileSizeMax()
Get the file_size_max.

Supported Platforms: Undocumented.

Returns:
file_size_max

getPipeSizeMax

public long getPipeSizeMax()
Get the pipe_size_max.

Supported Platforms: Undocumented.

Returns:
pipe_size_max

getPipeSizeCur

public long getPipeSizeCur()
Get the pipe_size_cur.

Supported Platforms: Undocumented.

Returns:
pipe_size_cur

getDataCur

public long getDataCur()
Get the data_cur.

Supported Platforms: Undocumented.

Returns:
data_cur

getDataMax

public long getDataMax()
Get the data_max.

Supported Platforms: Undocumented.

Returns:
data_max

getStackCur

public long getStackCur()
Get the stack_cur.

Supported Platforms: Undocumented.

Returns:
stack_cur

getStackMax

public long getStackMax()
Get the stack_max.

Supported Platforms: Undocumented.

Returns:
stack_max

getCoreCur

public long getCoreCur()
Get the core_cur.

Supported Platforms: Undocumented.

Returns:
core_cur

getCoreMax

public long getCoreMax()
Get the core_max.

Supported Platforms: Undocumented.

Returns:
core_max

getMemoryCur

public long getMemoryCur()
Get the memory_cur.

Supported Platforms: Undocumented.

Returns:
memory_cur

getMemoryMax

public long getMemoryMax()
Get the memory_max.

Supported Platforms: Undocumented.

Returns:
memory_max

getProcessesCur

public long getProcessesCur()
Get the processes_cur.

Supported Platforms: Undocumented.

Returns:
processes_cur

getProcessesMax

public long getProcessesMax()
Get the processes_max.

Supported Platforms: Undocumented.

Returns:
processes_max

getOpenFilesCur

public long getOpenFilesCur()
Get the open_files_cur.

Supported Platforms: Undocumented.

Returns:
open_files_cur

getOpenFilesMax

public long getOpenFilesMax()
Get the open_files_max.

Supported Platforms: Undocumented.

Returns:
open_files_max

getVirtualMemoryCur

public long getVirtualMemoryCur()
Get the virtual_memory_cur.

Supported Platforms: Undocumented.

Returns:
virtual_memory_cur

getVirtualMemoryMax

public long getVirtualMemoryMax()
Get the virtual_memory_max.

Supported Platforms: Undocumented.

Returns:
virtual_memory_max

INFINITY

public static long INFINITY()

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Sigar.html000066400000000000000000003451501210132627500250470ustar00rootroot00000000000000 Sigar (Sigar API)

org.hyperic.sigar
Class Sigar

java.lang.Object
  extended by org.hyperic.sigar.Sigar
All Implemented Interfaces:
SigarProxy

public class Sigar
extends java.lang.Object
implements SigarProxy

The Sigar class provides access to the sigar objects containing system information. The Sigar object itself maintains internal state specific to each platform. It also implements the SigarProxy interface which provides caching at the Java level.


Field Summary
static java.lang.String BUILD_DATE
          The date on which sigar.jar was built.
static long FIELD_NOTIMPL
           
static java.lang.String NATIVE_BUILD_DATE
          The date on which the sigar native binary was built.
static java.lang.String NATIVE_SCM_REVISION
          The scm (svn) revision from which the sigar native binary was built.
static java.lang.String NATIVE_VERSION_STRING
          The Sigar native version.
static java.lang.String SCM_REVISION
          The scm (svn) revision from which sigar.jar was built.
static java.lang.String VERSION_STRING
          The Sigar java version.
 
Constructor Summary
Sigar()
          Allocate and initialize the native Sigar object.
 
Method Summary
 void close()
          Release any native resources associated with this sigar instance.
 void enableLogging(boolean value)
          Enabling logging in the native Sigar code.
protected  void finalize()
           
static java.lang.String formatSize(long size)
          Format size in bytes to a human readable string.
 Cpu getCpu()
          Get system cpu info.
 CpuInfo[] getCpuInfoList()
          Get list of cpu infomation.
 Cpu[] getCpuList()
          Get list of per-cpu metrics.
 CpuPerc getCpuPerc()
          Get system CPU info in percentage format.
 CpuPerc[] getCpuPercList()
          Get system per-CPU info in percentage format.
 DirStat getDirStat(java.lang.String name)
           
 DirUsage getDirUsage(java.lang.String name)
           
 DiskUsage getDiskUsage(java.lang.String name)
          Get disk usage.
 FileInfo getFileInfo(java.lang.String name)
           
 FileSystem[] getFileSystemList()
          Get list of file systems.
 FileSystemMap getFileSystemMap()
           
 FileSystemUsage getFileSystemUsage(java.lang.String name)
          Get file system usage.
 java.lang.String getFQDN()
          Reliably retrieve the FQDN for a machine
 FileInfo getLinkInfo(java.lang.String name)
           
 double[] getLoadAverage()
          Get system load average.
 Mem getMem()
          Get system memory info.
 FileSystemUsage getMountedFileSystemUsage(java.lang.String name)
          Get file system usage of a mounted directory.
 MultiProcCpu getMultiProcCpu(java.lang.String query)
           
 ProcMem getMultiProcMem(java.lang.String query)
           
 java.io.File getNativeLibrary()
           
 NetConnection[] getNetConnectionList(int flags)
          Get list of network connections.
 NetInfo getNetInfo()
          Get general network info.
 NetInterfaceConfig getNetInterfaceConfig()
          Get default network interface configuration info.
 NetInterfaceConfig getNetInterfaceConfig(java.lang.String name)
          Get network interface configuration info.
 java.lang.String[] getNetInterfaceList()
          Get the list of configured network interface names.
 NetInterfaceStat getNetInterfaceStat(java.lang.String name)
          Get network interface stats.
 java.lang.String getNetListenAddress(long port)
          Get the TCP listen address for the given port.
 java.lang.String getNetListenAddress(java.lang.String port)
           
 NetRoute[] getNetRouteList()
          Get list of network routes.
 java.lang.String getNetServicesName(int protocol, long port)
           
 NetStat getNetStat()
           
 NetStat getNetStat(byte[] address, long port)
           
 NfsClientV2 getNfsClientV2()
           
 NfsClientV3 getNfsClientV3()
           
 NfsServerV2 getNfsServerV2()
           
 NfsServerV3 getNfsServerV3()
           
static java.lang.String getPassword(java.lang.String prompt)
          Prompt for a password, disabling terminal echo during user input if possible.
 long getPid()
          Get pid of the current process.
 java.lang.String[] getProcArgs(long pid)
          Get process arguments.
 java.lang.String[] getProcArgs(java.lang.String pid)
           
 ProcCpu getProcCpu(long pid)
          Get process cpu info.
 ProcCpu getProcCpu(java.lang.String pid)
           
 ProcCred getProcCred(long pid)
          Get process credential info.
 ProcCred getProcCred(java.lang.String pid)
           
 ProcCredName getProcCredName(long pid)
          Get process credential names.
 ProcCredName getProcCredName(java.lang.String pid)
           
 java.util.Map getProcEnv(long pid)
          Get process environment.
 java.lang.String getProcEnv(long pid, java.lang.String key)
          Get process environment variable value.
 java.util.Map getProcEnv(java.lang.String pid)
           
 java.lang.String getProcEnv(java.lang.String pid, java.lang.String key)
           
 ProcExe getProcExe(long pid)
          Get process current working directory.
 ProcExe getProcExe(java.lang.String pid)
           
 ProcFd getProcFd(long pid)
          Get process file descriptor info.
 ProcFd getProcFd(java.lang.String pid)
           
 long[] getProcList()
          Get system process list.
 ProcMem getProcMem(long pid)
          Get process memory info.
 ProcMem getProcMem(java.lang.String pid)
           
 java.util.List getProcModules(long pid)
           
 java.util.List getProcModules(java.lang.String pid)
           
 long getProcPort(int protocol, long port)
          Find the pid of the process which is listening on the given port.
 long getProcPort(java.lang.String protocol, java.lang.String port)
           
 ProcStat getProcStat()
          Get system process stats.
 ProcState getProcState(long pid)
          Get process state info.
 ProcState getProcState(java.lang.String pid)
           
 ProcTime getProcTime(long pid)
          Get process time info.
 ProcTime getProcTime(java.lang.String pid)
           
 ResourceLimit getResourceLimit()
          Get system resource limits.
 long getServicePid(java.lang.String name)
          Get pid for the Windows service with the given name.
static int getSigNum(java.lang.String name)
           
 Swap getSwap()
          Get system swap info.
 Tcp getTcp()
          TCP-MIB stats
 ThreadCpu getThreadCpu()
          Get the cumulative cpu time for the calling thread.
 Uptime getUptime()
          Get system uptime info.
 Who[] getWhoList()
           
 void kill(long pid, int signum)
          Send a signal to a process.
 void kill(long pid, java.lang.String signame)
          Send a signal to a process.
 void kill(java.lang.String pid, int signum)
          Send a signal to a process.
static void load()
           
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

FIELD_NOTIMPL

public static final long FIELD_NOTIMPL
See Also:
Constant Field Values

VERSION_STRING

public static final java.lang.String VERSION_STRING
The Sigar java version.

See Also:
Constant Field Values

NATIVE_VERSION_STRING

public static final java.lang.String NATIVE_VERSION_STRING
The Sigar native version.


SCM_REVISION

public static final java.lang.String SCM_REVISION
The scm (svn) revision from which sigar.jar was built.

See Also:
Constant Field Values

NATIVE_SCM_REVISION

public static final java.lang.String NATIVE_SCM_REVISION
The scm (svn) revision from which the sigar native binary was built.


BUILD_DATE

public static final java.lang.String BUILD_DATE
The date on which sigar.jar was built.

See Also:
Constant Field Values

NATIVE_BUILD_DATE

public static final java.lang.String NATIVE_BUILD_DATE
The date on which the sigar native binary was built.

Constructor Detail

Sigar

public Sigar()
Allocate and initialize the native Sigar object.

Method Detail

load

public static void load()
                 throws SigarException
Throws:
SigarException

getNativeLibrary

public java.io.File getNativeLibrary()

formatSize

public static java.lang.String formatSize(long size)
Format size in bytes to a human readable string.

Parameters:
size - The size to format.
Returns:
The formatted string.

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object

close

public void close()
Release any native resources associated with this sigar instance. The sigar object is no longer usable after it has been closed. If the close method is not called directly, the finalize method will call it if the Sigar object is garbage collected.


getPid

public long getPid()
Get pid of the current process.

Specified by:
getPid in interface SigarProxy
Throws:
SigarException - on failure.

getServicePid

public long getServicePid(java.lang.String name)
                   throws SigarException
Get pid for the Windows service with the given name. This method is implemented on Windows only as a helper for PTQL.

Specified by:
getServicePid in interface SigarProxy
Throws:
SigarException

kill

public void kill(long pid,
                 int signum)
          throws SigarException
Send a signal to a process.

Parameters:
pid - The process id.
signum - The signal number.
Throws:
SigarException - on failure.

kill

public void kill(long pid,
                 java.lang.String signame)
          throws SigarException
Send a signal to a process.

Parameters:
pid - The process id.
signame - The signal name.
Throws:
SigarException - on failure.

getSigNum

public static int getSigNum(java.lang.String name)

kill

public void kill(java.lang.String pid,
                 int signum)
          throws SigarException
Send a signal to a process.

Parameters:
pid - The process id or query.
signum - The signal number.
Throws:
SigarException - on failure.

getMem

public Mem getMem()
           throws SigarException
Get system memory info.

Specified by:
getMem in interface SigarProxy
Throws:
SigarException - on failure.

getSwap

public Swap getSwap()
             throws SigarException
Get system swap info.

Specified by:
getSwap in interface SigarProxy
Throws:
SigarException - on failure.

getCpu

public Cpu getCpu()
           throws SigarException
Get system cpu info.

Specified by:
getCpu in interface SigarProxy
Throws:
SigarException - on failure.

getCpuPerc

public CpuPerc getCpuPerc()
                   throws SigarException
Get system CPU info in percentage format. (i.e. fraction of 1)

Specified by:
getCpuPerc in interface SigarProxy
Throws:
SigarException - on failure.

getCpuPercList

public CpuPerc[] getCpuPercList()
                         throws SigarException
Get system per-CPU info in percentage format. (i.e. fraction of 1)

Specified by:
getCpuPercList in interface SigarProxy
Throws:
SigarException - on failure.

getResourceLimit

public ResourceLimit getResourceLimit()
                               throws SigarException
Get system resource limits.

Specified by:
getResourceLimit in interface SigarProxy
Throws:
SigarException - on failure.

getUptime

public Uptime getUptime()
                 throws SigarException
Get system uptime info.

Specified by:
getUptime in interface SigarProxy
Throws:
SigarException - on failure.

getLoadAverage

public double[] getLoadAverage()
                        throws SigarException
Get system load average.

Specified by:
getLoadAverage in interface SigarProxy
Returns:
The system load averages for the past 1, 5, and 15 minutes.
Throws:
SigarException - on failure.

getProcList

public long[] getProcList()
                   throws SigarException
Get system process list.

Specified by:
getProcList in interface SigarProxy
Returns:
Array of process ids.
Throws:
SigarException - on failure.

getProcStat

public ProcStat getProcStat()
                     throws SigarException
Get system process stats.

Specified by:
getProcStat in interface SigarProxy
Throws:
SigarException - on failure.

getProcMem

public ProcMem getProcMem(long pid)
                   throws SigarException
Get process memory info.

Specified by:
getProcMem in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcMem

public ProcMem getProcMem(java.lang.String pid)
                   throws SigarException
Specified by:
getProcMem in interface SigarProxy
Throws:
SigarException

getMultiProcMem

public ProcMem getMultiProcMem(java.lang.String query)
                        throws SigarException
Specified by:
getMultiProcMem in interface SigarProxy
Throws:
SigarException

getProcState

public ProcState getProcState(long pid)
                       throws SigarException
Get process state info.

Specified by:
getProcState in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcState

public ProcState getProcState(java.lang.String pid)
                       throws SigarException
Specified by:
getProcState in interface SigarProxy
Throws:
SigarException

getProcTime

public ProcTime getProcTime(long pid)
                     throws SigarException
Get process time info.

Specified by:
getProcTime in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcTime

public ProcTime getProcTime(java.lang.String pid)
                     throws SigarException
Specified by:
getProcTime in interface SigarProxy
Throws:
SigarException

getProcCpu

public ProcCpu getProcCpu(long pid)
                   throws SigarException
Get process cpu info.

Specified by:
getProcCpu in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcCpu

public ProcCpu getProcCpu(java.lang.String pid)
                   throws SigarException
Specified by:
getProcCpu in interface SigarProxy
Throws:
SigarException

getMultiProcCpu

public MultiProcCpu getMultiProcCpu(java.lang.String query)
                             throws SigarException
Specified by:
getMultiProcCpu in interface SigarProxy
Throws:
SigarException

getProcCred

public ProcCred getProcCred(long pid)
                     throws SigarException
Get process credential info.

Specified by:
getProcCred in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcCred

public ProcCred getProcCred(java.lang.String pid)
                     throws SigarException
Specified by:
getProcCred in interface SigarProxy
Throws:
SigarException

getProcCredName

public ProcCredName getProcCredName(long pid)
                             throws SigarException
Get process credential names.

Specified by:
getProcCredName in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcCredName

public ProcCredName getProcCredName(java.lang.String pid)
                             throws SigarException
Specified by:
getProcCredName in interface SigarProxy
Throws:
SigarException

getProcFd

public ProcFd getProcFd(long pid)
                 throws SigarException
Get process file descriptor info.

Specified by:
getProcFd in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcFd

public ProcFd getProcFd(java.lang.String pid)
                 throws SigarException
Specified by:
getProcFd in interface SigarProxy
Throws:
SigarException

getProcExe

public ProcExe getProcExe(long pid)
                   throws SigarException
Get process current working directory.

Specified by:
getProcExe in interface SigarProxy
Parameters:
pid - The process id.
Throws:
SigarException - on failure.

getProcExe

public ProcExe getProcExe(java.lang.String pid)
                   throws SigarException
Specified by:
getProcExe in interface SigarProxy
Throws:
SigarException

getProcArgs

public java.lang.String[] getProcArgs(long pid)
                               throws SigarException
Get process arguments.

Specified by:
getProcArgs in interface SigarProxy
Parameters:
pid - The process id.
Returns:
Array of argument strings.
Throws:
SigarException - on failure.

getProcArgs

public java.lang.String[] getProcArgs(java.lang.String pid)
                               throws SigarException
Specified by:
getProcArgs in interface SigarProxy
Throws:
SigarException

getProcEnv

public java.util.Map getProcEnv(long pid)
                         throws SigarException
Get process environment.

Specified by:
getProcEnv in interface SigarProxy
Parameters:
pid - The process id.
Returns:
Map of environment strings.
Throws:
SigarException - on failure.

getProcEnv

public java.util.Map getProcEnv(java.lang.String pid)
                         throws SigarException
Specified by:
getProcEnv in interface SigarProxy
Throws:
SigarException

getProcEnv

public java.lang.String getProcEnv(long pid,
                                   java.lang.String key)
                            throws SigarException
Get process environment variable value. This method is intended to avoid the overhead of creating a Map with all variables if only a single variable is needed.

Specified by:
getProcEnv in interface SigarProxy
Parameters:
pid - The process id.
key - Environment variable name.
Returns:
Environment variable value.
Throws:
SigarException - on failure.

getProcEnv

public java.lang.String getProcEnv(java.lang.String pid,
                                   java.lang.String key)
                            throws SigarException
Specified by:
getProcEnv in interface SigarProxy
Throws:
SigarException

getProcModules

public java.util.List getProcModules(long pid)
                              throws SigarException
Specified by:
getProcModules in interface SigarProxy
Throws:
SigarException

getProcModules

public java.util.List getProcModules(java.lang.String pid)
                              throws SigarException
Specified by:
getProcModules in interface SigarProxy
Throws:
SigarException

getProcPort

public long getProcPort(int protocol,
                        long port)
                 throws SigarException
Find the pid of the process which is listening on the given port.

Supported Platforms: Linux, Windows 2003, Windows XP, AIX.

Specified by:
getProcPort in interface SigarProxy
Parameters:
protocol - NetFlags.CONN_TCP or NetFlags.CONN_UDP.
port - The port number.
Returns:
pid of the process.
Throws:
SigarException - on failure.

getProcPort

public long getProcPort(java.lang.String protocol,
                        java.lang.String port)
                 throws SigarException
Specified by:
getProcPort in interface SigarProxy
Parameters:
protocol - "tcp" or "udp".
port - The port number.
Returns:
pid of the process.
Throws:
SigarException - on failure.

getThreadCpu

public ThreadCpu getThreadCpu()
                       throws SigarException
Get the cumulative cpu time for the calling thread.

Throws:
SigarException

getFileSystemList

public FileSystem[] getFileSystemList()
                               throws SigarException
Get list of file systems.

Specified by:
getFileSystemList in interface SigarProxy
Throws:
SigarException - on failure.

getFileSystemUsage

public FileSystemUsage getFileSystemUsage(java.lang.String name)
                                   throws SigarException
Get file system usage.

Specified by:
getFileSystemUsage in interface SigarProxy
Parameters:
name - Name of the directory on which filesystem is mounted.
Throws:
SigarException - on failure.

getDiskUsage

public DiskUsage getDiskUsage(java.lang.String name)
                       throws SigarException
Get disk usage.

Specified by:
getDiskUsage in interface SigarProxy
Parameters:
name - Name of disk
Throws:
SigarException - on failure.

getMountedFileSystemUsage

public FileSystemUsage getMountedFileSystemUsage(java.lang.String name)
                                          throws SigarException,
                                                 NfsUnreachableException
Get file system usage of a mounted directory. This method checks that the given directory is mounted. Unlike getFileSystemUsage() which only requires that the directory exists within a mounted file system. This method will also check that NFS servers are reachable via RPC before attempting to get the file system stats to prevent application hang when an NFS server is down.

Specified by:
getMountedFileSystemUsage in interface SigarProxy
Parameters:
name - Name of the directory on which filesystem is mounted.
Throws:
SigarException - If given directory is not mounted.
NfsUnreachableException - If NFS server is unreachable.
See Also:
getFileSystemUsage(java.lang.String)

getFileSystemMap

public FileSystemMap getFileSystemMap()
                               throws SigarException
Specified by:
getFileSystemMap in interface SigarProxy
Throws:
SigarException

getFileInfo

public FileInfo getFileInfo(java.lang.String name)
                     throws SigarException
Specified by:
getFileInfo in interface SigarProxy
Throws:
SigarException

getLinkInfo

public FileInfo getLinkInfo(java.lang.String name)
                     throws SigarException
Specified by:
getLinkInfo in interface SigarProxy
Throws:
SigarException

getDirStat

public DirStat getDirStat(java.lang.String name)
                   throws SigarException
Specified by:
getDirStat in interface SigarProxy
Throws:
SigarException

getDirUsage

public DirUsage getDirUsage(java.lang.String name)
                     throws SigarException
Specified by:
getDirUsage in interface SigarProxy
Throws:
SigarException

getCpuInfoList

public CpuInfo[] getCpuInfoList()
                         throws SigarException
Get list of cpu infomation.

Specified by:
getCpuInfoList in interface SigarProxy
Throws:
SigarException - on failure.

getCpuList

public Cpu[] getCpuList()
                 throws SigarException
Get list of per-cpu metrics.

Specified by:
getCpuList in interface SigarProxy
Throws:
SigarException - on failure.

getNetRouteList

public NetRoute[] getNetRouteList()
                           throws SigarException
Get list of network routes.

Specified by:
getNetRouteList in interface SigarProxy
Throws:
SigarException - on failure.

getNetConnectionList

public NetConnection[] getNetConnectionList(int flags)
                                     throws SigarException
Get list of network connections.

Specified by:
getNetConnectionList in interface SigarProxy
Throws:
SigarException - on failure.

getNetListenAddress

public java.lang.String getNetListenAddress(long port)
                                     throws SigarException
Get the TCP listen address for the given port. If there is not a listener on the given port, null will be returned.

Specified by:
getNetListenAddress in interface SigarProxy
Throws:
SigarException

getNetListenAddress

public java.lang.String getNetListenAddress(java.lang.String port)
                                     throws SigarException
Specified by:
getNetListenAddress in interface SigarProxy
Throws:
SigarException

getNetServicesName

public java.lang.String getNetServicesName(int protocol,
                                           long port)
Specified by:
getNetServicesName in interface SigarProxy

getNetStat

public NetStat getNetStat()
                   throws SigarException
Specified by:
getNetStat in interface SigarProxy
Throws:
SigarException

getNetStat

public NetStat getNetStat(byte[] address,
                          long port)
                   throws SigarException
Throws:
SigarException

getWhoList

public Who[] getWhoList()
                 throws SigarException
Specified by:
getWhoList in interface SigarProxy
Throws:
SigarException

getTcp

public Tcp getTcp()
           throws SigarException
TCP-MIB stats

Specified by:
getTcp in interface SigarProxy
Throws:
SigarException - on failure.

getNfsClientV2

public NfsClientV2 getNfsClientV2()
                           throws SigarException
Specified by:
getNfsClientV2 in interface SigarProxy
Throws:
SigarException

getNfsServerV2

public NfsServerV2 getNfsServerV2()
                           throws SigarException
Specified by:
getNfsServerV2 in interface SigarProxy
Throws:
SigarException

getNfsClientV3

public NfsClientV3 getNfsClientV3()
                           throws SigarException
Specified by:
getNfsClientV3 in interface SigarProxy
Throws:
SigarException

getNfsServerV3

public NfsServerV3 getNfsServerV3()
                           throws SigarException
Specified by:
getNfsServerV3 in interface SigarProxy
Throws:
SigarException

getNetInfo

public NetInfo getNetInfo()
                   throws SigarException
Get general network info.

Specified by:
getNetInfo in interface SigarProxy
Throws:
SigarException - on failure.

getNetInterfaceConfig

public NetInterfaceConfig getNetInterfaceConfig(java.lang.String name)
                                         throws SigarException
Get network interface configuration info.

Specified by:
getNetInterfaceConfig in interface SigarProxy
Throws:
SigarException - on failure.

getNetInterfaceConfig

public NetInterfaceConfig getNetInterfaceConfig()
                                         throws SigarException
Get default network interface configuration info. Iterates getNetInterfaceList(), returning the first available ethernet interface.

Specified by:
getNetInterfaceConfig in interface SigarProxy
Throws:
SigarException - on failure.

getNetInterfaceStat

public NetInterfaceStat getNetInterfaceStat(java.lang.String name)
                                     throws SigarException
Get network interface stats.

Specified by:
getNetInterfaceStat in interface SigarProxy
Throws:
SigarException - on failure.

getNetInterfaceList

public java.lang.String[] getNetInterfaceList()
                                       throws SigarException
Get the list of configured network interface names.

Specified by:
getNetInterfaceList in interface SigarProxy
Throws:
SigarException - on failure.

getPassword

public static java.lang.String getPassword(java.lang.String prompt)
                                    throws java.io.IOException
Prompt for a password, disabling terminal echo during user input if possible.

Parameters:
prompt - Text printed before disabling echo
Returns:
Text entered by the user.
Throws:
java.io.IOException - If input could not be read.

getFQDN

public java.lang.String getFQDN()
                         throws SigarException
Reliably retrieve the FQDN for a machine

Specified by:
getFQDN in interface SigarProxy
Returns:
The fully qualified domain name of the machine.
Throws:
SigarException - on failure.

enableLogging

public void enableLogging(boolean value)
Enabling logging in the native Sigar code. This method will hook log4j into the Sigar native logging methods. Note that the majority of logging in the native code is only at the DEBUG level.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarException.html000066400000000000000000000272761210132627500267340ustar00rootroot00000000000000 SigarException (Sigar API)

org.hyperic.sigar
Class SigarException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
MalformedQueryException, NfsUnreachableException, SigarFileNotFoundException, SigarNotImplementedException, SigarPermissionDeniedException, VMwareException, Win32Exception

public class SigarException
extends java.lang.Exception

Sigar base exception class.

See Also:
Serialized Form

Constructor Summary
SigarException()
           
SigarException(java.lang.String s)
           
 
Method Summary
 java.lang.String getMessage()
           
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

SigarException

public SigarException()

SigarException

public SigarException(java.lang.String s)
Method Detail

getMessage

public java.lang.String getMessage()
Overrides:
getMessage in class java.lang.Throwable


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarFileNotFoundException.html000066400000000000000000000247721210132627500312070ustar00rootroot00000000000000 SigarFileNotFoundException (Sigar API)

org.hyperic.sigar
Class SigarFileNotFoundException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.SigarFileNotFoundException
All Implemented Interfaces:
java.io.Serializable

public class SigarFileNotFoundException
extends SigarException

See Also:
Serialized Form

Constructor Summary
SigarFileNotFoundException(java.lang.String s)
           
 
Method Summary
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

SigarFileNotFoundException

public SigarFileNotFoundException(java.lang.String s)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarInvoker.html000066400000000000000000000362571210132627500264120ustar00rootroot00000000000000 SigarInvoker (Sigar API)

org.hyperic.sigar
Class SigarInvoker

java.lang.Object
  extended by org.hyperic.sigar.SigarInvoker

public class SigarInvoker
extends java.lang.Object

This class provides a string-ish interface to sigar. It is intended for use via JMX and Hyperic HQ measurement plugins. Method lookups are cached and the like for better performance.


Constructor Summary
protected SigarInvoker()
           
  SigarInvoker(SigarProxy proxy, java.lang.String type)
           
 
Method Summary
 java.lang.String getType()
          The type of this instance, as passed to the constructor.
 java.lang.Object invoke(java.lang.Object[] args, java.lang.String attr)
           
 java.lang.Object invoke(java.lang.Object arg, java.lang.String attr)
           
protected  void setProxy(SigarProxy proxy)
           
protected  void setType(java.lang.String val)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SigarInvoker

protected SigarInvoker()

SigarInvoker

public SigarInvoker(SigarProxy proxy,
                    java.lang.String type)
Parameters:
proxy - SigarProxy implementation such as SigarProxyCache
type - The sigar type. Valid name is any of the SigarProxy interface methods (minus the 'get' prefix).
Method Detail

setProxy

protected void setProxy(SigarProxy proxy)

setType

protected void setType(java.lang.String val)

getType

public java.lang.String getType()
The type of this instance, as passed to the constructor.


invoke

public java.lang.Object invoke(java.lang.Object arg,
                               java.lang.String attr)
                        throws SigarException,
                               SigarNotImplementedException,
                               SigarPermissionDeniedException
Throws:
SigarException
SigarNotImplementedException
SigarPermissionDeniedException

invoke

public java.lang.Object invoke(java.lang.Object[] args,
                               java.lang.String attr)
                        throws SigarException,
                               SigarNotImplementedException,
                               SigarPermissionDeniedException
Throws:
SigarException
SigarNotImplementedException
SigarPermissionDeniedException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarLoader.html000066400000000000000000000425051210132627500261740ustar00rootroot00000000000000 SigarLoader (Sigar API)

org.hyperic.sigar
Class SigarLoader

java.lang.Object
  extended by org.hyperic.jni.ArchLoader
      extended by org.hyperic.sigar.SigarLoader

public class SigarLoader
extends org.hyperic.jni.ArchLoader


Field Summary
static java.lang.String PROP_SIGAR_JAR_NAME
           
 
Fields inherited from class org.hyperic.jni.ArchLoader
IS_AIX, IS_DARWIN, IS_FREEBSD, IS_HPUX, IS_LINUX, IS_NETWARE, IS_OSF1, IS_SOLARIS, IS_WIN32
 
Constructor Summary
SigarLoader(java.lang.Class loaderClass)
           
 
Method Summary
 java.lang.String getArchLibName()
           
 java.lang.String getDefaultLibName()
           
 java.lang.String getJarName()
           
static java.lang.String getLocation()
          Returns the path where sigar.jar is located.
static java.lang.String getNativeLibraryName()
          Returns the name of the native sigar library.
static java.lang.String getSigarJarName()
           
static void setSigarJarName(java.lang.String jarName)
           
protected  void systemLoad(java.lang.String name)
           
protected  void systemLoadLibrary(java.lang.String name)
           
 
Methods inherited from class org.hyperic.jni.ArchLoader
containsNativeLibrary, findInJavaLibraryPath, findJarPath, findNativeLibrary, getClassLoader, getLibName, getLibraryExtension, getLibraryName, getLibraryPrefix, getLoaderClass, getName, getNativeLibrary, getPackageName, getResourcePath, getVersionedLibraryName, load, load, loadLibrary, setJarName, setLibName, setLoaderClass, setName, setPackageName, setResourcePath
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PROP_SIGAR_JAR_NAME

public static final java.lang.String PROP_SIGAR_JAR_NAME
See Also:
Constant Field Values
Constructor Detail

SigarLoader

public SigarLoader(java.lang.Class loaderClass)
Method Detail

getArchLibName

public java.lang.String getArchLibName()
                                throws org.hyperic.jni.ArchNotSupportedException
Overrides:
getArchLibName in class org.hyperic.jni.ArchLoader
Throws:
org.hyperic.jni.ArchNotSupportedException

getDefaultLibName

public java.lang.String getDefaultLibName()
                                   throws org.hyperic.jni.ArchNotSupportedException
Overrides:
getDefaultLibName in class org.hyperic.jni.ArchLoader
Throws:
org.hyperic.jni.ArchNotSupportedException

systemLoadLibrary

protected void systemLoadLibrary(java.lang.String name)
Overrides:
systemLoadLibrary in class org.hyperic.jni.ArchLoader

systemLoad

protected void systemLoad(java.lang.String name)
Overrides:
systemLoad in class org.hyperic.jni.ArchLoader

getJarName

public java.lang.String getJarName()
Overrides:
getJarName in class org.hyperic.jni.ArchLoader

setSigarJarName

public static void setSigarJarName(java.lang.String jarName)

getSigarJarName

public static java.lang.String getSigarJarName()

getLocation

public static java.lang.String getLocation()
Returns the path where sigar.jar is located.


getNativeLibraryName

public static java.lang.String getNativeLibraryName()
Returns the name of the native sigar library.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarLog.html000066400000000000000000000267161210132627500255150ustar00rootroot00000000000000 SigarLog (Sigar API)

org.hyperic.sigar
Class SigarLog

java.lang.Object
  extended by org.hyperic.sigar.SigarLog

public class SigarLog
extends java.lang.Object


Constructor Summary
SigarLog()
           
 
Method Summary
static void disable(Sigar sigar)
           
static void enable(Sigar sigar)
           
static org.apache.log4j.Logger getLogger(java.lang.String name)
           
static void setLevel(Sigar sigar, int level)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SigarLog

public SigarLog()
Method Detail

setLevel

public static void setLevel(Sigar sigar,
                            int level)

getLogger

public static org.apache.log4j.Logger getLogger(java.lang.String name)

enable

public static void enable(Sigar sigar)

disable

public static void disable(Sigar sigar)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarNotImplementedException.html000066400000000000000000000310231210132627500315620ustar00rootroot00000000000000 SigarNotImplementedException (Sigar API)

org.hyperic.sigar
Class SigarNotImplementedException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.SigarNotImplementedException
All Implemented Interfaces:
java.io.Serializable

public class SigarNotImplementedException
extends SigarException

Sigar exception class, thrown for methods which are not implemented on a given platform.

See Also:
Serialized Form

Field Summary
static SigarNotImplementedException INSTANCE
           
 
Constructor Summary
SigarNotImplementedException()
           
SigarNotImplementedException(java.lang.String s)
           
 
Method Summary
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

INSTANCE

public static final SigarNotImplementedException INSTANCE
Constructor Detail

SigarNotImplementedException

public SigarNotImplementedException()

SigarNotImplementedException

public SigarNotImplementedException(java.lang.String s)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarPermissionDeniedException.html000066400000000000000000000312271210132627500321050ustar00rootroot00000000000000 SigarPermissionDeniedException (Sigar API)

org.hyperic.sigar
Class SigarPermissionDeniedException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.SigarPermissionDeniedException
All Implemented Interfaces:
java.io.Serializable

public class SigarPermissionDeniedException
extends SigarException

See Also:
Serialized Form

Constructor Summary
SigarPermissionDeniedException(SigarProxy sigar, long pid)
           
SigarPermissionDeniedException(java.lang.String s)
           
 
Method Summary
static java.lang.String getUserDeniedMessage(SigarProxy sigar, long pid)
           
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

SigarPermissionDeniedException

public SigarPermissionDeniedException(java.lang.String s)

SigarPermissionDeniedException

public SigarPermissionDeniedException(SigarProxy sigar,
                                      long pid)
Method Detail

getUserDeniedMessage

public static java.lang.String getUserDeniedMessage(SigarProxy sigar,
                                                    long pid)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarProxy.html000066400000000000000000002162021210132627500261040ustar00rootroot00000000000000 SigarProxy (Sigar API)

org.hyperic.sigar
Interface SigarProxy

All Known Implementing Classes:
Sigar

public interface SigarProxy

The proxyable interface for caching via SigarProxyCache. This interface includes all methods which leave java land and gather info from the system. All other accessors, such as the objects returned by these methods do not leave java land.


Method Summary
 Cpu getCpu()
           
 CpuInfo[] getCpuInfoList()
           
 Cpu[] getCpuList()
           
 CpuPerc getCpuPerc()
           
 CpuPerc[] getCpuPercList()
           
 DirStat getDirStat(java.lang.String name)
           
 DirUsage getDirUsage(java.lang.String name)
           
 DiskUsage getDiskUsage(java.lang.String name)
           
 FileInfo getFileInfo(java.lang.String name)
           
 FileSystem[] getFileSystemList()
           
 FileSystemMap getFileSystemMap()
           
 FileSystemUsage getFileSystemUsage(java.lang.String name)
           
 java.lang.String getFQDN()
           
 FileInfo getLinkInfo(java.lang.String name)
           
 double[] getLoadAverage()
           
 Mem getMem()
           
 FileSystemUsage getMountedFileSystemUsage(java.lang.String name)
           
 MultiProcCpu getMultiProcCpu(java.lang.String query)
           
 ProcMem getMultiProcMem(java.lang.String query)
           
 NetConnection[] getNetConnectionList(int flags)
           
 NetInfo getNetInfo()
           
 NetInterfaceConfig getNetInterfaceConfig()
           
 NetInterfaceConfig getNetInterfaceConfig(java.lang.String name)
           
 java.lang.String[] getNetInterfaceList()
           
 NetInterfaceStat getNetInterfaceStat(java.lang.String name)
           
 java.lang.String getNetListenAddress(long port)
           
 java.lang.String getNetListenAddress(java.lang.String port)
           
 NetRoute[] getNetRouteList()
           
 java.lang.String getNetServicesName(int protocol, long port)
           
 NetStat getNetStat()
           
 NfsClientV2 getNfsClientV2()
           
 NfsClientV3 getNfsClientV3()
           
 NfsServerV2 getNfsServerV2()
           
 NfsServerV3 getNfsServerV3()
           
 long getPid()
           
 java.lang.String[] getProcArgs(long pid)
           
 java.lang.String[] getProcArgs(java.lang.String pid)
           
 ProcCpu getProcCpu(long pid)
           
 ProcCpu getProcCpu(java.lang.String pid)
           
 ProcCred getProcCred(long pid)
           
 ProcCred getProcCred(java.lang.String pid)
           
 ProcCredName getProcCredName(long pid)
           
 ProcCredName getProcCredName(java.lang.String pid)
           
 java.util.Map getProcEnv(long pid)
           
 java.lang.String getProcEnv(long pid, java.lang.String key)
           
 java.util.Map getProcEnv(java.lang.String pid)
           
 java.lang.String getProcEnv(java.lang.String pid, java.lang.String key)
           
 ProcExe getProcExe(long pid)
           
 ProcExe getProcExe(java.lang.String pid)
           
 ProcFd getProcFd(long pid)
           
 ProcFd getProcFd(java.lang.String pid)
           
 long[] getProcList()
           
 ProcMem getProcMem(long pid)
           
 ProcMem getProcMem(java.lang.String pid)
           
 java.util.List getProcModules(long pid)
           
 java.util.List getProcModules(java.lang.String pid)
           
 long getProcPort(int protocol, long port)
           
 long getProcPort(java.lang.String protocol, java.lang.String port)
           
 ProcStat getProcStat()
           
 ProcState getProcState(long pid)
           
 ProcState getProcState(java.lang.String pid)
           
 ProcTime getProcTime(long pid)
           
 ProcTime getProcTime(java.lang.String pid)
           
 ResourceLimit getResourceLimit()
           
 long getServicePid(java.lang.String name)
           
 Swap getSwap()
           
 Tcp getTcp()
           
 Uptime getUptime()
           
 Who[] getWhoList()
           
 

Method Detail

getPid

long getPid()

getServicePid

long getServicePid(java.lang.String name)
                   throws SigarException
Throws:
SigarException

getMem

Mem getMem()
           throws SigarException
Throws:
SigarException

getSwap

Swap getSwap()
             throws SigarException
Throws:
SigarException

getCpu

Cpu getCpu()
           throws SigarException
Throws:
SigarException

getCpuPerc

CpuPerc getCpuPerc()
                   throws SigarException
Throws:
SigarException

getUptime

Uptime getUptime()
                 throws SigarException
Throws:
SigarException

getResourceLimit

ResourceLimit getResourceLimit()
                               throws SigarException
Throws:
SigarException

getLoadAverage

double[] getLoadAverage()
                        throws SigarException
Throws:
SigarException

getProcList

long[] getProcList()
                   throws SigarException
Throws:
SigarException

getProcStat

ProcStat getProcStat()
                     throws SigarException
Throws:
SigarException

getProcMem

ProcMem getProcMem(long pid)
                   throws SigarException
Throws:
SigarException

getProcMem

ProcMem getProcMem(java.lang.String pid)
                   throws SigarException
Throws:
SigarException

getMultiProcMem

ProcMem getMultiProcMem(java.lang.String query)
                        throws SigarException
Throws:
SigarException

getProcState

ProcState getProcState(long pid)
                       throws SigarException
Throws:
SigarException

getProcState

ProcState getProcState(java.lang.String pid)
                       throws SigarException
Throws:
SigarException

getProcTime

ProcTime getProcTime(long pid)
                     throws SigarException
Throws:
SigarException

getProcTime

ProcTime getProcTime(java.lang.String pid)
                     throws SigarException
Throws:
SigarException

getProcCpu

ProcCpu getProcCpu(long pid)
                   throws SigarException
Throws:
SigarException

getProcCpu

ProcCpu getProcCpu(java.lang.String pid)
                   throws SigarException
Throws:
SigarException

getMultiProcCpu

MultiProcCpu getMultiProcCpu(java.lang.String query)
                             throws SigarException
Throws:
SigarException

getProcCred

ProcCred getProcCred(long pid)
                     throws SigarException
Throws:
SigarException

getProcCred

ProcCred getProcCred(java.lang.String pid)
                     throws SigarException
Throws:
SigarException

getProcCredName

ProcCredName getProcCredName(long pid)
                             throws SigarException
Throws:
SigarException

getProcCredName

ProcCredName getProcCredName(java.lang.String pid)
                             throws SigarException
Throws:
SigarException

getProcFd

ProcFd getProcFd(long pid)
                 throws SigarException
Throws:
SigarException

getProcFd

ProcFd getProcFd(java.lang.String pid)
                 throws SigarException
Throws:
SigarException

getProcExe

ProcExe getProcExe(long pid)
                   throws SigarException
Throws:
SigarException

getProcExe

ProcExe getProcExe(java.lang.String pid)
                   throws SigarException
Throws:
SigarException

getProcArgs

java.lang.String[] getProcArgs(long pid)
                               throws SigarException
Throws:
SigarException

getProcArgs

java.lang.String[] getProcArgs(java.lang.String pid)
                               throws SigarException
Throws:
SigarException

getProcEnv

java.util.Map getProcEnv(long pid)
                         throws SigarException
Throws:
SigarException

getProcEnv

java.util.Map getProcEnv(java.lang.String pid)
                         throws SigarException
Throws:
SigarException

getProcEnv

java.lang.String getProcEnv(long pid,
                            java.lang.String key)
                            throws SigarException
Throws:
SigarException

getProcEnv

java.lang.String getProcEnv(java.lang.String pid,
                            java.lang.String key)
                            throws SigarException
Throws:
SigarException

getProcModules

java.util.List getProcModules(long pid)
                              throws SigarException
Throws:
SigarException

getProcModules

java.util.List getProcModules(java.lang.String pid)
                              throws SigarException
Throws:
SigarException

getProcPort

long getProcPort(int protocol,
                 long port)
                 throws SigarException
Throws:
SigarException

getProcPort

long getProcPort(java.lang.String protocol,
                 java.lang.String port)
                 throws SigarException
Throws:
SigarException

getFileSystemList

FileSystem[] getFileSystemList()
                               throws SigarException
Throws:
SigarException

getFileSystemMap

FileSystemMap getFileSystemMap()
                               throws SigarException
Throws:
SigarException

getMountedFileSystemUsage

FileSystemUsage getMountedFileSystemUsage(java.lang.String name)
                                          throws SigarException
Throws:
SigarException

getFileSystemUsage

FileSystemUsage getFileSystemUsage(java.lang.String name)
                                   throws SigarException
Throws:
SigarException

getDiskUsage

DiskUsage getDiskUsage(java.lang.String name)
                       throws SigarException
Throws:
SigarException

getFileInfo

FileInfo getFileInfo(java.lang.String name)
                     throws SigarException
Throws:
SigarException

getLinkInfo

FileInfo getLinkInfo(java.lang.String name)
                     throws SigarException
Throws:
SigarException

getDirStat

DirStat getDirStat(java.lang.String name)
                   throws SigarException
Throws:
SigarException

getDirUsage

DirUsage getDirUsage(java.lang.String name)
                     throws SigarException
Throws:
SigarException

getCpuInfoList

CpuInfo[] getCpuInfoList()
                         throws SigarException
Throws:
SigarException

getCpuList

Cpu[] getCpuList()
                 throws SigarException
Throws:
SigarException

getCpuPercList

CpuPerc[] getCpuPercList()
                         throws SigarException
Throws:
SigarException

getNetRouteList

NetRoute[] getNetRouteList()
                           throws SigarException
Throws:
SigarException

getNetInterfaceConfig

NetInterfaceConfig getNetInterfaceConfig(java.lang.String name)
                                         throws SigarException
Throws:
SigarException

getNetInterfaceConfig

NetInterfaceConfig getNetInterfaceConfig()
                                         throws SigarException
Throws:
SigarException

getNetInterfaceStat

NetInterfaceStat getNetInterfaceStat(java.lang.String name)
                                     throws SigarException
Throws:
SigarException

getNetInterfaceList

java.lang.String[] getNetInterfaceList()
                                       throws SigarException
Throws:
SigarException

getNetConnectionList

NetConnection[] getNetConnectionList(int flags)
                                     throws SigarException
Throws:
SigarException

getNetListenAddress

java.lang.String getNetListenAddress(long port)
                                     throws SigarException
Throws:
SigarException

getNetListenAddress

java.lang.String getNetListenAddress(java.lang.String port)
                                     throws SigarException
Throws:
SigarException

getNetStat

NetStat getNetStat()
                   throws SigarException
Throws:
SigarException

getNetServicesName

java.lang.String getNetServicesName(int protocol,
                                    long port)

getWhoList

Who[] getWhoList()
                 throws SigarException
Throws:
SigarException

getTcp

Tcp getTcp()
           throws SigarException
Throws:
SigarException

getNfsClientV2

NfsClientV2 getNfsClientV2()
                           throws SigarException
Throws:
SigarException

getNfsServerV2

NfsServerV2 getNfsServerV2()
                           throws SigarException
Throws:
SigarException

getNfsClientV3

NfsClientV3 getNfsClientV3()
                           throws SigarException
Throws:
SigarException

getNfsServerV3

NfsServerV3 getNfsServerV3()
                           throws SigarException
Throws:
SigarException

getNetInfo

NetInfo getNetInfo()
                   throws SigarException
Throws:
SigarException

getFQDN

java.lang.String getFQDN()
                         throws SigarException
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SigarProxyCache.html000066400000000000000000000434601210132627500270340ustar00rootroot00000000000000 SigarProxyCache (Sigar API)

org.hyperic.sigar
Class SigarProxyCache

java.lang.Object
  extended by org.hyperic.sigar.SigarProxyCache
All Implemented Interfaces:
java.lang.reflect.InvocationHandler

public class SigarProxyCache
extends java.lang.Object
implements java.lang.reflect.InvocationHandler

This class implements a caching mechanism to avoid system calls with heavy Sigar usage in a short period of time. It is intended for use in applications such as Top.


Field Summary
static int EXPIRE_DEFAULT
           
 
Constructor Summary
SigarProxyCache(Sigar sigar, int expire)
           
 
Method Summary
static void clear(java.lang.Object proxy)
           
static Sigar getSigar(java.lang.Object proxy)
           
 java.lang.Object invoke(java.lang.Object proxy, java.lang.reflect.Method method, java.lang.Object[] args)
          The java.lang.reflect.InvocationHandler used by the Proxy.
static SigarProxy newInstance()
           
static SigarProxy newInstance(Sigar sigar)
           
static SigarProxy newInstance(Sigar sigar, int expire)
           
static void setExpire(SigarProxy proxy, java.lang.String type, int expire)
          Deprecated.  
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

EXPIRE_DEFAULT

public static final int EXPIRE_DEFAULT
See Also:
Constant Field Values
Constructor Detail

SigarProxyCache

public SigarProxyCache(Sigar sigar,
                       int expire)
Method Detail

newInstance

public static SigarProxy newInstance()

newInstance

public static SigarProxy newInstance(Sigar sigar)

newInstance

public static SigarProxy newInstance(Sigar sigar,
                                     int expire)

setExpire

public static void setExpire(SigarProxy proxy,
                             java.lang.String type,
                             int expire)
                      throws SigarException
Deprecated. 

Throws:
SigarException

clear

public static void clear(java.lang.Object proxy)

getSigar

public static Sigar getSigar(java.lang.Object proxy)

invoke

public java.lang.Object invoke(java.lang.Object proxy,
                               java.lang.reflect.Method method,
                               java.lang.Object[] args)
                        throws SigarException,
                               SigarNotImplementedException
The java.lang.reflect.InvocationHandler used by the Proxy. This method handles caching of all Sigar type objects.

Specified by:
invoke in interface java.lang.reflect.InvocationHandler
Throws:
SigarException
SigarNotImplementedException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SudoFileInputStream.html000066400000000000000000000376641210132627500277200ustar00rootroot00000000000000 SudoFileInputStream (Sigar API)

org.hyperic.sigar
Class SudoFileInputStream

java.lang.Object
  extended by java.io.InputStream
      extended by org.hyperic.sigar.SudoFileInputStream
All Implemented Interfaces:
java.io.Closeable

public class SudoFileInputStream
extends java.io.InputStream

InputStream wrapper for 'sudo cat filename'


Constructor Summary
SudoFileInputStream(java.io.File file)
           
SudoFileInputStream(java.lang.String file)
           
 
Method Summary
 int available()
           
 void close()
           
 void mark(int readlimit)
           
 boolean markSupported()
           
 int read()
           
 int read(byte[] b)
           
 int read(byte[] b, int off, int len)
           
 void reset()
           
 long skip(long n)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SudoFileInputStream

public SudoFileInputStream(java.lang.String file)
                    throws java.io.IOException,
                           java.io.FileNotFoundException
Throws:
java.io.IOException
java.io.FileNotFoundException

SudoFileInputStream

public SudoFileInputStream(java.io.File file)
                    throws java.io.IOException,
                           java.io.FileNotFoundException
Throws:
java.io.IOException
java.io.FileNotFoundException
Method Detail

close

public void close()
           throws java.io.IOException
Specified by:
close in interface java.io.Closeable
Overrides:
close in class java.io.InputStream
Throws:
java.io.IOException

read

public int read()
         throws java.io.IOException
Specified by:
read in class java.io.InputStream
Throws:
java.io.IOException

read

public int read(byte[] b)
         throws java.io.IOException
Overrides:
read in class java.io.InputStream
Throws:
java.io.IOException

read

public int read(byte[] b,
                int off,
                int len)
         throws java.io.IOException
Overrides:
read in class java.io.InputStream
Throws:
java.io.IOException

skip

public long skip(long n)
          throws java.io.IOException
Overrides:
skip in class java.io.InputStream
Throws:
java.io.IOException

available

public int available()
              throws java.io.IOException
Overrides:
available in class java.io.InputStream
Throws:
java.io.IOException

mark

public void mark(int readlimit)
Overrides:
mark in class java.io.InputStream

reset

public void reset()
           throws java.io.IOException
Overrides:
reset in class java.io.InputStream
Throws:
java.io.IOException

markSupported

public boolean markSupported()
Overrides:
markSupported in class java.io.InputStream


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Swap.html000066400000000000000000000362151210132627500247130ustar00rootroot00000000000000 Swap (Sigar API)

org.hyperic.sigar
Class Swap

java.lang.Object
  extended by org.hyperic.sigar.Swap
All Implemented Interfaces:
java.io.Serializable

public class Swap
extends java.lang.Object
implements java.io.Serializable

Swap sigar class.

See Also:
Serialized Form

Constructor Summary
Swap()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getFree()
          Get the Total free system swap.
 long getPageIn()
          Get the Pages in.
 long getPageOut()
          Get the Pages out.
 long getTotal()
          Get the Total system swap.
 long getUsed()
          Get the Total used system swap.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Swap

public Swap()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getTotal

public long getTotal()
Get the Total system swap.

Supported Platforms: All.

System equivalent commands:

  • AIX: lsps -s
  • Darwin: sysctl vm.swapusage
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris: swap -s
  • Win32:

Returns:
Total system swap

getUsed

public long getUsed()
Get the Total used system swap.

Supported Platforms: All.

System equivalent commands:

  • AIX: lsps -s
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris: swap -s
  • Win32:

Returns:
Total used system swap

getFree

public long getFree()
Get the Total free system swap.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: free
  • Solaris: swap -s
  • Win32:

Returns:
Total free system swap

getPageIn

public long getPageIn()
Get the Pages in.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: vmstat
  • Solaris: vmstat
  • Win32:

Returns:
Pages in

getPageOut

public long getPageOut()
Get the Pages out.

Supported Platforms: All.

System equivalent commands:

  • AIX:
  • Darwin:
  • FreeBSD:
  • HPUX:
  • Linux: vmstat
  • Solaris: vmstat
  • Win32:

Returns:
Pages out

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object

toMap

public java.util.Map toMap()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/SysInfo.html000066400000000000000000000422211210132627500253650ustar00rootroot00000000000000 SysInfo (Sigar API)

org.hyperic.sigar
Class SysInfo

java.lang.Object
  extended by org.hyperic.sigar.SysInfo
All Implemented Interfaces:
java.io.Serializable
Direct Known Subclasses:
OperatingSystem

public class SysInfo
extends java.lang.Object
implements java.io.Serializable

SysInfo sigar class.

See Also:
Serialized Form

Constructor Summary
SysInfo()
           
 
Method Summary
 void gather(Sigar sigar)
           
 java.lang.String getArch()
          Get the arch.
 java.lang.String getDescription()
          Get the description.
 java.lang.String getMachine()
          Get the machine.
 java.lang.String getName()
          Get the name.
 java.lang.String getPatchLevel()
          Get the patch_level.
 java.lang.String getVendor()
          Get the vendor.
 java.lang.String getVendorCodeName()
          Get the vendor_code_name.
 java.lang.String getVendorName()
          Get the vendor_name.
 java.lang.String getVendorVersion()
          Get the vendor_version.
 java.lang.String getVersion()
          Get the version.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

SysInfo

public SysInfo()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getName

public java.lang.String getName()
Get the name.

Supported Platforms: All.

Returns:
name

getVersion

public java.lang.String getVersion()
Get the version.

Supported Platforms: All.

Returns:
version

getArch

public java.lang.String getArch()
Get the arch.

Supported Platforms: All.

Returns:
arch

getMachine

public java.lang.String getMachine()
Get the machine.

Supported Platforms: All.

Returns:
machine

getDescription

public java.lang.String getDescription()
Get the description.

Supported Platforms: All.

Returns:
description

getPatchLevel

public java.lang.String getPatchLevel()
Get the patch_level.

Supported Platforms: Win32.

Returns:
patch_level

getVendor

public java.lang.String getVendor()
Get the vendor.

Supported Platforms: All.

Returns:
vendor

getVendorVersion

public java.lang.String getVendorVersion()
Get the vendor_version.

Supported Platforms: All.

Returns:
vendor_version

getVendorName

public java.lang.String getVendorName()
Get the vendor_name.

Supported Platforms: All.

Returns:
vendor_name

getVendorCodeName

public java.lang.String getVendorCodeName()
Get the vendor_code_name.

Supported Platforms: All.

Returns:
vendor_code_name

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Tcp.html000066400000000000000000000442271210132627500245310ustar00rootroot00000000000000 Tcp (Sigar API)

org.hyperic.sigar
Class Tcp

java.lang.Object
  extended by org.hyperic.sigar.Tcp
All Implemented Interfaces:
java.io.Serializable

public class Tcp
extends java.lang.Object
implements java.io.Serializable

Tcp sigar class.

See Also:
Serialized Form

Constructor Summary
Tcp()
           
 
Method Summary
 void gather(Sigar sigar)
           
 long getActiveOpens()
          Get the active_opens.
 long getAttemptFails()
          Get the attempt_fails.
 long getCurrEstab()
          Get the curr_estab.
 long getEstabResets()
          Get the estab_resets.
 long getInErrs()
          Get the in_errs.
 long getInSegs()
          Get the in_segs.
 long getOutRsts()
          Get the out_rsts.
 long getOutSegs()
          Get the out_segs.
 long getPassiveOpens()
          Get the passive_opens.
 long getRetransSegs()
          Get the retrans_segs.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Tcp

public Tcp()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getActiveOpens

public long getActiveOpens()
Get the active_opens.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
active_opens

getPassiveOpens

public long getPassiveOpens()
Get the passive_opens.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
passive_opens

getAttemptFails

public long getAttemptFails()
Get the attempt_fails.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
attempt_fails

getEstabResets

public long getEstabResets()
Get the estab_resets.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
estab_resets

getCurrEstab

public long getCurrEstab()
Get the curr_estab.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
curr_estab

getInSegs

public long getInSegs()
Get the in_segs.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
in_segs

getOutSegs

public long getOutSegs()
Get the out_segs.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
out_segs

getRetransSegs

public long getRetransSegs()
Get the retrans_segs.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
retrans_segs

getInErrs

public long getInErrs()
Get the in_errs.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
in_errs

getOutRsts

public long getOutRsts()
Get the out_rsts.

Supported Platforms: Undocumented.

System equivalent commands:

  • Linux: cat /proc/net/snmp
  • Solaris: netstat -s -P tcp

Returns:
out_rsts

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ThreadCpu.html000066400000000000000000000316571210132627500256650ustar00rootroot00000000000000 ThreadCpu (Sigar API)

org.hyperic.sigar
Class ThreadCpu

java.lang.Object
  extended by org.hyperic.sigar.ThreadCpu
All Implemented Interfaces:
java.io.Serializable

public class ThreadCpu
extends java.lang.Object
implements java.io.Serializable

ThreadCpu sigar class.

See Also:
Serialized Form

Constructor Summary
ThreadCpu()
           
 
Method Summary
 void gather(Sigar sigar, long pid)
           
 long getSys()
          Get the Thread cpu kernel time.
 long getTotal()
          Get the Thread cpu time (sum of User and Sys).
 long getUser()
          Get the Thread cpu user time.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ThreadCpu

public ThreadCpu()
Method Detail

gather

public void gather(Sigar sigar,
                   long pid)
            throws SigarException
Throws:
SigarException

getUser

public long getUser()
Get the Thread cpu user time.

Supported Platforms: AIX, HPUX, Linux, Solaris, Win32.

Returns:
Thread cpu user time

getSys

public long getSys()
Get the Thread cpu kernel time.

Supported Platforms: AIX, HPUX, Linux, Solaris, Win32.

Returns:
Thread cpu kernel time

getTotal

public long getTotal()
Get the Thread cpu time (sum of User and Sys).

Supported Platforms: AIX, HPUX, Linux, Solaris, Win32.

Returns:
Thread cpu time (sum of User and Sys)

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Uptime.html000066400000000000000000000275021210132627500252430ustar00rootroot00000000000000 Uptime (Sigar API)

org.hyperic.sigar
Class Uptime

java.lang.Object
  extended by org.hyperic.sigar.Uptime
All Implemented Interfaces:
java.io.Serializable

public class Uptime
extends java.lang.Object
implements java.io.Serializable

Uptime sigar class.

See Also:
Serialized Form

Constructor Summary
Uptime()
           
 
Method Summary
 void gather(Sigar sigar)
           
 double getUptime()
          Get the Time since machine started in seconds.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Uptime

public Uptime()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getUptime

public double getUptime()
Get the Time since machine started in seconds.

Supported Platforms: All.

System equivalent commands:

  • AIX: uptime
  • Darwin: uptime
  • FreeBSD: uptime
  • HPUX: uptime
  • Linux: uptime
  • Solaris: uptime
  • Win32:

Returns:
Time since machine started in seconds

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/Who.html000066400000000000000000000316631210132627500245400ustar00rootroot00000000000000 Who (Sigar API)

org.hyperic.sigar
Class Who

java.lang.Object
  extended by org.hyperic.sigar.Who
All Implemented Interfaces:
java.io.Serializable

public class Who
extends java.lang.Object
implements java.io.Serializable

Who sigar class.

See Also:
Serialized Form

Constructor Summary
Who()
           
 
Method Summary
 void gather(Sigar sigar)
           
 java.lang.String getDevice()
          Get the device.
 java.lang.String getHost()
          Get the host.
 long getTime()
          Get the time.
 java.lang.String getUser()
          Get the user.
 java.util.Map toMap()
           
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Who

public Who()
Method Detail

gather

public void gather(Sigar sigar)
            throws SigarException
Throws:
SigarException

getUser

public java.lang.String getUser()
Get the user.

Supported Platforms: Undocumented.

Returns:
user

getDevice

public java.lang.String getDevice()
Get the device.

Supported Platforms: Undocumented.

Returns:
device

getHost

public java.lang.String getHost()
Get the host.

Supported Platforms: Undocumented.

Returns:
host

getTime

public long getTime()
Get the time.

Supported Platforms: Undocumented.

Returns:
time

toMap

public java.util.Map toMap()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/000077500000000000000000000000001210132627500236475ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/CpuInfo.html000066400000000000000000000470341210132627500261100ustar00rootroot00000000000000 CpuInfo (Sigar API)

org.hyperic.sigar.cmd
Class CpuInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.CpuInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class CpuInfo
extends SigarCommandBase

Display cpu information for each cpu found on the system.


Field Summary
 boolean displayTimes
           
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
CpuInfo()
           
CpuInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

displayTimes

public boolean displayTimes
Constructor Detail

CpuInfo

public CpuInfo(Shell shell)

CpuInfo

public CpuInfo()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Df.html000066400000000000000000000553521210132627500251000ustar00rootroot00000000000000 Df (Sigar API)

org.hyperic.sigar.cmd
Class Df

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Df
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Df
extends SigarCommandBase

Report filesytem disk space usage.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Df()
           
Df(Shell shell)
           
 
Method Summary
 GetlineCompleter getCompleter()
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(FileSystem fs)
           
 void output(java.lang.String[] args)
           
 void printHeader()
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Df

public Df(Shell shell)

Df

public Df()
Method Detail

getCompleter

public GetlineCompleter getCompleter()
Overrides:
getCompleter in class SigarCommandBase

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

printHeader

public void printHeader()

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(FileSystem fs)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Du.html000066400000000000000000000473001210132627500251110ustar00rootroot00000000000000 Du (Sigar API)

org.hyperic.sigar.cmd
Class Du

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Du
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Du
extends SigarCommandBase

Display usage for a directory recursively


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Du()
           
Du(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Du

public Du(Shell shell)

Du

public Du()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/EventLogTail.html000066400000000000000000000227311210132627500270770ustar00rootroot00000000000000 EventLogTail (Sigar API)

org.hyperic.sigar.cmd
Class EventLogTail

java.lang.Object
  extended by org.hyperic.sigar.cmd.EventLogTail

public class EventLogTail
extends java.lang.Object


Constructor Summary
EventLogTail()
           
 
Method Summary
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

EventLogTail

public EventLogTail()
Method Detail

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/FileVersionInfo.html000066400000000000000000000514711210132627500276060ustar00rootroot00000000000000 FileVersionInfo (Sigar API)

org.hyperic.sigar.cmd
Class FileVersionInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.FileVersionInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class FileVersionInfo
extends SigarCommandBase

Display process file information.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
FileVersionInfo()
           
FileVersionInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String exe)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FileVersionInfo

public FileVersionInfo(Shell shell)

FileVersionInfo

public FileVersionInfo()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(java.lang.String exe)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Free.html000066400000000000000000000457661210132627500254400ustar00rootroot00000000000000 Free (Sigar API)

org.hyperic.sigar.cmd
Class Free

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Free
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Free
extends SigarCommandBase

Display amount of free and used memory in the system.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Free()
           
Free(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Free

public Free(Shell shell)

Free

public Free()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Ifconfig.html000066400000000000000000000540651210132627500262730ustar00rootroot00000000000000 Ifconfig (Sigar API)

org.hyperic.sigar.cmd
Class Ifconfig

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Ifconfig
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Ifconfig
extends SigarCommandBase

Display network interface configuration and metrics.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Ifconfig()
           
Ifconfig(Shell shell)
           
 
Method Summary
 java.util.Collection getCompletions()
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String name)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Ifconfig

public Ifconfig(Shell shell)

Ifconfig

public Ifconfig()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getCompletions

public java.util.Collection getCompletions()
Overrides:
getCompletions in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(java.lang.String name)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Iostat.html000066400000000000000000000610301210132627500260000ustar00rootroot00000000000000 Iostat (Sigar API)

org.hyperic.sigar.cmd
Class Iostat

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Iostat
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Iostat
extends SigarCommandBase

Report filesytem disk space usage.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Iostat()
           
Iostat(Shell shell)
           
 
Method Summary
 GetlineCompleter getCompleter()
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(FileSystem fs)
           
 void output(java.lang.String[] args)
           
 void outputDisk(java.lang.String name)
           
 void outputFileSystem(java.lang.String arg)
           
 void printHeader()
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Iostat

public Iostat(Shell shell)

Iostat

public Iostat()
Method Detail

getCompleter

public GetlineCompleter getCompleter()
Overrides:
getCompleter in class SigarCommandBase

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

printHeader

public void printHeader()

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

outputFileSystem

public void outputFileSystem(java.lang.String arg)
                      throws SigarException
Throws:
SigarException

outputDisk

public void outputDisk(java.lang.String name)
                throws SigarException
Throws:
SigarException

output

public void output(FileSystem fs)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Kill.html000066400000000000000000000521371210132627500254400ustar00rootroot00000000000000 Kill (Sigar API)

org.hyperic.sigar.cmd
Class Kill

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Kill
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Kill
extends SigarCommandBase

Send a signal to a process.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Kill()
           
Kill(Shell shell)
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Kill

public Kill(Shell shell)

Kill

public Kill()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Ls.html000066400000000000000000000472111210132627500251200ustar00rootroot00000000000000 Ls (Sigar API)

org.hyperic.sigar.cmd
Class Ls

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Ls
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Ls
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Ls()
           
Ls(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Ls

public Ls(Shell shell)

Ls

public Ls()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/MemWatch.html000066400000000000000000000226751210132627500262560ustar00rootroot00000000000000 MemWatch (Sigar API)

org.hyperic.sigar.cmd
Class MemWatch

java.lang.Object
  extended by org.hyperic.sigar.cmd.MemWatch

public class MemWatch
extends java.lang.Object

Watch for changes in program memory usage.


Constructor Summary
MemWatch()
           
 
Method Summary
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

MemWatch

public MemWatch()
Method Detail

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/MultiPs.html000066400000000000000000000522751210132627500261450ustar00rootroot00000000000000 MultiPs (Sigar API)

org.hyperic.sigar.cmd
Class MultiPs

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.MultiPs
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class MultiPs
extends SigarCommandBase

Show multi process status.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
MultiPs()
           
MultiPs(Shell shell)
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

MultiPs

public MultiPs(Shell shell)

MultiPs

public MultiPs()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/NetInfo.html000066400000000000000000000460141210132627500261040ustar00rootroot00000000000000 NetInfo (Sigar API)

org.hyperic.sigar.cmd
Class NetInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.NetInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class NetInfo
extends SigarCommandBase

Display network info.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
NetInfo()
           
NetInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

NetInfo

public NetInfo(Shell shell)

NetInfo

public NetInfo()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Netstat.html000066400000000000000000000506621210132627500261700ustar00rootroot00000000000000 Netstat (Sigar API)

org.hyperic.sigar.cmd
Class Netstat

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Netstat
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Netstat
extends SigarCommandBase

Display network connections.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Netstat()
           
Netstat(Shell shell)
           
 
Method Summary
static int getFlags(java.lang.String[] args, int flags)
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Netstat

public Netstat(Shell shell)

Netstat

public Netstat()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getFlags

public static int getFlags(java.lang.String[] args,
                           int flags)

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Nfsstat.html000066400000000000000000000462001210132627500261610ustar00rootroot00000000000000 Nfsstat (Sigar API)

org.hyperic.sigar.cmd
Class Nfsstat

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Nfsstat
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Nfsstat
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Nfsstat()
           
Nfsstat(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Nfsstat

public Nfsstat(Shell shell)

Nfsstat

public Nfsstat()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Pidof.html000066400000000000000000000474531210132627500256130ustar00rootroot00000000000000 Pidof (Sigar API)

org.hyperic.sigar.cmd
Class Pidof

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Pidof
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Pidof
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Pidof()
           
Pidof(Shell shell)
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Pidof

public Pidof(Shell shell)

Pidof

public Pidof()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/ProcFileInfo.html000066400000000000000000000525701210132627500270650ustar00rootroot00000000000000 ProcFileInfo (Sigar API)

org.hyperic.sigar.cmd
Class ProcFileInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.ProcFileInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class ProcFileInfo
extends SigarCommandBase

Display process file information.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ProcFileInfo()
           
ProcFileInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(long pid)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcFileInfo

public ProcFileInfo(Shell shell)

ProcFileInfo

public ProcFileInfo()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(long pid)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/ProcInfo.html000066400000000000000000000525251210132627500262650ustar00rootroot00000000000000 ProcInfo (Sigar API)

org.hyperic.sigar.cmd
Class ProcInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.ProcInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class ProcInfo
extends SigarCommandBase

Display all process information.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ProcInfo()
           
ProcInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(java.lang.String pid)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcInfo

public ProcInfo(Shell shell)

ProcInfo

public ProcInfo()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(java.lang.String pid)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/ProcModuleInfo.html000066400000000000000000000526431210132627500274340ustar00rootroot00000000000000 ProcModuleInfo (Sigar API)

org.hyperic.sigar.cmd
Class ProcModuleInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.ProcModuleInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class ProcModuleInfo
extends SigarCommandBase

Display process module info.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ProcModuleInfo()
           
ProcModuleInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(long pid)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcModuleInfo

public ProcModuleInfo(Shell shell)

ProcModuleInfo

public ProcModuleInfo()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(long pid)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Ps.html000066400000000000000000000614161210132627500251270ustar00rootroot00000000000000 Ps (Sigar API)

org.hyperic.sigar.cmd
Class Ps

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Ps
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Ps
extends SigarCommandBase

Show process status.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Ps()
           
Ps(Shell shell)
           
 
Method Summary
static java.lang.String getCpuTime(long total)
           
static java.lang.String getCpuTime(ProcTime time)
           
static java.util.List getInfo(SigarProxy sigar, long pid)
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static java.lang.String join(java.util.List info)
           
static void main(java.lang.String[] args)
           
 void output(long pid)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Ps

public Ps(Shell shell)

Ps

public Ps()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

join

public static java.lang.String join(java.util.List info)

getInfo

public static java.util.List getInfo(SigarProxy sigar,
                                     long pid)
                              throws SigarException
Throws:
SigarException

output

public void output(long pid)
            throws SigarException
Throws:
SigarException

getCpuTime

public static java.lang.String getCpuTime(long total)

getCpuTime

public static java.lang.String getCpuTime(ProcTime time)

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Route.html000066400000000000000000000456611210132627500256470ustar00rootroot00000000000000 Route (Sigar API)

org.hyperic.sigar.cmd
Class Route

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Route
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Route
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Route()
           
Route(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Route

public Route(Shell shell)

Route

public Route()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Runner.html000066400000000000000000000240501210132627500260070ustar00rootroot00000000000000 Runner (Sigar API)

org.hyperic.sigar.cmd
Class Runner

java.lang.Object
  extended by org.hyperic.sigar.cmd.Runner

public class Runner
extends java.lang.Object


Constructor Summary
Runner()
           
 
Method Summary
static java.net.URL[] getLibJars(java.lang.String dir)
           
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Runner

public Runner()
Method Detail

getLibJars

public static java.net.URL[] getLibJars(java.lang.String dir)
                                 throws java.lang.Exception
Throws:
java.lang.Exception

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Shell.html000066400000000000000000000650551210132627500256170ustar00rootroot00000000000000 Shell (Sigar API)

org.hyperic.sigar.cmd
Class Shell

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellBase
      extended by org.hyperic.sigar.cmd.Shell
All Implemented Interfaces:
ShellCommandMapper, SIGINT, GetlineCompleter

public class Shell
extends ShellBase

The Sigar Shell provides a command shell for running the example commands and Sigar tests.


Field Summary
static java.lang.String RCFILE_NAME
           
 
Fields inherited from class org.hyperic.sigar.shell.ShellBase
err, gl, out, PROP_PAGE_SIZE
 
Constructor Summary
Shell()
           
 
Method Summary
static void clearScreen()
           
 long[] findPids(java.lang.String query)
           
 long[] findPids(java.lang.String[] args)
           
static long[] getPids(SigarProxy sigar, java.lang.String[] args)
           
 Sigar getSigar()
           
 SigarProxy getSigarProxy()
           
 java.lang.String getUserDeniedMessage(long pid)
           
 boolean isInteractive()
           
static void main(java.lang.String[] args)
           
 void processCommand(ShellCommandHandler handler, java.lang.String[] args)
           
 void readCommandFile(java.lang.String dir)
           
 void registerCommands()
           
 void setInteractive(boolean value)
           
 void shutdown()
           
 
Methods inherited from class org.hyperic.sigar.shell.ShellBase
complete, complete, getCommandNameIterator, getDefaultPageControl, getErrStream, getGetline, getHandler, getHiddenInput, getInput, getInput, getOutStream, getPageSize, handleCommand, handleCommand, handlerIsHidden, handleSIGINT, hasCompleter, init, initHistory, initHistory, isRedirected, performPaging, performPaging, readRCFile, registerCommandHandler, registerSigIntHandler, run, sendToErrStream, sendToOutStream, setHandlerHidden, setPageSize, setPrompt
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

RCFILE_NAME

public static final java.lang.String RCFILE_NAME
See Also:
Constant Field Values
Constructor Detail

Shell

public Shell()
Method Detail

clearScreen

public static void clearScreen()

getSigarProxy

public SigarProxy getSigarProxy()

getSigar

public Sigar getSigar()

isInteractive

public boolean isInteractive()

setInteractive

public void setInteractive(boolean value)

registerCommands

public void registerCommands()
                      throws ShellCommandInitException
Throws:
ShellCommandInitException

processCommand

public void processCommand(ShellCommandHandler handler,
                           java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Overrides:
processCommand in class ShellBase
Throws:
ShellCommandUsageException
ShellCommandExecException

getPids

public static long[] getPids(SigarProxy sigar,
                             java.lang.String[] args)
                      throws SigarException
Throws:
SigarException

findPids

public long[] findPids(java.lang.String[] args)
                throws SigarException
Throws:
SigarException

findPids

public long[] findPids(java.lang.String query)
                throws SigarException
Throws:
SigarException

readCommandFile

public void readCommandFile(java.lang.String dir)

getUserDeniedMessage

public java.lang.String getUserDeniedMessage(long pid)

shutdown

public void shutdown()
Overrides:
shutdown in class ShellBase

main

public static void main(java.lang.String[] args)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/ShowArgs.html000066400000000000000000000524151210132627500263010ustar00rootroot00000000000000 ShowArgs (Sigar API)

org.hyperic.sigar.cmd
Class ShowArgs

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.ShowArgs
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class ShowArgs
extends SigarCommandBase

Show process command line arguments.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShowArgs()
           
ShowArgs(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(long pid)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShowArgs

public ShowArgs(Shell shell)

ShowArgs

public ShowArgs()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(long pid)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/ShowEnv.html000066400000000000000000000523771210132627500261440ustar00rootroot00000000000000 ShowEnv (Sigar API)

org.hyperic.sigar.cmd
Class ShowEnv

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.ShowEnv
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class ShowEnv
extends SigarCommandBase

Show process environment.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShowEnv()
           
ShowEnv(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 boolean isPidCompleter()
           
static void main(java.lang.String[] args)
           
 void output(long pid)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShowEnv

public ShowEnv(Shell shell)

ShowEnv

public ShowEnv()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

isPidCompleter

public boolean isPidCompleter()
Overrides:
isPidCompleter in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

output

public void output(long pid)
            throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/SigarCommandBase.html000066400000000000000000000765631210132627500277150ustar00rootroot00000000000000 SigarCommandBase (Sigar API)

org.hyperic.sigar.cmd
Class SigarCommandBase

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter
Direct Known Subclasses:
CpuInfo, Df, Du, FileVersionInfo, Free, Ifconfig, Iostat, Kill, Ls, MultiPs, NetInfo, Netstat, Nfsstat, Pidof, ProcFileInfo, ProcInfo, ProcModuleInfo, Ps, Route, ShowArgs, ShowEnv, SysInfo, Time, Ulimit, Uptime, Version, Who, Win32Service

public abstract class SigarCommandBase
extends ShellCommandBase
implements GetlineCompleter


Field Summary
protected  java.io.PrintStream err
           
protected  java.io.PrintStream out
           
protected  java.util.List output
           
protected  SigarProxy proxy
           
protected  Shell shell
           
protected  Sigar sigar
           
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
SigarCommandBase()
           
SigarCommandBase(Shell shell)
           
 
Method Summary
 java.lang.String complete(java.lang.String line)
           
 java.lang.String completePid(java.lang.String line)
           
 void flush()
           
 GetlineCompleter getCompleter()
           
 java.util.Collection getCompletions()
           
 PrintfFormat getFormatter()
           
 boolean isPidCompleter()
           
abstract  void output(java.lang.String[] args)
           
 void printf(java.util.List items)
           
 void printf(java.lang.Object[] items)
           
 void printf(java.lang.String format, java.lang.Object[] items)
           
 void println(java.lang.String line)
           
 void processCommand(java.lang.String[] args)
          Handle a command.
 void setOutputFormat(java.lang.String format)
           
 java.lang.String sprintf(java.lang.String format, java.lang.Object[] items)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, getUsageShort, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

shell

protected Shell shell

out

protected java.io.PrintStream out

err

protected java.io.PrintStream err

sigar

protected Sigar sigar

proxy

protected SigarProxy proxy

output

protected java.util.List output
Constructor Detail

SigarCommandBase

public SigarCommandBase(Shell shell)

SigarCommandBase

public SigarCommandBase()
Method Detail

setOutputFormat

public void setOutputFormat(java.lang.String format)

getFormatter

public PrintfFormat getFormatter()

sprintf

public java.lang.String sprintf(java.lang.String format,
                                java.lang.Object[] items)

printf

public void printf(java.lang.String format,
                   java.lang.Object[] items)

printf

public void printf(java.lang.Object[] items)

printf

public void printf(java.util.List items)

println

public void println(java.lang.String line)

flush

public void flush()

output

public abstract void output(java.lang.String[] args)
                     throws SigarException
Throws:
SigarException

validateArgs

protected boolean validateArgs(java.lang.String[] args)

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getCompletions

public java.util.Collection getCompletions()

getCompleter

public GetlineCompleter getCompleter()

isPidCompleter

public boolean isPidCompleter()

completePid

public java.lang.String completePid(java.lang.String line)

complete

public java.lang.String complete(java.lang.String line)
Specified by:
complete in interface GetlineCompleter


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/SysInfo.html000066400000000000000000000460351210132627500261370ustar00rootroot00000000000000 SysInfo (Sigar API)

org.hyperic.sigar.cmd
Class SysInfo

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.SysInfo
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class SysInfo
extends SigarCommandBase

Display System Information


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
SysInfo()
           
SysInfo(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SysInfo

public SysInfo(Shell shell)

SysInfo

public SysInfo()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Tail.html000066400000000000000000000305771210132627500254420ustar00rootroot00000000000000 Tail (Sigar API)

org.hyperic.sigar.cmd
Class Tail

java.lang.Object
  extended by org.hyperic.sigar.cmd.Tail

public class Tail
extends java.lang.Object

Display the last part of files to the standard output.


Field Summary
 java.util.List files
           
 boolean follow
           
 int number
           
 
Constructor Summary
Tail()
           
 
Method Summary
static void main(java.lang.String[] args)
           
 void parseArgs(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

follow

public boolean follow

number

public int number

files

public java.util.List files
Constructor Detail

Tail

public Tail()
Method Detail

parseArgs

public void parseArgs(java.lang.String[] args)
               throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws SigarException
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Time.html000066400000000000000000000505751210132627500254470ustar00rootroot00000000000000 Time (Sigar API)

org.hyperic.sigar.cmd
Class Time

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Time
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Time
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Time()
           
Time(Shell shell)
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Time

public Time(Shell shell)

Time

public Time()
Method Detail

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Top.html000066400000000000000000000231451210132627500253040ustar00rootroot00000000000000 Top (Sigar API)

org.hyperic.sigar.cmd
Class Top

java.lang.Object
  extended by org.hyperic.sigar.cmd.Top

public class Top
extends java.lang.Object

Display system resource utilization summaries and process information.

This version of the top command requires a ptql query to select which processes to display. Example to display java processes only:
% java -jar sigar-bin/lib/sigar.jar Top State.Name.eq=java


Constructor Summary
Top()
           
 
Method Summary
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Top

public Top()
Method Detail

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Ulimit.html000066400000000000000000000474201210132627500260070ustar00rootroot00000000000000 Ulimit (Sigar API)

org.hyperic.sigar.cmd
Class Ulimit

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Ulimit
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Ulimit
extends SigarCommandBase

Display system resource limits.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Ulimit()
           
Ulimit(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Ulimit

public Ulimit(Shell shell)

Ulimit

public Ulimit()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Uptime.html000066400000000000000000000501531210132627500260040ustar00rootroot00000000000000 Uptime (Sigar API)

org.hyperic.sigar.cmd
Class Uptime

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Uptime
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Uptime
extends SigarCommandBase

Display how long the system has been running and the current load averages.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Uptime()
           
Uptime(Shell shell)
           
 
Method Summary
static java.lang.String getInfo(SigarProxy sigar)
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Uptime

public Uptime(Shell shell)

Uptime

public Uptime()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

getInfo

public static java.lang.String getInfo(SigarProxy sigar)
                                throws SigarException
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Version.html000066400000000000000000000465041210132627500261730ustar00rootroot00000000000000 Version (Sigar API)

org.hyperic.sigar.cmd
Class Version

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Version
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Version
extends SigarCommandBase

Display Sigar, java and system version information.


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Version()
           
Version(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
static void printInfo(java.io.PrintStream os)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Version

public Version(Shell shell)

Version

public Version()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

printInfo

public static void printInfo(java.io.PrintStream os)

output

public void output(java.lang.String[] args)
Specified by:
output in class SigarCommandBase

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Watch.html000066400000000000000000000231301210132627500256020ustar00rootroot00000000000000 Watch (Sigar API)

org.hyperic.sigar.cmd
Class Watch

java.lang.Object
  extended by org.hyperic.sigar.cmd.Watch

public class Watch
extends java.lang.Object

Watch a file or directory displaying attribute changes.


Constructor Summary
Watch()
           
 
Method Summary
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Watch

public Watch()
Method Detail

main

public static void main(java.lang.String[] args)
                 throws SigarException
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Who.html000066400000000000000000000456231210132627500253040ustar00rootroot00000000000000 Who (Sigar API)

org.hyperic.sigar.cmd
Class Who

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Who
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Who
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Who()
           
Who(Shell shell)
           
 
Method Summary
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
static void main(java.lang.String[] args)
           
 void output(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getCompletions, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf, validateArgs
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Who

public Who(Shell shell)

Who

public Who()
Method Detail

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/Win32Service.html000066400000000000000000000507171210132627500267720ustar00rootroot00000000000000 Win32Service (Sigar API)

org.hyperic.sigar.cmd
Class Win32Service

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.cmd.SigarCommandBase
          extended by org.hyperic.sigar.cmd.Win32Service
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class Win32Service
extends SigarCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.cmd.SigarCommandBase
err, out, output, proxy, shell, sigar
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
Win32Service()
           
Win32Service(Shell shell)
           
 
Method Summary
 java.util.Collection getCompletions()
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void output(java.lang.String[] args)
           
protected  boolean validateArgs(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.cmd.SigarCommandBase
complete, completePid, flush, getCompleter, getFormatter, isPidCompleter, printf, printf, printf, println, processCommand, setOutputFormat, sprintf
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageHelp, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Win32Service

public Win32Service()

Win32Service

public Win32Service(Shell shell)
Method Detail

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

validateArgs

protected boolean validateArgs(java.lang.String[] args)
Overrides:
validateArgs in class SigarCommandBase

getCompletions

public java.util.Collection getCompletions()
Overrides:
getCompletions in class SigarCommandBase

output

public void output(java.lang.String[] args)
            throws SigarException
Specified by:
output in class SigarCommandBase
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/package-frame.html000066400000000000000000000103471210132627500272250ustar00rootroot00000000000000 org.hyperic.sigar.cmd (Sigar API) org.hyperic.sigar.cmd
Classes 
CpuInfo
Df
Du
EventLogTail
FileVersionInfo
Free
Ifconfig
Iostat
Kill
Ls
MemWatch
MultiPs
NetInfo
Netstat
Nfsstat
Pidof
ProcFileInfo
ProcInfo
ProcModuleInfo
Ps
Route
Runner
Shell
ShowArgs
ShowEnv
SigarCommandBase
SysInfo
Tail
Time
Top
Ulimit
Uptime
Version
Watch
Who
Win32Service
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/package-summary.html000066400000000000000000000340031210132627500276230ustar00rootroot00000000000000 org.hyperic.sigar.cmd (Sigar API)

Package org.hyperic.sigar.cmd

Example classes implementing familar unix tools in Java.

See:
          Description

Class Summary
CpuInfo Display cpu information for each cpu found on the system.
Df Report filesytem disk space usage.
Du Display usage for a directory recursively
EventLogTail  
FileVersionInfo Display process file information.
Free Display amount of free and used memory in the system.
Ifconfig Display network interface configuration and metrics.
Iostat Report filesytem disk space usage.
Kill Send a signal to a process.
Ls  
MemWatch Watch for changes in program memory usage.
MultiPs Show multi process status.
NetInfo Display network info.
Netstat Display network connections.
Nfsstat  
Pidof  
ProcFileInfo Display process file information.
ProcInfo Display all process information.
ProcModuleInfo Display process module info.
Ps Show process status.
Route  
Runner  
Shell The Sigar Shell provides a command shell for running the example commands and Sigar tests.
ShowArgs Show process command line arguments.
ShowEnv Show process environment.
SigarCommandBase  
SysInfo Display System Information
Tail Display the last part of files to the standard output.
Time  
Top Display system resource utilization summaries and process information.
Ulimit Display system resource limits.
Uptime Display how long the system has been running and the current load averages.
Version Display Sigar, java and system version information.
Watch Watch a file or directory displaying attribute changes.
Who  
Win32Service  
 

Package org.hyperic.sigar.cmd Description

Example classes implementing familar unix tools in Java.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/cmd/package-tree.html000066400000000000000000000303531210132627500270710ustar00rootroot00000000000000 org.hyperic.sigar.cmd Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar.cmd

Package Hierarchies:
All Packages

Class Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/package-frame.html000066400000000000000000000171711210132627500264640ustar00rootroot00000000000000 org.hyperic.sigar (Sigar API) org.hyperic.sigar
Interfaces 
SigarProxy
Classes 
Cpu
CpuInfo
CpuPerc
CpuTimer
CurrentProcessSummary
DirStat
DirUsage
DiskUsage
FileAttrs
FileInfo
FileSystem
FileSystemMap
FileSystemUsage
FileTail
FileWatcher
FileWatcherThread
Humidor
Mem
MultiProcCpu
MultiProcMem
NetConnection
NetFlags
NetInfo
NetInterfaceConfig
NetInterfaceStat
NetRoute
NetServices
NetStat
NfsClientV2
NfsClientV3
NfsFileSystem
NfsServerV2
NfsServerV3
OperatingSystem
ProcCpu
ProcCred
ProcCredName
ProcExe
ProcFd
ProcFileMirror
ProcMem
ProcStat
ProcState
ProcTime
ProcUtil
ResourceLimit
RPC
Sigar
SigarInvoker
SigarLoader
SigarLog
SigarProxyCache
SudoFileInputStream
Swap
SysInfo
Tcp
ThreadCpu
Uptime
Who
Exceptions 
NfsUnreachableException
SigarException
SigarFileNotFoundException
SigarNotImplementedException
SigarPermissionDeniedException
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/package-summary.html000066400000000000000000000500641210132627500270650ustar00rootroot00000000000000 org.hyperic.sigar (Sigar API)

Package org.hyperic.sigar

Sigar - System Information Gatherer And Reporter

See:
          Description

Interface Summary
SigarProxy The proxyable interface for caching via SigarProxyCache.
 

Class Summary
Cpu Cpu sigar class.
CpuInfo CpuInfo sigar class.
CpuPerc CPU percentage usage
CpuTimer  
CurrentProcessSummary Deprecated.  
DirStat DirStat sigar class.
DirUsage DirUsage sigar class.
DiskUsage DiskUsage sigar class.
FileAttrs FileAttrs sigar class.
FileInfo  
FileSystem FileSystem sigar class.
FileSystemMap Helper class to build a map of mounted file systems.
FileSystemUsage FileSystemUsage sigar class.
FileTail  
FileWatcher  
FileWatcherThread  
Humidor The Humidor provides access to a single Sigar instance.
Mem Mem sigar class.
MultiProcCpu Provide multi process cpu metrics.
MultiProcMem  
NetConnection NetConnection sigar class.
NetFlags Flag constants for network related ops.
NetInfo NetInfo sigar class.
NetInterfaceConfig NetInterfaceConfig sigar class.
NetInterfaceStat NetInterfaceStat sigar class.
NetRoute NetRoute sigar class.
NetServices Deprecated.  
NetStat  
NfsClientV2 NfsClientV2 sigar class.
NfsClientV3 NfsClientV3 sigar class.
NfsFileSystem  
NfsServerV2 NfsServerV2 sigar class.
NfsServerV3 NfsServerV3 sigar class.
OperatingSystem  
ProcCpu ProcCpu sigar class.
ProcCred ProcCred sigar class.
ProcCredName ProcCredName sigar class.
ProcExe ProcExe sigar class.
ProcFd ProcFd sigar class.
ProcFileMirror  
ProcMem ProcMem sigar class.
ProcStat ProcStat sigar class.
ProcState ProcState sigar class.
ProcTime ProcTime sigar class.
ProcUtil  
ResourceLimit ResourceLimit sigar class.
RPC  
Sigar The Sigar class provides access to the sigar objects containing system information.
SigarInvoker This class provides a string-ish interface to sigar.
SigarLoader  
SigarLog  
SigarProxyCache This class implements a caching mechanism to avoid system calls with heavy Sigar usage in a short period of time.
SudoFileInputStream InputStream wrapper for 'sudo cat filename'
Swap Swap sigar class.
SysInfo SysInfo sigar class.
Tcp Tcp sigar class.
ThreadCpu ThreadCpu sigar class.
Uptime Uptime sigar class.
Who Who sigar class.
 

Exception Summary
NfsUnreachableException  
SigarException Sigar base exception class.
SigarFileNotFoundException  
SigarNotImplementedException Sigar exception class, thrown for methods which are not implemented on a given platform.
SigarPermissionDeniedException  
 

Package org.hyperic.sigar Description

Sigar - System Information Gatherer And Reporter



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/package-tree.html000066400000000000000000000417101210132627500263250ustar00rootroot00000000000000 org.hyperic.sigar Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar

Package Hierarchies:
All Packages

Class Hierarchy

  • java.lang.Object
    • java.util.AbstractMap<K,V> (implements java.util.Map<K,V>)
      • java.util.HashMap<K,V> (implements java.lang.Cloneable, java.util.Map<K,V>, java.io.Serializable)
    • org.hyperic.jni.ArchLoader
    • org.hyperic.sigar.Cpu (implements java.io.Serializable)
    • org.hyperic.sigar.CpuInfo (implements java.io.Serializable)
    • org.hyperic.sigar.CpuPerc (implements java.io.Serializable)
    • org.hyperic.sigar.CpuTimer (implements org.hyperic.sigar.jmx.CpuTimerMBean)
    • org.hyperic.sigar.DirStat (implements java.io.Serializable)
    • org.hyperic.sigar.DirUsage (implements java.io.Serializable)
    • org.hyperic.sigar.DiskUsage (implements java.io.Serializable)
    • org.hyperic.sigar.FileAttrs (implements java.io.Serializable)
      • org.hyperic.sigar.FileInfo (implements java.io.Serializable)
    • org.hyperic.sigar.FileSystem (implements java.io.Serializable)
      • org.hyperic.sigar.NfsFileSystem (implements java.io.Serializable)
    • org.hyperic.sigar.FileSystemUsage (implements java.io.Serializable)
    • org.hyperic.sigar.FileWatcher
    • org.hyperic.sigar.FileWatcherThread (implements java.lang.Runnable)
    • org.hyperic.sigar.Humidor
    • java.io.InputStream (implements java.io.Closeable)
    • org.hyperic.sigar.Mem (implements java.io.Serializable)
    • org.hyperic.sigar.NetConnection (implements java.io.Serializable)
    • org.hyperic.sigar.NetFlags
    • org.hyperic.sigar.NetInfo (implements java.io.Serializable)
    • org.hyperic.sigar.NetInterfaceConfig (implements java.io.Serializable)
    • org.hyperic.sigar.NetInterfaceStat (implements java.io.Serializable)
    • org.hyperic.sigar.NetRoute (implements java.io.Serializable)
    • org.hyperic.sigar.NetServices
    • org.hyperic.sigar.NetStat (implements java.io.Serializable)
    • org.hyperic.sigar.NfsClientV2 (implements java.io.Serializable)
    • org.hyperic.sigar.NfsClientV3 (implements java.io.Serializable)
    • org.hyperic.sigar.NfsServerV2 (implements java.io.Serializable)
    • org.hyperic.sigar.NfsServerV3 (implements java.io.Serializable)
    • org.hyperic.sigar.ProcCpu (implements java.io.Serializable)
    • org.hyperic.sigar.ProcCred (implements java.io.Serializable)
    • org.hyperic.sigar.ProcCredName (implements java.io.Serializable)
    • org.hyperic.sigar.ProcExe (implements java.io.Serializable)
    • org.hyperic.sigar.ProcFd (implements java.io.Serializable)
    • org.hyperic.sigar.ProcMem (implements java.io.Serializable)
    • org.hyperic.sigar.ProcStat (implements java.io.Serializable)
    • org.hyperic.sigar.ProcState (implements java.io.Serializable)
    • org.hyperic.sigar.ProcTime (implements java.io.Serializable)
    • org.hyperic.sigar.ProcUtil
    • org.hyperic.sigar.ResourceLimit (implements java.io.Serializable)
    • org.hyperic.sigar.RPC
    • org.hyperic.sigar.Sigar (implements org.hyperic.sigar.SigarProxy)
    • org.hyperic.sigar.SigarInvoker
    • org.hyperic.sigar.SigarLog
    • org.hyperic.sigar.SigarProxyCache (implements java.lang.reflect.InvocationHandler)
    • org.hyperic.sigar.Swap (implements java.io.Serializable)
    • org.hyperic.sigar.SysInfo (implements java.io.Serializable)
    • org.hyperic.sigar.Tcp (implements java.io.Serializable)
    • org.hyperic.sigar.ThreadCpu (implements java.io.Serializable)
    • java.lang.Throwable (implements java.io.Serializable)
    • org.hyperic.sigar.Uptime (implements java.io.Serializable)
    • org.hyperic.sigar.Who (implements java.io.Serializable)

Interface Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/000077500000000000000000000000001210132627500240645ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/MalformedQueryException.html000066400000000000000000000256071210132627500315770ustar00rootroot00000000000000 MalformedQueryException (Sigar API)

org.hyperic.sigar.ptql
Class MalformedQueryException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.ptql.MalformedQueryException
All Implemented Interfaces:
java.io.Serializable

public class MalformedQueryException
extends SigarException

Exception for malformed process queries which cannot be parsed.

See Also:
Serialized Form

Constructor Summary
MalformedQueryException()
           
MalformedQueryException(java.lang.String message)
           
 
Method Summary
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MalformedQueryException

public MalformedQueryException()

MalformedQueryException

public MalformedQueryException(java.lang.String message)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/ProcessFinder.html000066400000000000000000000377411210132627500275340ustar00rootroot00000000000000 ProcessFinder (Sigar API)

org.hyperic.sigar.ptql
Class ProcessFinder

java.lang.Object
  extended by org.hyperic.sigar.ptql.ProcessFinder

public class ProcessFinder
extends java.lang.Object


Constructor Summary
ProcessFinder(Sigar sigar)
           
ProcessFinder(SigarProxy proxy)
          Deprecated.  
 
Method Summary
 long[] find(ProcessQuery query)
           
static long[] find(SigarProxy sigar, java.lang.String query)
           
static long[] find(Sigar sigar, java.lang.String query)
           
 long[] find(java.lang.String query)
           
 long findSingleProcess(ProcessQuery query)
           
 long findSingleProcess(java.lang.String query)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcessFinder

public ProcessFinder(SigarProxy proxy)
Deprecated. 


ProcessFinder

public ProcessFinder(Sigar sigar)
Method Detail

findSingleProcess

public long findSingleProcess(java.lang.String query)
                       throws SigarException
Throws:
SigarException

findSingleProcess

public long findSingleProcess(ProcessQuery query)
                       throws SigarException
Throws:
SigarException

find

public static long[] find(Sigar sigar,
                          java.lang.String query)
                   throws SigarException
Throws:
SigarException

find

public static long[] find(SigarProxy sigar,
                          java.lang.String query)
                   throws SigarException
Throws:
SigarException

find

public long[] find(java.lang.String query)
            throws SigarException
Throws:
SigarException

find

public long[] find(ProcessQuery query)
            throws SigarException
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/ProcessQuery.html000066400000000000000000000245341210132627500274260ustar00rootroot00000000000000 ProcessQuery (Sigar API)

org.hyperic.sigar.ptql
Interface ProcessQuery

All Known Implementing Classes:
SigarProcessQuery

public interface ProcessQuery


Method Summary
 long[] find(Sigar sigar)
           
 long findProcess(Sigar sigar)
           
 boolean match(Sigar sigar, long pid)
           
 

Method Detail

match

boolean match(Sigar sigar,
              long pid)
              throws SigarException
Throws:
SigarException

findProcess

long findProcess(Sigar sigar)
                 throws SigarException
Throws:
SigarException

find

long[] find(Sigar sigar)
            throws SigarException
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/ProcessQueryFactory.html000066400000000000000000000312461210132627500307540ustar00rootroot00000000000000 ProcessQueryFactory (Sigar API)

org.hyperic.sigar.ptql
Class ProcessQueryFactory

java.lang.Object
  extended by org.hyperic.sigar.ptql.ProcessQueryFactory

public class ProcessQueryFactory
extends java.lang.Object


Constructor Summary
ProcessQueryFactory()
           
 
Method Summary
 void clear()
           
static ProcessQueryFactory getInstance()
           
static ProcessQuery getInstance(java.lang.String query)
          Deprecated.  
 ProcessQuery getQuery(java.lang.String query)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcessQueryFactory

public ProcessQueryFactory()
Method Detail

clear

public void clear()

getInstance

public static ProcessQueryFactory getInstance()

getQuery

public ProcessQuery getQuery(java.lang.String query)
                      throws MalformedQueryException
Throws:
MalformedQueryException

getInstance

public static ProcessQuery getInstance(java.lang.String query)
                                throws MalformedQueryException
Deprecated. 

Throws:
MalformedQueryException
See Also:
getQuery(String)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/QueryLoadException.html000066400000000000000000000244641210132627500305500ustar00rootroot00000000000000 QueryLoadException (Sigar API)

org.hyperic.sigar.ptql
Class QueryLoadException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.lang.RuntimeException
              extended by org.hyperic.sigar.ptql.QueryLoadException
All Implemented Interfaces:
java.io.Serializable

Deprecated.

public class QueryLoadException
extends java.lang.RuntimeException

See Also:
Serialized Form

Constructor Summary
QueryLoadException()
          Deprecated.  
QueryLoadException(java.lang.String message)
          Deprecated.  
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

QueryLoadException

public QueryLoadException()
Deprecated. 

QueryLoadException

public QueryLoadException(java.lang.String message)
Deprecated. 


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/SigarProcessQuery.html000066400000000000000000000334521210132627500304130ustar00rootroot00000000000000 SigarProcessQuery (Sigar API)

org.hyperic.sigar.ptql
Class SigarProcessQuery

java.lang.Object
  extended by org.hyperic.sigar.ptql.SigarProcessQuery
All Implemented Interfaces:
ProcessQuery

public class SigarProcessQuery
extends java.lang.Object
implements ProcessQuery


Constructor Summary
SigarProcessQuery()
           
 
Method Summary
protected  void finalize()
           
 long[] find(Sigar sigar)
           
 long findProcess(Sigar sigar)
           
 boolean match(Sigar sigar, long pid)
           
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SigarProcessQuery

public SigarProcessQuery()
Method Detail

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object

match

public boolean match(Sigar sigar,
                     long pid)
              throws SigarException
Specified by:
match in interface ProcessQuery
Throws:
SigarException

findProcess

public long findProcess(Sigar sigar)
                 throws SigarException
Specified by:
findProcess in interface ProcessQuery
Throws:
SigarException

find

public long[] find(Sigar sigar)
            throws SigarException
Specified by:
find in interface ProcessQuery
Throws:
SigarException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/StringPattern.html000066400000000000000000000227271210132627500275700ustar00rootroot00000000000000 StringPattern (Sigar API)

org.hyperic.sigar.ptql
Class StringPattern

java.lang.Object
  extended by org.hyperic.sigar.ptql.StringPattern

public class StringPattern
extends java.lang.Object


Constructor Summary
StringPattern()
           
 
Method Summary
static boolean matches(java.lang.String source, java.lang.String regex)
          Wrapper around Pattern.compile(regex).matcher(source).find()
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

StringPattern

public StringPattern()
Method Detail

matches

public static boolean matches(java.lang.String source,
                              java.lang.String regex)
Wrapper around Pattern.compile(regex).matcher(source).find()



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/package-frame.html000066400000000000000000000037111210132627500274370ustar00rootroot00000000000000 org.hyperic.sigar.ptql (Sigar API) org.hyperic.sigar.ptql
Interfaces 
ProcessQuery
Classes 
ProcessFinder
ProcessQueryFactory
SigarProcessQuery
StringPattern
Exceptions 
MalformedQueryException
QueryLoadException
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/package-summary.html000066400000000000000000000202161210132627500300410ustar00rootroot00000000000000 org.hyperic.sigar.ptql (Sigar API)

Package org.hyperic.sigar.ptql

Process Table Query Language

See:
          Description

Interface Summary
ProcessQuery  
 

Class Summary
ProcessFinder  
ProcessQueryFactory  
SigarProcessQuery  
StringPattern  
 

Exception Summary
MalformedQueryException Exception for malformed process queries which cannot be parsed.
QueryLoadException Deprecated.  
 

Package org.hyperic.sigar.ptql Description

Process Table Query Language



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/ptql/package-tree.html000066400000000000000000000166721210132627500273160ustar00rootroot00000000000000 org.hyperic.sigar.ptql Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar.ptql

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/000077500000000000000000000000001210132627500242135ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/CollectionCompleter.html000066400000000000000000000366571210132627500310700ustar00rootroot00000000000000 CollectionCompleter (Sigar API)

org.hyperic.sigar.shell
Class CollectionCompleter

java.lang.Object
  extended by org.hyperic.sigar.shell.CollectionCompleter
All Implemented Interfaces:
GetlineCompleter
Direct Known Subclasses:
FileCompleter

public class CollectionCompleter
extends java.lang.Object
implements GetlineCompleter

GetlineCompleter implementation looks for possible completions using an Iterator.


Constructor Summary
CollectionCompleter()
           
CollectionCompleter(ShellBase shell)
           
CollectionCompleter(ShellBase shell, java.util.Collection collection)
           
 
Method Summary
 java.lang.String complete(java.lang.String line)
           
 java.lang.String displayPossible(java.util.List possible)
           
 java.lang.String displayPossible(java.lang.String[] possible)
           
 java.util.Collection getCollection()
           
 java.util.Iterator getIterator()
           
 java.lang.String getPartialCompletion(java.lang.String[] possible)
           
 void setCollection(java.util.Collection collection)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

CollectionCompleter

public CollectionCompleter()

CollectionCompleter

public CollectionCompleter(ShellBase shell)

CollectionCompleter

public CollectionCompleter(ShellBase shell,
                           java.util.Collection collection)
Method Detail

getIterator

public java.util.Iterator getIterator()

getCollection

public java.util.Collection getCollection()

setCollection

public void setCollection(java.util.Collection collection)

getPartialCompletion

public java.lang.String getPartialCompletion(java.lang.String[] possible)

displayPossible

public java.lang.String displayPossible(java.util.List possible)

displayPossible

public java.lang.String displayPossible(java.lang.String[] possible)

complete

public java.lang.String complete(java.lang.String line)
Specified by:
complete in interface GetlineCompleter


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/FileCompleter.html000066400000000000000000000364461210132627500276500ustar00rootroot00000000000000 FileCompleter (Sigar API)

org.hyperic.sigar.shell
Class FileCompleter

java.lang.Object
  extended by org.hyperic.sigar.shell.CollectionCompleter
      extended by org.hyperic.sigar.shell.FileCompleter
All Implemented Interfaces:
java.io.FilenameFilter, GetlineCompleter

public class FileCompleter
extends CollectionCompleter
implements java.io.FilenameFilter


Constructor Summary
FileCompleter()
           
FileCompleter(ShellBase shell)
           
 
Method Summary
 boolean accept(java.io.File dir, java.lang.String name)
           
 java.lang.String complete(java.lang.String line)
           
static java.lang.String expand(java.lang.String name)
           
 java.util.Iterator getIterator()
           
static void main(java.lang.String[] args)
           
 
Methods inherited from class org.hyperic.sigar.shell.CollectionCompleter
displayPossible, displayPossible, getCollection, getPartialCompletion, setCollection
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FileCompleter

public FileCompleter()

FileCompleter

public FileCompleter(ShellBase shell)
Method Detail

expand

public static java.lang.String expand(java.lang.String name)

accept

public boolean accept(java.io.File dir,
                      java.lang.String name)
Specified by:
accept in interface java.io.FilenameFilter

getIterator

public java.util.Iterator getIterator()
Overrides:
getIterator in class CollectionCompleter

complete

public java.lang.String complete(java.lang.String line)
Specified by:
complete in interface GetlineCompleter
Overrides:
complete in class CollectionCompleter

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/MultiwordShellCommand.html000066400000000000000000000466431210132627500313730ustar00rootroot00000000000000 MultiwordShellCommand (Sigar API)

org.hyperic.sigar.shell
Class MultiwordShellCommand

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.MultiwordShellCommand
All Implemented Interfaces:
ShellCommandHandler

public class MultiwordShellCommand
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
MultiwordShellCommand()
           
 
Method Summary
 java.util.Set getHandlerNames()
           
 ShellCommandHandler getSubHandler(java.lang.String subName)
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 void processCommand(java.lang.String[] args)
          Handle a command.
 void registerSubHandler(java.lang.String subName, ShellCommandHandler handler)
           
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getUsageShort, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

MultiwordShellCommand

public MultiwordShellCommand()
Method Detail

getSubHandler

public ShellCommandHandler getSubHandler(java.lang.String subName)

getHandlerNames

public java.util.Set getHandlerNames()

registerSubHandler

public void registerSubHandler(java.lang.String subName,
                               ShellCommandHandler handler)
                        throws ShellCommandInitException
Throws:
ShellCommandInitException

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/NormalQuitCommandException.html000066400000000000000000000237511210132627500323620ustar00rootroot00000000000000 NormalQuitCommandException (Sigar API)

org.hyperic.sigar.shell
Class NormalQuitCommandException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.lang.RuntimeException
              extended by org.hyperic.sigar.shell.NormalQuitCommandException
All Implemented Interfaces:
java.io.Serializable

public class NormalQuitCommandException
extends java.lang.RuntimeException

This exception is thrown when a command wants to exit the shell completely. Typically this is only done for quit commands.

See Also:
Serialized Form

Constructor Summary
NormalQuitCommandException()
           
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NormalQuitCommandException

public NormalQuitCommandException()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ProcessQueryCompleter.html000066400000000000000000000305641210132627500314300ustar00rootroot00000000000000 ProcessQueryCompleter (Sigar API)

org.hyperic.sigar.shell
Class ProcessQueryCompleter

java.lang.Object
  extended by org.hyperic.sigar.shell.ProcessQueryCompleter
All Implemented Interfaces:
GetlineCompleter

public class ProcessQueryCompleter
extends java.lang.Object
implements GetlineCompleter


Constructor Summary
ProcessQueryCompleter(ShellBase shell)
           
 
Method Summary
 java.lang.String complete(java.lang.String line)
           
static java.util.Collection getMethodOpNames(java.lang.reflect.Method method)
           
static java.util.Map getMethods()
           
static boolean isSigarClass(java.lang.Class type)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProcessQueryCompleter

public ProcessQueryCompleter(ShellBase shell)
Method Detail

getMethods

public static java.util.Map getMethods()

getMethodOpNames

public static java.util.Collection getMethodOpNames(java.lang.reflect.Method method)

isSigarClass

public static boolean isSigarClass(java.lang.Class type)

complete

public java.lang.String complete(java.lang.String line)
Specified by:
complete in interface GetlineCompleter


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/SIGINT.html000066400000000000000000000172051210132627500261030ustar00rootroot00000000000000 SIGINT (Sigar API)

org.hyperic.sigar.shell
Interface SIGINT

All Known Implementing Classes:
Shell, ShellBase

public interface SIGINT


Method Summary
 void handleSIGINT()
           
 

Method Detail

handleSIGINT

void handleSIGINT()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellBase.html000066400000000000000000001231201210132627500267420ustar00rootroot00000000000000 ShellBase (Sigar API)

org.hyperic.sigar.shell
Class ShellBase

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellBase
All Implemented Interfaces:
ShellCommandMapper, SIGINT, GetlineCompleter
Direct Known Subclasses:
Shell

public abstract class ShellBase
extends java.lang.Object
implements ShellCommandMapper, GetlineCompleter, SIGINT


Field Summary
protected  java.io.PrintStream err
           
protected  Getline gl
           
protected  java.io.PrintStream out
           
static java.lang.String PROP_PAGE_SIZE
           
 
Constructor Summary
ShellBase()
           
 
Method Summary
 java.lang.String complete(ShellCommandHandler handler, java.lang.String line)
           
 java.lang.String complete(java.lang.String line)
           
 java.util.Iterator getCommandNameIterator()
          Get an iterator for the command names.
 org.hyperic.sigar.pager.PageControl getDefaultPageControl()
           
 java.io.PrintStream getErrStream()
           
 Getline getGetline()
           
 ShellCommandHandler getHandler(java.lang.String command)
          Get the command handler for a command.
 java.lang.String getHiddenInput(java.lang.String prompt)
          If a command needs additional input via the console, they can get it this way.
 java.lang.String getInput(java.lang.String prompt)
          If a command needs additional input via the console, they can get it this way.
 java.lang.String getInput(java.lang.String prompt, boolean addToHistory)
          If a command needs additional input via the console, they can get it this way.
 java.io.PrintStream getOutStream()
           
 int getPageSize()
          Get the current page size used when paging data.
 void handleCommand(java.lang.String line)
           
 void handleCommand(java.lang.String line, java.lang.String[] args)
           
 boolean handlerIsHidden(java.lang.String handlerName)
           
 void handleSIGINT()
           
 boolean hasCompleter(ShellCommandHandler handler)
           
 void init(java.lang.String applicationName, java.io.PrintStream out, java.io.PrintStream err)
           
 void initHistory()
           
 void initHistory(java.io.File file)
           
 boolean isRedirected()
          Check to see if the currently running shell command is being redirected to a file.
 void performPaging(org.hyperic.sigar.pager.PageFetcher fetcher)
           
 void performPaging(org.hyperic.sigar.pager.PageFetcher fetcher, org.hyperic.sigar.pager.PageControl control)
           
 void processCommand(ShellCommandHandler handler, java.lang.String[] args)
           
 void readRCFile(java.io.File rcFile, boolean echoCommands)
          Read a .rc file into the shell, invoking everything in it (without saving the actions to history)
 void registerCommandHandler(java.lang.String commandName, ShellCommandHandler handler)
          Register a new command handler.
 void registerSigIntHandler()
           
 void run()
           
 void sendToErrStream(java.lang.String s)
          Write a string to this shell's output stream.
 void sendToOutStream(java.lang.String s)
          Write a string to this shell's output stream.
 void setHandlerHidden(java.lang.String handlerName, boolean isHidden)
           
 void setPageSize(int size)
          Set the page size for data paging.
 void setPrompt(java.lang.String prompt)
          Change the prompt
 void shutdown()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PROP_PAGE_SIZE

public static final java.lang.String PROP_PAGE_SIZE
See Also:
Constant Field Values

gl

protected Getline gl

out

protected java.io.PrintStream out

err

protected java.io.PrintStream err
Constructor Detail

ShellBase

public ShellBase()
Method Detail

handleSIGINT

public void handleSIGINT()
Specified by:
handleSIGINT in interface SIGINT

initHistory

public void initHistory()
                 throws java.io.IOException
Throws:
java.io.IOException

initHistory

public void initHistory(java.io.File file)
                 throws java.io.IOException
Throws:
java.io.IOException

registerSigIntHandler

public void registerSigIntHandler()

init

public void init(java.lang.String applicationName,
                 java.io.PrintStream out,
                 java.io.PrintStream err)

readRCFile

public void readRCFile(java.io.File rcFile,
                       boolean echoCommands)
                throws java.io.IOException
Read a .rc file into the shell, invoking everything in it (without saving the actions to history)

Parameters:
rcFile - File to read
Throws:
java.io.IOException

setPrompt

public void setPrompt(java.lang.String prompt)
Change the prompt

Parameters:
prompt -

registerCommandHandler

public void registerCommandHandler(java.lang.String commandName,
                                   ShellCommandHandler handler)
                            throws ShellCommandInitException
Register a new command handler.

Parameters:
commandName - The command that this handler will process.
handler - The handler to register.
Throws:
ShellCommandInitException

getInput

public java.lang.String getInput(java.lang.String prompt)
                          throws java.io.EOFException,
                                 java.io.IOException
If a command needs additional input via the console, they can get it this way.

Parameters:
prompt - The prompt to display.
Returns:
The data that the user typed in.
Throws:
java.io.EOFException
java.io.IOException

getInput

public java.lang.String getInput(java.lang.String prompt,
                                 boolean addToHistory)
                          throws java.io.EOFException,
                                 java.io.IOException
If a command needs additional input via the console, they can get it this way.

Parameters:
prompt - The prompt to display.
addToHistory - If true, the input entered will be added to the history file.
Returns:
The data that the user typed in.
Throws:
java.io.EOFException
java.io.IOException

getHiddenInput

public java.lang.String getHiddenInput(java.lang.String prompt)
                                throws java.io.EOFException,
                                       java.io.IOException
If a command needs additional input via the console, they can get it this way. The characters that the user types are not echoed.

Parameters:
prompt - The prompt to display.
Returns:
The data that the user typed in.
Throws:
java.io.EOFException
java.io.IOException

sendToOutStream

public void sendToOutStream(java.lang.String s)
Write a string to this shell's output stream.

Parameters:
s - The string to write to the output stream.

sendToErrStream

public void sendToErrStream(java.lang.String s)
Write a string to this shell's output stream.

Parameters:
s - The string to write to the output stream.

run

public void run()

handleCommand

public void handleCommand(java.lang.String line)

handleCommand

public void handleCommand(java.lang.String line,
                          java.lang.String[] args)

processCommand

public void processCommand(ShellCommandHandler handler,
                           java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Throws:
ShellCommandUsageException
ShellCommandExecException

getOutStream

public java.io.PrintStream getOutStream()

getErrStream

public java.io.PrintStream getErrStream()

getGetline

public Getline getGetline()

hasCompleter

public boolean hasCompleter(ShellCommandHandler handler)

complete

public java.lang.String complete(ShellCommandHandler handler,
                                 java.lang.String line)

complete

public java.lang.String complete(java.lang.String line)
Specified by:
complete in interface GetlineCompleter

getHandler

public ShellCommandHandler getHandler(java.lang.String command)
Description copied from interface: ShellCommandMapper
Get the command handler for a command.

Specified by:
getHandler in interface ShellCommandMapper
See Also:
ShellCommandMapper.getHandler(java.lang.String)

setHandlerHidden

public void setHandlerHidden(java.lang.String handlerName,
                             boolean isHidden)

handlerIsHidden

public boolean handlerIsHidden(java.lang.String handlerName)

getCommandNameIterator

public java.util.Iterator getCommandNameIterator()
Description copied from interface: ShellCommandMapper
Get an iterator for the command names.

Specified by:
getCommandNameIterator in interface ShellCommandMapper
See Also:
ShellCommandMapper.getCommandNameIterator()

shutdown

public void shutdown()

isRedirected

public boolean isRedirected()
Check to see if the currently running shell command is being redirected to a file.

Returns:
true if the shell is redirecting to a file, else false

setPageSize

public void setPageSize(int size)
Set the page size for data paging.

Parameters:
size - Number of rows to include in a page of data -- if 0, then unlimited rows will be used.

getPageSize

public int getPageSize()
Get the current page size used when paging data.

Returns:
the # of rows in the current page size.

getDefaultPageControl

public org.hyperic.sigar.pager.PageControl getDefaultPageControl()

performPaging

public void performPaging(org.hyperic.sigar.pager.PageFetcher fetcher)
                   throws org.hyperic.sigar.pager.PageFetchException
Throws:
org.hyperic.sigar.pager.PageFetchException

performPaging

public void performPaging(org.hyperic.sigar.pager.PageFetcher fetcher,
                          org.hyperic.sigar.pager.PageControl control)
                   throws org.hyperic.sigar.pager.PageFetchException
Throws:
org.hyperic.sigar.pager.PageFetchException


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommandBase.html000066400000000000000000000560451210132627500302540ustar00rootroot00000000000000 ShellCommandBase (Sigar API)

org.hyperic.sigar.shell
Class ShellCommandBase

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
All Implemented Interfaces:
ShellCommandHandler
Direct Known Subclasses:
MultiwordShellCommand, ShellCommand_alias, ShellCommand_get, ShellCommand_help, ShellCommand_quit, ShellCommand_set, ShellCommand_sleep, ShellCommand_source, SigarCommandBase

public class ShellCommandBase
extends java.lang.Object
implements ShellCommandHandler


Field Summary
protected  java.lang.String itsCommandName
           
protected  ShellBase itsShell
           
 
Constructor Summary
ShellCommandBase()
           
 
Method Summary
 java.lang.String getCommandName()
           
 java.io.PrintStream getErrStream()
           
 java.io.PrintStream getOutStream()
           
 ShellBase getShell()
           
 java.lang.String getSyntax()
          Get a description of the syntax for how a command should be invoked.
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void init(java.lang.String commandName, ShellBase shell)
          Initialize this command handler.
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

itsCommandName

protected java.lang.String itsCommandName

itsShell

protected ShellBase itsShell
Constructor Detail

ShellCommandBase

public ShellCommandBase()
Method Detail

getCommandName

public java.lang.String getCommandName()

getShell

public ShellBase getShell()

getOutStream

public java.io.PrintStream getOutStream()

getErrStream

public java.io.PrintStream getErrStream()

init

public void init(java.lang.String commandName,
                 ShellBase shell)
          throws ShellCommandInitException
Description copied from interface: ShellCommandHandler
Initialize this command handler.

Specified by:
init in interface ShellCommandHandler
Parameters:
commandName - The name of the command.
shell - The shell. This is useful for command that need to be able to interpret other commands, like the "help" command, and for commands that need to get additional user input, for example a login command that presents a password prompt.
Throws:
ShellCommandInitException

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntax

public java.lang.String getSyntax()
Description copied from interface: ShellCommandHandler
Get a description of the syntax for how a command should be invoked.

Specified by:
getSyntax in interface ShellCommandHandler
Returns:
A description of the syntax

getSyntaxArgs

public java.lang.String getSyntaxArgs()

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommandExecException.html000066400000000000000000000243501210132627500321370ustar00rootroot00000000000000 ShellCommandExecException (Sigar API)

org.hyperic.sigar.shell
Class ShellCommandExecException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.shell.ShellCommandExecException
All Implemented Interfaces:
java.io.Serializable

public class ShellCommandExecException
extends java.lang.Exception

See Also:
Serialized Form

Constructor Summary
ShellCommandExecException()
           
ShellCommandExecException(java.lang.String s)
           
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ShellCommandExecException

public ShellCommandExecException()

ShellCommandExecException

public ShellCommandExecException(java.lang.String s)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommandHandler.html000066400000000000000000000413671210132627500307600ustar00rootroot00000000000000 ShellCommandHandler (Sigar API)

org.hyperic.sigar.shell
Interface ShellCommandHandler

All Known Implementing Classes:
CpuInfo, Df, Du, FileVersionInfo, Free, Ifconfig, Iostat, Kill, Ls, MultiPs, MultiwordShellCommand, NetInfo, Netstat, Nfsstat, Pidof, ProcFileInfo, ProcInfo, ProcModuleInfo, Ps, Route, ShellCommand_alias, ShellCommand_get, ShellCommand_help, ShellCommand_quit, ShellCommand_set, ShellCommand_sleep, ShellCommand_source, ShellCommandBase, ShowArgs, ShowEnv, SigarCommandBase, SysInfo, Time, Ulimit, Uptime, Version, Who, Win32Service

public interface ShellCommandHandler


Method Summary
 java.lang.String getSyntax()
          Get a description of the syntax for how a command should be invoked.
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void init(java.lang.String commandName, ShellBase shell)
          Initialize this command handler.
 void processCommand(java.lang.String[] args)
          Handle a command.
 

Method Detail

init

void init(java.lang.String commandName,
          ShellBase shell)
          throws ShellCommandInitException
Initialize this command handler.

Parameters:
commandName - The name of the command.
shell - The shell. This is useful for command that need to be able to interpret other commands, like the "help" command, and for commands that need to get additional user input, for example a login command that presents a password prompt.
Throws:
ShellCommandInitException

processCommand

void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Handle a command.

Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getUsageHelp

java.lang.String getUsageHelp(java.lang.String[] args)
Get some info on how to invoke this command.

Returns:
Some usage information on how this command is expected to be invoked.

getUsageShort

java.lang.String getUsageShort()
Get a very brief (40 character) description of the command

Returns:
A description of the command.

getSyntax

java.lang.String getSyntax()
Get a description of the syntax for how a command should be invoked.

Returns:
A description of the syntax


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommandInitException.html000066400000000000000000000243641210132627500321630ustar00rootroot00000000000000 ShellCommandInitException (Sigar API)

org.hyperic.sigar.shell
Class ShellCommandInitException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.shell.ShellCommandInitException
All Implemented Interfaces:
java.io.Serializable

public class ShellCommandInitException
extends java.lang.Exception

See Also:
Serialized Form

Constructor Summary
ShellCommandInitException()
           
ShellCommandInitException(java.lang.String s)
           
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ShellCommandInitException

public ShellCommandInitException()

ShellCommandInitException

public ShellCommandInitException(java.lang.String s)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommandMapper.html000066400000000000000000000220721210132627500306170ustar00rootroot00000000000000 ShellCommandMapper (Sigar API)

org.hyperic.sigar.shell
Interface ShellCommandMapper

All Known Implementing Classes:
Shell, ShellBase

public interface ShellCommandMapper


Method Summary
 java.util.Iterator getCommandNameIterator()
          Get an iterator for the command names.
 ShellCommandHandler getHandler(java.lang.String command)
          Get the command handler for a command.
 

Method Detail

getHandler

ShellCommandHandler getHandler(java.lang.String command)
Get the command handler for a command.


getCommandNameIterator

java.util.Iterator getCommandNameIterator()
Get an iterator for the command names.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommandUsageException.html000066400000000000000000000243721210132627500323230ustar00rootroot00000000000000 ShellCommandUsageException (Sigar API)

org.hyperic.sigar.shell
Class ShellCommandUsageException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.shell.ShellCommandUsageException
All Implemented Interfaces:
java.io.Serializable

public class ShellCommandUsageException
extends java.lang.Exception

See Also:
Serialized Form

Constructor Summary
ShellCommandUsageException()
           
ShellCommandUsageException(java.lang.String s)
           
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ShellCommandUsageException

public ShellCommandUsageException()

ShellCommandUsageException

public ShellCommandUsageException(java.lang.String s)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_alias.html000066400000000000000000000460411210132627500306250ustar00rootroot00000000000000 ShellCommand_alias (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_alias

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_alias
All Implemented Interfaces:
ShellCommandHandler

public class ShellCommand_alias
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_alias()
           
 
Method Summary
static java.lang.String[] getAlias(java.lang.String alias)
           
static java.util.Iterator getAliases()
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_alias

public ShellCommand_alias()
Method Detail

getAlias

public static java.lang.String[] getAlias(java.lang.String alias)

getAliases

public static java.util.Iterator getAliases()

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_get.html000066400000000000000000000436511210132627500303170ustar00rootroot00000000000000 ShellCommand_get (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_get

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_get
All Implemented Interfaces:
ShellCommandHandler

public class ShellCommand_get
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_get()
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_get

public ShellCommand_get()
Method Detail

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_help.html000066400000000000000000000436701210132627500304710ustar00rootroot00000000000000 ShellCommand_help (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_help

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_help
All Implemented Interfaces:
ShellCommandHandler

public class ShellCommand_help
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_help()
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_help

public ShellCommand_help()
Method Detail

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_quit.html000066400000000000000000000423351210132627500305200ustar00rootroot00000000000000 ShellCommand_quit (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_quit

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_quit
All Implemented Interfaces:
ShellCommandHandler

public class ShellCommand_quit
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_quit()
           
 
Method Summary
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, getSyntaxArgs, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_quit

public ShellCommand_quit()
Method Detail

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_set.html000066400000000000000000000451421210132627500303300ustar00rootroot00000000000000 ShellCommand_set (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_set

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_set
All Implemented Interfaces:
ShellCommandHandler

public class ShellCommand_set
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_set()
           
 
Method Summary
 void addSetKey(java.lang.String key, java.lang.String description)
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_set

public ShellCommand_set()
Method Detail

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

addSetKey

public void addSetKey(java.lang.String key,
                      java.lang.String description)

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_sleep.html000066400000000000000000000437171210132627500306530ustar00rootroot00000000000000 ShellCommand_sleep (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_sleep

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_sleep
All Implemented Interfaces:
ShellCommandHandler

public class ShellCommand_sleep
extends ShellCommandBase


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_sleep()
           
 
Method Summary
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_sleep

public ShellCommand_sleep()
Method Detail

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellCommand_source.html000066400000000000000000000462041210132627500310350ustar00rootroot00000000000000 ShellCommand_source (Sigar API)

org.hyperic.sigar.shell
Class ShellCommand_source

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellCommandBase
      extended by org.hyperic.sigar.shell.ShellCommand_source
All Implemented Interfaces:
ShellCommandHandler, GetlineCompleter

public class ShellCommand_source
extends ShellCommandBase
implements GetlineCompleter


Field Summary
 
Fields inherited from class org.hyperic.sigar.shell.ShellCommandBase
itsCommandName, itsShell
 
Constructor Summary
ShellCommand_source()
           
 
Method Summary
 java.lang.String complete(java.lang.String line)
           
 java.lang.String getSyntaxArgs()
           
 java.lang.String getUsageHelp(java.lang.String[] args)
          Get some info on how to invoke this command.
 java.lang.String getUsageShort()
          Get a very brief (40 character) description of the command
 void processCommand(java.lang.String[] args)
          Handle a command.
 
Methods inherited from class org.hyperic.sigar.shell.ShellCommandBase
getCommandName, getErrStream, getOutStream, getShell, getSyntax, init
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellCommand_source

public ShellCommand_source()
Method Detail

complete

public java.lang.String complete(java.lang.String line)
Specified by:
complete in interface GetlineCompleter

processCommand

public void processCommand(java.lang.String[] args)
                    throws ShellCommandUsageException,
                           ShellCommandExecException
Description copied from interface: ShellCommandHandler
Handle a command.

Specified by:
processCommand in interface ShellCommandHandler
Overrides:
processCommand in class ShellCommandBase
Parameters:
args - The args to the command.
Throws:
ShellCommandUsageException - If the args are malformed.
ShellCommandExecException - If an error occurred executing the command.

getSyntaxArgs

public java.lang.String getSyntaxArgs()
Overrides:
getSyntaxArgs in class ShellCommandBase

getUsageShort

public java.lang.String getUsageShort()
Description copied from interface: ShellCommandHandler
Get a very brief (40 character) description of the command

Specified by:
getUsageShort in interface ShellCommandHandler
Overrides:
getUsageShort in class ShellCommandBase
Returns:
A description of the command.

getUsageHelp

public java.lang.String getUsageHelp(java.lang.String[] args)
Description copied from interface: ShellCommandHandler
Get some info on how to invoke this command.

Specified by:
getUsageHelp in interface ShellCommandHandler
Overrides:
getUsageHelp in class ShellCommandBase
Returns:
Some usage information on how this command is expected to be invoked.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/ShellIntHandler.html000066400000000000000000000306731210132627500301320ustar00rootroot00000000000000 ShellIntHandler (Sigar API)

org.hyperic.sigar.shell
Class ShellIntHandler

java.lang.Object
  extended by org.hyperic.sigar.shell.ShellIntHandler
All Implemented Interfaces:
sun.misc.SignalHandler

public class ShellIntHandler
extends java.lang.Object
implements sun.misc.SignalHandler


Field Summary
 
Fields inherited from interface sun.misc.SignalHandler
SIG_DFL, SIG_IGN
 
Constructor Summary
ShellIntHandler()
           
 
Method Summary
 void handle(sun.misc.Signal signal)
           
static void pop()
           
static void push(SIGINT handler)
           
static void register(ShellBase shell)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShellIntHandler

public ShellIntHandler()
Method Detail

register

public static void register(ShellBase shell)

handle

public void handle(sun.misc.Signal signal)
Specified by:
handle in interface sun.misc.SignalHandler

push

public static void push(SIGINT handler)

pop

public static void pop()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/package-frame.html000066400000000000000000000072751210132627500275770ustar00rootroot00000000000000 org.hyperic.sigar.shell (Sigar API) org.hyperic.sigar.shell
Interfaces 
ShellCommandHandler
ShellCommandMapper
SIGINT
Classes 
CollectionCompleter
FileCompleter
MultiwordShellCommand
ProcessQueryCompleter
ShellBase
ShellCommand_alias
ShellCommand_get
ShellCommand_help
ShellCommand_quit
ShellCommand_set
ShellCommand_sleep
ShellCommand_source
ShellCommandBase
ShellIntHandler
Exceptions 
NormalQuitCommandException
ShellCommandExecException
ShellCommandInitException
ShellCommandUsageException
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/package-summary.html000066400000000000000000000265231210132627500301770ustar00rootroot00000000000000 org.hyperic.sigar.shell (Sigar API)

Package org.hyperic.sigar.shell

Base package for implementing a command shell.

See:
          Description

Interface Summary
ShellCommandHandler  
ShellCommandMapper  
SIGINT  
 

Class Summary
CollectionCompleter GetlineCompleter implementation looks for possible completions using an Iterator.
FileCompleter  
MultiwordShellCommand  
ProcessQueryCompleter  
ShellBase  
ShellCommand_alias  
ShellCommand_get  
ShellCommand_help  
ShellCommand_quit  
ShellCommand_set  
ShellCommand_sleep  
ShellCommand_source  
ShellCommandBase  
ShellIntHandler  
 

Exception Summary
NormalQuitCommandException This exception is thrown when a command wants to exit the shell completely.
ShellCommandExecException  
ShellCommandInitException  
ShellCommandUsageException  
 

Package org.hyperic.sigar.shell Description

Base package for implementing a command shell.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/shell/package-tree.html000066400000000000000000000256061210132627500274420ustar00rootroot00000000000000 org.hyperic.sigar.shell Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar.shell

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/000077500000000000000000000000001210132627500240615ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/Getline.html000066400000000000000000000356111210132627500263440ustar00rootroot00000000000000 Getline (Sigar API)

org.hyperic.sigar.util
Class Getline

java.lang.Object
  extended by org.hyperic.sigar.util.Getline

public class Getline
extends java.lang.Object

This class provides Emacs style key bindings, history and tab completion for command shell applications. This class is a Java interface to the getline.c package: Copyright (C) 1991, 1992 by Chris Thewalt (thewalt@ce.berkeley.edu)


Constructor Summary
Getline()
           
Getline(java.lang.String prompt)
           
 
Method Summary
 void addToHistory(java.lang.String line)
           
 java.lang.String getLine()
           
 java.lang.String getLine(java.lang.String prompt)
           
 java.lang.String getLine(java.lang.String prompt, boolean addToHistory)
           
 void initHistoryFile(java.io.File file)
           
static boolean isTTY()
           
 void redraw()
           
 void reset()
           
static void setCompleter(GetlineCompleter completer)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Getline

public Getline()

Getline

public Getline(java.lang.String prompt)
Method Detail

setCompleter

public static void setCompleter(GetlineCompleter completer)

redraw

public void redraw()

reset

public void reset()

isTTY

public static boolean isTTY()

getLine

public java.lang.String getLine()
                         throws java.io.IOException,
                                java.io.EOFException
Throws:
java.io.IOException
java.io.EOFException

getLine

public java.lang.String getLine(java.lang.String prompt)
                         throws java.io.IOException,
                                java.io.EOFException
Throws:
java.io.IOException
java.io.EOFException

getLine

public java.lang.String getLine(java.lang.String prompt,
                                boolean addToHistory)
                         throws java.io.IOException,
                                java.io.EOFException
Throws:
java.io.IOException
java.io.EOFException

initHistoryFile

public void initHistoryFile(java.io.File file)
                     throws java.io.IOException
Throws:
java.io.IOException

addToHistory

public void addToHistory(java.lang.String line)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/GetlineCompleter.html000066400000000000000000000271721210132627500302220ustar00rootroot00000000000000 GetlineCompleter (Sigar API)

org.hyperic.sigar.util
Interface GetlineCompleter

All Known Implementing Classes:
CollectionCompleter, CpuInfo, Df, Du, FileCompleter, FileVersionInfo, Free, Ifconfig, Iostat, Kill, Ls, MultiPs, NetInfo, Netstat, Nfsstat, Pidof, ProcessQueryCompleter, ProcFileInfo, ProcInfo, ProcModuleInfo, Ps, Route, Shell, ShellBase, ShellCommand_source, ShowArgs, ShowEnv, SigarCommandBase, SysInfo, Time, Ulimit, Uptime, Version, Who, Win32Service

public interface GetlineCompleter


Method Summary
 java.lang.String complete(java.lang.String line)
           
 

Method Detail

complete

java.lang.String complete(java.lang.String line)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/IteratorIterator.html000066400000000000000000000265271210132627500302660ustar00rootroot00000000000000 IteratorIterator (Sigar API)

org.hyperic.sigar.util
Class IteratorIterator

java.lang.Object
  extended by org.hyperic.sigar.util.IteratorIterator
All Implemented Interfaces:
java.util.Iterator

public class IteratorIterator
extends java.lang.Object
implements java.util.Iterator

Iterator for multiple Iterators.


Constructor Summary
IteratorIterator()
           
 
Method Summary
 void add(java.util.Iterator iterator)
           
 boolean hasNext()
           
 java.lang.Object next()
           
 void remove()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

IteratorIterator

public IteratorIterator()
Method Detail

add

public void add(java.util.Iterator iterator)

hasNext

public boolean hasNext()
Specified by:
hasNext in interface java.util.Iterator

next

public java.lang.Object next()
Specified by:
next in interface java.util.Iterator

remove

public void remove()
Specified by:
remove in interface java.util.Iterator


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/PrintfFormat.html000066400000000000000000001001321210132627500273570ustar00rootroot00000000000000 PrintfFormat (Sigar API)

org.hyperic.sigar.util
Class PrintfFormat

java.lang.Object
  extended by org.hyperic.sigar.util.PrintfFormat

public class PrintfFormat
extends java.lang.Object

PrintfFormat allows the formatting of an array of objects embedded within a string. Primitive types must be passed using wrapper types. The formatting is controlled by a control string.

A control string is a Java string that contains a control specification. The control specification starts at the first percent sign (%) in the string, provided that this percent sign

  1. is not escaped protected by a matching % or is not an escape % character,
  2. is not at the end of the format string, and
  3. precedes a sequence of characters that parses as a valid control specification.

A control specification usually takes the form:

 % ['-+ #0]* [0..9]* { . [0..9]* }+
                { [hlL] }+ [idfgGoxXeEcs]
There are variants of this basic form that are discussed below.

The format is composed of zero or more directives defined as follows:

  • ordinary characters, which are simply copied to the output stream;
  • escape sequences, which represent non-graphic characters; and
  • conversion specifications, each of which results in the fetching of zero or more arguments.

The results are undefined if there are insufficient arguments for the format. Usually an unchecked exception will be thrown. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored. In format strings containing the % form of conversion specifications, each argument in the argument list is used exactly once.

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion characer % is replaced by the sequence %n$, where n is a decimal integer giving the position of the argument in the argument list.

In format strings containing the %n$ form of conversion specifications, each argument in the argument list is used exactly once.

Escape Sequences

The following table lists escape sequences and associated actions on display devices capable of the action.
Sequence Name Description
\\backlashNone.
\aalertAttempts to alert the user through audible or visible notification.
\bbackspaceMoves the printing position to one column before the current position, unless the current position is the start of a line.
\fform-feedMoves the printing position to the initial printing position of the next logical page.
\nnewlineMoves the printing position to the start of the next line.
\rcarriage-returnMoves the printing position to the start of the current line.
\ttabMoves the printing position to the next implementation- defined horizontal tab position.
\vvertical-tabMoves the printing position to the start of the next implementation-defined vertical tab position.

Conversion Specifications

Each conversion specification is introduced by the percent sign character (%). After the character %, the following appear in sequence:

Zero or more flags (in any order), which modify the meaning of the conversion specification.

An optional minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces by default on the left; t will be padded on the right, if the left- adjustment flag (-), described below, is given to the field width. The field width takes the form of a decimal integer. If the conversion character is s, the field width is the the minimum number of characters to be printed.

An optional precision that gives the minumum number of digits to appear for the d, i, o, x or X conversions (the field is padded with leading zeros); the number of digits to appear after the radix character for the e, E, and f conversions, the maximum number of significant digits for the g and G conversions; or the maximum number of characters to be written from a string is s and S conversions. The precision takes the form of an optional decimal digit string, where a null digit string is treated as 0. If a precision appears with a c conversion character the precision is ignored.

An optional h specifies that a following d, i, o, x, or X conversion character applies to a type short argument (the argument will be promoted according to the integral promotions and its value converted to type short before printing).

An optional l (ell) specifies that a following d, i, o, x, or X conversion character applies to a type long argument.

A field width or precision may be indicated by an asterisk (*) instead of a digit string. In this case, an integer argument supplised the field width precision. The argument that is actually converted is not fetched until the conversion letter is seen, so the the arguments specifying field width or precision must appear before the argument (if any) to be converted. If the precision argument is negative, it will be changed to zero. A negative field width argument is taken as a - flag, followed by a positive field width.

In format strings containing the %n$ form of a conversion specification, a field width or precision may be indicated by the sequence *m$, where m is a decimal integer giving the position in the argument list (after the format argument) of an integer argument containing the field width or precision.

The format can contain either numbered argument specifications (that is, %n$ and *m$), or unnumbered argument specifications (that is % and *), but normally not both. The only exception to this is that %% can be mixed with the %n$ form. The results of mixing numbered and unnumbered argument specifications in a format string are undefined.

Flag Characters

The flags and their meanings are:

'
integer portion of the result of a decimal conversion (%i, %d, %f, %g, or %G) will be formatted with thousands' grouping characters. For other conversions the flag is ignored. The non-monetary grouping character is used.
-
result of the conversion is left-justified within the field. (It will be right-justified if this flag is not specified).
+
result of a signed conversion always begins with a sign (+ or -). (It will begin with a sign only when a negative value is converted if this flag is not specified.)
<space>
If the first character of a signed conversion is not a sign, a space character will be placed before the result. This means that if the space character and + flags both appear, the space flag will be ignored.
#
value is to be converted to an alternative form. For c, d, i, and s conversions, the flag has no effect. For o conversion, it increases the precision to force the first digit of the result to be a zero. For x or X conversion, a non-zero result has 0x or 0X prefixed to it, respectively. For e, E, f, g, and G conversions, the result always contains a radix character, even if no digits follow the radix character (normally, a decimal point appears in the result of these conversions only if a digit follows it). For g and G conversions, trailing zeros will not be removed from the result as they normally are.
0
d, i, o, x, X, e, E, f, g, and G conversions, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed. If the 0 and - flags both appear, the 0 flag is ignored. For d, i, o, x, and X conversions, if a precision is specified, the 0 flag will be ignored. For c conversions, the flag is ignored.

Conversion Characters

Each conversion character results in fetching zero or more arguments. The results are undefined if there are insufficient arguments for the format. Usually, an unchecked exception will be thrown. If the format is exhausted while arguments remain, the excess arguments are ignored.

The conversion characters and their meanings are:

d,i
The int argument is converted to a signed decimal in the style [-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it will be expanded with leading zeros. The default precision is 1. The result of converting 0 with an explicit precision of 0 is no characters.
o
The int argument is converted to unsigned octal format in the style ddddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it will be expanded with leading zeros. The default precision is 1. The result of converting 0 with an explicit precision of 0 is no characters.
x
The int argument is converted to unsigned hexadecimal format in the style dddd; the letters abcdef are used. The precision specifies the minimum numberof digits to appear; if the value being converted can be represented in fewer digits, it will be expanded with leading zeros. The default precision is 1. The result of converting 0 with an explicit precision of 0 is no characters.
X
Behaves the same as the x conversion character except that letters ABCDEF are used instead of abcdef.
f
The floating point number argument is written in decimal notation in the style [-]ddd.ddd, where the number of digits after the radix character (shown here as a decimal point) is equal to the precision specification. A Locale is used to determine the radix character to use in this format. If the precision is omitted from the argument, six digits are written after the radix character; if the precision is explicitly 0 and the # flag is not specified, no radix character appears. If a radix character appears, at least 1 digit appears before it. The value is rounded to the appropriate number of digits.
e,E
The floating point number argument is written in the style [-]d.ddde{+-}dd (the symbols {+-} indicate either a plus or minus sign), where there is one digit before the radix character (shown here as a decimal point) and the number of digits after it is equal to the precision. A Locale is used to determine the radix character to use in this format. When the precision is missing, six digits are written after the radix character; if the precision is 0 and the # flag is not specified, no radix character appears. The E conversion will produce a number with E instead of e introducing the exponent. The exponent always contains at least two digits. However, if the value to be written requires an exponent greater than two digits, additional exponent digits are written as necessary. The value is rounded to the appropriate number of digits.
g,G
The floating point number argument is written in style f or e (or in sytle E in the case of a G conversion character), with the precision specifying the number of significant digits. If the precision is zero, it is taken as one. The style used depends on the value converted: style e (or E) will be used only if the exponent resulting from the conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the result. A radix character appears only if it is followed by a digit.
c,C
The integer argument is converted to a char and the result is written.
s,S
The argument is taken to be a string and bytes from the string are written until the end of the string or the number of bytes indicated by the precision specification of the argument is reached. If the precision is omitted from the argument, it is taken to be infinite, so all characters up to the end of the string are written.
%
Write a % character; no argument is converted.

If a conversion specification does not match one of the above forms, an IllegalArgumentException is thrown and the instance of PrintfFormat is not created.

If a floating point value is the internal representation for infinity, the output is [+]Infinity, where Infinity is either Infinity or Inf, depending on the desired output string length. Printing of the sign follows the rules described above.

If a floating point value is the internal representation for "not-a-number," the output is [+]NaN. Printing of the sign follows the rules described above.

In no case does a non-existent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is simply expanded to contain the conversion result.

The behavior is like printf. One exception is that the minimum number of exponent digits is 3 instead of 2 for e and E formats when the optional L is used before the e, E, g, or G conversion character. The optional L does not imply conversion to a long long double.

The biggest divergence from the C printf specification is in the use of 16 bit characters. This allows the handling of characters beyond the small ASCII character set and allows the utility to interoperate correctly with the rest of the Java runtime environment.

Omissions from the C printf specification are numerous. All the known omissions are present because Java never uses bytes to represent characters and does not have pointers:

  • %c is the same as %C.
  • %s is the same as %S.
  • u, p, and n conversion characters.
  • %ws format.
  • h modifier applied to an n conversion character.
  • l (ell) modifier applied to the c, n, or s conversion characters.
  • ll (ell ell) modifier to d, i, o, u, x, or X conversion characters.
  • ll (ell ell) modifier to an n conversion character.
  • c, C, d,i,o,u,x, and X conversion characters apply to Byte, Character, Short, Integer, Long types.
  • f, e, E, g, and G conversion characters apply to Float and Double types.
  • s and S conversion characters apply to String types.
  • All other reference types can be formatted using the s or S conversion characters only.

Most of this specification is quoted from the Unix man page for the sprintf utility.

(c) 2000 Sun Microsystems, Inc.


Constructor Summary
PrintfFormat(java.util.Locale locale, java.lang.String fmtArg)
          Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings.
PrintfFormat(java.lang.String fmtArg)
          Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings.
 
Method Summary
 java.lang.String sprintf()
          Format nothing.
 java.lang.String sprintf(double x)
          Format a double.
 java.lang.String sprintf(int x)
          Format an int.
 java.lang.String sprintf(long x)
          Format an long.
 java.lang.String sprintf(java.lang.Object x)
          Format an Object.
 java.lang.String sprintf(java.lang.Object[] o)
          Format an array of objects.
 java.lang.String sprintf(java.lang.String x)
          Format a String.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

PrintfFormat

public PrintfFormat(java.lang.String fmtArg)
             throws java.lang.IllegalArgumentException
Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings. Control strings begin with unpaired percent signs. A pair of successive percent signs designates a single percent sign in the format.

Parameters:
fmtArg - Control string.
Throws:
java.lang.IllegalArgumentException - if the control string is null, zero length, or otherwise malformed.

PrintfFormat

public PrintfFormat(java.util.Locale locale,
                    java.lang.String fmtArg)
             throws java.lang.IllegalArgumentException
Constructs an array of control specifications possibly preceded, separated, or followed by ordinary strings. Control strings begin with unpaired percent signs. A pair of successive percent signs designates a single percent sign in the format.

Parameters:
fmtArg - Control string.
Throws:
java.lang.IllegalArgumentException - if the control string is null, zero length, or otherwise malformed.
Method Detail

sprintf

public java.lang.String sprintf(java.lang.Object[] o)
Format an array of objects. Byte, Short, Integer, Long, Float, Double, and Character arguments are treated as wrappers for primitive types.

Parameters:
o - The array of objects to format.
Returns:
The formatted String.

sprintf

public java.lang.String sprintf()
Format nothing. Just use the control string.

Returns:
the formatted String.

sprintf

public java.lang.String sprintf(int x)
                         throws java.lang.IllegalArgumentException
Format an int.

Parameters:
x - The int to format.
Returns:
The formatted String.
Throws:
java.lang.IllegalArgumentException - if the conversion character is f, e, E, g, G, s, or S.

sprintf

public java.lang.String sprintf(long x)
                         throws java.lang.IllegalArgumentException
Format an long.

Parameters:
x - The long to format.
Returns:
The formatted String.
Throws:
java.lang.IllegalArgumentException - if the conversion character is f, e, E, g, G, s, or S.

sprintf

public java.lang.String sprintf(double x)
                         throws java.lang.IllegalArgumentException
Format a double.

Parameters:
x - The double to format.
Returns:
The formatted String.
Throws:
java.lang.IllegalArgumentException - if the conversion character is c, C, s, S, d, d, x, X, or o.

sprintf

public java.lang.String sprintf(java.lang.String x)
                         throws java.lang.IllegalArgumentException
Format a String.

Parameters:
x - The String to format.
Returns:
The formatted String.
Throws:
java.lang.IllegalArgumentException - if the conversion character is neither s nor S.

sprintf

public java.lang.String sprintf(java.lang.Object x)
                         throws java.lang.IllegalArgumentException
Format an Object. Convert wrapper types to their primitive equivalents and call the appropriate internal formatting method. Convert Strings using an internal formatting method for Strings. Otherwise use the default formatter (use toString).

Parameters:
x - the Object to format.
Returns:
the formatted String.
Throws:
java.lang.IllegalArgumentException - if the conversion character is inappropriate for formatting an unwrapped value.


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/ReferenceMap.MapReference.html000066400000000000000000000204011210132627500316330ustar00rootroot00000000000000 ReferenceMap.MapReference (Sigar API)

org.hyperic.sigar.util
Interface ReferenceMap.MapReference

All Known Implementing Classes:
ReferenceMap.SoftValue, ReferenceMap.WeakValue
Enclosing class:
ReferenceMap

protected static interface ReferenceMap.MapReference


Method Summary
 java.lang.Object getKey()
           
 

Method Detail

getKey

java.lang.Object getKey()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/ReferenceMap.SoftValue.html000066400000000000000000000243371210132627500312230ustar00rootroot00000000000000 ReferenceMap.SoftValue (Sigar API)

org.hyperic.sigar.util
Class ReferenceMap.SoftValue

java.lang.Object
  extended by java.lang.ref.Reference<T>
      extended by java.lang.ref.SoftReference
          extended by org.hyperic.sigar.util.ReferenceMap.SoftValue
All Implemented Interfaces:
ReferenceMap.MapReference
Enclosing class:
ReferenceMap

protected static final class ReferenceMap.SoftValue
extends java.lang.ref.SoftReference
implements ReferenceMap.MapReference


Method Summary
 java.lang.Object getKey()
           
 
Methods inherited from class java.lang.ref.SoftReference
get
 
Methods inherited from class java.lang.ref.Reference
clear, enqueue, isEnqueued
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

getKey

public java.lang.Object getKey()
Specified by:
getKey in interface ReferenceMap.MapReference


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/ReferenceMap.WeakValue.html000066400000000000000000000270001210132627500311650ustar00rootroot00000000000000 ReferenceMap.WeakValue (Sigar API)

org.hyperic.sigar.util
Class ReferenceMap.WeakValue

java.lang.Object
  extended by java.lang.ref.Reference<T>
      extended by java.lang.ref.WeakReference
          extended by org.hyperic.sigar.util.ReferenceMap.WeakValue
All Implemented Interfaces:
ReferenceMap.MapReference
Enclosing class:
ReferenceMap

protected static final class ReferenceMap.WeakValue
extends java.lang.ref.WeakReference
implements ReferenceMap.MapReference


Constructor Summary
protected ReferenceMap.WeakValue(java.lang.Object key, java.lang.Object value, java.lang.ref.ReferenceQueue queue)
           
 
Method Summary
 java.lang.Object getKey()
           
 
Methods inherited from class java.lang.ref.Reference
clear, enqueue, get, isEnqueued
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ReferenceMap.WeakValue

protected ReferenceMap.WeakValue(java.lang.Object key,
                                 java.lang.Object value,
                                 java.lang.ref.ReferenceQueue queue)
Method Detail

getKey

public java.lang.Object getKey()
Specified by:
getKey in interface ReferenceMap.MapReference


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/ReferenceMap.html000066400000000000000000000507251210132627500273140ustar00rootroot00000000000000 ReferenceMap (Sigar API)

org.hyperic.sigar.util
Class ReferenceMap

java.lang.Object
  extended by java.util.AbstractMap
      extended by org.hyperic.sigar.util.ReferenceMap
All Implemented Interfaces:
java.util.Map
Direct Known Subclasses:
WeakReferenceMap

public class ReferenceMap
extends java.util.AbstractMap


Nested Class Summary
protected static interface ReferenceMap.MapReference
           
protected static class ReferenceMap.SoftValue
           
protected static class ReferenceMap.WeakValue
           
 
Nested classes/interfaces inherited from class java.util.AbstractMap
java.util.AbstractMap.SimpleEntry<K,V>, java.util.AbstractMap.SimpleImmutableEntry<K,V>
 
Nested classes/interfaces inherited from interface java.util.Map
java.util.Map.Entry<K,V>
 
Field Summary
protected  java.util.Map map
           
protected  java.lang.ref.ReferenceQueue queue
           
 
Constructor Summary
ReferenceMap()
           
ReferenceMap(java.util.Map map)
           
 
Method Summary
 void clear()
           
 java.util.Set entrySet()
           
 java.lang.Object get(java.lang.Object key)
           
static java.util.Map newInstance()
           
static java.util.Map newInstance(java.util.Map map)
           
protected  void poll()
           
 java.lang.Object put(java.lang.Object key, java.lang.Object value)
           
 java.lang.Object remove(java.lang.Object key)
           
 int size()
           
static java.util.Map synchronizedMap()
           
 
Methods inherited from class java.util.AbstractMap
clone, containsKey, containsValue, equals, hashCode, isEmpty, keySet, putAll, toString, values
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

queue

protected java.lang.ref.ReferenceQueue queue

map

protected java.util.Map map
Constructor Detail

ReferenceMap

public ReferenceMap()

ReferenceMap

public ReferenceMap(java.util.Map map)
Method Detail

synchronizedMap

public static java.util.Map synchronizedMap()

newInstance

public static java.util.Map newInstance()

newInstance

public static java.util.Map newInstance(java.util.Map map)

get

public java.lang.Object get(java.lang.Object key)
Specified by:
get in interface java.util.Map
Overrides:
get in class java.util.AbstractMap

put

public java.lang.Object put(java.lang.Object key,
                            java.lang.Object value)
Specified by:
put in interface java.util.Map
Overrides:
put in class java.util.AbstractMap

remove

public java.lang.Object remove(java.lang.Object key)
Specified by:
remove in interface java.util.Map
Overrides:
remove in class java.util.AbstractMap

clear

public void clear()
Specified by:
clear in interface java.util.Map
Overrides:
clear in class java.util.AbstractMap

size

public int size()
Specified by:
size in interface java.util.Map
Overrides:
size in class java.util.AbstractMap

entrySet

public java.util.Set entrySet()
Specified by:
entrySet in interface java.util.Map
Specified by:
entrySet in class java.util.AbstractMap

poll

protected void poll()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/WeakReferenceMap.html000066400000000000000000000366071210132627500301270ustar00rootroot00000000000000 WeakReferenceMap (Sigar API)

org.hyperic.sigar.util
Class WeakReferenceMap

java.lang.Object
  extended by java.util.AbstractMap
      extended by org.hyperic.sigar.util.ReferenceMap
          extended by org.hyperic.sigar.util.WeakReferenceMap
All Implemented Interfaces:
java.util.Map

public class WeakReferenceMap
extends ReferenceMap


Nested Class Summary
 
Nested classes/interfaces inherited from class org.hyperic.sigar.util.ReferenceMap
ReferenceMap.MapReference, ReferenceMap.SoftValue, ReferenceMap.WeakValue
 
Nested classes/interfaces inherited from class java.util.AbstractMap
java.util.AbstractMap.SimpleEntry<K,V>, java.util.AbstractMap.SimpleImmutableEntry<K,V>
 
Nested classes/interfaces inherited from interface java.util.Map
java.util.Map.Entry<K,V>
 
Field Summary
 
Fields inherited from class org.hyperic.sigar.util.ReferenceMap
map, queue
 
Constructor Summary
WeakReferenceMap()
           
 
Method Summary
 java.lang.Object put(java.lang.Object key, java.lang.Object value)
           
 
Methods inherited from class org.hyperic.sigar.util.ReferenceMap
clear, entrySet, get, newInstance, newInstance, poll, remove, size, synchronizedMap
 
Methods inherited from class java.util.AbstractMap
clone, containsKey, containsValue, equals, hashCode, isEmpty, keySet, putAll, toString, values
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

WeakReferenceMap

public WeakReferenceMap()
Method Detail

put

public java.lang.Object put(java.lang.Object key,
                            java.lang.Object value)
Specified by:
put in interface java.util.Map
Overrides:
put in class ReferenceMap


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/package-frame.html000066400000000000000000000040131210132627500274300ustar00rootroot00000000000000 org.hyperic.sigar.util (Sigar API) org.hyperic.sigar.util
Interfaces 
GetlineCompleter
ReferenceMap.MapReference
Classes 
Getline
IteratorIterator
PrintfFormat
ReferenceMap
ReferenceMap.SoftValue
ReferenceMap.WeakValue
WeakReferenceMap
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/package-summary.html000066400000000000000000000206651210132627500300460ustar00rootroot00000000000000 org.hyperic.sigar.util (Sigar API)

Package org.hyperic.sigar.util

Utility classes independent of Sigar.

See:
          Description

Interface Summary
GetlineCompleter  
ReferenceMap.MapReference  
 

Class Summary
Getline This class provides Emacs style key bindings, history and tab completion for command shell applications.
IteratorIterator Iterator for multiple Iterators.
PrintfFormat PrintfFormat allows the formatting of an array of objects embedded within a string.
ReferenceMap  
ReferenceMap.SoftValue  
ReferenceMap.WeakValue  
WeakReferenceMap  
 

Package org.hyperic.sigar.util Description

Utility classes independent of Sigar.



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/util/package-tree.html000066400000000000000000000177601210132627500273120ustar00rootroot00000000000000 org.hyperic.sigar.util Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar.util

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/000077500000000000000000000000001210132627500244055ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/ConnectParams.html000066400000000000000000000271341210132627500300370ustar00rootroot00000000000000 ConnectParams (Sigar API)

org.hyperic.sigar.vmware
Class ConnectParams

java.lang.Object
  extended by org.hyperic.sigar.vmware.ConnectParams

public class ConnectParams
extends java.lang.Object


Field Summary
static boolean LOADED
           
 
Constructor Summary
ConnectParams()
           
ConnectParams(java.lang.String host, int port, java.lang.String user, java.lang.String pass)
           
 
Method Summary
 void dispose()
           
protected  void finalize()
           
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOADED

public static final boolean LOADED
Constructor Detail

ConnectParams

public ConnectParams()

ConnectParams

public ConnectParams(java.lang.String host,
                     int port,
                     java.lang.String user,
                     java.lang.String pass)
Method Detail

dispose

public void dispose()

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/VM.html000066400000000000000000002113251210132627500256210ustar00rootroot00000000000000 VM (Sigar API)

org.hyperic.sigar.vmware
Class VM

java.lang.Object
  extended by org.hyperic.sigar.vmware.VM

public class VM
extends java.lang.Object


Field Summary
static java.lang.String ESX
           
static int EXECUTION_STATE_OFF
           
static int EXECUTION_STATE_ON
           
static int EXECUTION_STATE_STUCK
           
static int EXECUTION_STATE_SUSPENDED
           
static int EXECUTION_STATE_UNKNOWN
           
static java.lang.String[] EXECUTION_STATES
           
static java.lang.String GSX
           
static boolean LOADED
           
static int PERM_EXECUTE
           
static int PERM_READ
           
static int PERM_WRITE
           
static int PLATFORM_LINUX
           
static int PLATFORM_UNKNOWN
           
static int PLATFORM_VMNIX
           
static int PLATFORM_WINDOWS
           
static java.lang.String[] PLATFORMS
           
static int POWEROP_MODE_HARD
           
static int POWEROP_MODE_SOFT
           
static int POWEROP_MODE_TRYSOFT
           
static int PRODINFO_BUILD
           
static int PRODINFO_PLATFORM
           
static int PRODINFO_PRODUCT
           
static int PRODINFO_VERSION_MAJOR
           
static int PRODINFO_VERSION_MINOR
           
static int PRODINFO_VERSION_REVISION
           
static int PRODUCT_ESX
           
static int PRODUCT_GSX
           
static int PRODUCT_SERVER
           
static int PRODUCT_UNKNOWN
           
static int PRODUCT_WS
           
static java.lang.String[] PRODUCTS
           
static java.lang.String SERVER
           
 
Constructor Summary
VM()
           
 
Method Summary
 boolean canExecute()
           
 boolean canRead()
           
 boolean canWrite()
           
 void connect(ConnectParams params, java.lang.String config)
           
 void connect(ConnectParams params, java.lang.String config, boolean mks)
           
 void createSnapshot(java.lang.String name, java.lang.String description, boolean quiesce, boolean memory)
           
 void deviceConnect(java.lang.String device)
           
 void deviceDisconnect(java.lang.String device)
           
 boolean deviceIsConnected(java.lang.String device)
           
 void disconnect()
           
 void dispose()
           
protected  void finalize()
           
 java.lang.String getConfig(java.lang.String key)
           
 java.lang.String getDisplayName()
           
 int getExecutionState()
           
 java.lang.String getFullVersion()
           
 java.lang.String getGuestInfo(java.lang.String key)
           
 java.lang.String getGuestOS()
           
 int getHeartbeat()
           
 int getId()
           
 java.lang.String getMemSize()
           
 int getPermissions()
           
 java.lang.String getPermissionsString()
           
 long getPid()
           
 int getProductInfo(int type)
           
 java.lang.String getProductName()
           
 java.lang.String getProductPlatform()
           
 int getRemoteConnections()
           
 java.lang.String getResource(java.lang.String key)
           
 java.lang.String getRunAsUser()
           
 int getToolsLastActive()
           
 int getUptime()
           
 java.lang.String getVersion()
           
 boolean hasSnapshot()
           
 boolean isConnected()
           
 boolean isESX()
           
 boolean isGSX()
           
 boolean isOff()
           
 boolean isOn()
           
 boolean isStuck()
           
 boolean isSuspended()
           
 void removeAllSnapshots()
           
 void reset()
           
 void reset(int mode)
           
 void resume()
           
 void resume(int mode)
           
 void revertToSnapshot()
           
 void saveScreenshot(java.lang.String name)
           
 void setGuestInfo(java.lang.String key, java.lang.String value)
           
 void start()
           
 void start(int mode)
           
 void stop()
           
 void stop(int mode)
           
 void suspend()
           
 void suspend(int mode)
           
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

EXECUTION_STATE_ON

public static final int EXECUTION_STATE_ON
See Also:
Constant Field Values

EXECUTION_STATE_OFF

public static final int EXECUTION_STATE_OFF
See Also:
Constant Field Values

EXECUTION_STATE_SUSPENDED

public static final int EXECUTION_STATE_SUSPENDED
See Also:
Constant Field Values

EXECUTION_STATE_STUCK

public static final int EXECUTION_STATE_STUCK
See Also:
Constant Field Values

EXECUTION_STATE_UNKNOWN

public static final int EXECUTION_STATE_UNKNOWN
See Also:
Constant Field Values

EXECUTION_STATES

public static final java.lang.String[] EXECUTION_STATES

POWEROP_MODE_HARD

public static final int POWEROP_MODE_HARD
See Also:
Constant Field Values

POWEROP_MODE_SOFT

public static final int POWEROP_MODE_SOFT
See Also:
Constant Field Values

POWEROP_MODE_TRYSOFT

public static final int POWEROP_MODE_TRYSOFT
See Also:
Constant Field Values

PRODUCT_WS

public static final int PRODUCT_WS
See Also:
Constant Field Values

PRODUCT_GSX

public static final int PRODUCT_GSX
See Also:
Constant Field Values

PRODUCT_ESX

public static final int PRODUCT_ESX
See Also:
Constant Field Values

PRODUCT_SERVER

public static final int PRODUCT_SERVER
See Also:
Constant Field Values

PRODUCT_UNKNOWN

public static final int PRODUCT_UNKNOWN
See Also:
Constant Field Values

GSX

public static final java.lang.String GSX
See Also:
Constant Field Values

ESX

public static final java.lang.String ESX
See Also:
Constant Field Values

SERVER

public static final java.lang.String SERVER
See Also:
Constant Field Values

PRODUCTS

public static final java.lang.String[] PRODUCTS

PLATFORM_WINDOWS

public static final int PLATFORM_WINDOWS
See Also:
Constant Field Values

PLATFORM_LINUX

public static final int PLATFORM_LINUX
See Also:
Constant Field Values

PLATFORM_VMNIX

public static final int PLATFORM_VMNIX
See Also:
Constant Field Values

PLATFORM_UNKNOWN

public static final int PLATFORM_UNKNOWN
See Also:
Constant Field Values

PLATFORMS

public static final java.lang.String[] PLATFORMS

PRODINFO_PRODUCT

public static final int PRODINFO_PRODUCT
See Also:
Constant Field Values

PRODINFO_PLATFORM

public static final int PRODINFO_PLATFORM
See Also:
Constant Field Values

PRODINFO_BUILD

public static final int PRODINFO_BUILD
See Also:
Constant Field Values

PRODINFO_VERSION_MAJOR

public static final int PRODINFO_VERSION_MAJOR
See Also:
Constant Field Values

PRODINFO_VERSION_MINOR

public static final int PRODINFO_VERSION_MINOR
See Also:
Constant Field Values

PRODINFO_VERSION_REVISION

public static final int PRODINFO_VERSION_REVISION
See Also:
Constant Field Values

PERM_READ

public static final int PERM_READ
See Also:
Constant Field Values

PERM_WRITE

public static final int PERM_WRITE
See Also:
Constant Field Values

PERM_EXECUTE

public static final int PERM_EXECUTE
See Also:
Constant Field Values

LOADED

public static final boolean LOADED
Constructor Detail

VM

public VM()
Method Detail

connect

public void connect(ConnectParams params,
                    java.lang.String config,
                    boolean mks)
             throws VMwareException
Throws:
VMwareException

connect

public void connect(ConnectParams params,
                    java.lang.String config)
             throws VMwareException
Throws:
VMwareException

disconnect

public void disconnect()

isConnected

public boolean isConnected()

getExecutionState

public int getExecutionState()
                      throws VMwareException
Throws:
VMwareException

getRemoteConnections

public int getRemoteConnections()
                         throws VMwareException
Throws:
VMwareException

getUptime

public int getUptime()
              throws VMwareException
Throws:
VMwareException

getHeartbeat

public int getHeartbeat()
                 throws VMwareException
Throws:
VMwareException

getToolsLastActive

public int getToolsLastActive()
                       throws VMwareException
Throws:
VMwareException

getRunAsUser

public java.lang.String getRunAsUser()
                              throws VMwareException
Throws:
VMwareException

getPermissions

public int getPermissions()
                   throws VMwareException
Throws:
VMwareException

getPermissionsString

public java.lang.String getPermissionsString()

canRead

public boolean canRead()

canWrite

public boolean canWrite()

canExecute

public boolean canExecute()

getConfig

public java.lang.String getConfig(java.lang.String key)
                           throws VMwareException
Throws:
VMwareException

getResource

public java.lang.String getResource(java.lang.String key)
                             throws VMwareException
Throws:
VMwareException

getGuestInfo

public java.lang.String getGuestInfo(java.lang.String key)
                              throws VMwareException
Throws:
VMwareException

setGuestInfo

public void setGuestInfo(java.lang.String key,
                         java.lang.String value)
                  throws VMwareException
Throws:
VMwareException

getProductInfo

public int getProductInfo(int type)
                   throws VMwareException
Throws:
VMwareException

getPid

public long getPid()
            throws VMwareException
Throws:
VMwareException

getId

public int getId()
          throws VMwareException
Throws:
VMwareException

getVersion

public java.lang.String getVersion()
                            throws VMwareException
Throws:
VMwareException

getFullVersion

public java.lang.String getFullVersion()
                                throws VMwareException
Throws:
VMwareException

getDisplayName

public java.lang.String getDisplayName()

getGuestOS

public java.lang.String getGuestOS()

getMemSize

public java.lang.String getMemSize()

getProductName

public java.lang.String getProductName()

getProductPlatform

public java.lang.String getProductPlatform()

isOn

public boolean isOn()

isOff

public boolean isOff()

isSuspended

public boolean isSuspended()

isStuck

public boolean isStuck()

isESX

public boolean isESX()

isGSX

public boolean isGSX()

start

public void start(int mode)
           throws VMwareException
Throws:
VMwareException

start

public void start()
           throws VMwareException
Throws:
VMwareException

stop

public void stop(int mode)
          throws VMwareException
Throws:
VMwareException

stop

public void stop()
          throws VMwareException
Throws:
VMwareException

reset

public void reset(int mode)
           throws VMwareException
Throws:
VMwareException

reset

public void reset()
           throws VMwareException
Throws:
VMwareException

suspend

public void suspend(int mode)
             throws VMwareException
Throws:
VMwareException

suspend

public void suspend()
             throws VMwareException
Throws:
VMwareException

resume

public void resume(int mode)
            throws VMwareException
Throws:
VMwareException

resume

public void resume()
            throws VMwareException
Throws:
VMwareException

createSnapshot

public void createSnapshot(java.lang.String name,
                           java.lang.String description,
                           boolean quiesce,
                           boolean memory)
                    throws VMwareException
Throws:
VMwareException

revertToSnapshot

public void revertToSnapshot()
                      throws VMwareException
Throws:
VMwareException

removeAllSnapshots

public void removeAllSnapshots()
                        throws VMwareException
Throws:
VMwareException

hasSnapshot

public boolean hasSnapshot()
                    throws VMwareException
Throws:
VMwareException

saveScreenshot

public void saveScreenshot(java.lang.String name)
                    throws VMwareException
Throws:
VMwareException

deviceConnect

public void deviceConnect(java.lang.String device)
                   throws VMwareException
Throws:
VMwareException

deviceDisconnect

public void deviceDisconnect(java.lang.String device)
                      throws VMwareException
Throws:
VMwareException

deviceIsConnected

public boolean deviceIsConnected(java.lang.String device)
                          throws VMwareException
Throws:
VMwareException

dispose

public void dispose()

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/VMControlLibrary.html000066400000000000000000000346551210132627500305200ustar00rootroot00000000000000 VMControlLibrary (Sigar API)

org.hyperic.sigar.vmware
Class VMControlLibrary

java.lang.Object
  extended by org.hyperic.sigar.vmware.VMControlLibrary

public class VMControlLibrary
extends java.lang.Object


Field Summary
static java.lang.String PROP_VMCONTROL_SHLIB
           
static java.lang.String REGISTRY_ROOT
           
 
Constructor Summary
VMControlLibrary()
           
 
Method Summary
static java.lang.String getSharedLibrary()
           
static boolean isLoaded()
           
static void link()
           
static void link(java.lang.String name)
           
static void main(java.lang.String[] args)
           
static void setSharedLibrary(java.lang.String lib)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

REGISTRY_ROOT

public static final java.lang.String REGISTRY_ROOT
See Also:
Constant Field Values

PROP_VMCONTROL_SHLIB

public static final java.lang.String PROP_VMCONTROL_SHLIB
See Also:
Constant Field Values
Constructor Detail

VMControlLibrary

public VMControlLibrary()
Method Detail

getSharedLibrary

public static java.lang.String getSharedLibrary()

setSharedLibrary

public static void setSharedLibrary(java.lang.String lib)

link

public static void link()
                 throws java.io.IOException
Throws:
java.io.IOException

link

public static void link(java.lang.String name)
                 throws java.io.IOException
Throws:
java.io.IOException

isLoaded

public static boolean isLoaded()

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/VMwareException.html000066400000000000000000000256151210132627500303640ustar00rootroot00000000000000 VMwareException (Sigar API)

org.hyperic.sigar.vmware
Class VMwareException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.vmware.VMwareException
All Implemented Interfaces:
java.io.Serializable

public class VMwareException
extends SigarException

See Also:
Serialized Form

Constructor Summary
VMwareException()
           
VMwareException(java.lang.String msg)
           
 
Method Summary
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

VMwareException

public VMwareException()

VMwareException

public VMwareException(java.lang.String msg)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/VMwareServer.html000066400000000000000000000406321210132627500276700ustar00rootroot00000000000000 VMwareServer (Sigar API)

org.hyperic.sigar.vmware
Class VMwareServer

java.lang.Object
  extended by org.hyperic.sigar.vmware.VMwareServer

public class VMwareServer
extends java.lang.Object


Field Summary
static boolean LOADED
           
 
Constructor Summary
VMwareServer()
           
 
Method Summary
 boolean connect(ConnectParams params)
           
 void disconnect()
           
 void dispose()
           
 java.lang.String exec(java.lang.String xml)
           
protected  void finalize()
           
 java.util.List getRegisteredVmNames()
           
 java.lang.String getResource(java.lang.String key)
           
 boolean isConnected()
           
 boolean isRegistered(java.lang.String config)
           
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOADED

public static final boolean LOADED
Constructor Detail

VMwareServer

public VMwareServer()
Method Detail

connect

public boolean connect(ConnectParams params)
                throws VMwareException
Throws:
VMwareException

disconnect

public void disconnect()

isConnected

public boolean isConnected()

isRegistered

public boolean isRegistered(java.lang.String config)
                     throws VMwareException
Throws:
VMwareException

getRegisteredVmNames

public java.util.List getRegisteredVmNames()
                                    throws VMwareException
Throws:
VMwareException

getResource

public java.lang.String getResource(java.lang.String key)
                             throws VMwareException
Throws:
VMwareException

exec

public java.lang.String exec(java.lang.String xml)
                      throws VMwareException
Throws:
VMwareException

dispose

public void dispose()

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/package-frame.html000066400000000000000000000027711210132627500277650ustar00rootroot00000000000000 org.hyperic.sigar.vmware (Sigar API) org.hyperic.sigar.vmware
Classes 
ConnectParams
VM
VMControlLibrary
VMwareServer
Exceptions 
VMwareException
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/package-summary.html000066400000000000000000000160171210132627500303660ustar00rootroot00000000000000 org.hyperic.sigar.vmware (Sigar API)

Package org.hyperic.sigar.vmware

Class Summary
ConnectParams  
VM  
VMControlLibrary  
VMwareServer  
 

Exception Summary
VMwareException  
 



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/vmware/package-tree.html000066400000000000000000000155161210132627500276330ustar00rootroot00000000000000 org.hyperic.sigar.vmware Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar.vmware

Package Hierarchies:
All Packages

Class Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/000077500000000000000000000000001210132627500240465ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/EventLog.html000066400000000000000000000647561210132627500265010ustar00rootroot00000000000000 EventLog (Sigar API)

org.hyperic.sigar.win32
Class EventLog

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
      extended by org.hyperic.sigar.win32.EventLog

public class EventLog
extends Win32


Field Summary
static java.lang.String APPLICATION
           
static int EVENTLOG_AUDIT_FAILURE
           
static int EVENTLOG_AUDIT_SUCCESS
           
static int EVENTLOG_ERROR_TYPE
           
static int EVENTLOG_INFORMATION_TYPE
           
static int EVENTLOG_SUCCESS
           
static int EVENTLOG_WAIT_INFINITE
           
static int EVENTLOG_WARNING_TYPE
           
static java.lang.String SECURITY
           
static java.lang.String SYSTEM
           
 
Fields inherited from class org.hyperic.sigar.win32.Win32
EXE_EXT
 
Constructor Summary
EventLog()
          Create an event log.
 
Method Summary
 void close()
          Close the event log.
static java.lang.String[] getLogNames()
          Eventlog names are store in the registry under: SYSTEM\CurrentControlSet\Services\Eventlog This method returns the list of these entries.
 int getNewestRecord()
          Get the newest event log record.
 int getNumberOfRecords()
          Get the number of records for this event log
 int getOldestRecord()
          Get the oldest event log record
 void open(java.lang.String name)
          Open the event log.
 void openlog(java.lang.String name)
           
 EventLogRecord read(int recordOffset)
          Read an event log record.
 void waitForChange(int timeout)
          Wait for a change to the event log.
 
Methods inherited from class org.hyperic.sigar.win32.Win32
findExecutable, findScriptExecutable, getFileVersion, main
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SYSTEM

public static final java.lang.String SYSTEM
See Also:
Constant Field Values

APPLICATION

public static final java.lang.String APPLICATION
See Also:
Constant Field Values

SECURITY

public static final java.lang.String SECURITY
See Also:
Constant Field Values

EVENTLOG_SUCCESS

public static final int EVENTLOG_SUCCESS
See Also:
Constant Field Values

EVENTLOG_ERROR_TYPE

public static final int EVENTLOG_ERROR_TYPE
See Also:
Constant Field Values

EVENTLOG_WARNING_TYPE

public static final int EVENTLOG_WARNING_TYPE
See Also:
Constant Field Values

EVENTLOG_INFORMATION_TYPE

public static final int EVENTLOG_INFORMATION_TYPE
See Also:
Constant Field Values

EVENTLOG_AUDIT_SUCCESS

public static final int EVENTLOG_AUDIT_SUCCESS
See Also:
Constant Field Values

EVENTLOG_AUDIT_FAILURE

public static final int EVENTLOG_AUDIT_FAILURE
See Also:
Constant Field Values

EVENTLOG_WAIT_INFINITE

public static final int EVENTLOG_WAIT_INFINITE
See Also:
Constant Field Values
Constructor Detail

EventLog

public EventLog()
Create an event log.

Method Detail

open

public void open(java.lang.String name)
          throws Win32Exception
Open the event log. This must be done before any other operation.

Parameters:
name - Name of the event log to open. For example: "Application", "System" or "Security".
Throws:
Win32Exception - If opening the event log fails.

openlog

public void openlog(java.lang.String name)
             throws Win32Exception
Throws:
Win32Exception

close

public void close()
           throws Win32Exception
Close the event log.

Throws:
Win32Excepion - If closing of the event log fails.
Win32Exception

getNumberOfRecords

public int getNumberOfRecords()
                       throws Win32Exception
Get the number of records for this event log

Throws:
Win32Exception - If the event log is not open

getOldestRecord

public int getOldestRecord()
                    throws Win32Exception
Get the oldest event log record

Throws:
Win32Exception - If the event log is not open

getNewestRecord

public int getNewestRecord()
                    throws Win32Exception
Get the newest event log record.

Throws:
Win32Exception - If the event log is not open

read

public EventLogRecord read(int recordOffset)
                    throws Win32Exception
Read an event log record. This method only support the EVENTLOG_SEEK_READ flag, no sequential reading is currently supported.

Parameters:
recordOffset - The record offset to read.
Throws:
Win32Exception - If the event log is not open, or if the specified record could not be found

waitForChange

public void waitForChange(int timeout)
                   throws Win32Exception
Wait for a change to the event log. This function will return on event log change, or when the timeout pops. Windows PulseEvent will fire no more than once per 5 seconds, so multiple events may occur before the application is notified.

Parameters:
timeout - Time to wait in milliseconds.
Throws:
Win32Exception - If the event log is not open, or there is an error waiting for the the event.

getLogNames

public static java.lang.String[] getLogNames()
Eventlog names are store in the registry under: SYSTEM\CurrentControlSet\Services\Eventlog This method returns the list of these entries.

Returns:
All Eventlog names


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/EventLogNotification.html000066400000000000000000000220721210132627500310310ustar00rootroot00000000000000 EventLogNotification (Sigar API)

org.hyperic.sigar.win32
Interface EventLogNotification


public interface EventLogNotification

Register for event log notifications.


Method Summary
 void handleNotification(EventLogRecord event)
          Called if matches() returns true
 boolean matches(EventLogRecord event)
          Determine if we want to handle this event.
 

Method Detail

matches

boolean matches(EventLogRecord event)
Determine if we want to handle this event.


handleNotification

void handleNotification(EventLogRecord event)
Called if matches() returns true



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/EventLogRecord.html000066400000000000000000000417051210132627500276250ustar00rootroot00000000000000 EventLogRecord (Sigar API)

org.hyperic.sigar.win32
Class EventLogRecord

java.lang.Object
  extended by org.hyperic.sigar.win32.EventLogRecord

public class EventLogRecord
extends java.lang.Object

Class to represent event log records


Method Summary
 short getCategory()
          Get the category for this event.
 java.lang.String getCategoryString()
          Get the formatted string for the category.
 java.lang.String getComputerName()
          Get the machine name where the event was generated
 long getEventId()
          Event identifier.
 short getEventType()
          Return the event type.
 java.lang.String getEventTypeString()
           
 java.lang.String getLogName()
           
 java.lang.String getMessage()
          Get the message for the event.
 long getRecordNumber()
           
 java.lang.String getSource()
          Get the application which triggered the event
 java.lang.String getStringData()
          Deprecated.  
 long getTimeGenerated()
          Get the time at which this entry was submitted.
 long getTimeWritten()
          Get the time at which this entry was received by the service to be written to the logfile.
 java.lang.String getUser()
          Get the user who generated the event.
 java.lang.String toString()
          For debugging
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Method Detail

getLogName

public java.lang.String getLogName()
Returns:
Event log name which generated the event

getRecordNumber

public long getRecordNumber()

getTimeGenerated

public long getTimeGenerated()
Get the time at which this entry was submitted. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970, Universal Coordinated Time.


getTimeWritten

public long getTimeWritten()
Get the time at which this entry was received by the service to be written to the logfile. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970, Universal Coordinated Time.


getEventId

public long getEventId()
Event identifier. The value is specific to the event source for the event, and is used with source name to locate a description string in the message file for the event source. XXX: This is probably not needed


getEventType

public short getEventType()
Return the event type. See the EVENTLOG_* constants in the EventLog class


getEventTypeString

public java.lang.String getEventTypeString()

getCategory

public short getCategory()
Get the category for this event. The meaning of this value depends on the event source.


getCategoryString

public java.lang.String getCategoryString()
Get the formatted string for the category.


getSource

public java.lang.String getSource()
Get the application which triggered the event


getComputerName

public java.lang.String getComputerName()
Get the machine name where the event was generated


getUser

public java.lang.String getUser()
Get the user who generated the event. May be null if no user is associated with the event.


getMessage

public java.lang.String getMessage()
Get the message for the event.


getStringData

public java.lang.String getStringData()
Deprecated. 


toString

public java.lang.String toString()
For debugging

Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/EventLogThread.html000066400000000000000000000436261210132627500276220ustar00rootroot00000000000000 EventLogThread (Sigar API)

org.hyperic.sigar.win32
Class EventLogThread

java.lang.Object
  extended by org.hyperic.sigar.win32.EventLogThread
All Implemented Interfaces:
java.lang.Runnable

public class EventLogThread
extends java.lang.Object
implements java.lang.Runnable

A simple thread that runs forever monitoring the event log.


Field Summary
static int DEFAULT_INTERVAL
           
 
Constructor Summary
EventLogThread()
           
 
Method Summary
 void add(EventLogNotification notifier)
           
static void closeInstances()
           
 void die()
           
 void doStart()
           
 void doStop()
           
static EventLogThread getInstance()
          Deprecated.  
static EventLogThread getInstance(java.lang.String name)
           
static void main(java.lang.String[] args)
           
 void remove(EventLogNotification notifier)
           
 void run()
           
 void setInterval(long interval)
           
 void setLogName(java.lang.String logName)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_INTERVAL

public static final int DEFAULT_INTERVAL
See Also:
Constant Field Values
Constructor Detail

EventLogThread

public EventLogThread()
Method Detail

getInstance

public static EventLogThread getInstance()
Deprecated. 


getInstance

public static EventLogThread getInstance(java.lang.String name)

closeInstances

public static void closeInstances()

setInterval

public void setInterval(long interval)

setLogName

public void setLogName(java.lang.String logName)

doStart

public void doStart()

doStop

public void doStop()

add

public void add(EventLogNotification notifier)

remove

public void remove(EventLogNotification notifier)

run

public void run()
Specified by:
run in interface java.lang.Runnable

die

public void die()

main

public static void main(java.lang.String[] args)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/FileVersion.html000066400000000000000000000322001210132627500271560ustar00rootroot00000000000000 FileVersion (Sigar API)

org.hyperic.sigar.win32
Class FileVersion

java.lang.Object
  extended by org.hyperic.sigar.win32.FileVersion

public class FileVersion
extends java.lang.Object


Method Summary
 int getFileBuild()
           
 int getFileMajor()
           
 int getFileMinor()
           
 int getFileRevision()
           
 java.lang.String getFileVersion()
           
 java.util.Map getInfo()
           
 int getProductBuild()
           
 int getProductMajor()
           
 int getProductMinor()
           
 int getProductRevision()
           
 java.lang.String getProductVersion()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

getProductMajor

public int getProductMajor()

getProductMinor

public int getProductMinor()

getProductBuild

public int getProductBuild()

getProductRevision

public int getProductRevision()

getFileMajor

public int getFileMajor()

getFileMinor

public int getFileMinor()

getFileBuild

public int getFileBuild()

getFileRevision

public int getFileRevision()

getInfo

public java.util.Map getInfo()

getProductVersion

public java.lang.String getProductVersion()

getFileVersion

public java.lang.String getFileVersion()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/LocaleInfo.html000066400000000000000000000503671210132627500267620ustar00rootroot00000000000000 LocaleInfo (Sigar API)

org.hyperic.sigar.win32
Class LocaleInfo

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
      extended by org.hyperic.sigar.win32.LocaleInfo

public class LocaleInfo
extends Win32


Field Summary
static int LANG_ENGLISH
          English primary language id
static int LOCALE_SENGCOUNTRY
          English name of country
static int LOCALE_SENGLANGUAGE
          English name of language
 
Fields inherited from class org.hyperic.sigar.win32.Win32
EXE_EXT
 
Constructor Summary
LocaleInfo()
           
LocaleInfo(int id)
           
LocaleInfo(java.lang.Integer id)
           
LocaleInfo(int primary, int sub)
           
 
Method Summary
 java.lang.String getAttribute(int attr)
           
 java.lang.String getEnglishCountryName()
           
 java.lang.String getEnglishLanguageName()
           
 int getId()
           
 java.lang.String getPerflibLangId()
           
 int getPrimaryLangId()
           
 int getSubLangId()
           
static boolean isEnglish()
           
static int makeLangId(int primary, int sub)
           
 void setId(int id)
           
 java.lang.String toString()
           
 
Methods inherited from class org.hyperic.sigar.win32.Win32
findExecutable, findScriptExecutable, getFileVersion, main
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

LOCALE_SENGLANGUAGE

public static final int LOCALE_SENGLANGUAGE
English name of language

See Also:
Constant Field Values

LOCALE_SENGCOUNTRY

public static final int LOCALE_SENGCOUNTRY
English name of country

See Also:
Constant Field Values

LANG_ENGLISH

public static final int LANG_ENGLISH
English primary language id

See Also:
Constant Field Values
Constructor Detail

LocaleInfo

public LocaleInfo()

LocaleInfo

public LocaleInfo(java.lang.Integer id)

LocaleInfo

public LocaleInfo(int id)

LocaleInfo

public LocaleInfo(int primary,
                  int sub)
Method Detail

makeLangId

public static final int makeLangId(int primary,
                                   int sub)

getId

public int getId()

setId

public void setId(int id)

getPrimaryLangId

public int getPrimaryLangId()

getSubLangId

public int getSubLangId()

isEnglish

public static boolean isEnglish()

getPerflibLangId

public java.lang.String getPerflibLangId()

getAttribute

public java.lang.String getAttribute(int attr)

getEnglishLanguageName

public java.lang.String getEnglishLanguageName()

getEnglishCountryName

public java.lang.String getEnglishCountryName()

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/MetaBase.html000066400000000000000000000632171210132627500264260ustar00rootroot00000000000000 MetaBase (Sigar API)

org.hyperic.sigar.win32
Class MetaBase

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
      extended by org.hyperic.sigar.win32.MetaBase

public class MetaBase
extends Win32


Field Summary
static int MD_CONNECTION_TIMEOUT
           
static int MD_DOWNLEVEL_ADMIN_INSTANCE
           
static int MD_IISADMIN_EXTENSIONS
           
static int MD_LEVELS_TO_SCAN
           
static int MD_LOGFILEDIRECTORY
           
static int MD_MAX_CONNECTIONS
           
static int MD_MAX_ENDPOINT_CONNECTIONS
           
static int MD_SECURE_BINDINGS
           
static int MD_SERVER_AUTOSTART
           
static int MD_SERVER_BINDINGS
           
static int MD_SERVER_COMMAND
           
static int MD_SERVER_COMMENT
           
static int MD_SERVER_CONFIGURATION_INFO
           
static int MD_SERVER_LISTEN_BACKLOG
           
static int MD_SERVER_LISTEN_TIMEOUT
           
static int MD_SERVER_SIZE
           
static int MD_SERVER_STATE
           
 
Fields inherited from class org.hyperic.sigar.win32.Win32
EXE_EXT
 
Constructor Summary
MetaBase()
           
 
Method Summary
 void close()
           
 int getIntValue(int datakey)
           
 int getIntValue(int datakey, int defaultValue)
           
 java.lang.String[] getMultiStringValue(int datakey)
           
 java.lang.String getStringValue(int datakey)
           
 java.lang.String getStringValue(int datakey, java.lang.String defaultValue)
           
 java.lang.String[] getSubKeyNames()
           
static void main(java.lang.String[] args)
           
 void OpenSubKey(java.lang.String subkey)
           
 
Methods inherited from class org.hyperic.sigar.win32.Win32
findExecutable, findScriptExecutable, getFileVersion
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MD_SERVER_COMMAND

public static int MD_SERVER_COMMAND

MD_CONNECTION_TIMEOUT

public static int MD_CONNECTION_TIMEOUT

MD_MAX_CONNECTIONS

public static int MD_MAX_CONNECTIONS

MD_SERVER_COMMENT

public static int MD_SERVER_COMMENT

MD_SERVER_STATE

public static int MD_SERVER_STATE

MD_SERVER_AUTOSTART

public static int MD_SERVER_AUTOSTART

MD_SERVER_SIZE

public static int MD_SERVER_SIZE

MD_SERVER_LISTEN_BACKLOG

public static int MD_SERVER_LISTEN_BACKLOG

MD_SERVER_LISTEN_TIMEOUT

public static int MD_SERVER_LISTEN_TIMEOUT

MD_DOWNLEVEL_ADMIN_INSTANCE

public static int MD_DOWNLEVEL_ADMIN_INSTANCE

MD_LEVELS_TO_SCAN

public static int MD_LEVELS_TO_SCAN

MD_SERVER_BINDINGS

public static int MD_SERVER_BINDINGS

MD_MAX_ENDPOINT_CONNECTIONS

public static int MD_MAX_ENDPOINT_CONNECTIONS

MD_SERVER_CONFIGURATION_INFO

public static int MD_SERVER_CONFIGURATION_INFO

MD_IISADMIN_EXTENSIONS

public static int MD_IISADMIN_EXTENSIONS

MD_LOGFILEDIRECTORY

public static int MD_LOGFILEDIRECTORY

MD_SECURE_BINDINGS

public static int MD_SECURE_BINDINGS
Constructor Detail

MetaBase

public MetaBase()
Method Detail

close

public void close()

OpenSubKey

public void OpenSubKey(java.lang.String subkey)

getIntValue

public int getIntValue(int datakey)
                throws Win32Exception
Throws:
Win32Exception

getIntValue

public int getIntValue(int datakey,
                       int defaultValue)

getStringValue

public java.lang.String getStringValue(int datakey)
                                throws Win32Exception
Throws:
Win32Exception

getStringValue

public java.lang.String getStringValue(int datakey,
                                       java.lang.String defaultValue)

getMultiStringValue

public java.lang.String[] getMultiStringValue(int datakey)
                                       throws Win32Exception
Throws:
Win32Exception

getSubKeyNames

public java.lang.String[] getSubKeyNames()

main

public static void main(java.lang.String[] args)


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/Pdh.html000066400000000000000000001047361210132627500254620ustar00rootroot00000000000000 Pdh (Sigar API)

org.hyperic.sigar.win32
Class Pdh

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
      extended by org.hyperic.sigar.win32.Pdh

public class Pdh
extends Win32


Field Summary
static int BAD_COUNTERNAME
          Unable to parse the counter path.
static int NO_COUNTER
          The specified counter could not be found.
static int NO_INSTANCE
          The specified instance is not present.
static int NO_MACHINE
          Unable to connect to specified machine or machine is off line.
static int NO_OBJECT
          The specified object is not found on the system.
static long PERF_TYPE_COUNTER
           
static long PERF_TYPE_NUMBER
           
static long PERF_TYPE_TEXT
           
static long PERF_TYPE_ZERO
           
static java.lang.String PERFLIB_KEY
           
static int VALID_DATA
          The returned data is valid.
 
Fields inherited from class org.hyperic.sigar.win32.Win32
EXE_EXT
 
Constructor Summary
Pdh()
           
Pdh(java.lang.String hostName)
           
 
Method Summary
 void close()
           
static void enableTranslation()
           
protected  void finalize()
           
static java.lang.String getCounterName(int index)
           
 long getCounterType(java.lang.String path)
           
 java.lang.String getDescription(java.lang.String path)
           
static java.util.Map getEnglishPerflibCounterMap()
           
 double getFormattedValue(java.lang.String path)
           
static java.lang.String[] getInstances(java.lang.String path)
           
static java.lang.String[] getKeys(java.lang.String path)
           
static java.lang.String[] getObjects()
           
static java.util.Map getPerflibCounterMap(LocaleInfo locale)
           
 double getRawValue(java.lang.String path)
           
 double getSingleValue(java.lang.String path)
          Deprecated.  
static void main(java.lang.String[] args)
          Main method for dumping the entire PDH Usage: Pdh [OPTION] Show information from the Windows PDH -v, --values include key values [default=no] --object=NAME only print info on this object --contains=NAME only print info on objects that contain this substring -i, --instance show instances [default=no] -k, --keys show keys [default=no] -h, --help display help and exit
static java.lang.String translate(java.lang.String path)
           
static int validate(java.lang.String path)
           
 
Methods inherited from class org.hyperic.sigar.win32.Win32
findExecutable, findScriptExecutable, getFileVersion
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

VALID_DATA

public static final int VALID_DATA
The returned data is valid.

See Also:
Constant Field Values

NO_INSTANCE

public static final int NO_INSTANCE
The specified instance is not present.

See Also:
Constant Field Values

NO_COUNTER

public static final int NO_COUNTER
The specified counter could not be found.

See Also:
Constant Field Values

NO_OBJECT

public static final int NO_OBJECT
The specified object is not found on the system.

See Also:
Constant Field Values

NO_MACHINE

public static final int NO_MACHINE
Unable to connect to specified machine or machine is off line.

See Also:
Constant Field Values

BAD_COUNTERNAME

public static final int BAD_COUNTERNAME
Unable to parse the counter path.

See Also:
Constant Field Values

PERFLIB_KEY

public static final java.lang.String PERFLIB_KEY
See Also:
Constant Field Values

PERF_TYPE_NUMBER

public static final long PERF_TYPE_NUMBER
See Also:
Constant Field Values

PERF_TYPE_COUNTER

public static final long PERF_TYPE_COUNTER
See Also:
Constant Field Values

PERF_TYPE_TEXT

public static final long PERF_TYPE_TEXT
See Also:
Constant Field Values

PERF_TYPE_ZERO

public static final long PERF_TYPE_ZERO
See Also:
Constant Field Values
Constructor Detail

Pdh

public Pdh()
    throws Win32Exception
Throws:
Win32Exception

Pdh

public Pdh(java.lang.String hostName)
    throws Win32Exception
Throws:
Win32Exception
Method Detail

finalize

protected void finalize()
                 throws java.lang.Throwable
Overrides:
finalize in class java.lang.Object
Throws:
java.lang.Throwable

close

public void close()
           throws Win32Exception
Throws:
Win32Exception

enableTranslation

public static void enableTranslation()
                              throws Win32Exception
Throws:
Win32Exception

getEnglishPerflibCounterMap

public static java.util.Map getEnglishPerflibCounterMap()
                                                 throws Win32Exception
Throws:
Win32Exception

getPerflibCounterMap

public static java.util.Map getPerflibCounterMap(LocaleInfo locale)
                                          throws Win32Exception
Throws:
Win32Exception

getCounterName

public static java.lang.String getCounterName(int index)
                                       throws Win32Exception
Throws:
Win32Exception

getSingleValue

public double getSingleValue(java.lang.String path)
                      throws Win32Exception
Deprecated. 

Throws:
Win32Exception
See Also:
getRawValue(String path)

getRawValue

public double getRawValue(java.lang.String path)
                   throws Win32Exception
Throws:
Win32Exception

getFormattedValue

public double getFormattedValue(java.lang.String path)
                         throws Win32Exception
Throws:
Win32Exception

translate

public static java.lang.String translate(java.lang.String path)
                                  throws Win32Exception
Throws:
Win32Exception

getDescription

public java.lang.String getDescription(java.lang.String path)
                                throws Win32Exception
Throws:
Win32Exception

getCounterType

public long getCounterType(java.lang.String path)
                    throws Win32Exception
Throws:
Win32Exception

getInstances

public static java.lang.String[] getInstances(java.lang.String path)
                                       throws Win32Exception
Throws:
Win32Exception

getKeys

public static java.lang.String[] getKeys(java.lang.String path)
                                  throws Win32Exception
Throws:
Win32Exception

getObjects

public static java.lang.String[] getObjects()
                                     throws Win32Exception
Throws:
Win32Exception

validate

public static final int validate(java.lang.String path)

main

public static void main(java.lang.String[] args)
Main method for dumping the entire PDH Usage: Pdh [OPTION] Show information from the Windows PDH -v, --values include key values [default=no] --object=NAME only print info on this object --contains=NAME only print info on objects that contain this substring -i, --instance show instances [default=no] -k, --keys show keys [default=no] -h, --help display help and exit



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/RegistryKey.html000066400000000000000000000667271210132627500272370ustar00rootroot00000000000000 RegistryKey (Sigar API)

org.hyperic.sigar.win32
Class RegistryKey

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
      extended by org.hyperic.sigar.win32.RegistryKey

public class RegistryKey
extends Win32


Field Summary
static RegistryKey ClassesRoot
          HKEY_CLASSES_ROOT
static RegistryKey CurrentUser
          HKEY_CURRENT_USER
static RegistryKey LocalMachine
          HKEY_LOCAL_MACHINE
 
Fields inherited from class org.hyperic.sigar.win32.Win32
EXE_EXT
 
Method Summary
 void close()
           
 RegistryKey createSubKey(java.lang.String subkey)
           
 RegistryKey createSubKey(java.lang.String subkey, int value)
           
 RegistryKey createSubKey(java.lang.String subkey, java.lang.String value)
           
 void deleteSubKey(java.lang.String subkey)
           
 void deleteSubKeyTree(java.lang.String subkey)
           
 void deleteValue(java.lang.String name)
           
protected  void finalize()
           
 void flush()
           
 int getIntValue(java.lang.String name)
           
 int getIntValue(java.lang.String name, int defaultValue)
           
 void getMultiStringValue(java.lang.String name, java.util.List values)
           
 java.lang.String getStringValue(java.lang.String name)
           
 java.lang.String getStringValue(java.lang.String name, java.lang.String defaultValue)
           
 java.lang.String getSubKeyName()
           
 java.lang.String[] getSubKeyNames()
           
 java.lang.String[] getValueNames()
           
 RegistryKey openSubKey(java.lang.String subkey)
           
 void setIntValue(java.lang.String name, int value)
           
 void setStringValue(java.lang.String name, java.lang.String value)
           
 
Methods inherited from class org.hyperic.sigar.win32.Win32
findExecutable, findScriptExecutable, getFileVersion, main
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ClassesRoot

public static final RegistryKey ClassesRoot
HKEY_CLASSES_ROOT


CurrentUser

public static final RegistryKey CurrentUser
HKEY_CURRENT_USER


LocalMachine

public static final RegistryKey LocalMachine
HKEY_LOCAL_MACHINE

Method Detail

close

public void close()

createSubKey

public RegistryKey createSubKey(java.lang.String subkey)

getSubKeyName

public java.lang.String getSubKeyName()

createSubKey

public RegistryKey createSubKey(java.lang.String subkey,
                                java.lang.String value)
                         throws Win32Exception
Throws:
Win32Exception

createSubKey

public RegistryKey createSubKey(java.lang.String subkey,
                                int value)
                         throws Win32Exception
Throws:
Win32Exception

deleteSubKey

public void deleteSubKey(java.lang.String subkey)

deleteSubKeyTree

public void deleteSubKeyTree(java.lang.String subkey)

deleteValue

public void deleteValue(java.lang.String name)

flush

public void flush()

getIntValue

public int getIntValue(java.lang.String name)
                throws Win32Exception
Throws:
Win32Exception

getIntValue

public int getIntValue(java.lang.String name,
                       int defaultValue)

getStringValue

public java.lang.String getStringValue(java.lang.String name)
                                throws Win32Exception
Throws:
Win32Exception

getMultiStringValue

public void getMultiStringValue(java.lang.String name,
                                java.util.List values)
                         throws Win32Exception
Throws:
Win32Exception

getStringValue

public java.lang.String getStringValue(java.lang.String name,
                                       java.lang.String defaultValue)

getSubKeyNames

public java.lang.String[] getSubKeyNames()

getValueNames

public java.lang.String[] getValueNames()

openSubKey

public RegistryKey openSubKey(java.lang.String subkey)
                       throws Win32Exception
Throws:
Win32Exception

setIntValue

public void setIntValue(java.lang.String name,
                        int value)
                 throws Win32Exception
Throws:
Win32Exception

setStringValue

public void setStringValue(java.lang.String name,
                           java.lang.String value)
                    throws Win32Exception
Throws:
Win32Exception

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/Service.html000066400000000000000000001043551210132627500263440ustar00rootroot00000000000000 Service (Sigar API)

org.hyperic.sigar.win32
Class Service

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
      extended by org.hyperic.sigar.win32.Service

public class Service
extends Win32


Field Summary
static int SERVICE_CONTINUE_PENDING
           
static int SERVICE_PAUSE_PENDING
           
static int SERVICE_PAUSED
           
static int SERVICE_RUNNING
           
static int SERVICE_START_PENDING
           
static int SERVICE_STOP_PENDING
           
static int SERVICE_STOPPED
           
 
Fields inherited from class org.hyperic.sigar.win32.Win32
EXE_EXT
 
Constructor Summary
Service(java.lang.String serviceName)
           
 
Method Summary
 void close()
           
static Service create(ServiceConfig config)
           
 void delete()
           
protected  void finalize()
           
 ServiceConfig getConfig()
           
static java.util.List getServiceConfigs(Sigar sigar, java.lang.String exe)
           
static java.util.List getServiceConfigs(java.lang.String exe)
          Deprecated.  
static java.util.List getServiceNames()
           
static java.util.List getServiceNames(Sigar sigar, java.lang.String ptql)
           
 int getStatus()
           
 java.lang.String getStatusString()
           
 void list(java.io.PrintStream out)
           
static void main(java.lang.String[] args)
           
 void pause()
           
 void pause(long timeout)
           
 void resume()
           
 void setDescription(java.lang.String description)
           
 void start()
           
 void start(long timeout)
           
 int status()
          Deprecated.  
 void stop()
           
 void stop(long timeout)
           
 void stopAndWait(long timeout)
          Deprecated.  
 
Methods inherited from class org.hyperic.sigar.win32.Win32
findExecutable, findScriptExecutable, getFileVersion
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SERVICE_STOPPED

public static final int SERVICE_STOPPED
See Also:
Constant Field Values

SERVICE_START_PENDING

public static final int SERVICE_START_PENDING
See Also:
Constant Field Values

SERVICE_STOP_PENDING

public static final int SERVICE_STOP_PENDING
See Also:
Constant Field Values

SERVICE_RUNNING

public static final int SERVICE_RUNNING
See Also:
Constant Field Values

SERVICE_CONTINUE_PENDING

public static final int SERVICE_CONTINUE_PENDING
See Also:
Constant Field Values

SERVICE_PAUSE_PENDING

public static final int SERVICE_PAUSE_PENDING
See Also:
Constant Field Values

SERVICE_PAUSED

public static final int SERVICE_PAUSED
See Also:
Constant Field Values
Constructor Detail

Service

public Service(java.lang.String serviceName)
        throws Win32Exception
Throws:
Win32Exception
Method Detail

getServiceNames

public static java.util.List getServiceNames(Sigar sigar,
                                             java.lang.String ptql)
                                      throws Win32Exception
Throws:
Win32Exception

getServiceNames

public static java.util.List getServiceNames()
                                      throws Win32Exception
Throws:
Win32Exception

getServiceConfigs

public static java.util.List getServiceConfigs(Sigar sigar,
                                               java.lang.String exe)
                                        throws Win32Exception
Throws:
Win32Exception

getServiceConfigs

public static java.util.List getServiceConfigs(java.lang.String exe)
                                        throws Win32Exception
Deprecated. 

Throws:
Win32Exception

finalize

protected void finalize()
Overrides:
finalize in class java.lang.Object

close

public void close()

create

public static Service create(ServiceConfig config)
                      throws Win32Exception
Throws:
Win32Exception

delete

public void delete()
            throws Win32Exception
Throws:
Win32Exception

setDescription

public void setDescription(java.lang.String description)

status

public int status()
Deprecated. 

See Also:
getStatus()

getStatus

public int getStatus()

getStatusString

public java.lang.String getStatusString()

stop

public void stop()
          throws Win32Exception
Throws:
Win32Exception

stopAndWait

public void stopAndWait(long timeout)
                 throws Win32Exception
Deprecated. 

Throws:
Win32Exception

stop

public void stop(long timeout)
          throws Win32Exception
Throws:
Win32Exception

start

public void start()
           throws Win32Exception
Throws:
Win32Exception

start

public void start(long timeout)
           throws Win32Exception
Throws:
Win32Exception

pause

public void pause()
           throws Win32Exception
Throws:
Win32Exception

pause

public void pause(long timeout)
           throws Win32Exception
Throws:
Win32Exception

resume

public void resume()
            throws Win32Exception
Throws:
Win32Exception

getConfig

public ServiceConfig getConfig()
                        throws Win32Exception
Throws:
Win32Exception

list

public void list(java.io.PrintStream out)
          throws Win32Exception
Throws:
Win32Exception

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/ServiceConfig.html000066400000000000000000001163241210132627500274710ustar00rootroot00000000000000 ServiceConfig (Sigar API)

org.hyperic.sigar.win32
Class ServiceConfig

java.lang.Object
  extended by org.hyperic.sigar.win32.ServiceConfig

public class ServiceConfig
extends java.lang.Object


Field Summary
static int ERROR_CRITICAL
          The startup program logs the error, if possible.
static int ERROR_IGNORE
          The startup (boot) program logs the error but continues the startup operation.
static int ERROR_NORMAL
          The startup program logs the error and displays a message box pop-up but continues the startup operation.
static int ERROR_SEVERE
          The startup program logs the error.
static int START_AUTO
          A service started automatically by the service control manager during system startup.
static int START_BOOT
          A device driver started by the system loader.
static int START_DISABLED
          A service that cannot be started.
static int START_MANUAL
          A service started by the service control manager when a process calls the StartService function.
static int START_SYSTEM
          A device driver started by the IoInitSystem function.
static int TYPE_ADAPTER
           
static int TYPE_FILE_SYSTEM_DRIVER
          File system driver service.
static int TYPE_INTERACTIVE_PROCESS
          The service can interact with the desktop.
static int TYPE_KERNEL_DRIVER
          Driver service.
static int TYPE_RECOGNIZER_DRIVER
           
static int TYPE_WIN32_OWN_PROCESS
          Service that runs in its own process.
static int TYPE_WIN32_SHARE_PROCESS
          Service that shares a process with other services.
 
Constructor Summary
ServiceConfig(java.lang.String name)
           
 
Method Summary
 java.lang.String[] getArgv()
           
 java.lang.String[] getDependencies()
           
 java.lang.String getDescription()
           
 java.lang.String getDisplayName()
           
 int getErrorControl()
           
 java.lang.String getErrorControlString()
           
 java.lang.String getExe()
           
 java.lang.String getLoadOrderGroup()
           
 java.lang.String getName()
           
 java.lang.String getPassword()
           
 java.lang.String getPath()
           
 java.lang.String getStartName()
           
 int getStartType()
           
 java.lang.String getStartTypeString()
           
 int getTagId()
           
 int getType()
           
 java.util.List getTypeList()
           
 void list(java.io.PrintStream out)
           
 void setDependencies(java.lang.String[] dependencies)
           
 void setDescription(java.lang.String description)
           
 void setDisplayName(java.lang.String displayName)
           
 void setErrorControl(int errorControl)
           
 void setLoadOrderGroup(java.lang.String loadOrderGroup)
           
 void setName(java.lang.String name)
           
 void setPassword(java.lang.String password)
           
 void setPath(java.lang.String path)
           
 void setStartName(java.lang.String startName)
           
 void setStartType(int startType)
           
 void setTagId(int tagId)
           
 void setType(int type)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

START_BOOT

public static final int START_BOOT
A device driver started by the system loader. This value is valid only for driver services.

See Also:
Constant Field Values

START_SYSTEM

public static final int START_SYSTEM
A device driver started by the IoInitSystem function. This value is valid only for driver services.

See Also:
Constant Field Values

START_AUTO

public static final int START_AUTO
A service started automatically by the service control manager during system startup.

See Also:
Constant Field Values

START_MANUAL

public static final int START_MANUAL
A service started by the service control manager when a process calls the StartService function.

See Also:
Constant Field Values

START_DISABLED

public static final int START_DISABLED
A service that cannot be started. Attempts to start the service result in the error code ERROR_SERVICE_DISABLED.

See Also:
Constant Field Values

TYPE_KERNEL_DRIVER

public static final int TYPE_KERNEL_DRIVER
Driver service.

See Also:
Constant Field Values

TYPE_FILE_SYSTEM_DRIVER

public static final int TYPE_FILE_SYSTEM_DRIVER
File system driver service.

See Also:
Constant Field Values

TYPE_ADAPTER

public static final int TYPE_ADAPTER
See Also:
Constant Field Values

TYPE_RECOGNIZER_DRIVER

public static final int TYPE_RECOGNIZER_DRIVER
See Also:
Constant Field Values

TYPE_WIN32_OWN_PROCESS

public static final int TYPE_WIN32_OWN_PROCESS
Service that runs in its own process.

See Also:
Constant Field Values

TYPE_WIN32_SHARE_PROCESS

public static final int TYPE_WIN32_SHARE_PROCESS
Service that shares a process with other services.

See Also:
Constant Field Values

TYPE_INTERACTIVE_PROCESS

public static final int TYPE_INTERACTIVE_PROCESS
The service can interact with the desktop.

See Also:
Constant Field Values

ERROR_IGNORE

public static final int ERROR_IGNORE
The startup (boot) program logs the error but continues the startup operation.

See Also:
Constant Field Values

ERROR_NORMAL

public static final int ERROR_NORMAL
The startup program logs the error and displays a message box pop-up but continues the startup operation.

See Also:
Constant Field Values

ERROR_SEVERE

public static final int ERROR_SEVERE
The startup program logs the error. If the last-known good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.

See Also:
Constant Field Values

ERROR_CRITICAL

public static final int ERROR_CRITICAL
The startup program logs the error, if possible. If the last-known good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.

See Also:
Constant Field Values
Constructor Detail

ServiceConfig

public ServiceConfig(java.lang.String name)
Method Detail

getPath

public java.lang.String getPath()
Returns:
Returns the path.

setPath

public void setPath(java.lang.String path)
Parameters:
path - The path to set.

getArgv

public java.lang.String[] getArgv()

getExe

public java.lang.String getExe()

getDependencies

public java.lang.String[] getDependencies()
Returns:
Returns the dependencies.

setDependencies

public void setDependencies(java.lang.String[] dependencies)
Parameters:
dependencies - The dependencies to set.

getDisplayName

public java.lang.String getDisplayName()
Returns:
Returns the displayName.

setDisplayName

public void setDisplayName(java.lang.String displayName)
Parameters:
displayName - The displayName to set.

getErrorControl

public int getErrorControl()
Returns:
Returns the errorControl, one of ERROR_* constants.

setErrorControl

public void setErrorControl(int errorControl)
Parameters:
errorControl - The errorControl to set, one of ERROR_* constants.

getErrorControlString

public java.lang.String getErrorControlString()

getLoadOrderGroup

public java.lang.String getLoadOrderGroup()
Returns:
Returns the loadOrderGroup.

setLoadOrderGroup

public void setLoadOrderGroup(java.lang.String loadOrderGroup)
Parameters:
loadOrderGroup - The loadOrderGroup to set.

getStartName

public java.lang.String getStartName()
Returns:
Returns the startName.

setStartName

public void setStartName(java.lang.String startName)
Parameters:
startName - The startName to set.

getStartType

public int getStartType()
Returns:
Returns the startType, one of START_* constants.

setStartType

public void setStartType(int startType)
Parameters:
startType - The startType to set, one of START_* constants.

getStartTypeString

public java.lang.String getStartTypeString()

getTagId

public int getTagId()
Returns:
Returns the tagId.

setTagId

public void setTagId(int tagId)
Parameters:
tagId - The tagId to set.

getType

public int getType()
Returns:
Returns the type, one of TYPE_* constants.

getTypeList

public java.util.List getTypeList()

setType

public void setType(int type)
Parameters:
type - The type to set, one of TYPE_* constants.

getDescription

public java.lang.String getDescription()
Returns:
Returns the description.

setDescription

public void setDescription(java.lang.String description)
Parameters:
description - The description to set.

getPassword

public java.lang.String getPassword()
Returns:
Returns the password.

setPassword

public void setPassword(java.lang.String password)
Parameters:
password - The password to set.

getName

public java.lang.String getName()
Returns:
Returns the name.

setName

public void setName(java.lang.String name)
Parameters:
name - The name to set.

list

public void list(java.io.PrintStream out)
          throws Win32Exception
Throws:
Win32Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/Win32.html000066400000000000000000000334121210132627500256410ustar00rootroot00000000000000 Win32 (Sigar API)

org.hyperic.sigar.win32
Class Win32

java.lang.Object
  extended by org.hyperic.sigar.win32.Win32
Direct Known Subclasses:
EventLog, LocaleInfo, MetaBase, Pdh, RegistryKey, Service

public abstract class Win32
extends java.lang.Object


Field Summary
static java.lang.String EXE_EXT
           
 
Constructor Summary
Win32()
           
 
Method Summary
static java.lang.String findExecutable(java.lang.String name)
           
static java.lang.String findScriptExecutable(java.lang.String name)
           
static FileVersion getFileVersion(java.lang.String name)
           
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

EXE_EXT

public static final java.lang.String EXE_EXT
See Also:
Constant Field Values
Constructor Detail

Win32

public Win32()
Method Detail

findExecutable

public static java.lang.String findExecutable(java.lang.String name)
                                       throws SigarException
Throws:
SigarException

findScriptExecutable

public static java.lang.String findScriptExecutable(java.lang.String name)

getFileVersion

public static FileVersion getFileVersion(java.lang.String name)

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Throws:
java.lang.Exception


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/Win32Exception.html000066400000000000000000000267621210132627500275320ustar00rootroot00000000000000 Win32Exception (Sigar API)

org.hyperic.sigar.win32
Class Win32Exception

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.hyperic.sigar.SigarException
              extended by org.hyperic.sigar.win32.Win32Exception
All Implemented Interfaces:
java.io.Serializable

public class Win32Exception
extends SigarException

See Also:
Serialized Form

Constructor Summary
Win32Exception(int error, java.lang.String s)
           
Win32Exception(java.lang.String s)
           
 
Method Summary
 int getErrorCode()
           
 
Methods inherited from class org.hyperic.sigar.SigarException
getMessage
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Win32Exception

public Win32Exception(java.lang.String s)

Win32Exception

public Win32Exception(int error,
                      java.lang.String s)
Method Detail

getErrorCode

public int getErrorCode()


Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/package-frame.html000066400000000000000000000050131210132627500274160ustar00rootroot00000000000000 org.hyperic.sigar.win32 (Sigar API) org.hyperic.sigar.win32
Interfaces 
EventLogNotification
Classes 
EventLog
EventLogRecord
EventLogThread
FileVersion
LocaleInfo
MetaBase
Pdh
RegistryKey
Service
ServiceConfig
Win32
Exceptions 
Win32Exception
hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/package-summary.html000066400000000000000000000215411210132627500300250ustar00rootroot00000000000000 org.hyperic.sigar.win32 (Sigar API)

Package org.hyperic.sigar.win32

Interface Summary
EventLogNotification Register for event log notifications.
 

Class Summary
EventLog  
EventLogRecord Class to represent event log records
EventLogThread A simple thread that runs forever monitoring the event log.
FileVersion  
LocaleInfo  
MetaBase  
Pdh  
RegistryKey  
Service  
ServiceConfig  
Win32  
 

Exception Summary
Win32Exception  
 



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/org/hyperic/sigar/win32/package-tree.html000066400000000000000000000200621210132627500272640ustar00rootroot00000000000000 org.hyperic.sigar.win32 Class Hierarchy (Sigar API)

Hierarchy For Package org.hyperic.sigar.win32

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/overview-frame.html000066400000000000000000000034331210132627500233740ustar00rootroot00000000000000 Overview List (Sigar API)
All Classes

Packages
org.hyperic.sigar
org.hyperic.sigar.cmd
org.hyperic.sigar.ptql
org.hyperic.sigar.shell
org.hyperic.sigar.util
org.hyperic.sigar.vmware
org.hyperic.sigar.win32

  hyperic-sigar-1.6.4+dfsg/docs/javadoc/overview-summary.html000066400000000000000000000153001210132627500237730ustar00rootroot00000000000000 Overview (Sigar API)



Sigar

Sigar
org.hyperic.sigar Sigar - System Information Gatherer And Reporter

 
Other Packages
org.hyperic.sigar.cmd Example classes implementing familar unix tools in Java.
org.hyperic.sigar.ptql Process Table Query Language
org.hyperic.sigar.shell Base package for implementing a command shell.
org.hyperic.sigar.util Utility classes independent of Sigar.
org.hyperic.sigar.vmware  
org.hyperic.sigar.win32  

 



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/overview-tree.html000066400000000000000000001005601210132627500232400ustar00rootroot00000000000000 Class Hierarchy (Sigar API)

Hierarchy For All Packages

Package Hierarchies:
org.hyperic.sigar, org.hyperic.sigar.cmd, org.hyperic.sigar.ptql, org.hyperic.sigar.shell, org.hyperic.sigar.util, org.hyperic.sigar.vmware, org.hyperic.sigar.win32

Class Hierarchy

Interface Hierarchy



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/package-list000066400000000000000000000002371210132627500220360ustar00rootroot00000000000000org.hyperic.sigar org.hyperic.sigar.cmd org.hyperic.sigar.ptql org.hyperic.sigar.shell org.hyperic.sigar.util org.hyperic.sigar.vmware org.hyperic.sigar.win32 hyperic-sigar-1.6.4+dfsg/docs/javadoc/resources/000077500000000000000000000000001210132627500215575ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/docs/javadoc/resources/inherit.gif000066400000000000000000000000711210132627500237060ustar00rootroot00000000000000GIF89a, DrjԐ;߀Q@N;hyperic-sigar-1.6.4+dfsg/docs/javadoc/serialized-form.html000066400000000000000000002115341210132627500235350ustar00rootroot00000000000000 Serialized Form (Sigar API)

Serialized Form


Package org.hyperic.sigar

Class org.hyperic.sigar.Cpu extends java.lang.Object implements Serializable

serialVersionUID: 8076L

Serialized Fields

user

long user

sys

long sys

nice

long nice

idle

long idle

wait

long wait

irq

long irq

softIrq

long softIrq

stolen

long stolen

total

long total

Class org.hyperic.sigar.CpuInfo extends java.lang.Object implements Serializable

serialVersionUID: 9710L

Serialized Fields

vendor

java.lang.String vendor

model

java.lang.String model

mhz

int mhz

cacheSize

long cacheSize

totalCores

int totalCores

totalSockets

int totalSockets

coresPerSocket

int coresPerSocket

Class org.hyperic.sigar.CpuPerc extends java.lang.Object implements Serializable

serialVersionUID: 1393671L

Serialized Fields

user

double user

sys

double sys

nice

double nice

idle

double idle

wait

double wait

irq

double irq

softIrq

double softIrq

stolen

double stolen

combined

double combined

Class org.hyperic.sigar.CurrentProcessSummary extends ProcStat implements Serializable

Class org.hyperic.sigar.DirStat extends java.lang.Object implements Serializable

serialVersionUID: 9250L

Serialized Fields

total

long total

files

long files

subdirs

long subdirs

symlinks

long symlinks

chrdevs

long chrdevs

blkdevs

long blkdevs

sockets

long sockets

diskUsage

long diskUsage

Class org.hyperic.sigar.DirUsage extends java.lang.Object implements Serializable

serialVersionUID: 9250L

Serialized Fields

total

long total

files

long files

subdirs

long subdirs

symlinks

long symlinks

chrdevs

long chrdevs

blkdevs

long blkdevs

sockets

long sockets

diskUsage

long diskUsage

Class org.hyperic.sigar.DiskUsage extends java.lang.Object implements Serializable

serialVersionUID: 8090L

Serialized Fields

reads

long reads

writes

long writes

readBytes

long readBytes

writeBytes

long writeBytes

queue

double queue

serviceTime

double serviceTime

Class org.hyperic.sigar.FileAttrs extends java.lang.Object implements Serializable

serialVersionUID: 10323L

Serialized Fields

permissions

long permissions

type

int type

uid

long uid

gid

long gid

inode

long inode

device

long device

nlink

long nlink

size

long size

atime

long atime

ctime

long ctime

mtime

long mtime

Class org.hyperic.sigar.FileInfo extends FileAttrs implements Serializable

serialVersionUID: 607239L

Serialized Fields

name

java.lang.String name

dirStatEnabled

boolean dirStatEnabled

stat

DirStat stat

lstat

boolean lstat

oldInfo

FileInfo oldInfo

Class org.hyperic.sigar.FileSystem extends java.lang.Object implements Serializable

serialVersionUID: 9641L

Serialized Fields

dirName

java.lang.String dirName

devName

java.lang.String devName

typeName

java.lang.String typeName

sysTypeName

java.lang.String sysTypeName

options

java.lang.String options

type

int type

flags

long flags

Class org.hyperic.sigar.FileSystemMap extends java.util.HashMap implements Serializable

Class org.hyperic.sigar.FileSystemUsage extends java.lang.Object implements Serializable

serialVersionUID: 18905L

Serialized Fields

total

long total

free

long free

used

long used

avail

long avail

files

long files

freeFiles

long freeFiles

diskReads

long diskReads

diskWrites

long diskWrites

diskReadBytes

long diskReadBytes

diskWriteBytes

long diskWriteBytes

diskQueue

double diskQueue

diskServiceTime

double diskServiceTime

usePercent

double usePercent

Class org.hyperic.sigar.Mem extends java.lang.Object implements Serializable

serialVersionUID: 10181L

Serialized Fields

total

long total

ram

long ram

used

long used

free

long free

actualUsed

long actualUsed

actualFree

long actualFree

usedPercent

double usedPercent

freePercent

double freePercent

Class org.hyperic.sigar.MultiProcCpu extends ProcCpu implements Serializable

Serialized Fields

pid

long pid

nproc

int nproc

Class org.hyperic.sigar.MultiProcMem extends ProcMem implements Serializable

Class org.hyperic.sigar.NetConnection extends java.lang.Object implements Serializable

serialVersionUID: 12776L

Serialized Fields

localPort

long localPort

localAddress

java.lang.String localAddress

remotePort

long remotePort

remoteAddress

java.lang.String remoteAddress

type

int type

state

int state

sendQueue

long sendQueue

receiveQueue

long receiveQueue

Class org.hyperic.sigar.NetInfo extends java.lang.Object implements Serializable

serialVersionUID: 9427L

Serialized Fields

defaultGateway

java.lang.String defaultGateway

hostName

java.lang.String hostName

domainName

java.lang.String domainName

primaryDns

java.lang.String primaryDns

secondaryDns

java.lang.String secondaryDns

Class org.hyperic.sigar.NetInterfaceConfig extends java.lang.Object implements Serializable

serialVersionUID: 15948L

Serialized Fields

name

java.lang.String name

hwaddr

java.lang.String hwaddr

type

java.lang.String type

description

java.lang.String description

address

java.lang.String address

destination

java.lang.String destination

broadcast

java.lang.String broadcast

netmask

java.lang.String netmask

flags

long flags

mtu

long mtu

metric

long metric

Class org.hyperic.sigar.NetInterfaceStat extends java.lang.Object implements Serializable

serialVersionUID: 20008L

Serialized Fields

rxBytes

long rxBytes

rxPackets

long rxPackets

rxErrors

long rxErrors

rxDropped

long rxDropped

rxOverruns

long rxOverruns

rxFrame

long rxFrame

txBytes

long txBytes

txPackets

long txPackets

txErrors

long txErrors

txDropped

long txDropped

txOverruns

long txOverruns

txCollisions

long txCollisions

txCarrier

long txCarrier

speed

long speed

Class org.hyperic.sigar.NetRoute extends java.lang.Object implements Serializable

serialVersionUID: 13039L

Serialized Fields

destination

java.lang.String destination

gateway

java.lang.String gateway

flags

long flags

refcnt

long refcnt

use

long use

metric

long metric

mask

java.lang.String mask

mtu

long mtu

window

long window

irtt

long irtt

ifname

java.lang.String ifname

Class org.hyperic.sigar.NetStat extends java.lang.Object implements Serializable

serialVersionUID: 1070087L

Serialized Fields

tcpStates

int[] tcpStates

tcpInboundTotal

int tcpInboundTotal

tcpOutboundTotal

int tcpOutboundTotal

allInboundTotal

int allInboundTotal

allOutboundTotal

int allOutboundTotal

Class org.hyperic.sigar.NfsClientV2 extends java.lang.Object implements Serializable

serialVersionUID: 18751L

Serialized Fields

_null

long _null

getattr

long getattr

setattr

long setattr

root

long root

lookup

long lookup

readlink

long readlink

read

long read

writecache

long writecache

write

long write

create

long create

remove

long remove

rename

long rename

link

long link

symlink

long symlink

mkdir

long mkdir

rmdir

long rmdir

readdir

long readdir

fsstat

long fsstat

Class org.hyperic.sigar.NfsClientV3 extends java.lang.Object implements Serializable

serialVersionUID: 23335L

Serialized Fields

_null

long _null

getattr

long getattr

setattr

long setattr

lookup

long lookup

access

long access

readlink

long readlink

read

long read

write

long write

create

long create

mkdir

long mkdir

symlink

long symlink

mknod

long mknod

remove

long remove

rmdir

long rmdir

rename

long rename

link

long link

readdir

long readdir

readdirplus

long readdirplus

fsstat

long fsstat

fsinfo

long fsinfo

pathconf

long pathconf

commit

long commit

Class org.hyperic.sigar.NfsFileSystem extends FileSystem implements Serializable

serialVersionUID: 607239L

Serialized Fields

hostname

java.lang.String hostname

Class org.hyperic.sigar.NfsServerV2 extends java.lang.Object implements Serializable

serialVersionUID: 18751L

Serialized Fields

_null

long _null

getattr

long getattr

setattr

long setattr

root

long root

lookup

long lookup

readlink

long readlink

read

long read

writecache

long writecache

write

long write

create

long create

remove

long remove

rename

long rename

link

long link

symlink

long symlink

mkdir

long mkdir

rmdir

long rmdir

readdir

long readdir

fsstat

long fsstat

Class org.hyperic.sigar.NfsServerV3 extends java.lang.Object implements Serializable

serialVersionUID: 23335L

Serialized Fields

_null

long _null

getattr

long getattr

setattr

long setattr

lookup

long lookup

access

long access

readlink

long readlink

read

long read

write

long write

create

long create

mkdir

long mkdir

symlink

long symlink

mknod

long mknod

remove

long remove

rmdir

long rmdir

rename

long rename

link

long link

readdir

long readdir

readdirplus

long readdirplus

fsstat

long fsstat

fsinfo

long fsinfo

pathconf

long pathconf

commit

long commit

Class org.hyperic.sigar.NfsUnreachableException extends SigarException implements Serializable

Class org.hyperic.sigar.OperatingSystem extends SysInfo implements Serializable

Serialized Fields

dataModel

java.lang.String dataModel

cpuEndian

java.lang.String cpuEndian

Class org.hyperic.sigar.ProcCpu extends java.lang.Object implements Serializable

serialVersionUID: 6748L

Serialized Fields

percent

double percent

lastTime

long lastTime

startTime

long startTime

user

long user

sys

long sys

total

long total

Class org.hyperic.sigar.ProcCred extends java.lang.Object implements Serializable

serialVersionUID: 3062L

Serialized Fields

uid

long uid

gid

long gid

euid

long euid

egid

long egid

Class org.hyperic.sigar.ProcCredName extends java.lang.Object implements Serializable

serialVersionUID: 2266L

Serialized Fields

user

java.lang.String user

group

java.lang.String group

Class org.hyperic.sigar.ProcExe extends java.lang.Object implements Serializable

serialVersionUID: 1997L

Serialized Fields

name

java.lang.String name

cwd

java.lang.String cwd

Class org.hyperic.sigar.ProcFd extends java.lang.Object implements Serializable

serialVersionUID: 948L

Serialized Fields

total

long total

Class org.hyperic.sigar.ProcMem extends java.lang.Object implements Serializable

serialVersionUID: 7985L

Serialized Fields

size

long size

resident

long resident

share

long share

minorFaults

long minorFaults

majorFaults

long majorFaults

pageFaults

long pageFaults

Class org.hyperic.sigar.ProcStat extends java.lang.Object implements Serializable

serialVersionUID: 7546L

Serialized Fields

total

long total

idle

long idle

running

long running

sleeping

long sleeping

stopped

long stopped

zombie

long zombie

threads

long threads

Class org.hyperic.sigar.ProcState extends java.lang.Object implements Serializable

serialVersionUID: 7805L

Serialized Fields

state

char state

name

java.lang.String name

ppid

long ppid

tty

int tty

nice

int nice

priority

int priority

threads

long threads

processor

int processor

Class org.hyperic.sigar.ProcTime extends java.lang.Object implements Serializable

serialVersionUID: 4030L

Serialized Fields

startTime

long startTime

user

long user

sys

long sys

total

long total

Class org.hyperic.sigar.ResourceLimit extends java.lang.Object implements Serializable

serialVersionUID: 32184L

Serialized Fields

cpuCur

long cpuCur

cpuMax

long cpuMax

fileSizeCur

long fileSizeCur

fileSizeMax

long fileSizeMax

pipeSizeMax

long pipeSizeMax

pipeSizeCur

long pipeSizeCur

dataCur

long dataCur

dataMax

long dataMax

stackCur

long stackCur

stackMax

long stackMax

coreCur

long coreCur

coreMax

long coreMax

memoryCur

long memoryCur

memoryMax

long memoryMax

processesCur

long processesCur

processesMax

long processesMax

openFilesCur

long openFilesCur

openFilesMax

long openFilesMax

virtualMemoryCur

long virtualMemoryCur

virtualMemoryMax

long virtualMemoryMax

Class org.hyperic.sigar.SigarException extends java.lang.Exception implements Serializable

Serialized Fields

message

java.lang.String message

Class org.hyperic.sigar.SigarFileNotFoundException extends SigarException implements Serializable

Class org.hyperic.sigar.SigarNotImplementedException extends SigarException implements Serializable

Class org.hyperic.sigar.SigarPermissionDeniedException extends SigarException implements Serializable

Class org.hyperic.sigar.Swap extends java.lang.Object implements Serializable

serialVersionUID: 4974L

Serialized Fields

total

long total

used

long used

free

long free

pageIn

long pageIn

pageOut

long pageOut

Class org.hyperic.sigar.SysInfo extends java.lang.Object implements Serializable

serialVersionUID: 16002L

Serialized Fields

name

java.lang.String name

version

java.lang.String version

arch

java.lang.String arch

machine

java.lang.String machine

description

java.lang.String description

patchLevel

java.lang.String patchLevel

vendor

java.lang.String vendor

vendorVersion

java.lang.String vendorVersion

vendorName

java.lang.String vendorName

vendorCodeName

java.lang.String vendorCodeName

Class org.hyperic.sigar.Tcp extends java.lang.Object implements Serializable

serialVersionUID: 14992L

Serialized Fields

activeOpens

long activeOpens

passiveOpens

long passiveOpens

attemptFails

long attemptFails

estabResets

long estabResets

currEstab

long currEstab

inSegs

long inSegs

outSegs

long outSegs

retransSegs

long retransSegs

inErrs

long inErrs

outRsts

long outRsts

Class org.hyperic.sigar.ThreadCpu extends java.lang.Object implements Serializable

serialVersionUID: 2546L

Serialized Fields

user

long user

sys

long sys

total

long total

Class org.hyperic.sigar.Uptime extends java.lang.Object implements Serializable

serialVersionUID: 1263L

Serialized Fields

uptime

double uptime

Class org.hyperic.sigar.Who extends java.lang.Object implements Serializable

serialVersionUID: 4241L

Serialized Fields

user

java.lang.String user

device

java.lang.String device

host

java.lang.String host

time

long time

Package org.hyperic.sigar.ptql

Class org.hyperic.sigar.ptql.MalformedQueryException extends SigarException implements Serializable

Class org.hyperic.sigar.ptql.QueryLoadException extends java.lang.RuntimeException implements Serializable


Package org.hyperic.sigar.shell

Class org.hyperic.sigar.shell.NormalQuitCommandException extends java.lang.RuntimeException implements Serializable

Class org.hyperic.sigar.shell.ShellCommandExecException extends java.lang.Exception implements Serializable

Class org.hyperic.sigar.shell.ShellCommandInitException extends java.lang.Exception implements Serializable

Class org.hyperic.sigar.shell.ShellCommandUsageException extends java.lang.Exception implements Serializable


Package org.hyperic.sigar.vmware

Class org.hyperic.sigar.vmware.VMwareException extends SigarException implements Serializable


Package org.hyperic.sigar.win32

Class org.hyperic.sigar.win32.Win32Exception extends SigarException implements Serializable

Serialized Fields

errorCode

int errorCode



Copyright ? 2004-2009 Hyperic. All Rights Reserved. hyperic-sigar-1.6.4+dfsg/docs/javadoc/stylesheet.css000066400000000000000000000025571210132627500224610ustar00rootroot00000000000000/* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF; color:#000000 } /* Headings */ h1 { font-size: 145% } /* Table colors */ .TableHeadingColor { background: #CCCCFF; color:#000000 } /* Dark mauve */ .TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* Light mauve */ .TableRowColor { background: #FFFFFF; color:#000000 } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#EEEEFF; color:#000000} /* Light mauve */ .NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* Dark Blue */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} hyperic-sigar-1.6.4+dfsg/include/000077500000000000000000000000001210132627500166315ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/include/sigar.h000066400000000000000000000557221210132627500201220ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 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. */ #ifndef SIGAR_H #define SIGAR_H /* System Information Gatherer And Reporter */ #include #ifdef __cplusplus extern "C" { #endif #if defined(_LP64) || \ defined(__LP64__) || \ defined(__64BIT__) || \ defined(__powerpc64__) || \ defined(__osf__) #define SIGAR_64BIT #endif /* for printf sigar_uint64_t */ #ifdef SIGAR_64BIT # define SIGAR_F_U64 "%lu" #else # define SIGAR_F_U64 "%Lu" #endif #if defined(WIN32) typedef unsigned __int32 sigar_uint32_t; typedef unsigned __int64 sigar_uint64_t; typedef __int32 sigar_int32_t; typedef __int64 sigar_int64_t; #elif ULONG_MAX > 4294967295UL typedef unsigned int sigar_uint32_t; typedef unsigned long sigar_uint64_t; typedef int sigar_int32_t; typedef long sigar_int64_t; #else typedef unsigned int sigar_uint32_t; typedef unsigned long long sigar_uint64_t; typedef int sigar_int32_t; typedef long long sigar_int64_t; #endif #define SIGAR_FIELD_NOTIMPL -1 #define SIGAR_OK 0 #define SIGAR_START_ERROR 20000 #define SIGAR_ENOTIMPL (SIGAR_START_ERROR + 1) #define SIGAR_OS_START_ERROR (SIGAR_START_ERROR*2) #ifdef WIN32 # define SIGAR_ENOENT ERROR_FILE_NOT_FOUND # define SIGAR_EACCES ERROR_ACCESS_DENIED # define SIGAR_ENXIO ERROR_BAD_DRIVER_LEVEL #else # define SIGAR_ENOENT ENOENT # define SIGAR_EACCES EACCES # define SIGAR_ENXIO ENXIO #endif #ifdef WIN32 # define SIGAR_DECLARE(type) \ __declspec(dllexport) type __stdcall #else # define SIGAR_DECLARE(type) type #endif #if defined(PATH_MAX) # define SIGAR_PATH_MAX PATH_MAX #elif defined(MAXPATHLEN) # define SIGAR_PATH_MAX MAXPATHLEN #else # define SIGAR_PATH_MAX 4096 #endif #ifdef WIN32 typedef sigar_uint64_t sigar_pid_t; typedef unsigned long sigar_uid_t; typedef unsigned long sigar_gid_t; #else #include typedef pid_t sigar_pid_t; typedef uid_t sigar_uid_t; typedef gid_t sigar_gid_t; #endif typedef struct sigar_t sigar_t; SIGAR_DECLARE(int) sigar_open(sigar_t **sigar); SIGAR_DECLARE(int) sigar_close(sigar_t *sigar); SIGAR_DECLARE(sigar_pid_t) sigar_pid_get(sigar_t *sigar); SIGAR_DECLARE(int) sigar_proc_kill(sigar_pid_t pid, int signum); SIGAR_DECLARE(int) sigar_signum_get(char *name); SIGAR_DECLARE(char *) sigar_strerror(sigar_t *sigar, int err); /* system memory info */ typedef struct { sigar_uint64_t ram, total, used, free, actual_used, actual_free; double used_percent; double free_percent; } sigar_mem_t; SIGAR_DECLARE(int) sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem); typedef struct { sigar_uint64_t total, used, free, page_in, page_out; } sigar_swap_t; SIGAR_DECLARE(int) sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap); typedef struct { sigar_uint64_t user, sys, nice, idle, wait, irq, soft_irq, stolen, total; } sigar_cpu_t; SIGAR_DECLARE(int) sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu); typedef struct { unsigned long number; unsigned long size; sigar_cpu_t *data; } sigar_cpu_list_t; SIGAR_DECLARE(int) sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist); SIGAR_DECLARE(int) sigar_cpu_list_destroy(sigar_t *sigar, sigar_cpu_list_t *cpulist); typedef struct { char vendor[128]; char model[128]; int mhz; sigar_uint64_t cache_size; int total_sockets; int total_cores; int cores_per_socket; } sigar_cpu_info_t; typedef struct { unsigned long number; unsigned long size; sigar_cpu_info_t *data; } sigar_cpu_info_list_t; SIGAR_DECLARE(int) sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos); SIGAR_DECLARE(int) sigar_cpu_info_list_destroy(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos); typedef struct { double uptime; } sigar_uptime_t; SIGAR_DECLARE(int) sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime); typedef struct { double loadavg[3]; } sigar_loadavg_t; SIGAR_DECLARE(int) sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg); typedef struct { unsigned long number; unsigned long size; sigar_pid_t *data; } sigar_proc_list_t; typedef struct { /* RLIMIT_CPU */ sigar_uint64_t cpu_cur, cpu_max; /* RLIMIT_FSIZE */ sigar_uint64_t file_size_cur, file_size_max; /* PIPE_BUF */ sigar_uint64_t pipe_size_cur, pipe_size_max; /* RLIMIT_DATA */ sigar_uint64_t data_cur, data_max; /* RLIMIT_STACK */ sigar_uint64_t stack_cur, stack_max; /* RLIMIT_CORE */ sigar_uint64_t core_cur, core_max; /* RLIMIT_RSS */ sigar_uint64_t memory_cur, memory_max; /* RLIMIT_NPROC */ sigar_uint64_t processes_cur, processes_max; /* RLIMIT_NOFILE */ sigar_uint64_t open_files_cur, open_files_max; /* RLIMIT_AS */ sigar_uint64_t virtual_memory_cur, virtual_memory_max; } sigar_resource_limit_t; SIGAR_DECLARE(int) sigar_resource_limit_get(sigar_t *sigar, sigar_resource_limit_t *rlimit); SIGAR_DECLARE(int) sigar_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist); SIGAR_DECLARE(int) sigar_proc_list_destroy(sigar_t *sigar, sigar_proc_list_t *proclist); typedef struct { sigar_uint64_t total; sigar_uint64_t sleeping; sigar_uint64_t running; sigar_uint64_t zombie; sigar_uint64_t stopped; sigar_uint64_t idle; sigar_uint64_t threads; } sigar_proc_stat_t; SIGAR_DECLARE(int) sigar_proc_stat_get(sigar_t *sigar, sigar_proc_stat_t *procstat); typedef struct { sigar_uint64_t size, resident, share, minor_faults, major_faults, page_faults; } sigar_proc_mem_t; SIGAR_DECLARE(int) sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem); typedef struct { sigar_uid_t uid; sigar_gid_t gid; sigar_uid_t euid; sigar_gid_t egid; } sigar_proc_cred_t; SIGAR_DECLARE(int) sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred); #define SIGAR_CRED_NAME_MAX 512 typedef struct { char user[SIGAR_CRED_NAME_MAX]; char group[SIGAR_CRED_NAME_MAX]; } sigar_proc_cred_name_t; SIGAR_DECLARE(int) sigar_proc_cred_name_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_name_t *proccredname); typedef struct { sigar_uint64_t start_time, user, sys, total; } sigar_proc_time_t; SIGAR_DECLARE(int) sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime); typedef struct { /* must match sigar_proc_time_t fields */ sigar_uint64_t start_time, user, sys, total; sigar_uint64_t last_time; double percent; } sigar_proc_cpu_t; SIGAR_DECLARE(int) sigar_proc_cpu_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cpu_t *proccpu); #define SIGAR_PROC_STATE_SLEEP 'S' #define SIGAR_PROC_STATE_RUN 'R' #define SIGAR_PROC_STATE_STOP 'T' #define SIGAR_PROC_STATE_ZOMBIE 'Z' #define SIGAR_PROC_STATE_IDLE 'D' #define SIGAR_PROC_NAME_LEN 128 typedef struct { char name[SIGAR_PROC_NAME_LEN]; char state; sigar_pid_t ppid; int tty; int priority; int nice; int processor; sigar_uint64_t threads; } sigar_proc_state_t; SIGAR_DECLARE(int) sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate); typedef struct { unsigned long number; unsigned long size; char **data; } sigar_proc_args_t; SIGAR_DECLARE(int) sigar_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs); SIGAR_DECLARE(int) sigar_proc_args_destroy(sigar_t *sigar, sigar_proc_args_t *procargs); typedef struct { void *data; /* user data */ enum { SIGAR_PROC_ENV_ALL, SIGAR_PROC_ENV_KEY } type; /* used for SIGAR_PROC_ENV_KEY */ const char *key; int klen; int (*env_getter)(void *, const char *, int, char *, int); } sigar_proc_env_t; SIGAR_DECLARE(int) sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv); typedef struct { sigar_uint64_t total; /* XXX - which are files, sockets, etc. */ } sigar_proc_fd_t; SIGAR_DECLARE(int) sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd); typedef struct { char name[SIGAR_PATH_MAX+1]; char cwd[SIGAR_PATH_MAX+1]; char root[SIGAR_PATH_MAX+1]; } sigar_proc_exe_t; SIGAR_DECLARE(int) sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe); typedef struct { void *data; /* user data */ int (*module_getter)(void *, char *, int); } sigar_proc_modules_t; SIGAR_DECLARE(int) sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods); typedef struct { sigar_uint64_t user; sigar_uint64_t sys; sigar_uint64_t total; } sigar_thread_cpu_t; SIGAR_DECLARE(int) sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu); typedef enum { SIGAR_FSTYPE_UNKNOWN, SIGAR_FSTYPE_NONE, SIGAR_FSTYPE_LOCAL_DISK, SIGAR_FSTYPE_NETWORK, SIGAR_FSTYPE_RAM_DISK, SIGAR_FSTYPE_CDROM, SIGAR_FSTYPE_SWAP, SIGAR_FSTYPE_MAX } sigar_file_system_type_e; #define SIGAR_FS_NAME_LEN SIGAR_PATH_MAX #define SIGAR_FS_INFO_LEN 256 typedef struct { char dir_name[SIGAR_FS_NAME_LEN]; char dev_name[SIGAR_FS_NAME_LEN]; char type_name[SIGAR_FS_INFO_LEN]; /* e.g. "local" */ char sys_type_name[SIGAR_FS_INFO_LEN]; /* e.g. "ext3" */ char options[SIGAR_FS_INFO_LEN]; sigar_file_system_type_e type; unsigned long flags; } sigar_file_system_t; typedef struct { unsigned long number; unsigned long size; sigar_file_system_t *data; } sigar_file_system_list_t; SIGAR_DECLARE(int) sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist); SIGAR_DECLARE(int) sigar_file_system_list_destroy(sigar_t *sigar, sigar_file_system_list_t *fslist); typedef struct { sigar_uint64_t reads; sigar_uint64_t writes; sigar_uint64_t write_bytes; sigar_uint64_t read_bytes; sigar_uint64_t rtime; sigar_uint64_t wtime; sigar_uint64_t qtime; sigar_uint64_t time; sigar_uint64_t snaptime; double service_time; double queue; } sigar_disk_usage_t; /* XXX for sigar_file_system_usage_t compat */ #define disk_reads disk.reads #define disk_writes disk.writes #define disk_write_bytes disk.write_bytes #define disk_read_bytes disk.read_bytes #define disk_queue disk.queue #define disk_service_time disk.service_time typedef struct { sigar_disk_usage_t disk; double use_percent; sigar_uint64_t total; sigar_uint64_t free; sigar_uint64_t used; sigar_uint64_t avail; sigar_uint64_t files; sigar_uint64_t free_files; } sigar_file_system_usage_t; #undef SIGAR_DISK_USAGE_T SIGAR_DECLARE(int) sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage); SIGAR_DECLARE(int) sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *disk); SIGAR_DECLARE(int) sigar_file_system_ping(sigar_t *sigar, sigar_file_system_t *fs); typedef struct { enum { SIGAR_AF_UNSPEC, SIGAR_AF_INET, SIGAR_AF_INET6, SIGAR_AF_LINK } family; union { sigar_uint32_t in; sigar_uint32_t in6[4]; unsigned char mac[8]; } addr; } sigar_net_address_t; #define SIGAR_INET6_ADDRSTRLEN 46 #define SIGAR_MAXDOMAINNAMELEN 256 #define SIGAR_MAXHOSTNAMELEN 256 typedef struct { char default_gateway[SIGAR_INET6_ADDRSTRLEN]; char host_name[SIGAR_MAXHOSTNAMELEN]; char domain_name[SIGAR_MAXDOMAINNAMELEN]; char primary_dns[SIGAR_INET6_ADDRSTRLEN]; char secondary_dns[SIGAR_INET6_ADDRSTRLEN]; } sigar_net_info_t; SIGAR_DECLARE(int) sigar_net_info_get(sigar_t *sigar, sigar_net_info_t *netinfo); #define SIGAR_RTF_UP 0x1 #define SIGAR_RTF_GATEWAY 0x2 #define SIGAR_RTF_HOST 0x4 typedef struct { sigar_net_address_t destination; sigar_net_address_t gateway; sigar_net_address_t mask; sigar_uint64_t flags, refcnt, use, metric, mtu, window, irtt; char ifname[16]; } sigar_net_route_t; typedef struct { unsigned long number; unsigned long size; sigar_net_route_t *data; } sigar_net_route_list_t; SIGAR_DECLARE(int) sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist); SIGAR_DECLARE(int) sigar_net_route_list_destroy(sigar_t *sigar, sigar_net_route_list_t *routelist); /* * platforms define most of these "standard" flags, * but of course, with different values in some cases. */ #define SIGAR_IFF_UP 0x1 #define SIGAR_IFF_BROADCAST 0x2 #define SIGAR_IFF_DEBUG 0x4 #define SIGAR_IFF_LOOPBACK 0x8 #define SIGAR_IFF_POINTOPOINT 0x10 #define SIGAR_IFF_NOTRAILERS 0x20 #define SIGAR_IFF_RUNNING 0x40 #define SIGAR_IFF_NOARP 0x80 #define SIGAR_IFF_PROMISC 0x100 #define SIGAR_IFF_ALLMULTI 0x200 #define SIGAR_IFF_MULTICAST 0x800 #define SIGAR_IFF_SLAVE 0x1000 #define SIGAR_NULL_HWADDR "00:00:00:00:00:00" typedef struct { char name[16]; char type[64]; char description[256]; sigar_net_address_t hwaddr; sigar_net_address_t address; sigar_net_address_t destination; sigar_net_address_t broadcast; sigar_net_address_t netmask; sigar_uint64_t flags, mtu, metric; } sigar_net_interface_config_t; SIGAR_DECLARE(int) sigar_net_interface_config_get(sigar_t *sigar, const char *name, sigar_net_interface_config_t *ifconfig); SIGAR_DECLARE(int) sigar_net_interface_config_primary_get(sigar_t *sigar, sigar_net_interface_config_t *ifconfig); typedef struct { sigar_uint64_t /* received */ rx_packets, rx_bytes, rx_errors, rx_dropped, rx_overruns, rx_frame, /* transmitted */ tx_packets, tx_bytes, tx_errors, tx_dropped, tx_overruns, tx_collisions, tx_carrier, speed; } sigar_net_interface_stat_t; SIGAR_DECLARE(int) sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat); typedef struct { unsigned long number; unsigned long size; char **data; } sigar_net_interface_list_t; SIGAR_DECLARE(int) sigar_net_interface_list_get(sigar_t *sigar, sigar_net_interface_list_t *iflist); SIGAR_DECLARE(int) sigar_net_interface_list_destroy(sigar_t *sigar, sigar_net_interface_list_t *iflist); #define SIGAR_NETCONN_CLIENT 0x01 #define SIGAR_NETCONN_SERVER 0x02 #define SIGAR_NETCONN_TCP 0x10 #define SIGAR_NETCONN_UDP 0x20 #define SIGAR_NETCONN_RAW 0x40 #define SIGAR_NETCONN_UNIX 0x80 enum { SIGAR_TCP_ESTABLISHED = 1, SIGAR_TCP_SYN_SENT, SIGAR_TCP_SYN_RECV, SIGAR_TCP_FIN_WAIT1, SIGAR_TCP_FIN_WAIT2, SIGAR_TCP_TIME_WAIT, SIGAR_TCP_CLOSE, SIGAR_TCP_CLOSE_WAIT, SIGAR_TCP_LAST_ACK, SIGAR_TCP_LISTEN, SIGAR_TCP_CLOSING, SIGAR_TCP_IDLE, SIGAR_TCP_BOUND, SIGAR_TCP_UNKNOWN }; typedef struct { unsigned long local_port; sigar_net_address_t local_address; unsigned long remote_port; sigar_net_address_t remote_address; sigar_uid_t uid; unsigned long inode; int type; int state; unsigned long send_queue; unsigned long receive_queue; } sigar_net_connection_t; typedef struct { unsigned long number; unsigned long size; sigar_net_connection_t *data; } sigar_net_connection_list_t; SIGAR_DECLARE(int) sigar_net_connection_list_get(sigar_t *sigar, sigar_net_connection_list_t *connlist, int flags); SIGAR_DECLARE(int) sigar_net_connection_list_destroy(sigar_t *sigar, sigar_net_connection_list_t *connlist); typedef struct sigar_net_connection_walker_t sigar_net_connection_walker_t; /* alternative to sigar_net_connection_list_get */ struct sigar_net_connection_walker_t { sigar_t *sigar; int flags; void *data; /* user data */ int (*add_connection)(sigar_net_connection_walker_t *walker, sigar_net_connection_t *connection); }; SIGAR_DECLARE(int) sigar_net_connection_walk(sigar_net_connection_walker_t *walker); typedef struct { int tcp_states[SIGAR_TCP_UNKNOWN]; sigar_uint32_t tcp_inbound_total; sigar_uint32_t tcp_outbound_total; sigar_uint32_t all_inbound_total; sigar_uint32_t all_outbound_total; } sigar_net_stat_t; SIGAR_DECLARE(int) sigar_net_stat_get(sigar_t *sigar, sigar_net_stat_t *netstat, int flags); SIGAR_DECLARE(int) sigar_net_stat_port_get(sigar_t *sigar, sigar_net_stat_t *netstat, int flags, sigar_net_address_t *address, unsigned long port); /* TCP-MIB */ typedef struct { sigar_uint64_t active_opens; sigar_uint64_t passive_opens; sigar_uint64_t attempt_fails; sigar_uint64_t estab_resets; sigar_uint64_t curr_estab; sigar_uint64_t in_segs; sigar_uint64_t out_segs; sigar_uint64_t retrans_segs; sigar_uint64_t in_errs; sigar_uint64_t out_rsts; } sigar_tcp_t; SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp); typedef struct { sigar_uint64_t null; sigar_uint64_t getattr; sigar_uint64_t setattr; sigar_uint64_t root; sigar_uint64_t lookup; sigar_uint64_t readlink; sigar_uint64_t read; sigar_uint64_t writecache; sigar_uint64_t write; sigar_uint64_t create; sigar_uint64_t remove; sigar_uint64_t rename; sigar_uint64_t link; sigar_uint64_t symlink; sigar_uint64_t mkdir; sigar_uint64_t rmdir; sigar_uint64_t readdir; sigar_uint64_t fsstat; } sigar_nfs_v2_t; typedef sigar_nfs_v2_t sigar_nfs_client_v2_t; typedef sigar_nfs_v2_t sigar_nfs_server_v2_t; SIGAR_DECLARE(int) sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs); SIGAR_DECLARE(int) sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs); typedef struct { sigar_uint64_t null; sigar_uint64_t getattr; sigar_uint64_t setattr; sigar_uint64_t lookup; sigar_uint64_t access; sigar_uint64_t readlink; sigar_uint64_t read; sigar_uint64_t write; sigar_uint64_t create; sigar_uint64_t mkdir; sigar_uint64_t symlink; sigar_uint64_t mknod; sigar_uint64_t remove; sigar_uint64_t rmdir; sigar_uint64_t rename; sigar_uint64_t link; sigar_uint64_t readdir; sigar_uint64_t readdirplus; sigar_uint64_t fsstat; sigar_uint64_t fsinfo; sigar_uint64_t pathconf; sigar_uint64_t commit; } sigar_nfs_v3_t; typedef sigar_nfs_v3_t sigar_nfs_client_v3_t; typedef sigar_nfs_v3_t sigar_nfs_server_v3_t; SIGAR_DECLARE(int) sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs); SIGAR_DECLARE(int) sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs); SIGAR_DECLARE(int) sigar_net_listen_address_get(sigar_t *sigar, unsigned long port, sigar_net_address_t *address); typedef struct { char user[32]; char device[32]; char host[256]; sigar_uint64_t time; } sigar_who_t; typedef struct { unsigned long number; unsigned long size; sigar_who_t *data; } sigar_who_list_t; SIGAR_DECLARE(int) sigar_who_list_get(sigar_t *sigar, sigar_who_list_t *wholist); SIGAR_DECLARE(int) sigar_who_list_destroy(sigar_t *sigar, sigar_who_list_t *wholist); SIGAR_DECLARE(int) sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid); typedef struct { const char *build_date; const char *scm_revision; const char *version; const char *archname; const char *archlib; const char *binname; const char *description; int major, minor, maint, build; } sigar_version_t; SIGAR_DECLARE(sigar_version_t *) sigar_version_get(void); #define SIGAR_SYS_INFO_LEN SIGAR_MAXHOSTNAMELEN /* more than enough */ typedef struct { char name[SIGAR_SYS_INFO_LEN]; /* canonicalized sysname */ char version[SIGAR_SYS_INFO_LEN]; /* utsname.release */ char arch[SIGAR_SYS_INFO_LEN]; char machine[SIGAR_SYS_INFO_LEN]; char description[SIGAR_SYS_INFO_LEN]; char patch_level[SIGAR_SYS_INFO_LEN]; char vendor[SIGAR_SYS_INFO_LEN]; char vendor_version[SIGAR_SYS_INFO_LEN]; char vendor_name[SIGAR_SYS_INFO_LEN]; /* utsname.sysname */ char vendor_code_name[SIGAR_SYS_INFO_LEN]; } sigar_sys_info_t; SIGAR_DECLARE(int) sigar_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo); #define SIGAR_FQDN_LEN 512 SIGAR_DECLARE(int) sigar_fqdn_get(sigar_t *sigar, char *name, int namelen); SIGAR_DECLARE(int) sigar_rpc_ping(char *hostname, int protocol, unsigned long program, unsigned long version); SIGAR_DECLARE(char *) sigar_rpc_strerror(int err); SIGAR_DECLARE(char *) sigar_password_get(const char *prompt); #ifdef __cplusplus } #endif #endif hyperic-sigar-1.6.4+dfsg/include/sigar_fileinfo.h000066400000000000000000000145451210132627500217730ustar00rootroot00000000000000/* * Copyright (c) 2004-2005 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. */ /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ #include "sigar.h" typedef enum { SIGAR_FILETYPE_NOFILE = 0, /**< no file type determined */ SIGAR_FILETYPE_REG, /**< a regular file */ SIGAR_FILETYPE_DIR, /**< a directory */ SIGAR_FILETYPE_CHR, /**< a character device */ SIGAR_FILETYPE_BLK, /**< a block device */ SIGAR_FILETYPE_PIPE, /**< a FIFO / pipe */ SIGAR_FILETYPE_LNK, /**< a symbolic link */ SIGAR_FILETYPE_SOCK, /**< a [unix domain] socket */ SIGAR_FILETYPE_UNKFILE /**< a file of some other unknown type */ } sigar_file_type_e; #define SIGAR_UREAD 0x0400 /**< Read by user */ #define SIGAR_UWRITE 0x0200 /**< Write by user */ #define SIGAR_UEXECUTE 0x0100 /**< Execute by user */ #define SIGAR_GREAD 0x0040 /**< Read by group */ #define SIGAR_GWRITE 0x0020 /**< Write by group */ #define SIGAR_GEXECUTE 0x0010 /**< Execute by group */ #define SIGAR_WREAD 0x0004 /**< Read by others */ #define SIGAR_WWRITE 0x0002 /**< Write by others */ #define SIGAR_WEXECUTE 0x0001 /**< Execute by others */ typedef struct { /** The access permissions of the file. Mimics Unix access rights. */ sigar_uint64_t permissions; sigar_file_type_e type; /** The user id that owns the file */ sigar_uid_t uid; /** The group id that owns the file */ sigar_gid_t gid; /** The inode of the file. */ sigar_uint64_t inode; /** The id of the device the file is on. */ sigar_uint64_t device; /** The number of hard links to the file. */ sigar_uint64_t nlink; /** The size of the file */ sigar_uint64_t size; /** The time the file was last accessed */ sigar_uint64_t atime; /** The time the file was last modified */ sigar_uint64_t mtime; /** The time the file was last changed */ sigar_uint64_t ctime; } sigar_file_attrs_t; typedef struct { sigar_uint64_t total; sigar_uint64_t files; sigar_uint64_t subdirs; sigar_uint64_t symlinks; sigar_uint64_t chrdevs; sigar_uint64_t blkdevs; sigar_uint64_t sockets; sigar_uint64_t disk_usage; } sigar_dir_stat_t; typedef sigar_dir_stat_t sigar_dir_usage_t; SIGAR_DECLARE(const char *) sigar_file_attrs_type_string_get(sigar_file_type_e type); SIGAR_DECLARE(int) sigar_file_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs); SIGAR_DECLARE(int) sigar_link_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs); SIGAR_DECLARE(int)sigar_file_attrs_mode_get(sigar_uint64_t permissions); SIGAR_DECLARE(char *) sigar_file_attrs_permissions_string_get(sigar_uint64_t permissions, char *str); SIGAR_DECLARE(int) sigar_dir_stat_get(sigar_t *sigar, const char *dir, sigar_dir_stat_t *dirstats); SIGAR_DECLARE(int) sigar_dir_usage_get(sigar_t *sigar, const char *dir, sigar_dir_usage_t *dirusage); hyperic-sigar-1.6.4+dfsg/include/sigar_format.h000066400000000000000000000042001210132627500214530ustar00rootroot00000000000000/* * Copyright (c) 2007-2008 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. */ #ifndef SIGAR_FORMAT_H #define SIGAR_FORMAT_H typedef struct { double user; double sys; double nice; double idle; double wait; double irq; double soft_irq; double stolen; double combined; } sigar_cpu_perc_t; SIGAR_DECLARE(int) sigar_cpu_perc_calculate(sigar_cpu_t *prev, sigar_cpu_t *curr, sigar_cpu_perc_t *perc); SIGAR_DECLARE(int) sigar_uptime_string(sigar_t *sigar, sigar_uptime_t *uptime, char *buffer, int buflen); SIGAR_DECLARE(char *) sigar_format_size(sigar_uint64_t size, char *buf); SIGAR_DECLARE(int) sigar_net_address_equals(sigar_net_address_t *addr1, sigar_net_address_t *addr2); SIGAR_DECLARE(int) sigar_net_address_to_string(sigar_t *sigar, sigar_net_address_t *address, char *addr_str); SIGAR_DECLARE(sigar_uint32_t) sigar_net_address_hash(sigar_net_address_t *address); SIGAR_DECLARE(const char *)sigar_net_connection_type_get(int type); SIGAR_DECLARE(const char *)sigar_net_connection_state_get(int state); SIGAR_DECLARE(char *) sigar_net_interface_flags_to_string(sigar_uint64_t flags, char *buf); SIGAR_DECLARE(char *)sigar_net_services_name_get(sigar_t *sigar, int protocol, unsigned long port); #endif hyperic-sigar-1.6.4+dfsg/include/sigar_getline.h000066400000000000000000000012061210132627500216150ustar00rootroot00000000000000#ifndef SIGAR_GETLINE_H #define SIGAR_GETLINE_H #include "sigar.h" typedef int (*sigar_getline_completer_t)(char *, int, int *); SIGAR_DECLARE(char *) sigar_getline(char *prompt); SIGAR_DECLARE(void) sigar_getline_setwidth(int width); SIGAR_DECLARE(void) sigar_getline_redraw(void); SIGAR_DECLARE(void) sigar_getline_reset(void); SIGAR_DECLARE(void) sigar_getline_windowchanged(); SIGAR_DECLARE(void) sigar_getline_histinit(char *file); SIGAR_DECLARE(void) sigar_getline_histadd(char *buf); SIGAR_DECLARE(int) sigar_getline_eof(); SIGAR_DECLARE(void) sigar_getline_completer_set(sigar_getline_completer_t func); #endif /* SIGAR_GETLINE_H */ hyperic-sigar-1.6.4+dfsg/include/sigar_log.h000066400000000000000000000043541210132627500207560ustar00rootroot00000000000000/* * Copyright (c) 2004, 2006 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. */ #ifndef SIGAR_LOG_H #define SIGAR_LOG_H #include #define SIGAR_LOG_FATAL 0 #define SIGAR_LOG_ERROR 1 #define SIGAR_LOG_WARN 2 #define SIGAR_LOG_INFO 3 #define SIGAR_LOG_DEBUG 4 #define SIGAR_LOG_TRACE 5 #define SIGAR_LOG_IS_FATAL(sigar) \ (sigar->log_level >= SIGAR_LOG_FATAL) #define SIGAR_LOG_IS_ERROR(sigar) \ (sigar->log_level >= SIGAR_LOG_ERROR) #define SIGAR_LOG_IS_WARN(sigar) \ (sigar->log_level >= SIGAR_LOG_WARN) #define SIGAR_LOG_IS_INFO(sigar) \ (sigar->log_level >= SIGAR_LOG_INFO) #define SIGAR_LOG_IS_DEBUG(sigar) \ (sigar->log_level >= SIGAR_LOG_DEBUG) #define SIGAR_LOG_IS_TRACE(sigar) \ (sigar->log_level >= SIGAR_LOG_TRACE) #define SIGAR_STRINGIFY(n) #n #define SIGAR_LOG_FILELINE \ __FILE__ ":" SIGAR_STRINGIFY(__LINE__) #if defined(__GNUC__) # if (__GNUC__ > 2) # define SIGAR_FUNC __func__ # else # define SIGAR_FUNC __FUNCTION__ # endif #else # define SIGAR_FUNC SIGAR_LOG_FILELINE #endif typedef void (*sigar_log_impl_t)(sigar_t *, void *, int, char *); SIGAR_DECLARE(void) sigar_log_printf(sigar_t *sigar, int level, const char *format, ...); SIGAR_DECLARE(void) sigar_log(sigar_t *sigar, int level, char *message); SIGAR_DECLARE(void) sigar_log_impl_set(sigar_t *sigar, void *data, sigar_log_impl_t impl); SIGAR_DECLARE(void) sigar_log_impl_file(sigar_t *sigar, void *data, int level, char *message); SIGAR_DECLARE(int) sigar_log_level_get(sigar_t *sigar); SIGAR_DECLARE(void) sigar_log_level_set(sigar_t *sigar, int level); #endif /* SIGAR_LOG_H */ hyperic-sigar-1.6.4+dfsg/include/sigar_private.h000066400000000000000000000227331210132627500216500ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 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. */ #ifndef SIGAR_PRIVATE_DOT_H #define SIGAR_PRIVATE_DOT_H #include "sigar_log.h" #include "sigar_ptql.h" #include #include #include #ifndef WIN32 #include #include #ifndef DARWIN #include #endif #endif #ifdef DMALLOC #define _MEMORY_H /* exclude memory.h on solaris */ #define DMALLOC_FUNC_CHECK #include #endif /* common to all os sigar_t's */ /* XXX: this is ugly; but don't want the same stuffs * duplicated on 4 platforms and am too lazy to change * sigar_t to the way it was originally where sigar_t was * common and contained a sigar_os_t. * feel free trav ;-) */ #define SIGAR_T_BASE \ int cpu_list_cores; \ int log_level; \ void *log_data; \ sigar_log_impl_t log_impl; \ void *ptql_re_data; \ sigar_ptql_re_impl_t ptql_re_impl; \ unsigned int ncpu; \ unsigned long version; \ unsigned long boot_time; \ int ticks; \ sigar_pid_t pid; \ char errbuf[256]; \ char *ifconf_buf; \ int ifconf_len; \ char *self_path; \ sigar_proc_list_t *pids; \ sigar_cache_t *fsdev; \ sigar_cache_t *proc_cpu; \ sigar_cache_t *net_listen; \ sigar_cache_t *net_services_tcp; \ sigar_cache_t *net_services_udp #if defined(WIN32) # define SIGAR_INLINE __inline #elif defined(__GNUC__) # define SIGAR_INLINE inline #else # define SIGAR_INLINE #endif #ifdef DMALLOC /* linux has its own strdup macro, make sure we use dmalloc's */ #define sigar_strdup(s) \ dmalloc_strndup(__FILE__, __LINE__, (s), -1, 0) #else # ifdef WIN32 # define sigar_strdup(s) _strdup(s) # else # define sigar_strdup(s) strdup(s) # endif #endif #define SIGAR_ZERO(s) \ memset(s, '\0', sizeof(*(s))) #define SIGAR_STRNCPY(dest, src, len) \ strncpy(dest, src, len); \ dest[len-1] = '\0' /* we use fixed size buffers pretty much everywhere */ /* this is strncpy + ensured \0 terminator */ #define SIGAR_SSTRCPY(dest, src) \ SIGAR_STRNCPY(dest, src, sizeof(dest)) #ifndef strEQ #define strEQ(s1, s2) (strcmp(s1, s2) == 0) #endif #ifndef strnEQ #define strnEQ(s1, s2, n) (strncmp(s1, s2, n) == 0) #endif #ifdef WIN32 #define strcasecmp stricmp #define strncasecmp strnicmp #endif #ifndef strcaseEQ #define strcaseEQ(s1, s2) (strcasecmp(s1, s2) == 0) #endif #ifndef strncaseEQ #define strncaseEQ(s1, s2, n) (strncasecmp(s1, s2, n) == 0) #endif #ifdef offsetof #define sigar_offsetof offsetof #else #define sigar_offsetof(type, field) ((size_t)(&((type *)0)->field)) #endif #define SIGAR_MSEC 1000L #define SIGAR_USEC 1000000L #define SIGAR_NSEC 1000000000L #define SIGAR_SEC2NANO(s) \ ((sigar_uint64_t)(s) * (sigar_uint64_t)SIGAR_NSEC) /* cpu ticks to milliseconds */ #define SIGAR_TICK2MSEC(s) \ ((sigar_uint64_t)(s) * ((sigar_uint64_t)SIGAR_MSEC / (double)sigar->ticks)) #define SIGAR_TICK2NSEC(s) \ ((sigar_uint64_t)(s) * ((sigar_uint64_t)SIGAR_NSEC / (double)sigar->ticks)) /* nanoseconds to milliseconds */ #define SIGAR_NSEC2MSEC(s) \ ((sigar_uint64_t)(s) / ((sigar_uint64_t)1000000L)) #define IFTYPE_LO 2 #define IFTYPE_ETH 3 #define SIGAR_LAST_PROC_EXPIRE 2 #define SIGAR_FS_MAX 10 #define SIGAR_CPU_INFO_MAX 4 #define SIGAR_CPU_LIST_MAX 4 #define SIGAR_PROC_LIST_MAX 256 #define SIGAR_PROC_ARGS_MAX 12 #define SIGAR_NET_ROUTE_LIST_MAX 6 #define SIGAR_NET_IFLIST_MAX 20 #define SIGAR_NET_CONNLIST_MAX 20 #define SIGAR_WHO_LIST_MAX 12 int sigar_os_open(sigar_t **sigar); int sigar_os_close(sigar_t *sigar); char *sigar_os_error_string(sigar_t *sigar, int err); char *sigar_strerror_get(int err, char *errbuf, int buflen); void sigar_strerror_set(sigar_t *sigar, char *msg); void sigar_strerror_printf(sigar_t *sigar, const char *format, ...); int sigar_sys_info_get_uname(sigar_sys_info_t *sysinfo); int sigar_os_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo); int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist); int sigar_proc_list_create(sigar_proc_list_t *proclist); int sigar_proc_list_grow(sigar_proc_list_t *proclist); #define SIGAR_PROC_LIST_GROW(proclist) \ if (proclist->number >= proclist->size) { \ sigar_proc_list_grow(proclist); \ } int sigar_proc_args_create(sigar_proc_args_t *proclist); int sigar_proc_args_grow(sigar_proc_args_t *procargs); #define SIGAR_PROC_ARGS_GROW(procargs) \ if (procargs->number >= procargs->size) { \ sigar_proc_args_grow(procargs); \ } int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs); int sigar_file_system_list_create(sigar_file_system_list_t *fslist); int sigar_file_system_list_grow(sigar_file_system_list_t *fslist); #define SIGAR_FILE_SYSTEM_LIST_GROW(fslist) \ if (fslist->number >= fslist->size) { \ sigar_file_system_list_grow(fslist); \ } int sigar_os_fs_type_get(sigar_file_system_t *fsp); /* os plugins that set fsp->type call fs_type_get directly */ #define sigar_fs_type_init(fsp) \ fsp->type = SIGAR_FSTYPE_UNKNOWN; \ sigar_fs_type_get(fsp) void sigar_fs_type_get(sigar_file_system_t *fsp); int sigar_cpu_info_list_create(sigar_cpu_info_list_t *cpu_infos); int sigar_cpu_info_list_grow(sigar_cpu_info_list_t *cpu_infos); #define SIGAR_CPU_INFO_LIST_GROW(cpu_infos) \ if (cpu_infos->number >= cpu_infos->size) { \ sigar_cpu_info_list_grow(cpu_infos); \ } int sigar_cpu_list_create(sigar_cpu_list_t *cpulist); int sigar_cpu_list_grow(sigar_cpu_list_t *cpulist); #define SIGAR_CPU_LIST_GROW(cpulist) \ if (cpulist->number >= cpulist->size) { \ sigar_cpu_list_grow(cpulist); \ } int sigar_net_route_list_create(sigar_net_route_list_t *routelist); int sigar_net_route_list_grow(sigar_net_route_list_t *net_routelist); #define SIGAR_NET_ROUTE_LIST_GROW(routelist) \ if (routelist->number >= routelist->size) { \ sigar_net_route_list_grow(routelist); \ } int sigar_net_interface_list_create(sigar_net_interface_list_t *iflist); int sigar_net_interface_list_grow(sigar_net_interface_list_t *iflist); #define SIGAR_NET_IFLIST_GROW(iflist) \ if (iflist->number >= iflist->size) { \ sigar_net_interface_list_grow(iflist); \ } int sigar_net_connection_list_create(sigar_net_connection_list_t *connlist); int sigar_net_connection_list_grow(sigar_net_connection_list_t *connlist); #define SIGAR_NET_CONNLIST_GROW(connlist) \ if (connlist->number >= connlist->size) { \ sigar_net_connection_list_grow(connlist); \ } #define sigar_net_address_set(a, val) \ (a).addr.in = val; \ (a).family = SIGAR_AF_INET #define sigar_net_address6_set(a, val) \ memcpy(&((a).addr.in6), val, sizeof((a).addr.in6)); \ (a).family = SIGAR_AF_INET6 #define SIGAR_IFHWADDRLEN 6 #define sigar_net_address_mac_set(a, val, len) \ memcpy(&((a).addr.mac), val, len); \ (a).family = SIGAR_AF_LINK #define sigar_hwaddr_set_null(ifconfig) \ SIGAR_ZERO(&ifconfig->hwaddr.addr.mac); \ ifconfig->hwaddr.family = SIGAR_AF_LINK int sigar_tcp_curr_estab(sigar_t *sigar, sigar_tcp_t *tcp); int sigar_who_list_create(sigar_who_list_t *wholist); int sigar_who_list_grow(sigar_who_list_t *wholist); #define SIGAR_WHO_LIST_GROW(wholist) \ if (wholist->number >= wholist->size) { \ sigar_who_list_grow(wholist); \ } int sigar_user_id_get(sigar_t *sigar, const char *name, int *uid); int sigar_user_name_get(sigar_t *sigar, int uid, char *buf, int buflen); int sigar_group_name_get(sigar_t *sigar, int gid, char *buf, int buflen); #define SIGAR_PROC_ENV_KEY_LOOKUP() \ if ((procenv->type == SIGAR_PROC_ENV_KEY) && \ (pid == sigar->pid)) \ { \ char *value = getenv(procenv->key); \ if (value != NULL) { \ procenv->env_getter(procenv->data, \ procenv->key, \ procenv->klen, \ value, strlen(value)); \ } \ return SIGAR_OK; \ } #define SIGAR_DISK_STATS_INIT(disk) \ (disk)->reads = (disk)->writes = \ (disk)->read_bytes = (disk)->write_bytes = \ (disk)->rtime = (disk)->wtime = (disk)->qtime = (disk)->time = \ (disk)->queue = (disk)->service_time = SIGAR_FIELD_NOTIMPL; \ (disk)->snaptime = 0 /* key used for filesystem (/) -> device (/dev/hda1) mapping */ /* and disk_usage cache for service_time */ #define SIGAR_FSDEV_ID(sb) \ (S_ISBLK((sb).st_mode) ? (sb).st_rdev : ((sb).st_ino + (sb).st_dev)) #if defined(WIN32) || defined(NETWARE) int sigar_get_iftype(const char *name, int *type, int *inst); #endif #define SIGAR_NIC_LOOPBACK "Local Loopback" #define SIGAR_NIC_ETHERNET "Ethernet" #define SIGAR_NIC_NETROM "AMPR NET/ROM" #ifndef WIN32 #include #endif #define SIGAR_HOSTENT_LEN 512 #if defined(_AIX) #define SIGAR_HAS_HOSTENT_DATA #endif typedef struct { char buffer[SIGAR_HOSTENT_LEN]; int error; #ifndef WIN32 struct hostent hs; #endif #ifdef SIGAR_HAS_HOSTENT_DATA struct hostent_data hd; #endif } sigar_hostent_t; #endif hyperic-sigar-1.6.4+dfsg/include/sigar_ptql.h000066400000000000000000000036461210132627500211600ustar00rootroot00000000000000/* * Copyright (c) 2006-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SIGAR_PTQL_H #define SIGAR_PTQL_H #define SIGAR_PTQL_MALFORMED_QUERY -1 typedef struct sigar_ptql_query_t sigar_ptql_query_t; #define SIGAR_PTQL_ERRMSG_SIZE 1024 typedef struct { char message[SIGAR_PTQL_ERRMSG_SIZE]; } sigar_ptql_error_t; typedef int (*sigar_ptql_re_impl_t)(void *, char *, char *); SIGAR_DECLARE(void) sigar_ptql_re_impl_set(sigar_t *sigar, void *data, sigar_ptql_re_impl_t impl); SIGAR_DECLARE(int) sigar_ptql_query_create(sigar_ptql_query_t **query, char *ptql, sigar_ptql_error_t *error); SIGAR_DECLARE(int) sigar_ptql_query_match(sigar_t *sigar, sigar_ptql_query_t *query, sigar_pid_t pid); SIGAR_DECLARE(int) sigar_ptql_query_destroy(sigar_ptql_query_t *query); SIGAR_DECLARE(int) sigar_ptql_query_find_process(sigar_t *sigar, sigar_ptql_query_t *query, sigar_pid_t *pid); SIGAR_DECLARE(int) sigar_ptql_query_find(sigar_t *sigar, sigar_ptql_query_t *query, sigar_proc_list_t *proclist); #endif /*SIGAR_PTQL_H*/ hyperic-sigar-1.6.4+dfsg/include/sigar_util.h000066400000000000000000000122271210132627500211500ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ #ifndef SIGAR_UTIL_H #define SIGAR_UTIL_H /* most of this is crap for dealing with linux /proc */ #define UITOA_BUFFER_SIZE \ (sizeof(int) * 3 + 1) #define SSTRLEN(s) \ (sizeof(s)-1) #define sigar_strtoul(ptr) \ strtoul(ptr, &ptr, 10) #define sigar_strtoull(ptr) \ strtoull(ptr, &ptr, 10) #define sigar_isspace(c) \ (isspace(((unsigned char)(c)))) #define sigar_isdigit(c) \ (isdigit(((unsigned char)(c)))) #define sigar_isalpha(c) \ (isalpha(((unsigned char)(c)))) #define sigar_isupper(c) \ (isupper(((unsigned char)(c)))) #define sigar_tolower(c) \ (tolower(((unsigned char)(c)))) #ifdef WIN32 #define sigar_fileno _fileno #define sigar_isatty _isatty #define sigar_write _write #else #define sigar_fileno fileno #define sigar_isatty isatty #define sigar_write write #endif #ifndef PROC_FS_ROOT #define PROC_FS_ROOT "/proc/" #endif #ifndef PROCP_FS_ROOT #define PROCP_FS_ROOT "/proc/" #endif sigar_int64_t sigar_time_now_millis(void); char *sigar_uitoa(char *buf, unsigned int n, int *len); int sigar_inet_ntoa(sigar_t *sigar, sigar_uint32_t address, char *addr_str); struct hostent *sigar_gethostbyname(const char *name, sigar_hostent_t *data); SIGAR_INLINE char *sigar_skip_line(char *buffer, int buflen); SIGAR_INLINE char *sigar_skip_token(char *p); SIGAR_INLINE char *sigar_skip_multiple_token(char *p, int count); char *sigar_getword(char **line, char stop); char *sigar_strcasestr(const char *s1, const char *s2); int sigar_file2str(const char *fname, char *buffer, int buflen); int sigar_proc_file2str(char *buffer, int buflen, sigar_pid_t pid, const char *fname, int fname_len); #define SIGAR_PROC_FILE2STR(buffer, pid, fname) \ sigar_proc_file2str(buffer, sizeof(buffer), \ pid, fname, SSTRLEN(fname)) #define SIGAR_PROC_FILENAME(buffer, pid, fname) \ sigar_proc_filename(buffer, sizeof(buffer), \ pid, fname, SSTRLEN(fname)) #define SIGAR_SKIP_SPACE(ptr) \ while (sigar_isspace(*ptr)) ++ptr char *sigar_proc_filename(char *buffer, int buflen, sigar_pid_t pid, const char *fname, int fname_len); int sigar_proc_list_procfs_get(sigar_t *sigar, sigar_proc_list_t *proclist); int sigar_proc_fd_count(sigar_t *sigar, sigar_pid_t pid, sigar_uint64_t *total); /* linux + freebsd */ int sigar_procfs_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs); int sigar_mem_calc_ram(sigar_t *sigar, sigar_mem_t *mem); int sigar_statvfs(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage); double sigar_file_system_usage_calc_used(sigar_t *sigar, sigar_file_system_usage_t *fs); #define SIGAR_DEV_PREFIX "/dev/" #define SIGAR_NAME_IS_DEV(dev) \ strnEQ(dev, SIGAR_DEV_PREFIX, SSTRLEN(SIGAR_DEV_PREFIX)) typedef struct { char name[256]; int is_partition; sigar_disk_usage_t disk; } sigar_iodev_t; sigar_iodev_t *sigar_iodev_get(sigar_t *sigar, const char *dirname); int sigar_cpu_core_count(sigar_t *sigar); /* e.g. VM guest may have 1 virtual ncpu on multicore hosts */ #define sigar_cpu_socket_count(sigar) \ (sigar->ncpu < sigar->lcpu) ? sigar->ncpu : \ (sigar->ncpu / sigar->lcpu) int sigar_cpu_core_rollup(sigar_t *sigar); void sigar_cpu_model_adjust(sigar_t *sigar, sigar_cpu_info_t *info); int sigar_cpu_mhz_from_model(char *model); char *sigar_get_self_path(sigar_t *sigar); #if defined(__sun) || defined(__FreeBSD__) #define SIGAR_HAS_DLINFO_MODULES #include #include int sigar_dlinfo_modules(sigar_t *sigar, sigar_proc_modules_t *procmods); #endif typedef struct sigar_cache_entry_t sigar_cache_entry_t; struct sigar_cache_entry_t { sigar_cache_entry_t *next; sigar_uint64_t id; void *value; }; typedef struct { sigar_cache_entry_t **entries; unsigned int count, size; void (*free_value)(void *ptr); } sigar_cache_t; sigar_cache_t *sigar_cache_new(int size); sigar_cache_entry_t *sigar_cache_get(sigar_cache_t *table, sigar_uint64_t key); sigar_cache_entry_t *sigar_cache_find(sigar_cache_t *table, sigar_uint64_t key); void sigar_cache_destroy(sigar_cache_t *table); #endif /* SIGAR_UTIL_H */ hyperic-sigar-1.6.4+dfsg/src/000077500000000000000000000000001210132627500157755ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/000077500000000000000000000000001210132627500164165ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/aix/000077500000000000000000000000001210132627500171775ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/aix/aix_sigar.c000066400000000000000000001403351210132627500213170ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /* pull in time.h before resource.h does w/ _KERNEL */ #include #define _KERNEL 1 #include /* for struct file */ #include /* for rlimit32 in 64-bit mode */ #undef _KERNEL #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* for proc_port */ #include #include #include #include /* for net_connection_list */ #include #include #include #include /* for odm api */ #include #include #include #include /* not defined in aix 4.3 */ #ifndef SBITS #define SBITS 16 #endif #ifndef PTHRDSINFO_RUSAGE_START #define PTHRDSINFO_RUSAGE_START 0x00000001 #define PTHRDSINFO_RUSAGE_STOP 0x00000002 #define PTHRDSINFO_RUSAGE_COLLECT 0x00000004 #endif /* * from libperfstat.h: * "To calculate the load average, divide the numbers by (1<." */ #define FIXED_TO_DOUBLE(x) (((double)x) / (1<koffsets[i] = klist[i].n_value; } return SIGAR_OK; } static int kread(sigar_t *sigar, void *data, int size, long offset) { if (sigar->kmem < 0) { return SIGAR_EPERM_KMEM; } if (lseek(sigar->kmem, offset, SEEK_SET) != offset) { return errno; } if (read(sigar->kmem, data, size) != size) { return errno; } return SIGAR_OK; } static int sigar_thread_rusage(struct rusage *usage, int mode) { return pthread_getrusage_np(pthread_self(), usage, mode); } static int sigar_perfstat_memory(perfstat_memory_total_t *memory) { return perfstat_memory_total(NULL, memory, sizeof(*memory), 1); } static int sigar_perfstat_cpu(perfstat_cpu_total_t *cpu_total) { return perfstat_cpu_total(NULL, cpu_total, sizeof(*cpu_total), 1); } int sigar_os_open(sigar_t **sigar) { int status, i; int kmem = -1; struct utsname name; kmem = open("/dev/kmem", O_RDONLY); *sigar = malloc(sizeof(**sigar)); (*sigar)->getprocfd = NULL; /*XXX*/ (*sigar)->kmem = kmem; (*sigar)->pagesize = 0; (*sigar)->ticks = sysconf(_SC_CLK_TCK); (*sigar)->boot_time = 0; (*sigar)->last_pid = -1; (*sigar)->pinfo = NULL; (*sigar)->cpuinfo = NULL; (*sigar)->cpuinfo_size = 0; SIGAR_ZERO(&(*sigar)->swaps); i = getpagesize(); while ((i >>= 1) > 0) { (*sigar)->pagesize++; } if (kmem > 0) { if ((status = get_koffsets(*sigar)) != SIGAR_OK) { /* libperfstat only mode (aix 6) */ close((*sigar)->kmem); (*sigar)->kmem = -1; } } (*sigar)->cpu_mhz = -1; (*sigar)->model[0] = '\0'; uname(&name); (*sigar)->aix_version = atoi(name.version); (*sigar)->thrusage = PTHRDSINFO_RUSAGE_STOP; (*sigar)->diskmap = NULL; return SIGAR_OK; } static void swaps_free(swaps_t *swaps); int sigar_os_close(sigar_t *sigar) { swaps_free(&sigar->swaps); if (sigar->kmem > 0) { close(sigar->kmem); } if (sigar->pinfo) { free(sigar->pinfo); } if (sigar->cpuinfo) { free(sigar->cpuinfo); } if (sigar->diskmap) { sigar_cache_destroy(sigar->diskmap); } if (sigar->thrusage == PTHRDSINFO_RUSAGE_START) { struct rusage usage; sigar_thread_rusage(&usage, PTHRDSINFO_RUSAGE_STOP); } free(sigar); return SIGAR_OK; } char *sigar_os_error_string(sigar_t *sigar, int err) { switch (err) { case SIGAR_EPERM_KMEM: return "Failed to open /dev/kmem for reading"; default: return NULL; } } #define PAGESHIFT(v) \ ((v) << sigar->pagesize) int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem) { int status; perfstat_memory_total_t minfo; sigar_uint64_t kern; if (sigar_perfstat_memory(&minfo) == 1) { mem->total = PAGESHIFT(minfo.real_total); mem->free = PAGESHIFT(minfo.real_free); kern = PAGESHIFT(minfo.numperm); /* number of pages in file cache */ } else { return errno; } mem->used = mem->total - mem->free; mem->actual_used = mem->used - kern; mem->actual_free = mem->free + kern; sigar_mem_calc_ram(sigar, mem); return SIGAR_OK; } static void swaps_free(swaps_t *swaps) { if (swaps->num) { int i; for (i=0; inum; i++) { free(swaps->devs[i]); } free(swaps->devs); swaps->num = 0; } } /* * there is no public api for parsing this file. * well, there is something, but its super ugly and requires * linking 2 static libraries (libodm and something else) * maybe will switch to that if it can add value elsewhere too. */ #define SWAPSPACES "/etc/swapspaces" static int swaps_get(swaps_t *swaps) { FILE *fp; char buf[512]; char *ptr; struct stat statbuf; if (stat(SWAPSPACES, &statbuf) < 0) { return errno; } /* only re-parse if file has changed */ if (swaps->mtime == statbuf.st_mtime) { return 0; } swaps->mtime = statbuf.st_mtime; /* easier to just start from scratch */ swaps_free(swaps); if (!(fp = fopen(SWAPSPACES, "r"))) { return errno; } while ((ptr = fgets(buf, sizeof(buf), fp))) { if (!isalpha(*ptr)) { continue; } if (strchr(ptr, ':')) { int len; ptr = fgets(buf, sizeof(buf), fp); while (isspace(*ptr)) { ++ptr; } if (strncmp(ptr, "dev", 3)) { continue; } ptr += 3; while (isspace(*ptr) || (*ptr == '=')) { ++ptr; } len = strlen(ptr); ptr[len-1] = '\0'; /* -1 == chomp \n */ swaps->devs = realloc(swaps->devs, swaps->num+1 * sizeof(char *)); swaps->devs[swaps->num] = malloc(len); memcpy(swaps->devs[swaps->num], ptr, len); swaps->num++; } } fclose(fp); return 0; } /* * documented in aix tech ref, * but this prototype is not in any friggin header file. * struct pginfo is in sys/vminfo.h */ int swapqry(char *path, struct pginfo *info); static int sigar_swap_get_swapqry(sigar_t *sigar, sigar_swap_t *swap) { int status, i; if ((status = swaps_get(&sigar->swaps)) != SIGAR_OK) { return status; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[swap] pagesize=%d, shift=%d", getpagesize(), sigar->pagesize); } swap->total = swap->free = 0; for (i=0; iswaps.num; i++) { struct pginfo info; status = swapqry(sigar->swaps.devs[i], &info); if (status != 0) { if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[swap] swapqry(%s) failed: %s", sigar->swaps.devs[i], sigar_strerror(sigar, errno)); } continue; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[swap] %s total=%d/%d, free=%d/%d", sigar->swaps.devs[i], info.size, PAGESHIFT(info.size), info.free, PAGESHIFT(info.free)); } swap->total += PAGESHIFT(info.size); /* lsps -a */ swap->free += PAGESHIFT(info.free); } swap->used = swap->total - swap->free; return SIGAR_OK; } #define SWAP_DEV(ps) \ ((ps.type == LV_PAGING) ? \ ps.u.lv_paging.vgname : \ ps.u.nfs_paging.filename) #define SWAP_MB_TO_BYTES(v) ((v) * (1024 * 1024)) int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) { perfstat_memory_total_t minfo; perfstat_pagingspace_t ps; perfstat_id_t id; id.name[0] = '\0'; SIGAR_ZERO(swap); do { if (perfstat_pagingspace(&id, &ps, sizeof(ps), 1) != 1) { if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[swap] dev=%s query failed: %s", SWAP_DEV(ps), sigar_strerror(sigar, errno)); } continue; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[swap] dev=%s: active=%s, " "total=%lluMb, used=%lluMb", SWAP_DEV(ps), ((ps.active == 1) ? "yes" : "no"), ps.mb_size, ps.mb_used); } if (ps.active != 1) { continue; } /* convert MB sizes to bytes */ swap->total += SWAP_MB_TO_BYTES(ps.mb_size); swap->used += SWAP_MB_TO_BYTES(ps.mb_used); } while (id.name[0] != '\0'); swap->free = swap->total - swap->used; if (sigar_perfstat_memory(&minfo) == 1) { swap->page_in = minfo.pgins; swap->page_out = minfo.pgouts; } else { swap->page_in = swap->page_out = -1; } return SIGAR_OK; } int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu) { int i, status; struct sysinfo data; perfstat_cpu_total_t cpu_data; if (sigar_perfstat_cpu(&cpu_data) == 1) { cpu->user = SIGAR_TICK2MSEC(cpu_data.user); cpu->nice = SIGAR_FIELD_NOTIMPL; /* N/A */ cpu->sys = SIGAR_TICK2MSEC(cpu_data.sys); cpu->idle = SIGAR_TICK2MSEC(cpu_data.idle); cpu->wait = SIGAR_TICK2MSEC(cpu_data.wait); cpu->irq = 0; /*N/A*/ cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->sys + cpu->idle + cpu->wait; return SIGAR_OK; } else { return errno; } } /* * other possible metrics we could add: * struct cpuinfo { * long cpu[CPU_NTIMES]; * long pswitch; * long syscall; * long sysread; * long syswrite; * long sysfork; * long sysexec; * long readch; * long writech; * long iget; * long namei; * long dirblk; * long msg; * long sema; * long bread; * long bwrite; * long lread; * long lwrite; * long phread; * long phwrite; * }; */ int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { perfstat_cpu_t data; int i, ncpu = _system_configuration.ncpus; /* this can change */ perfstat_id_t id; id.name[0] = '\0'; sigar_cpu_list_create(cpulist); for (i=0; idata[cpulist->number++]; if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "cpu%d perfstat_id='%s'", i, id.name); } if (perfstat_cpu(&id, &data, sizeof(data), 1) == 1) { cpu->user = SIGAR_TICK2MSEC(data.user); cpu->nice = SIGAR_FIELD_NOTIMPL; /* N/A */ cpu->sys = SIGAR_TICK2MSEC(data.sys); cpu->idle = SIGAR_TICK2MSEC(data.idle); cpu->wait = SIGAR_TICK2MSEC(data.wait); cpu->irq = 0; /*N/A*/ cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->sys + cpu->idle + cpu->wait; } else { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "cpu%d perfstat_cpu(%s) failed: %s", i, id.name, sigar_strerror(sigar, errno)); SIGAR_ZERO(cpu); } } return SIGAR_OK; } static int boot_time(sigar_t *sigar, time_t *time) { int fd; struct utmp data; if ((fd = open(UTMP_FILE, O_RDONLY)) < 0) { return errno; } do { if (read(fd, &data, sizeof(data)) != sizeof(data)) { int status = errno; close(fd); return status; } } while (data.ut_type != BOOT_TIME); *time = data.ut_time; close(fd); return SIGAR_OK; } int sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime) { if (sigar->boot_time == 0) { int status; time_t time; if ((status = boot_time(sigar, &time)) != SIGAR_OK) { return status; } sigar->boot_time = time; } uptime->uptime = time(NULL) - sigar->boot_time; return SIGAR_OK; } #define WHOCPY(dest, src) \ SIGAR_SSTRCPY(dest, src); \ if (sizeof(src) < sizeof(dest)) \ dest[sizeof(dest)-1] = '\0' static int sigar_who_utmp(sigar_t *sigar, sigar_who_list_t *wholist) { struct utmp ut; FILE *fp; if (!(fp = fopen(UTMP_FILE, "r"))) { return errno; } while (fread(&ut, sizeof(ut), 1, fp) == 1) { sigar_who_t *who; if (*ut.ut_name == '\0') { continue; } if (ut.ut_type != USER_PROCESS) { continue; } SIGAR_WHO_LIST_GROW(wholist); who = &wholist->data[wholist->number++]; WHOCPY(who->user, ut.ut_user); WHOCPY(who->device, ut.ut_line); WHOCPY(who->host, ut.ut_host); who->time = ut.ut_time; } fclose(fp); return SIGAR_OK; } int sigar_who_list_get(sigar_t *sigar, sigar_who_list_t *wholist) { int status; sigar_who_list_create(wholist); status = sigar_who_utmp(sigar, wholist); if (status != SIGAR_OK) { sigar_who_list_destroy(sigar, wholist); return status; } return SIGAR_OK; } int sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg) { int status, i; int data[3]; perfstat_cpu_total_t cpu_data; if (sigar_perfstat_cpu(&cpu_data) == 1) { for (i=0; i<3; i++) { loadavg->loadavg[i] = FIXED_TO_DOUBLE(cpu_data.loadavg[i]); } return SIGAR_OK; } else { return errno; } } int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { pid_t pid = 0; struct procsinfo info; for (;;) { int num = getprocs(&info, sizeof(info), NULL, 0, &pid, 1); if (num == 0) { break; } SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = info.pi_pid; } return SIGAR_OK; } static int sigar_getprocs(sigar_t *sigar, sigar_pid_t pid) { int status, num; time_t timenow = time(NULL); if (sigar->pinfo == NULL) { sigar->pinfo = malloc(sizeof(*sigar->pinfo)); } if (sigar->last_pid == pid) { if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) { return SIGAR_OK; } } sigar->last_pid = pid; sigar->last_getprocs = timenow; num = getprocs(sigar->pinfo, sizeof(*sigar->pinfo), NULL, 0, &pid, 1); if (num != 1) { return ESRCH; } return SIGAR_OK; } int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem) { int status = sigar_getprocs(sigar, pid); struct procsinfo64 *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } procmem->size = PAGESHIFT(pinfo->pi_size); /* XXX fold in pi_dvm ? */ procmem->share = PAGESHIFT(pinfo->pi_sdsize); procmem->resident = PAGESHIFT(pinfo->pi_drss + pinfo->pi_trss); procmem->minor_faults = pinfo->pi_minflt; procmem->major_faults = pinfo->pi_majflt; procmem->page_faults = procmem->minor_faults + procmem->major_faults; return SIGAR_OK; } int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred) { int status = sigar_getprocs(sigar, pid); struct procsinfo64 *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } proccred->uid = pinfo->pi_cred.cr_ruid; proccred->euid = pinfo->pi_cred.cr_uid; if (proccred->uid == -1) { /* * aix 5.2 has a process named 'jfsz' * where uid is '-1', getpwuid returns EPERM */ proccred->uid = proccred->euid = 0; } proccred->gid = pinfo->pi_cred.cr_rgid; proccred->egid = pinfo->pi_cred.cr_gid; return SIGAR_OK; } int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime) { int status = sigar_getprocs(sigar, pid); struct procsinfo64 *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } proctime->start_time = pinfo->pi_start; proctime->start_time *= SIGAR_MSEC; /* convert to ms */ proctime->user = pinfo->pi_utime * SIGAR_MSEC; proctime->sys = pinfo->pi_stime * SIGAR_MSEC; proctime->total = proctime->user + proctime->sys; return SIGAR_OK; } int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { int status = sigar_getprocs(sigar, pid); struct procsinfo64 *pinfo = sigar->pinfo; tid_t tid = 0; struct thrdsinfo64 thrinfo; if (status != SIGAR_OK) { return status; } if (getthrds(pid, &thrinfo, sizeof(thrinfo), &tid, 1) == 1) { procstate->processor = thrinfo.ti_affinity; } else { procstate->processor = SIGAR_FIELD_NOTIMPL; } SIGAR_SSTRCPY(procstate->name, pinfo->pi_comm); procstate->ppid = pinfo->pi_ppid; procstate->nice = pinfo->pi_nice; procstate->tty = pinfo->pi_ttyd; procstate->priority = pinfo->pi_pri; procstate->threads = pinfo->pi_thcount; switch (pinfo->pi_state) { case SACTIVE: procstate->state = 'R'; break; case SIDL: procstate->state = 'D'; break; case SSTOP: procstate->state = 'S'; break; case SZOMB: procstate->state = 'Z'; break; case SSWAP: procstate->state = 'S'; break; } return SIGAR_OK; } int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { /* XXX if buffer is not large enough args are truncated */ char buffer[8192], *ptr; struct procsinfo pinfo; pinfo.pi_pid = pid; if (getargs(&pinfo, sizeof(pinfo), buffer, sizeof(buffer)) != 0) { return errno; } ptr = buffer; while (*ptr) { int alen = strlen(ptr)+1; char *arg = malloc(alen); SIGAR_PROC_ARGS_GROW(procargs); memcpy(arg, ptr, alen); procargs->data[procargs->number++] = arg; ptr += alen; } return SIGAR_OK; } int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { /* XXX if buffer is not large enough args are truncated */ char buffer[8192], *ptr; struct procsinfo pinfo; pinfo.pi_pid = pid; if (getevars(&pinfo, sizeof(pinfo), buffer, sizeof(buffer)) != 0) { return errno; } ptr = buffer; while (*ptr) { char *val = strchr(ptr, '='); int klen, vlen, status; char key[128]; /* XXX is there a max key size? */ if (val == NULL) { /* not key=val format */ procenv->env_getter(procenv->data, ptr, strlen(ptr), NULL, 0); break; } klen = val - ptr; SIGAR_SSTRCPY(key, ptr); key[klen] = '\0'; ++val; vlen = strlen(val); status = procenv->env_getter(procenv->data, key, klen, val, vlen); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } ptr += (klen + 1 + vlen + 1); } return SIGAR_OK; } int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd) { #ifdef SIGAR_64BIT /* XXX no getuser() in 64-bit mode */ return SIGAR_ENOTIMPL; #else int i; struct procsinfo pinfo; struct user uinfo; procfd->total = 0; pinfo.pi_pid = pid; if (getuser(&pinfo, sizeof(pinfo), &uinfo, sizeof(uinfo)) != 0) { if (errno == EINVAL) { return SIGAR_ENOTIMPL; /*XXX 5.2+*/ } } /* see sys/user.h */ for (i=0; itotal++; } } return SIGAR_OK; #endif } int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { int len; char buffer[8192]; struct procsinfo pinfo; pinfo.pi_pid = pid; if (getargs(&pinfo, sizeof(pinfo), buffer, sizeof(buffer)) != 0) { return errno; } /* XXX argv[0] might be relative */ len = strlen(buffer); SIGAR_SSTRCPY(procexe->name, buffer); (void)SIGAR_PROC_FILENAME(buffer, pid, "/cwd"); if ((len = readlink(buffer, procexe->cwd, sizeof(procexe->cwd)-1)) < 0) { return errno; } procexe->cwd[len] = '\0'; procexe->root[0] = '\0'; return SIGAR_OK; } static int sigar_proc_modules_local_get(sigar_t *sigar, sigar_proc_modules_t *procmods) { struct ld_info *info; char *buffer; int size = 2048, status; unsigned int offset; buffer = malloc(size); while ((loadquery(L_GETINFO, buffer, size) == -1) && (errno == ENOMEM)) { size += 2048; buffer = realloc(buffer, size); } info = (struct ld_info *)buffer; do { char *name = info->ldinfo_filename; status = procmods->module_getter(procmods->data, name, strlen(name)); if (status != SIGAR_OK) { /* not an error; just stop iterating */ free(buffer); return status; } offset = info->ldinfo_next; info = (struct ld_info *)((char*)info + offset); } while(offset); free(buffer); return SIGAR_OK; } int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { if (pid == sigar_pid_get(sigar)) { return sigar_proc_modules_local_get(sigar, procmods); } else { return SIGAR_ENOTIMPL; } } #define SIGAR_MICROSEC2NANO(s) \ ((sigar_uint64_t)(s) * (sigar_uint64_t)1000) #define TIME_NSEC(t) \ (SIGAR_SEC2NANO((t).tv_sec) + SIGAR_MICROSEC2NANO((t).tv_usec)) int sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu) { struct rusage usage; int retval; if (sigar->thrusage != PTHRDSINFO_RUSAGE_START) { sigar->thrusage = PTHRDSINFO_RUSAGE_START; retval = sigar_thread_rusage(&usage, PTHRDSINFO_RUSAGE_START); if (retval != 0) { return retval; } } retval = sigar_thread_rusage(&usage, PTHRDSINFO_RUSAGE_COLLECT); if (retval != 0) { return retval; } cpu->user = TIME_NSEC(usage.ru_utime); cpu->sys = TIME_NSEC(usage.ru_stime); cpu->total = TIME_NSEC(usage.ru_utime) + TIME_NSEC(usage.ru_stime); return SIGAR_OK; } int sigar_os_fs_type_get(sigar_file_system_t *fsp) { return fsp->type; } #ifndef MNT_NFS4 /* another one documented in aix tech ref * with no friggin prototype in any header file... * ...but added in 5.2 */ int mntctl(int command, int size, char *buffer); #endif int sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist) { int i, size, num; char *buf, *mntlist; /* get required size */ if (mntctl(MCTL_QUERY, sizeof(size), (char *)&size) < 0) { return errno; } mntlist = buf = malloc(size); if ((num = mntctl(MCTL_QUERY, size, buf)) < 0) { free(buf); return errno; } sigar_file_system_list_create(fslist); for (i=0; ivmt_length; SIGAR_FILE_SYSTEM_LIST_GROW(fslist); fsp = &fslist->data[fslist->number++]; switch (ent->vmt_gfstype) { case MNT_AIX: typename = "aix"; fsp->type = SIGAR_FSTYPE_LOCAL_DISK; break; case MNT_JFS: typename = "jfs"; fsp->type = SIGAR_FSTYPE_LOCAL_DISK; break; case MNT_NFS: case MNT_NFS3: typename = "nfs"; fsp->type = SIGAR_FSTYPE_NETWORK; break; case MNT_CDROM: fsp->type = SIGAR_FSTYPE_CDROM; break; case MNT_SFS: case MNT_CACHEFS: case MNT_AUTOFS: default: if (ent->vmt_flags & MNT_REMOTE) { fsp->type = SIGAR_FSTYPE_NETWORK; } else { fsp->type = SIGAR_FSTYPE_NONE; } } SIGAR_SSTRCPY(fsp->dir_name, vmt2dataptr(ent, VMT_STUB)); SIGAR_SSTRCPY(fsp->options, vmt2dataptr(ent, VMT_ARGS)); devname = vmt2dataptr(ent, VMT_OBJECT); if (fsp->type == SIGAR_FSTYPE_NETWORK) { char *hostname = vmt2dataptr(ent, VMT_HOSTNAME); #if 0 /* XXX: these do not seem reliable */ int hostname_len = vmt2datasize(ent, VMT_HOSTNAME)-1; /* -1 == skip '\0' */ int devname_len = vmt2datasize(ent, VMT_OBJECT); /* includes '\0' */ #else int hostname_len = strlen(hostname); int devname_len = strlen(devname) + 1; #endif int total_len = hostname_len + devname_len + 1; /* 1 == strlen(":") */ if (total_len > sizeof(fsp->dev_name)) { /* justincase - prevent overflow. chances: slim..none */ SIGAR_SSTRCPY(fsp->dev_name, devname); } else { /* sprintf(fsp->devname, "%s:%s", hostname, devname) */ char *ptr = fsp->dev_name; memcpy(ptr, hostname, hostname_len); ptr += hostname_len; *ptr++ = ':'; memcpy(ptr, devname, devname_len); } } else { SIGAR_SSTRCPY(fsp->dev_name, devname); } /* we set fsp->type, just looking up sigar.c:fstype_names[type] */ sigar_fs_type_get(fsp); if (typename == NULL) { typename = fsp->type_name; } SIGAR_SSTRCPY(fsp->sys_type_name, typename); } free(buf); return SIGAR_OK; } typedef struct { char name[IDENTIFIER_LENGTH]; long addr; } aix_diskio_t; static int create_diskmap(sigar_t *sigar) { int i, total, num; perfstat_disk_t *disk; perfstat_id_t id; total = perfstat_disk(NULL, NULL, sizeof(*disk), 0); if (total < 1) { return ENOENT; } disk = malloc(total * sizeof(*disk)); id.name[0] = '\0'; num = perfstat_disk(&id, disk, sizeof(*disk), total); if (num < 1) { free(disk); return ENOENT; } sigar->diskmap = sigar_cache_new(25); odm_initialize(); for (i=0; iname, "label", 0, &num))) { retval = stat(attr->value, &sb); if (retval == 0) { aix_diskio_t *diskio = malloc(sizeof(*diskio)); SIGAR_SSTRCPY(diskio->name, disk[i].name); diskio->addr = -1; ent = sigar_cache_get(sigar->diskmap, SIGAR_FSDEV_ID(sb)); ent->value = diskio; } free(attr); } } odm_free_list(dv, &info); } free(disk); odm_terminate(); return SIGAR_OK; } int sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *usage) { perfstat_disk_t disk; perfstat_id_t id; SIGAR_SSTRCPY(id.name, name); if (perfstat_disk(&id, &disk, sizeof(disk), 1) != 1) { return ENXIO; } usage->reads = disk.rblks; usage->writes = disk.wblks; usage->read_bytes = disk.rblks * disk.bsize; usage->write_bytes = disk.wblks * disk.bsize; usage->queue = disk.qdepth; usage->time = disk.time; usage->rtime = SIGAR_FIELD_NOTIMPL; usage->wtime = SIGAR_FIELD_NOTIMPL; return SIGAR_OK; } int sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { sigar_cache_entry_t *ent; struct stat sb; int status; status = sigar_statvfs(sigar, dirname, fsusage); if (status != SIGAR_OK) { return status; } fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage); SIGAR_DISK_STATS_INIT(&fsusage->disk); if (!sigar->diskmap) { status = create_diskmap(sigar); if (status != SIGAR_OK) { return SIGAR_OK; } } status = stat(dirname, &sb); if (status == 0) { sigar_cache_entry_t *ent = sigar_cache_get(sigar->diskmap, SIGAR_FSDEV_ID(sb)); if (!ent->value) { return SIGAR_OK; } sigar_disk_usage_get(sigar, ((aix_diskio_t *)ent->value)->name, &fsusage->disk); } return SIGAR_OK; } /* from sys/systemcfg.h, not defined in 4.3 headers */ #ifndef POWER_4 #define POWER_4 0x0800 #endif #ifndef POWER_MPC7450 #define POWER_MPC7450 0x1000 #endif #ifndef POWER_5 #define POWER_5 0x2000 #endif static char *sigar_get_odm_model(sigar_t *sigar) { if (sigar->model[0] == '\0') { struct CuAt *odm_obj; int num; odm_initialize(); if ((odm_obj = getattr("proc0", "type", 0, &num))) { SIGAR_SSTRCPY(sigar->model, odm_obj->value); free(odm_obj); } odm_terminate(); } return sigar->model; } #define SIGAR_CPU_CACHE_SIZE \ (_system_configuration.L2_cache_size / 1024) static int sigar_get_cpu_mhz(sigar_t *sigar) { if (sigar->cpu_mhz == SIGAR_FIELD_NOTIMPL) { perfstat_cpu_total_t data; if (sigar_perfstat_cpu(&data) == 1) { sigar->cpu_mhz = data.processorHZ / 1000000; } else { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "perfstat_cpu_total failed: %s", sigar_strerror(sigar, errno)); } } return sigar->cpu_mhz; } static char *get_cpu_arch(void) { switch (_system_configuration.architecture) { case POWER_RS: return "Power Classic"; case POWER_PC: return "PowerPC"; case IA64: return "IA64"; default: return "PowerPC"; /* what else could it be */ } } static char *get_ppc_cpu_model(void) { switch (_system_configuration.implementation) { case POWER_RS1: return "RS1"; case POWER_RSC: return "RSC"; case POWER_RS2: return "RS2"; case POWER_601: return "601"; case POWER_603: return "603"; case POWER_604: return "604"; case POWER_620: return "620"; case POWER_630: return "630"; case POWER_A35: return "A35"; case POWER_RS64II: return "RS64-II"; case POWER_RS64III: return "RS64-III"; case POWER_4: return "POWER4"; case POWER_MPC7450: return "MPC7450"; case POWER_5: return "POWER5"; default: return "Unknown"; } } static char *get_ia64_cpu_model(void) { switch (_system_configuration.implementation) { case IA64_M1: return "M1"; case IA64_M2: return "M2"; default: return "Unknown"; } } static char *get_cpu_model(void) { if (_system_configuration.architecture == IA64) { return get_ia64_cpu_model(); } else { return get_ppc_cpu_model(); } } int sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { int i; int ncpu = _system_configuration.ncpus; /* this can change */ char *arch = get_cpu_arch(), *model = get_cpu_model(); /*XXX should only do this once*/ sigar_cpu_info_list_create(cpu_infos); for (i=0; idata[cpu_infos->number++]; info->total_cores = ncpu; info->cores_per_socket = 1; /*XXX*/ info->total_sockets = ncpu; /*XXX*/ info->cache_size = SIGAR_CPU_CACHE_SIZE; info->mhz = sigar_get_cpu_mhz(sigar); if (*arch == 'P') { SIGAR_SSTRCPY(info->vendor, "IBM"); } else if (*arch == 'I') { SIGAR_SSTRCPY(info->vendor, "Intel"); } else { SIGAR_SSTRCPY(info->vendor, "Unknown"); } snprintf(info->model, sizeof(info->model), "%s %s", arch, model); } return SIGAR_OK; } int sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist) { return SIGAR_ENOTIMPL; } int sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { perfstat_id_t id; perfstat_netinterface_t data; sigar_log(sigar, SIGAR_LOG_DEBUG, "[ifstat] using libperfstat"); SIGAR_SSTRCPY(id.name, name); if (perfstat_netinterface(&id, &data, sizeof(data), 1) == 1) { ifstat->rx_bytes = data.ibytes; ifstat->rx_packets = data.ipackets; ifstat->rx_errors = data.ierrors; ifstat->rx_dropped = SIGAR_FIELD_NOTIMPL; ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->rx_frame = SIGAR_FIELD_NOTIMPL; ifstat->tx_bytes = data.obytes; ifstat->tx_packets = data.opackets; ifstat->tx_errors = data.oerrors; ifstat->tx_dropped = SIGAR_FIELD_NOTIMPL; ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->tx_collisions = data.collisions; ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL; ifstat->speed = data.bitrate; return SIGAR_OK; } else { return errno; } } #define IS_TCP_SERVER(state, flags) \ ((flags & SIGAR_NETCONN_SERVER) && (state == TCPS_LISTEN)) #define IS_TCP_CLIENT(state, flags) \ ((flags & SIGAR_NETCONN_CLIENT) && (state != TCPS_LISTEN)) static int net_conn_get_tcp(sigar_net_connection_walker_t *walker) { sigar_t *sigar = walker->sigar; int flags = walker->flags; int status; struct inpcb tcp_inpcb; struct tcpcb tcpcb; struct inpcb *entry; status = kread(sigar, &tcp_inpcb, sizeof(tcp_inpcb), sigar->koffsets[KOFFSET_TCB]); if (status != SIGAR_OK) { return status; } entry = tcp_inpcb.inp_next; while (entry) { struct inpcb pcb; int state; status = kread(sigar, &pcb, sizeof(pcb), (long)entry); if (status != SIGAR_OK) { return status; } status = kread(sigar, &tcpcb, sizeof(tcpcb), (long)pcb.inp_ppcb); if (status != SIGAR_OK) { return status; } state = tcpcb.t_state; if ((IS_TCP_SERVER(state, flags) || IS_TCP_CLIENT(state, flags))) { sigar_net_connection_t conn; SIGAR_ZERO(&conn); conn.type = SIGAR_NETCONN_TCP; sigar_net_address_set(conn.local_address, pcb.inp_laddr.s_addr); sigar_net_address_set(conn.remote_address, pcb.inp_faddr.s_addr); conn.local_port = ntohs(pcb.inp_lport); conn.remote_port = ntohs(pcb.inp_fport); conn.send_queue = conn.receive_queue = SIGAR_FIELD_NOTIMPL; switch (state) { case TCPS_CLOSED: conn.state = SIGAR_TCP_CLOSE; break; case TCPS_LISTEN: conn.state = SIGAR_TCP_LISTEN; break; case TCPS_SYN_SENT: conn.state = SIGAR_TCP_SYN_SENT; break; case TCPS_SYN_RECEIVED: conn.state = SIGAR_TCP_SYN_RECV; break; case TCPS_ESTABLISHED: conn.state = SIGAR_TCP_ESTABLISHED; break; case TCPS_CLOSE_WAIT: conn.state = SIGAR_TCP_CLOSE_WAIT; break; case TCPS_FIN_WAIT_1: conn.state = SIGAR_TCP_FIN_WAIT1; break; case TCPS_CLOSING: conn.state = SIGAR_TCP_CLOSING; break; case TCPS_LAST_ACK: conn.state = SIGAR_TCP_LAST_ACK; break; case TCPS_FIN_WAIT_2: conn.state = SIGAR_TCP_FIN_WAIT2; break; case TCPS_TIME_WAIT: conn.state = SIGAR_TCP_TIME_WAIT; break; default: conn.state = SIGAR_TCP_UNKNOWN; break; } if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } entry = pcb.inp_next; if (entry == tcp_inpcb.inp_next) { break; } } return SIGAR_OK; } int sigar_net_connection_walk(sigar_net_connection_walker_t *walker) { int status; if (walker->flags & SIGAR_NETCONN_TCP) { status = net_conn_get_tcp(walker); if (status != SIGAR_OK) { return status; } } #if 0 if (walker->flags & SIGAR_NETCONN_UDP) { status = net_conn_get_udp(walker); if (status != SIGAR_OK) { return status; } } #endif return SIGAR_OK; } SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp) { perfstat_id_t id; perfstat_protocol_t proto; SIGAR_SSTRCPY(id.name, "tcp"); if (perfstat_protocol(&id, &proto, sizeof(proto), 1) != 1) { return ENOENT; } tcp->active_opens = proto.u.tcp.initiated; tcp->passive_opens = proto.u.tcp.accepted; tcp->attempt_fails = proto.u.tcp.dropped; tcp->estab_resets = proto.u.tcp.dropped; tcp->curr_estab = proto.u.tcp.established; tcp->in_segs = proto.u.tcp.ipackets; tcp->out_segs = proto.u.tcp.opackets; tcp->retrans_segs = 0; tcp->in_errs = proto.u.tcp.ierrors; tcp->out_rsts = 0; } #define NFS_V2_STAT_SET(type) \ nfs->null = proto.u.nfsv2.type.null; \ nfs->getattr = proto.u.nfsv2.type.getattr; \ nfs->setattr = proto.u.nfsv2.type.setattr; \ nfs->root = proto.u.nfsv2.type.root; \ nfs->lookup = proto.u.nfsv2.type.lookup; \ nfs->readlink = proto.u.nfsv2.type.readlink; \ nfs->read = proto.u.nfsv2.type.read; \ nfs->writecache = proto.u.nfsv2.type.writecache; \ nfs->write = proto.u.nfsv2.type.write; \ nfs->create = proto.u.nfsv2.type.create; \ nfs->remove = proto.u.nfsv2.type.remove; \ nfs->rename = proto.u.nfsv2.type.rename; \ nfs->link = proto.u.nfsv2.type.link; \ nfs->symlink = proto.u.nfsv2.type.symlink; \ nfs->mkdir = proto.u.nfsv2.type.mkdir; \ nfs->rmdir = proto.u.nfsv2.type.rmdir; \ nfs->readdir = proto.u.nfsv2.type.readdir; \ nfs->fsstat = proto.u.nfsv2.type.statfs int sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs) { perfstat_id_t id; perfstat_protocol_t proto; SIGAR_SSTRCPY(id.name, "nfsv2"); if (perfstat_protocol(&id, &proto, sizeof(proto), 1) != 1) { return ENOENT; } NFS_V2_STAT_SET(client); return SIGAR_OK; } int sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs) { perfstat_id_t id; perfstat_protocol_t proto; SIGAR_SSTRCPY(id.name, "nfsv2"); if (perfstat_protocol(&id, &proto, sizeof(proto), 1) != 1) { return ENOENT; } NFS_V2_STAT_SET(server); return SIGAR_OK; } #define NFS_V3_STAT_SET(type) \ nfs->null = proto.u.nfsv3.type.null; \ nfs->getattr = proto.u.nfsv3.type.getattr; \ nfs->setattr = proto.u.nfsv3.type.setattr; \ nfs->lookup = proto.u.nfsv3.type.lookup; \ nfs->access = proto.u.nfsv3.type.access; \ nfs->readlink = proto.u.nfsv3.type.readlink; \ nfs->read = proto.u.nfsv3.type.read; \ nfs->write = proto.u.nfsv3.type.write; \ nfs->create = proto.u.nfsv3.type.create; \ nfs->mkdir = proto.u.nfsv3.type.mkdir; \ nfs->symlink = proto.u.nfsv3.type.symlink; \ nfs->mknod = proto.u.nfsv3.type.mknod; \ nfs->remove = proto.u.nfsv3.type.remove; \ nfs->rmdir = proto.u.nfsv3.type.rmdir; \ nfs->rename = proto.u.nfsv3.type.rename; \ nfs->link = proto.u.nfsv3.type.link; \ nfs->readdir = proto.u.nfsv3.type.readdir; \ nfs->readdirplus = proto.u.nfsv3.type.readdirplus; \ nfs->fsstat = proto.u.nfsv3.type.fsstat; \ nfs->fsinfo = proto.u.nfsv3.type.fsinfo; \ nfs->pathconf = proto.u.nfsv3.type.pathconf; \ nfs->commit = proto.u.nfsv3.type.commit int sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs) { perfstat_id_t id; perfstat_protocol_t proto; SIGAR_SSTRCPY(id.name, "nfsv3"); if (perfstat_protocol(&id, &proto, sizeof(proto), 1) != 1) { return ENOENT; } NFS_V3_STAT_SET(client); return SIGAR_OK; } int sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs) { perfstat_id_t id; perfstat_protocol_t proto; SIGAR_SSTRCPY(id.name, "nfsv3"); if (perfstat_protocol(&id, &proto, sizeof(proto), 1) != 1) { return ENOENT; } NFS_V3_STAT_SET(server); return SIGAR_OK; } /* derived from pidentd's k_aix432.c */ int sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pidp) { struct procsinfo pinfo; struct fdsinfo finfo; pid_t pid = 0; int type; switch (protocol) { case SIGAR_NETCONN_TCP: type = IPPROTO_TCP; break; case SIGAR_NETCONN_UDP: type = IPPROTO_UDP; break; default: return SIGAR_ENOTIMPL; } for (;;) { int fd, status; int num = getprocs(&pinfo, sizeof(pinfo), &finfo, sizeof(finfo), &pid, 1); if (num == 0) { break; } if ((pinfo.pi_state == 0) || (pinfo.pi_state == SZOMB)) { continue; } for (fd = 0; fd < pinfo.pi_maxofile; fd++) { struct file file; struct socket socket, *sockp; struct protosw protosw; struct domain domain; struct inpcb inpcb; long ptr; if (!(ptr = (long)finfo.pi_ufd[fd].fp)) { continue; } status = kread(sigar, &file, sizeof(file), ptr); if (status != SIGAR_OK) { continue; } if (file.f_type != DTYPE_SOCKET) { continue; } if (!(sockp = (struct socket *)file.f_data)) { continue; } status = kread(sigar, &socket, sizeof(socket), (long)sockp); if (status != SIGAR_OK) { continue; } if (!(ptr = (long)socket.so_proto)) { continue; } status = kread(sigar, &protosw, sizeof(protosw), ptr); if (status != SIGAR_OK) { continue; } if (protosw.pr_protocol != type) { continue; } if (!(ptr = (long)protosw.pr_domain)) { continue; } status = kread(sigar, &domain, sizeof(domain), ptr); if (status != SIGAR_OK) { continue; } if ((domain.dom_family != AF_INET) && domain.dom_family != AF_INET6) { continue; } if (!(ptr = (long)socket.so_pcb)) { continue; } status = kread(sigar, &inpcb, sizeof(inpcb), ptr); if (status != SIGAR_OK) { continue; } if (sockp != inpcb.inp_socket) { continue; } if (inpcb.inp_lport != port) { continue; } *pidp = pinfo.pi_pid; return SIGAR_OK; } } return ENOENT; } int sigar_os_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo) { struct utsname name; uname(&name); SIGAR_SSTRCPY(sysinfo->vendor, "IBM"); SIGAR_SSTRCPY(sysinfo->arch, get_cpu_arch()); /* utsname.machine is a sequence number */ /* XXX odm might have something better */ snprintf(sysinfo->machine, sizeof(sysinfo->machine), "%s %s", sysinfo->arch, get_cpu_model()); snprintf(sysinfo->version, sizeof(sysinfo->version), "%s.%s", name.version, name.release); SIGAR_SSTRCPY(sysinfo->vendor_version, sysinfo->version); snprintf(sysinfo->description, sizeof(sysinfo->description), "%s %s", sysinfo->name, sysinfo->version); return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/os/aix/sigar_os.h000066400000000000000000000031621210132627500211600ustar00rootroot00000000000000/* * Copyright (c) 2004-2007, 2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #include #include #include #include #include enum { KOFFSET_LOADAVG, KOFFSET_VAR, KOFFSET_SYSINFO, KOFFSET_IFNET, KOFFSET_VMINFO, KOFFSET_CPUINFO, KOFFSET_TCB, KOFFSET_MAX }; typedef struct { time_t mtime; int num; char **devs; } swaps_t; typedef int (*proc_fd_func_t) (sigar_t *, sigar_pid_t, sigar_proc_fd_t *); struct sigar_t { SIGAR_T_BASE; int kmem; /* offsets for seeking on kmem */ long koffsets[KOFFSET_MAX]; proc_fd_func_t getprocfd; int pagesize; swaps_t swaps; time_t last_getprocs; sigar_pid_t last_pid; struct procsinfo64 *pinfo; struct cpuinfo *cpuinfo; int cpuinfo_size; int cpu_mhz; char model[128]; int aix_version; int thrusage; sigar_cache_t *diskmap; }; #define HAVE_STRERROR_R #define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES) #endif /* SIGAR_OS_H */ hyperic-sigar-1.6.4+dfsg/src/os/darwin/000077500000000000000000000000001210132627500177025ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/darwin/Info.plist.in000066400000000000000000000006161210132627500222620ustar00rootroot00000000000000 CFBundleDevelopmentRegion English CFBundleIdentifier org.hyperic.sigar CFBundleInfoDictionaryVersion 6.0 CFBundleName sigar CFBundleVersion @@VERSION_STRING@@ hyperic-sigar-1.6.4+dfsg/src/os/darwin/darwin_sigar.c000066400000000000000000002654361210132627500225370ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #include #include #if !(defined(__FreeBSD__) && (__FreeBSD_version >= 800000)) #include #endif #include #ifdef DARWIN #include #include #include #include #include #include #include #include #include #include #include #if !defined(HAVE_SHARED_REGION_H) && defined(__MAC_10_5) /* see Availability.h */ # define HAVE_SHARED_REGION_H /* suckit autoconf */ #endif #ifdef HAVE_SHARED_REGION_H #include /* does not exist in 10.4 SDK */ #else #include /* deprecated in Leopard */ #endif #include #define __OPENTRANSPORTPROVIDERS__ #include #include #include #include #include #include #include #else #include #include #include #include #include #include #include #endif #if defined(__FreeBSD__) && (__FreeBSD_version >= 500013) #define SIGAR_FREEBSD5_NFSSTAT #include #include #else #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __NetBSD__ #include #include #include #define SRUN LSRUN #define SSLEEP LSSLEEP #define SDEAD LSDEAD #define SONPROC LSONPROC #define SSUSPENDED LSSUSPENDED #include #endif #include #include #define NMIB(mib) (sizeof(mib)/sizeof(mib[0])) #ifdef __FreeBSD__ # if (__FreeBSD_version >= 500013) # define SIGAR_FREEBSD5 # else # define SIGAR_FREEBSD4 # endif #endif #if defined(SIGAR_FREEBSD5) #define KI_FD ki_fd #define KI_PID ki_pid #define KI_PPID ki_ppid #define KI_PRI ki_pri.pri_user #define KI_NICE ki_nice #define KI_COMM ki_comm #define KI_STAT ki_stat #define KI_UID ki_ruid #define KI_GID ki_rgid #define KI_EUID ki_svuid #define KI_EGID ki_svgid #define KI_SIZE ki_size #define KI_RSS ki_rssize #define KI_TSZ ki_tsize #define KI_DSZ ki_dsize #define KI_SSZ ki_ssize #define KI_FLAG ki_flag #define KI_START ki_start #elif defined(DARWIN) || defined(SIGAR_FREEBSD4) || defined(__OpenBSD__) || defined(__NetBSD__) #define KI_FD kp_proc.p_fd #define KI_PID kp_proc.p_pid #define KI_PPID kp_eproc.e_ppid #define KI_PRI kp_proc.p_priority #define KI_NICE kp_proc.p_nice #define KI_COMM kp_proc.p_comm #define KI_STAT kp_proc.p_stat #define KI_UID kp_eproc.e_pcred.p_ruid #define KI_GID kp_eproc.e_pcred.p_rgid #define KI_EUID kp_eproc.e_pcred.p_svuid #define KI_EGID kp_eproc.e_pcred.p_svgid #define KI_SIZE XXX #define KI_RSS kp_eproc.e_vm.vm_rssize #define KI_TSZ kp_eproc.e_vm.vm_tsize #define KI_DSZ kp_eproc.e_vm.vm_dsize #define KI_SSZ kp_eproc.e_vm.vm_ssize #define KI_FLAG kp_eproc.e_flag #define KI_START kp_proc.p_starttime #endif #ifndef DARWIN #define PROCFS_STATUS(status) \ ((((status) != SIGAR_OK) && !sigar->proc_mounted) ? \ SIGAR_ENOTIMPL : status) static int get_koffsets(sigar_t *sigar) { int i; struct nlist klist[] = { { "_cp_time" }, { "_cnt" }, #if defined(__OpenBSD__) || defined(__NetBSD__) { "_tcpstat" }, { "_tcbtable" }, #endif { NULL } }; if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } kvm_nlist(sigar->kmem, klist); for (i=0; ikoffsets[i] = klist[i].n_value; } return SIGAR_OK; } static int kread(sigar_t *sigar, void *data, int size, long offset) { if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } if (kvm_read(sigar->kmem, offset, data, size) != size) { return errno; } return SIGAR_OK; } #endif int sigar_os_open(sigar_t **sigar) { int mib[2]; int ncpu; size_t len; struct timeval boottime; #ifndef DARWIN struct stat sb; #endif len = sizeof(ncpu); mib[0] = CTL_HW; mib[1] = HW_NCPU; if (sysctl(mib, NMIB(mib), &ncpu, &len, NULL, 0) < 0) { return errno; } len = sizeof(boottime); mib[0] = CTL_KERN; mib[1] = KERN_BOOTTIME; if (sysctl(mib, NMIB(mib), &boottime, &len, NULL, 0) < 0) { return errno; } *sigar = malloc(sizeof(**sigar)); #ifdef DARWIN (*sigar)->mach_port = mach_host_self(); # ifdef DARWIN_HAS_LIBPROC_H if (((*sigar)->libproc = dlopen("/usr/lib/libproc.dylib", 0))) { (*sigar)->proc_pidinfo = dlsym((*sigar)->libproc, "proc_pidinfo"); (*sigar)->proc_pidfdinfo = dlsym((*sigar)->libproc, "proc_pidfdinfo"); } # endif #else (*sigar)->kmem = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL); if (stat("/proc/curproc", &sb) < 0) { (*sigar)->proc_mounted = 0; } else { (*sigar)->proc_mounted = 1; } #endif #ifndef DARWIN get_koffsets(*sigar); #endif (*sigar)->ncpu = ncpu; (*sigar)->lcpu = -1; (*sigar)->argmax = 0; (*sigar)->boot_time = boottime.tv_sec; /* XXX seems off a bit */ (*sigar)->pagesize = getpagesize(); #ifdef __FreeBSD__ (*sigar)->ticks = 100; /* sysconf(_SC_CLK_TCK) == 128 !? */ #else (*sigar)->ticks = sysconf(_SC_CLK_TCK); #endif (*sigar)->last_pid = -1; (*sigar)->pinfo = NULL; return SIGAR_OK; } int sigar_os_close(sigar_t *sigar) { if (sigar->pinfo) { free(sigar->pinfo); } #ifndef DARWIN if (sigar->kmem) { kvm_close(sigar->kmem); } #endif free(sigar); return SIGAR_OK; } char *sigar_os_error_string(sigar_t *sigar, int err) { switch (err) { case SIGAR_EPERM_KMEM: return "Failed to open /dev/kmem for reading"; case SIGAR_EPROC_NOENT: return "/proc filesystem is not mounted"; default: return NULL; } } /* ARG_MAX in FreeBSD 6.0 == 262144, which blows up the stack */ #define SIGAR_ARG_MAX 65536 #ifdef DARWIN static size_t sigar_argmax_get(sigar_t *sigar) { #ifdef KERN_ARGMAX int mib[] = { CTL_KERN, KERN_ARGMAX }; size_t size = sizeof(sigar->argmax); if (sigar->argmax != 0) { return sigar->argmax; } if (sysctl(mib, NMIB(mib), &sigar->argmax, &size, NULL, 0) == 0) { return sigar->argmax; } #endif return SIGAR_ARG_MAX; } #endif /* DARWIN */ #if defined(DARWIN) static int sigar_vmstat(sigar_t *sigar, vm_statistics_data_t *vmstat) { kern_return_t status; mach_msg_type_number_t count = sizeof(*vmstat) / sizeof(integer_t); status = host_statistics(sigar->mach_port, HOST_VM_INFO, (host_info_t)vmstat, &count); if (status == KERN_SUCCESS) { return SIGAR_OK; } else { return errno; } } #elif defined(__FreeBSD__) static int sigar_vmstat(sigar_t *sigar, struct vmmeter *vmstat) { int status; size_t size = sizeof(unsigned int); status = kread(sigar, vmstat, sizeof(*vmstat), sigar->koffsets[KOFFSET_VMMETER]); if (status == SIGAR_OK) { return SIGAR_OK; } SIGAR_ZERO(vmstat); /* derived from src/usr.bin/vmstat/vmstat.c */ /* only collect the ones we actually use */ #define GET_VM_STATS(cat, name, used) \ if (used) sysctlbyname("vm.stats." #cat "." #name, &vmstat->name, &size, NULL, 0) /* sys */ GET_VM_STATS(sys, v_swtch, 0); GET_VM_STATS(sys, v_trap, 0); GET_VM_STATS(sys, v_syscall, 0); GET_VM_STATS(sys, v_intr, 0); GET_VM_STATS(sys, v_soft, 0); /* vm */ GET_VM_STATS(vm, v_vm_faults, 0); GET_VM_STATS(vm, v_cow_faults, 0); GET_VM_STATS(vm, v_cow_optim, 0); GET_VM_STATS(vm, v_zfod, 0); GET_VM_STATS(vm, v_ozfod, 0); GET_VM_STATS(vm, v_swapin, 1); GET_VM_STATS(vm, v_swapout, 1); GET_VM_STATS(vm, v_swappgsin, 0); GET_VM_STATS(vm, v_swappgsout, 0); GET_VM_STATS(vm, v_vnodein, 1); GET_VM_STATS(vm, v_vnodeout, 1); GET_VM_STATS(vm, v_vnodepgsin, 0); GET_VM_STATS(vm, v_vnodepgsout, 0); GET_VM_STATS(vm, v_intrans, 0); GET_VM_STATS(vm, v_reactivated, 0); GET_VM_STATS(vm, v_pdwakeups, 0); GET_VM_STATS(vm, v_pdpages, 0); GET_VM_STATS(vm, v_dfree, 0); GET_VM_STATS(vm, v_pfree, 0); GET_VM_STATS(vm, v_tfree, 0); GET_VM_STATS(vm, v_page_size, 0); GET_VM_STATS(vm, v_page_count, 0); GET_VM_STATS(vm, v_free_reserved, 0); GET_VM_STATS(vm, v_free_target, 0); GET_VM_STATS(vm, v_free_min, 0); GET_VM_STATS(vm, v_free_count, 1); GET_VM_STATS(vm, v_wire_count, 0); GET_VM_STATS(vm, v_active_count, 0); GET_VM_STATS(vm, v_inactive_target, 0); GET_VM_STATS(vm, v_inactive_count, 1); GET_VM_STATS(vm, v_cache_count, 1); GET_VM_STATS(vm, v_cache_min, 0); GET_VM_STATS(vm, v_cache_max, 0); GET_VM_STATS(vm, v_pageout_free_min, 0); GET_VM_STATS(vm, v_interrupt_free_min, 0); GET_VM_STATS(vm, v_forks, 0); GET_VM_STATS(vm, v_vforks, 0); GET_VM_STATS(vm, v_rforks, 0); GET_VM_STATS(vm, v_kthreads, 0); GET_VM_STATS(vm, v_forkpages, 0); GET_VM_STATS(vm, v_vforkpages, 0); GET_VM_STATS(vm, v_rforkpages, 0); GET_VM_STATS(vm, v_kthreadpages, 0); #undef GET_VM_STATS return SIGAR_OK; } #elif defined(__OpenBSD__) || defined(__NetBSD__) static int sigar_vmstat(sigar_t *sigar, struct uvmexp *vmstat) { size_t size = sizeof(*vmstat); int mib[] = { CTL_VM, VM_UVMEXP }; if (sysctl(mib, NMIB(mib), vmstat, &size, NULL, 0) < 0) { return errno; } else { return SIGAR_OK; } } #endif int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem) { sigar_uint64_t kern = 0; #ifdef DARWIN vm_statistics_data_t vmstat; uint64_t mem_total; #else unsigned long mem_total; #endif #if defined(__FreeBSD__) struct vmmeter vmstat; #elif defined(__OpenBSD__) || defined(__NetBSD__) struct uvmexp vmstat; #endif int mib[2]; size_t len; int status; mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; len = sizeof(sigar->pagesize); if (sysctl(mib, NMIB(mib), &sigar->pagesize, &len, NULL, 0) < 0) { return errno; } #ifdef DARWIN mib[1] = HW_MEMSIZE; #else mib[1] = HW_PHYSMEM; #endif len = sizeof(mem_total); if (sysctl(mib, NMIB(mib), &mem_total, &len, NULL, 0) < 0) { return errno; } mem->total = mem_total; #if defined(DARWIN) if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) { return status; } mem->free = vmstat.free_count; mem->free *= sigar->pagesize; kern = vmstat.inactive_count; kern *= sigar->pagesize; #elif defined(__FreeBSD__) if ((status = sigar_vmstat(sigar, &vmstat)) == SIGAR_OK) { kern = vmstat.v_cache_count + vmstat.v_inactive_count; kern *= sigar->pagesize; mem->free = vmstat.v_free_count; mem->free *= sigar->pagesize; } #elif defined(__OpenBSD__) || defined(__NetBSD__) if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) { return status; } mem->free = vmstat.free; kern = vmstat.inactive; # if defined(__OpenBSD__) kern += vmstat.vnodepages + vmstat.vtextpages; # elif defined(__NetBSD__) kern += vmstat.filepages + vmstat.execpages; # endif kern *= sigar->pagesize; #endif mem->used = mem->total - mem->free; mem->actual_free = mem->free + kern; mem->actual_used = mem->used - kern; sigar_mem_calc_ram(sigar, mem); return SIGAR_OK; } #define SWI_MAXMIB 3 #ifdef SIGAR_FREEBSD5 /* code in this function is based on FreeBSD 5.3 kvm_getswapinfo.c */ static int getswapinfo_sysctl(struct kvm_swap *swap_ary, int swap_max) { int ti, ttl; size_t mibi, len, size; int soid[SWI_MAXMIB]; struct xswdev xsd; struct kvm_swap tot; int unswdev, dmmax; /* XXX this can be optimized by using os_open */ size = sizeof(dmmax); if (sysctlbyname("vm.dmmax", &dmmax, &size, NULL, 0) == -1) { return errno; } mibi = SWI_MAXMIB - 1; if (sysctlnametomib("vm.swap_info", soid, &mibi) == -1) { return errno; } bzero(&tot, sizeof(tot)); for (unswdev = 0;; unswdev++) { soid[mibi] = unswdev; len = sizeof(xsd); if (sysctl(soid, mibi + 1, &xsd, &len, NULL, 0) == -1) { if (errno == ENOENT) { break; } return errno; } #if 0 if (len != sizeof(xsd)) { _kvm_err(kd, kd->program, "struct xswdev has unexpected " "size; kernel and libkvm out of sync?"); return -1; } if (xsd.xsw_version != XSWDEV_VERSION) { _kvm_err(kd, kd->program, "struct xswdev version " "mismatch; kernel and libkvm out of sync?"); return -1; } #endif ttl = xsd.xsw_nblks - dmmax; if (unswdev < swap_max - 1) { bzero(&swap_ary[unswdev], sizeof(swap_ary[unswdev])); swap_ary[unswdev].ksw_total = ttl; swap_ary[unswdev].ksw_used = xsd.xsw_used; swap_ary[unswdev].ksw_flags = xsd.xsw_flags; } tot.ksw_total += ttl; tot.ksw_used += xsd.xsw_used; } ti = unswdev; if (ti >= swap_max) { ti = swap_max - 1; } if (ti >= 0) { swap_ary[ti] = tot; } return SIGAR_OK; } #else #define getswapinfo_sysctl(swap_ary, swap_max) SIGAR_ENOTIMPL #endif #define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1) #ifdef DARWIN #define VM_DIR "/private/var/vm" #define SWAPFILE "swapfile" static int sigar_swap_fs_get(sigar_t *sigar, sigar_swap_t *swap) /* <= 10.3 */ { DIR *dirp; struct dirent *ent; char swapfile[SSTRLEN(VM_DIR) + SSTRLEN("/") + SSTRLEN(SWAPFILE) + 12]; struct stat swapstat; struct statfs vmfs; sigar_uint64_t val, bsize; swap->used = swap->total = swap->free = 0; if (!(dirp = opendir(VM_DIR))) { return errno; } /* looking for "swapfile0", "swapfile1", etc. */ while ((ent = readdir(dirp))) { char *ptr = swapfile; if ((ent->d_namlen < SSTRLEN(SWAPFILE)+1) || /* n/a, see comment above */ (ent->d_namlen > SSTRLEN(SWAPFILE)+11)) /* ensure no overflow */ { continue; } if (!strnEQ(ent->d_name, SWAPFILE, SSTRLEN(SWAPFILE))) { continue; } /* sprintf(swapfile, "%s/%s", VM_DIR, ent->d_name) */ memcpy(ptr, VM_DIR, SSTRLEN(VM_DIR)); ptr += SSTRLEN(VM_DIR); *ptr++ = '/'; memcpy(ptr, ent->d_name, ent->d_namlen+1); if (stat(swapfile, &swapstat) < 0) { continue; } swap->used += swapstat.st_size; } closedir(dirp); if (statfs(VM_DIR, &vmfs) < 0) { return errno; } bsize = vmfs.f_bsize / 512; val = vmfs.f_bfree; swap->total = SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) + swap->used; swap->free = swap->total - swap->used; return SIGAR_OK; } static int sigar_swap_sysctl_get(sigar_t *sigar, sigar_swap_t *swap) { #ifdef VM_SWAPUSAGE /* => 10.4 */ struct xsw_usage sw_usage; size_t size = sizeof(sw_usage); int mib[] = { CTL_VM, VM_SWAPUSAGE }; if (sysctl(mib, NMIB(mib), &sw_usage, &size, NULL, 0) != 0) { return errno; } swap->total = sw_usage.xsu_total; swap->used = sw_usage.xsu_used; swap->free = sw_usage.xsu_avail; return SIGAR_OK; #else return SIGAR_ENOTIMPL; /* <= 10.3 */ #endif } #endif /* DARWIN */ int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) { int status; #if defined(DARWIN) vm_statistics_data_t vmstat; if (sigar_swap_sysctl_get(sigar, swap) != SIGAR_OK) { status = sigar_swap_fs_get(sigar, swap); /* <= 10.3 */ if (status != SIGAR_OK) { return status; } } if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) { return status; } swap->page_in = vmstat.pageins; swap->page_out = vmstat.pageouts; #elif defined(__FreeBSD__) struct kvm_swap kswap[1]; struct vmmeter vmstat; if (getswapinfo_sysctl(kswap, 1) != SIGAR_OK) { if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } if (kvm_getswapinfo(sigar->kmem, kswap, 1, 0) < 0) { return errno; } } if (kswap[0].ksw_total == 0) { swap->total = 0; swap->used = 0; swap->free = 0; return SIGAR_OK; } swap->total = kswap[0].ksw_total * sigar->pagesize; swap->used = kswap[0].ksw_used * sigar->pagesize; swap->free = swap->total - swap->used; if ((status = sigar_vmstat(sigar, &vmstat)) == SIGAR_OK) { swap->page_in = vmstat.v_swapin + vmstat.v_vnodein; swap->page_out = vmstat.v_swapout + vmstat.v_vnodeout; } else { swap->page_in = swap->page_out = -1; } #elif defined(__OpenBSD__) || defined(__NetBSD__) struct uvmexp vmstat; if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) { return status; } swap->total = vmstat.swpages * sigar->pagesize; swap->used = vmstat.swpginuse * sigar->pagesize; swap->free = swap->total - swap->used; swap->page_in = vmstat.pageins; swap->page_out = vmstat.pdpageouts; #endif return SIGAR_OK; } #ifndef KERN_CPTIME #define KERN_CPTIME KERN_CP_TIME #endif #if defined(__NetBSD__) typedef uint64_t cp_time_t; #else typedef unsigned long cp_time_t; #endif int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu) { #if defined(DARWIN) kern_return_t status; mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; host_cpu_load_info_data_t cpuload; status = host_statistics(sigar->mach_port, HOST_CPU_LOAD_INFO, (host_info_t)&cpuload, &count); if (status != KERN_SUCCESS) { return errno; } cpu->user = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_USER]); cpu->sys = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_SYSTEM]); cpu->idle = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_IDLE]); cpu->nice = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_NICE]); cpu->wait = 0; /*N/A*/ cpu->irq = 0; /*N/A*/ cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle; #elif defined(__FreeBSD__) || (__OpenBSD__) || defined(__NetBSD__) int status; cp_time_t cp_time[CPUSTATES]; size_t size = sizeof(cp_time); # if defined(__OpenBSD__) || defined(__NetBSD__) int mib[] = { CTL_KERN, KERN_CPTIME }; if (sysctl(mib, NMIB(mib), &cp_time, &size, NULL, 0) == -1) { status = errno; } # else /* try sysctl first, does not require /dev/kmem perms */ if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) == -1) { status = kread(sigar, &cp_time, sizeof(cp_time), sigar->koffsets[KOFFSET_CPUINFO]); } # endif else { status = SIGAR_OK; } if (status != SIGAR_OK) { return status; } cpu->user = SIGAR_TICK2MSEC(cp_time[CP_USER]); cpu->nice = SIGAR_TICK2MSEC(cp_time[CP_NICE]); cpu->sys = SIGAR_TICK2MSEC(cp_time[CP_SYS]); cpu->idle = SIGAR_TICK2MSEC(cp_time[CP_IDLE]); cpu->wait = 0; /*N/A*/ cpu->irq = SIGAR_TICK2MSEC(cp_time[CP_INTR]); cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle + cpu->irq; #endif return SIGAR_OK; } #if defined(__FreeBSD__) && (__FreeBSD_version >= 700000) #define HAVE_KERN_CP_TIMES /* kern.cp_times came later than 7.0, not sure exactly when */ static int sigar_cp_times_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { int maxcpu, status; size_t len = sizeof(maxcpu), size; long *times; if (sysctlbyname("kern.smp.maxcpus", &maxcpu, &len, NULL, 0) == -1) { return errno; } size = sizeof(long) * maxcpu * CPUSTATES; times = malloc(size); if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1) { status = errno; } else { int i, maxid = (size / CPUSTATES / sizeof(long)); long *cp_time = times; status = SIGAR_OK; for (i=0; idata[cpulist->number++]; cpu->user = SIGAR_TICK2MSEC(cp_time[CP_USER]); cpu->nice = SIGAR_TICK2MSEC(cp_time[CP_NICE]); cpu->sys = SIGAR_TICK2MSEC(cp_time[CP_SYS]); cpu->idle = SIGAR_TICK2MSEC(cp_time[CP_IDLE]); cpu->wait = 0; /*N/A*/ cpu->irq = SIGAR_TICK2MSEC(cp_time[CP_INTR]); cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle + cpu->irq; cp_time += CPUSTATES; } } free(times); return status; } #endif int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { #ifdef DARWIN kern_return_t status; mach_msg_type_number_t count; processor_cpu_load_info_data_t *cpuload; natural_t i, ncpu; status = host_processor_info(sigar->mach_port, PROCESSOR_CPU_LOAD_INFO, &ncpu, (processor_info_array_t*)&cpuload, &count); if (status != KERN_SUCCESS) { return errno; } sigar_cpu_list_create(cpulist); for (i=0; idata[cpulist->number++]; cpu->user = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_USER]); cpu->sys = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_SYSTEM]); cpu->idle = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_IDLE]); cpu->nice = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_NICE]); cpu->wait = 0; /*N/A*/ cpu->irq = 0; /*N/A*/ cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle; } vm_deallocate(mach_task_self(), (vm_address_t)cpuload, count); return SIGAR_OK; #else int status, i; sigar_cpu_t *cpu; sigar_cpu_list_create(cpulist); #ifdef HAVE_KERN_CP_TIMES if ((status = sigar_cp_times_get(sigar, cpulist)) == SIGAR_OK) { return SIGAR_OK; } #endif /* XXX no multi cpu in freebsd < 7.0, howbout others? * for now just report all metrics on the 1st cpu * 0's for the rest */ cpu = &cpulist->data[cpulist->number++]; status = sigar_cpu_get(sigar, cpu); if (status != SIGAR_OK) { return status; } for (i=1; incpu; i++) { SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; SIGAR_ZERO(cpu); } return SIGAR_OK; #endif } int sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime) { uptime->uptime = time(NULL) - sigar->boot_time; return SIGAR_OK; } int sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg) { getloadavg(loadavg->loadavg, 3); return SIGAR_OK; } #if defined(DARWIN) && defined(DARWIN_HAS_LIBPROC_H) static int proc_fdinfo_get(sigar_t *sigar, sigar_pid_t pid, int *num) { int rsize; const int init_size = PROC_PIDLISTFD_SIZE * 32; if (!sigar->libproc) { return SIGAR_ENOTIMPL; } if (sigar->ifconf_len == 0) { sigar->ifconf_len = init_size; sigar->ifconf_buf = malloc(sigar->ifconf_len); } while (1) { rsize = sigar->proc_pidinfo(pid, PROC_PIDLISTFDS, 0, sigar->ifconf_buf, sigar->ifconf_len); if (rsize <= 0) { return errno; } if ((rsize + PROC_PIDLISTFD_SIZE) < sigar->ifconf_len) { break; } sigar->ifconf_len += init_size; sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len); } *num = rsize / PROC_PIDLISTFD_SIZE; return SIGAR_OK; } #endif #ifndef KERN_PROC_PROC /* freebsd 4.x */ #define KERN_PROC_PROC KERN_PROC_ALL #endif int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { #if defined(DARWIN) || defined(SIGAR_FREEBSD5) || defined(__OpenBSD__) || defined(__NetBSD__) int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0 }; int i, num; size_t len; struct kinfo_proc *proc; if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) { return errno; } proc = malloc(len); if (sysctl(mib, NMIB(mib), proc, &len, NULL, 0) < 0) { free(proc); return errno; } num = len/sizeof(*proc); for (i=0; idata[proclist->number++] = proc[i].KI_PID; } free(proc); return SIGAR_OK; #else int i, num; struct kinfo_proc *proc; if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } proc = kvm_getprocs(sigar->kmem, KERN_PROC_PROC, 0, &num); for (i=0; idata[proclist->number++] = proc[i].KI_PID; } #endif return SIGAR_OK; } static int sigar_get_pinfo(sigar_t *sigar, sigar_pid_t pid) { #if defined(__OpenBSD__) || defined(__NetBSD__) int mib[] = { CTL_KERN, KERN_PROC2, KERN_PROC_PID, 0, sizeof(*sigar->pinfo), 1 }; #else int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 }; #endif size_t len = sizeof(*sigar->pinfo); time_t timenow = time(NULL); mib[3] = pid; if (sigar->pinfo == NULL) { sigar->pinfo = malloc(len); } if (sigar->last_pid == pid) { if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) { return SIGAR_OK; } } sigar->last_pid = pid; sigar->last_getprocs = timenow; if (sysctl(mib, NMIB(mib), sigar->pinfo, &len, NULL, 0) < 0) { return errno; } return SIGAR_OK; } #if defined(SHARED_TEXT_REGION_SIZE) && defined(SHARED_DATA_REGION_SIZE) # define GLOBAL_SHARED_SIZE (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE) /* 10.4 SDK */ #endif #if defined(DARWIN) && defined(DARWIN_HAS_LIBPROC_H) && !defined(GLOBAL_SHARED_SIZE) /* get the CPU type of the process for the given pid */ static int sigar_proc_cpu_type(sigar_t *sigar, sigar_pid_t pid, cpu_type_t *type) { int status; int mib[CTL_MAXNAME]; size_t len, miblen = NMIB(mib); status = sysctlnametomib("sysctl.proc_cputype", mib, &miblen); if (status != SIGAR_OK) { return status; } mib[miblen] = pid; len = sizeof(*type); return sysctl(mib, miblen + 1, type, &len, NULL, 0); } /* shared memory region size for the given cpu_type_t */ static mach_vm_size_t sigar_shared_region_size(cpu_type_t type) { switch (type) { case CPU_TYPE_ARM: return SHARED_REGION_SIZE_ARM; case CPU_TYPE_POWERPC: return SHARED_REGION_SIZE_PPC; case CPU_TYPE_POWERPC64: return SHARED_REGION_SIZE_PPC64; case CPU_TYPE_I386: return SHARED_REGION_SIZE_I386; case CPU_TYPE_X86_64: return SHARED_REGION_SIZE_X86_64; default: return SHARED_REGION_SIZE_I386; /* assume 32-bit x86|ppc */ } } #endif /* DARWIN */ int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem) { #if defined(DARWIN) mach_port_t task, self = mach_task_self(); kern_return_t status; task_basic_info_data_t info; task_events_info_data_t events; mach_msg_type_number_t count; # ifdef DARWIN_HAS_LIBPROC_H struct proc_taskinfo pti; struct proc_regioninfo pri; if (sigar->libproc) { int sz = sigar->proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)); if (sz == sizeof(pti)) { procmem->size = pti.pti_virtual_size; procmem->resident = pti.pti_resident_size; procmem->page_faults = pti.pti_faults; procmem->minor_faults = SIGAR_FIELD_NOTIMPL; procmem->major_faults = SIGAR_FIELD_NOTIMPL; procmem->share = SIGAR_FIELD_NOTIMPL; sz = sigar->proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, sizeof(pri)); if (sz == sizeof(pri)) { if (pri.pri_share_mode == SM_EMPTY) { mach_vm_size_t shared_size; #ifdef GLOBAL_SHARED_SIZE shared_size = GLOBAL_SHARED_SIZE; /* 10.4 SDK */ #else cpu_type_t cpu_type; if (sigar_proc_cpu_type(sigar, pid, &cpu_type) == SIGAR_OK) { shared_size = sigar_shared_region_size(cpu_type); } else { shared_size = SHARED_REGION_SIZE_I386; /* assume 32-bit x86|ppc */ } #endif if (procmem->size > shared_size) { procmem->size -= shared_size; /* SIGAR-123 */ } } } return SIGAR_OK; } } # endif status = task_for_pid(self, pid, &task); if (status != KERN_SUCCESS) { return errno; } count = TASK_BASIC_INFO_COUNT; status = task_info(task, TASK_BASIC_INFO, (task_info_t)&info, &count); if (status != KERN_SUCCESS) { return errno; } count = TASK_EVENTS_INFO_COUNT; status = task_info(task, TASK_EVENTS_INFO, (task_info_t)&events, &count); if (status == KERN_SUCCESS) { procmem->page_faults = events.faults; } else { procmem->page_faults = SIGAR_FIELD_NOTIMPL; } procmem->minor_faults = SIGAR_FIELD_NOTIMPL; procmem->major_faults = SIGAR_FIELD_NOTIMPL; if (task != self) { mach_port_deallocate(self, task); } procmem->size = info.virtual_size; procmem->resident = info.resident_size; procmem->share = SIGAR_FIELD_NOTIMPL; return SIGAR_OK; #elif defined(__FreeBSD__) int status = sigar_get_pinfo(sigar, pid); bsd_pinfo_t *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } procmem->size = (pinfo->KI_TSZ + pinfo->KI_DSZ + pinfo->KI_SSZ) * sigar->pagesize; procmem->resident = pinfo->KI_RSS * sigar->pagesize; procmem->share = SIGAR_FIELD_NOTIMPL; procmem->page_faults = SIGAR_FIELD_NOTIMPL; procmem->minor_faults = SIGAR_FIELD_NOTIMPL; procmem->major_faults = SIGAR_FIELD_NOTIMPL; #elif defined(__OpenBSD__) || defined(__NetBSD__) int status = sigar_get_pinfo(sigar, pid); bsd_pinfo_t *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } procmem->size = (pinfo->p_vm_tsize + pinfo->p_vm_dsize + pinfo->p_vm_ssize) * sigar->pagesize; procmem->resident = pinfo->p_vm_rssize * sigar->pagesize; procmem->share = SIGAR_FIELD_NOTIMPL; procmem->minor_faults = pinfo->p_uru_minflt; procmem->major_faults = pinfo->p_uru_majflt; procmem->page_faults = procmem->minor_faults + procmem->major_faults; #endif return SIGAR_OK; } int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred) { int status = sigar_get_pinfo(sigar, pid); bsd_pinfo_t *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } #if defined(__OpenBSD__) || defined(__NetBSD__) proccred->uid = pinfo->p_ruid; proccred->gid = pinfo->p_rgid; proccred->euid = pinfo->p_uid; proccred->egid = pinfo->p_gid; #else proccred->uid = pinfo->KI_UID; proccred->gid = pinfo->KI_GID; proccred->euid = pinfo->KI_EUID; proccred->egid = pinfo->KI_EGID; #endif return SIGAR_OK; } #define tv2msec(tv) \ (((sigar_uint64_t)tv.tv_sec * SIGAR_MSEC) + (((sigar_uint64_t)tv.tv_usec) / 1000)) #ifdef DARWIN #define tval2msec(tval) \ ((tval.seconds * SIGAR_MSEC) + (tval.microseconds / 1000)) #define tval2nsec(tval) \ (SIGAR_SEC2NANO((tval).seconds) + SIGAR_MICROSEC2NANO((tval).microseconds)) static int get_proc_times(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *time) { unsigned int count; time_value_t utime = {0, 0}, stime = {0, 0}; task_basic_info_data_t ti; task_thread_times_info_data_t tti; task_port_t task, self; kern_return_t status; # ifdef DARWIN_HAS_LIBPROC_H if (sigar->libproc) { struct proc_taskinfo pti; int sz = sigar->proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)); if (sz == sizeof(pti)) { time->user = SIGAR_NSEC2MSEC(pti.pti_total_user); time->sys = SIGAR_NSEC2MSEC(pti.pti_total_system); time->total = time->user + time->sys; return SIGAR_OK; } } # endif self = mach_task_self(); status = task_for_pid(self, pid, &task); if (status != KERN_SUCCESS) { return errno; } count = TASK_BASIC_INFO_COUNT; status = task_info(task, TASK_BASIC_INFO, (task_info_t)&ti, &count); if (status != KERN_SUCCESS) { if (task != self) { mach_port_deallocate(self, task); } return errno; } count = TASK_THREAD_TIMES_INFO_COUNT; status = task_info(task, TASK_THREAD_TIMES_INFO, (task_info_t)&tti, &count); if (status != KERN_SUCCESS) { if (task != self) { mach_port_deallocate(self, task); } return errno; } time_value_add(&utime, &ti.user_time); time_value_add(&stime, &ti.system_time); time_value_add(&utime, &tti.user_time); time_value_add(&stime, &tti.system_time); time->user = tval2msec(utime); time->sys = tval2msec(stime); time->total = time->user + time->sys; return SIGAR_OK; } #endif int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime) { #ifdef SIGAR_FREEBSD4 struct user user; #endif int status = sigar_get_pinfo(sigar, pid); bsd_pinfo_t *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } #if defined(DARWIN) if ((status = get_proc_times(sigar, pid, proctime)) != SIGAR_OK) { return status; } proctime->start_time = tv2msec(pinfo->KI_START); #elif defined(SIGAR_FREEBSD5) proctime->user = tv2msec(pinfo->ki_rusage.ru_utime); proctime->sys = tv2msec(pinfo->ki_rusage.ru_stime); proctime->total = proctime->user + proctime->sys; proctime->start_time = tv2msec(pinfo->KI_START); #elif defined(SIGAR_FREEBSD4) if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } status = kread(sigar, &user, sizeof(user), (u_long)pinfo->kp_proc.p_addr); if (status != SIGAR_OK) { return status; } proctime->user = tv2msec(user.u_stats.p_ru.ru_utime); proctime->sys = tv2msec(user.u_stats.p_ru.ru_stime); proctime->total = proctime->user + proctime->sys; proctime->start_time = tv2msec(user.u_stats.p_start); #elif defined(__OpenBSD__) || defined(__NetBSD__) /* XXX *_usec */ proctime->user = pinfo->p_uutime_sec * SIGAR_MSEC; proctime->sys = pinfo->p_ustime_sec * SIGAR_MSEC; proctime->total = proctime->user + proctime->sys; proctime->start_time = pinfo->p_ustart_sec * SIGAR_MSEC; #endif return SIGAR_OK; } #ifdef DARWIN /* thread state mapping derived from ps.tproj */ static const char const thread_states[] = { /*0*/ '-', /*1*/ SIGAR_PROC_STATE_RUN, /*2*/ SIGAR_PROC_STATE_ZOMBIE, /*3*/ SIGAR_PROC_STATE_SLEEP, /*4*/ SIGAR_PROC_STATE_IDLE, /*5*/ SIGAR_PROC_STATE_STOP, /*6*/ SIGAR_PROC_STATE_STOP, /*7*/ '?' }; static int thread_state_get(thread_basic_info_data_t *info) { switch (info->run_state) { case TH_STATE_RUNNING: return 1; case TH_STATE_UNINTERRUPTIBLE: return 2; case TH_STATE_WAITING: return (info->sleep_time > 20) ? 4 : 3; case TH_STATE_STOPPED: return 5; case TH_STATE_HALTED: return 6; default: return 7; } } static int sigar_proc_threads_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { mach_port_t task, self = mach_task_self(); kern_return_t status; thread_array_t threads; mach_msg_type_number_t count, i; int state = TH_STATE_HALTED + 1; status = task_for_pid(self, pid, &task); if (status != KERN_SUCCESS) { return errno; } status = task_threads(task, &threads, &count); if (status != KERN_SUCCESS) { return errno; } procstate->threads = count; for (i=0; istate = thread_states[state]; return SIGAR_OK; } #endif int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { int status = sigar_get_pinfo(sigar, pid); bsd_pinfo_t *pinfo = sigar->pinfo; #if defined(__OpenBSD__) || defined(__NetBSD__) int state = pinfo->p_stat; #else int state = pinfo->KI_STAT; #endif if (status != SIGAR_OK) { return status; } #if defined(__OpenBSD__) || defined(__NetBSD__) SIGAR_SSTRCPY(procstate->name, pinfo->p_comm); procstate->ppid = pinfo->p_ppid; procstate->priority = pinfo->p_priority; procstate->nice = pinfo->p_nice; procstate->tty = pinfo->p_tdev; procstate->threads = SIGAR_FIELD_NOTIMPL; procstate->processor = pinfo->p_cpuid; #else SIGAR_SSTRCPY(procstate->name, pinfo->KI_COMM); procstate->ppid = pinfo->KI_PPID; procstate->priority = pinfo->KI_PRI; procstate->nice = pinfo->KI_NICE; procstate->tty = SIGAR_FIELD_NOTIMPL; /*XXX*/ procstate->threads = SIGAR_FIELD_NOTIMPL; procstate->processor = SIGAR_FIELD_NOTIMPL; #endif #ifdef DARWIN status = sigar_proc_threads_get(sigar, pid, procstate); if (status == SIGAR_OK) { return status; } #endif switch (state) { case SIDL: procstate->state = 'D'; break; case SRUN: #ifdef SONPROC case SONPROC: #endif procstate->state = 'R'; break; case SSLEEP: procstate->state = 'S'; break; case SSTOP: procstate->state = 'T'; break; case SZOMB: procstate->state = 'Z'; break; default: procstate->state = '?'; break; } return SIGAR_OK; } #if defined(DARWIN) typedef struct { char *buf, *ptr, *end; int count; } sigar_kern_proc_args_t; static void sigar_kern_proc_args_destroy(sigar_kern_proc_args_t *kargs) { if (kargs->buf) { free(kargs->buf); kargs->buf = NULL; } } /* re-usable hack for use by proc_args and proc_env */ static int sigar_kern_proc_args_get(sigar_t *sigar, sigar_pid_t pid, char *exe, sigar_kern_proc_args_t *kargs) { /* * derived from: * http://darwinsource.opendarwin.org/10.4.1/adv_cmds-79.1/ps.tproj/print.c */ int mib[3], len; size_t size = sigar_argmax_get(sigar); kargs->buf = malloc(size); mib[0] = CTL_KERN; mib[1] = KERN_PROCARGS2; mib[2] = pid; if (sysctl(mib, NMIB(mib), kargs->buf, &size, NULL, 0) < 0) { sigar_kern_proc_args_destroy(kargs); return errno; } kargs->end = &kargs->buf[size]; memcpy(&kargs->count, kargs->buf, sizeof(kargs->count)); kargs->ptr = kargs->buf + sizeof(kargs->count); len = strlen(kargs->ptr); if (exe) { memcpy(exe, kargs->ptr, len+1); } kargs->ptr += len+1; if (kargs->ptr == kargs->end) { sigar_kern_proc_args_destroy(kargs); return exe ? SIGAR_OK : ENOENT; } for (; kargs->ptr < kargs->end; kargs->ptr++) { if (*kargs->ptr != '\0') { break; /* start of argv[0] */ } } if (kargs->ptr == kargs->end) { sigar_kern_proc_args_destroy(kargs); return exe ? SIGAR_OK : ENOENT; } return SIGAR_OK; } static int kern_proc_args_skip_argv(sigar_kern_proc_args_t *kargs) { char *ptr = kargs->ptr; char *end = kargs->end; int count = kargs->count; /* skip over argv */ while ((ptr < end) && (count-- > 0)) { int alen = strlen(ptr)+1; ptr += alen; } kargs->ptr = ptr; kargs->end = end; kargs->count = 0; if (ptr >= end) { return ENOENT; } return SIGAR_OK; } #endif int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { #if defined(DARWIN) int status, count; sigar_kern_proc_args_t kargs; char *ptr, *end; status = sigar_kern_proc_args_get(sigar, pid, NULL, &kargs); if (status != SIGAR_OK) { return status; } count = kargs.count; ptr = kargs.ptr; end = kargs.end; while ((ptr < end) && (count-- > 0)) { int slen = strlen(ptr); int alen = slen+1; char *arg; /* * trim trailing whitespace. * seen w/ postgresql, probably related * to messing with argv[0] */ while (*(ptr + (slen-1)) == ' ') { if (--slen <= 0) { break; } } arg = malloc(slen+1); SIGAR_PROC_ARGS_GROW(procargs); memcpy(arg, ptr, slen); *(arg+slen) = '\0'; procargs->data[procargs->number++] = arg; ptr += alen; } sigar_kern_proc_args_destroy(&kargs); return SIGAR_OK; #elif defined(__FreeBSD__) || defined(__NetBSD__) char buffer[SIGAR_ARG_MAX+1], *ptr=buffer; size_t len = sizeof(buffer); # ifdef __NetBSD__ int mib[] = { CTL_KERN, KERN_PROC_ARGS, 0, KERN_PROC_ARGV }; mib[2] = pid; # else int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, 0 }; mib[3] = pid; # endif if (sysctl(mib, NMIB(mib), buffer, &len, NULL, 0) < 0) { return errno; } if (len == 0) { procargs->number = 0; return SIGAR_OK; } buffer[len] = '\0'; while (len > 0) { int alen = strlen(ptr)+1; char *arg = malloc(alen); SIGAR_PROC_ARGS_GROW(procargs); memcpy(arg, ptr, alen); procargs->data[procargs->number++] = arg; len -= alen; if (len > 0) { ptr += alen; } } return SIGAR_OK; #elif defined(__OpenBSD__) char buffer[SIGAR_ARG_MAX+1], **ptr=(char **)buffer; size_t len = sizeof(buffer); int mib[] = { CTL_KERN, KERN_PROC_ARGS, 0, KERN_PROC_ARGV }; mib[2] = pid; if (sysctl(mib, NMIB(mib), buffer, &len, NULL, 0) < 0) { return errno; } if (len == 0) { procargs->number = 0; return SIGAR_OK; } for (; *ptr; ptr++) { int alen = strlen(*ptr)+1; char *arg = malloc(alen); SIGAR_PROC_ARGS_GROW(procargs); memcpy(arg, *ptr, alen); procargs->data[procargs->number++] = arg; } return SIGAR_OK; #else return SIGAR_ENOTIMPL; #endif } int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { #ifdef DARWIN int status, count; sigar_kern_proc_args_t kargs; char *ptr, *end; status = sigar_kern_proc_args_get(sigar, pid, NULL, &kargs); if (status != SIGAR_OK) { return status; } status = kern_proc_args_skip_argv(&kargs); if (status != SIGAR_OK) { sigar_kern_proc_args_destroy(&kargs); return status; } count = kargs.count; ptr = kargs.ptr; end = kargs.end; /* into environ */ while (ptr < end) { char *val = strchr(ptr, '='); int klen, vlen, status; char key[256]; /* XXX is there a max key size? */ if (val == NULL) { /* not key=val format */ break; } klen = val - ptr; SIGAR_SSTRCPY(key, ptr); key[klen] = '\0'; ++val; vlen = strlen(val); status = procenv->env_getter(procenv->data, key, klen, val, vlen); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } ptr += (klen + 1 + vlen + 1); if (*ptr == '\0') { break; } } sigar_kern_proc_args_destroy(&kargs); return SIGAR_OK; #else char **env; struct kinfo_proc *pinfo; int num; if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } pinfo = kvm_getprocs(sigar->kmem, KERN_PROC_PID, pid, &num); if (!pinfo || (num < 1)) { return errno; } if (!(env = kvm_getenvv(sigar->kmem, pinfo, 9086))) { return errno; } while (*env) { char *ptr = *env++; char *val = strchr(ptr, '='); int klen, vlen, status; char key[128]; /* XXX is there a max key size? */ if (val == NULL) { /* not key=val format */ procenv->env_getter(procenv->data, ptr, strlen(ptr), NULL, 0); break; } klen = val - ptr; SIGAR_SSTRCPY(key, ptr); key[klen] = '\0'; ++val; vlen = strlen(val); status = procenv->env_getter(procenv->data, key, klen, val, vlen); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } ptr += (klen + 1 + vlen + 1); } return SIGAR_OK; #endif } int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd) { #ifdef __FreeBSD__ int status; bsd_pinfo_t *pinfo; struct filedesc filed; #if 0 struct file **ofiles; int nfiles, i; size_t size; #endif if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } if ((status = sigar_get_pinfo(sigar, pid)) != SIGAR_OK) { return status; } pinfo = sigar->pinfo; status = kread(sigar, &filed, sizeof(filed), (u_long)pinfo->KI_FD); if (status != SIGAR_OK) { return status; } #if 0 nfiles = filed.fd_lastfile+1; size = sizeof(*ofiles) * nfiles; ofiles = malloc(size); status = kread(sigar, ofiles, size, (u_long)filed.fd_ofiles); if (status != SIGAR_OK) { free(ofiles); return status; } procfd->total = 0; for (i=0; itotal++; } free(ofiles); #else /* seems the same as the above */ procfd->total = filed.fd_lastfile; #endif return SIGAR_OK; #else return SIGAR_ENOTIMPL; #endif } int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { #ifdef DARWIN int status; sigar_kern_proc_args_t kargs; status = sigar_kern_proc_args_get(sigar, pid, procexe->name, &kargs); if (status != SIGAR_OK) { return status; } procexe->cwd[0] = '\0'; procexe->root[0] = '\0'; /* attempt to determine cwd from $PWD */ status = kern_proc_args_skip_argv(&kargs); if (status == SIGAR_OK) { char *ptr = kargs.ptr; char *end = kargs.end; /* into environ */ while (ptr < end) { int len = strlen(ptr); if ((len > 4) && (ptr[0] == 'P') && (ptr[1] == 'W') && (ptr[2] == 'D') && (ptr[3] == '=')) { memcpy(procexe->cwd, ptr+4, len-3); break; } ptr += len+1; } } sigar_kern_proc_args_destroy(&kargs); return SIGAR_OK; #else int len; char name[1024]; procexe->cwd[0] = '\0'; procexe->root[0] = '\0'; (void)SIGAR_PROC_FILENAME(name, pid, "/file"); if ((len = readlink(name, procexe->name, sizeof(procexe->name)-1)) < 0) { return PROCFS_STATUS(errno); } procexe->name[len] = '\0'; return SIGAR_OK; #endif } #ifdef DARWIN static int sigar_dlinfo_modules(sigar_t *sigar, sigar_proc_modules_t *procmods) { uint32_t i, count = _dyld_image_count(); for (i=0; imodule_getter(procmods->data, (char *)name, strlen(name)); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } } return SIGAR_OK; } #endif /* DARWIN */ int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { #if defined(SIGAR_HAS_DLINFO_MODULES) || defined(DARWIN) if (pid == sigar_pid_get(sigar)) { return sigar_dlinfo_modules(sigar, procmods); } #endif return SIGAR_ENOTIMPL; } #define SIGAR_MICROSEC2NANO(s) \ ((sigar_uint64_t)(s) * (sigar_uint64_t)1000) #define TIME_NSEC(t) \ (SIGAR_SEC2NANO((t).tv_sec) + SIGAR_MICROSEC2NANO((t).tv_usec)) int sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu) { #if defined(DARWIN) mach_port_t self = mach_thread_self(); thread_basic_info_data_t info; mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; kern_return_t status; status = thread_info(self, THREAD_BASIC_INFO, (thread_info_t)&info, &count); if (status != KERN_SUCCESS) { return errno; } mach_port_deallocate(mach_task_self(), self); cpu->user = tval2nsec(info.user_time); cpu->sys = tval2nsec(info.system_time); cpu->total = cpu->user + cpu->sys; #elif defined(__NetBSD__) return SIGAR_ENOTIMPL; /* http://tinyurl.com/chbvln */ #else /* XXX this is not per-thread, it is for the whole-process. * just want to use for the shell time command at the moment. */ struct rusage usage; getrusage(RUSAGE_SELF, &usage); cpu->user = TIME_NSEC(usage.ru_utime); cpu->sys = TIME_NSEC(usage.ru_stime); cpu->total = TIME_NSEC(usage.ru_utime) + TIME_NSEC(usage.ru_stime); #endif return SIGAR_OK; } int sigar_os_fs_type_get(sigar_file_system_t *fsp) { char *type = fsp->sys_type_name; /* see sys/disklabel.h */ switch (*type) { case 'f': if (strEQ(type, "ffs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'h': if (strEQ(type, "hfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'u': if (strEQ(type, "ufs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; } return fsp->type; } static void get_fs_options(char *opts, int osize, long flags) { *opts = '\0'; if (flags & MNT_RDONLY) strncat(opts, "ro", osize); else strncat(opts, "rw", osize); if (flags & MNT_SYNCHRONOUS) strncat(opts, ",sync", osize); if (flags & MNT_NOEXEC) strncat(opts, ",noexec", osize); if (flags & MNT_NOSUID) strncat(opts, ",nosuid", osize); #ifdef MNT_NODEV if (flags & MNT_NODEV) strncat(opts, ",nodev", osize); #endif #ifdef MNT_UNION if (flags & MNT_UNION) strncat(opts, ",union", osize); #endif if (flags & MNT_ASYNC) strncat(opts, ",async", osize); #ifdef MNT_NOATIME if (flags & MNT_NOATIME) strncat(opts, ",noatime", osize); #endif #ifdef MNT_NOCLUSTERR if (flags & MNT_NOCLUSTERR) strncat(opts, ",noclusterr", osize); #endif #ifdef MNT_NOCLUSTERW if (flags & MNT_NOCLUSTERW) strncat(opts, ",noclusterw", osize); #endif #ifdef MNT_NOSYMFOLLOW if (flags & MNT_NOSYMFOLLOW) strncat(opts, ",nosymfollow", osize); #endif #ifdef MNT_SUIDDIR if (flags & MNT_SUIDDIR) strncat(opts, ",suiddir", osize); #endif #ifdef MNT_SOFTDEP if (flags & MNT_SOFTDEP) strncat(opts, ",soft-updates", osize); #endif if (flags & MNT_LOCAL) strncat(opts, ",local", osize); if (flags & MNT_QUOTA) strncat(opts, ",quota", osize); if (flags & MNT_ROOTFS) strncat(opts, ",rootfs", osize); #ifdef MNT_USER if (flags & MNT_USER) strncat(opts, ",user", osize); #endif #ifdef MNT_IGNORE if (flags & MNT_IGNORE) strncat(opts, ",ignore", osize); #endif if (flags & MNT_EXPORTED) strncat(opts, ",nfs", osize); } #ifdef __NetBSD__ #define sigar_statfs statvfs #define sigar_getfsstat getvfsstat #define sigar_f_flags f_flag #else #define sigar_statfs statfs #define sigar_getfsstat getfsstat #define sigar_f_flags f_flags #endif int sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist) { struct sigar_statfs *fs; int num, i; int is_debug = SIGAR_LOG_IS_DEBUG(sigar); long len; if ((num = sigar_getfsstat(NULL, 0, MNT_NOWAIT)) < 0) { return errno; } len = sizeof(*fs) * num; fs = malloc(len); if ((num = sigar_getfsstat(fs, len, MNT_NOWAIT)) < 0) { free(fs); return errno; } sigar_file_system_list_create(fslist); for (i=0; idata[fslist->number++]; SIGAR_SSTRCPY(fsp->dir_name, fs[i].f_mntonname); SIGAR_SSTRCPY(fsp->dev_name, fs[i].f_mntfromname); SIGAR_SSTRCPY(fsp->sys_type_name, fs[i].f_fstypename); get_fs_options(fsp->options, sizeof(fsp->options)-1, fs[i].sigar_f_flags); sigar_fs_type_init(fsp); } free(fs); return SIGAR_OK; } #ifdef DARWIN #define IoStatGetValue(key, val) \ if ((number = (CFNumberRef)CFDictionaryGetValue(stats, CFSTR(kIOBlockStorageDriverStatistics##key)))) \ CFNumberGetValue(number, kCFNumberSInt64Type, &val) #endif int sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *disk) { #if defined(DARWIN) kern_return_t status; io_registry_entry_t parent; io_service_t service; CFDictionaryRef props; CFNumberRef number; sigar_iodev_t *iodev = sigar_iodev_get(sigar, name); char dname[256], *ptr; SIGAR_DISK_STATS_INIT(disk); if (!iodev) { return ENXIO; } /* "/dev/disk0s1" -> "disk0" */ /* XXX better way? */ ptr = &iodev->name[SSTRLEN(SIGAR_DEV_PREFIX)]; SIGAR_SSTRCPY(dname, ptr); ptr = dname; if (strnEQ(ptr, "disk", 4)) { ptr += 4; if ((ptr = strchr(ptr, 's')) && isdigit(*(ptr+1))) { *ptr = '\0'; } } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[disk_usage] map %s -> %s", iodev->name, dname); } /* e.g. name == "disk0" */ service = IOServiceGetMatchingService(kIOMasterPortDefault, IOBSDNameMatching(kIOMasterPortDefault, 0, dname)); if (!service) { return errno; } status = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent); if (status != KERN_SUCCESS) { IOObjectRelease(service); return status; } status = IORegistryEntryCreateCFProperties(parent, (CFMutableDictionaryRef *)&props, kCFAllocatorDefault, kNilOptions); if (props) { CFDictionaryRef stats = (CFDictionaryRef)CFDictionaryGetValue(props, CFSTR(kIOBlockStorageDriverStatisticsKey)); if (stats) { IoStatGetValue(ReadsKey, disk->reads); IoStatGetValue(BytesReadKey, disk->read_bytes); IoStatGetValue(TotalReadTimeKey, disk->rtime); IoStatGetValue(WritesKey, disk->writes); IoStatGetValue(BytesWrittenKey, disk->write_bytes); IoStatGetValue(TotalWriteTimeKey, disk->wtime); disk->time = disk->rtime + disk->wtime; } CFRelease(props); } IOObjectRelease(service); IOObjectRelease(parent); return SIGAR_OK; #elif defined(__FreeBSD__) /* XXX incomplete */ struct sigar_statfs buf; if (sigar_statfs(name, &buf) < 0) { return errno; } SIGAR_DISK_STATS_INIT(disk); disk->reads = buf.f_syncreads + buf.f_asyncreads; disk->writes = buf.f_syncwrites + buf.f_asyncwrites; return SIGAR_OK; #else SIGAR_DISK_STATS_INIT(disk); return SIGAR_ENOTIMPL; #endif } int sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { int status = sigar_statvfs(sigar, dirname, fsusage); if (status != SIGAR_OK) { return status; } fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage); sigar_disk_usage_get(sigar, dirname, &fsusage->disk); return SIGAR_OK; } #ifdef DARWIN #define CTL_HW_FREQ "hw.cpufrequency" #else /* XXX FreeBSD 5.x+ only? */ #define CTL_HW_FREQ "machdep.tsc_freq" #endif int sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { int i; unsigned int mhz; int cache_size=SIGAR_FIELD_NOTIMPL; size_t size; char model[128], vendor[128], *ptr; size = sizeof(mhz); (void)sigar_cpu_core_count(sigar); #if defined(DARWIN) { int mib[] = { CTL_HW, HW_CPU_FREQ }; size = sizeof(mhz); if (sysctl(mib, NMIB(mib), &mhz, &size, NULL, 0) < 0) { mhz = SIGAR_FIELD_NOTIMPL; } } #elif defined(__FreeBSD__) if (sysctlbyname(CTL_HW_FREQ, &mhz, &size, NULL, 0) < 0) { mhz = SIGAR_FIELD_NOTIMPL; } #else /*XXX OpenBSD*/ mhz = SIGAR_FIELD_NOTIMPL; #endif if (mhz != SIGAR_FIELD_NOTIMPL) { mhz /= 1000000; } size = sizeof(model); #ifdef __OpenBSD__ if (1) { #else if (sysctlbyname("hw.model", &model, &size, NULL, 0) < 0) { #endif int mib[] = { CTL_HW, HW_MODEL }; size = sizeof(model); if (sysctl(mib, NMIB(mib), &model[0], &size, NULL, 0) < 0) { #ifdef DARWIN strcpy(model, "powerpc"); #else strcpy(model, "Unknown"); #endif } } if (mhz == SIGAR_FIELD_NOTIMPL) { /* freebsd4 */ mhz = sigar_cpu_mhz_from_model(model); } #ifdef DARWIN size = sizeof(vendor); if (sysctlbyname("machdep.cpu.vendor", &vendor, &size, NULL, 0) < 0) { SIGAR_SSTRCPY(vendor, "Apple"); } else { /* GenuineIntel -> Intel */ if (strstr(vendor, "Intel")) { SIGAR_SSTRCPY(vendor, "Intel"); } } #endif if ((ptr = strchr(model, ' '))) { if (strstr(model, "Intel")) { SIGAR_SSTRCPY(vendor, "Intel"); } else if (strstr(model, "AMD")) { SIGAR_SSTRCPY(vendor, "AMD"); } else { SIGAR_SSTRCPY(vendor, "Unknown"); } SIGAR_SSTRCPY(model, ptr+1); } #ifdef DARWIN { int mib[] = { CTL_HW, HW_L2CACHESIZE }; /* in bytes */ size = sizeof(cache_size); if (sysctl(mib, NMIB(mib), &cache_size, &size, NULL, 0) < 0) { cache_size = SIGAR_FIELD_NOTIMPL; } else { cache_size /= 1024; /* convert to KB */ } } #endif sigar_cpu_info_list_create(cpu_infos); for (i=0; incpu; i++) { sigar_cpu_info_t *info; SIGAR_CPU_INFO_LIST_GROW(cpu_infos); info = &cpu_infos->data[cpu_infos->number++]; SIGAR_SSTRCPY(info->vendor, vendor); SIGAR_SSTRCPY(info->model, model); sigar_cpu_model_adjust(sigar, info); info->mhz = mhz; info->cache_size = cache_size; info->total_cores = sigar->ncpu; info->cores_per_socket = sigar->lcpu; info->total_sockets = sigar_cpu_socket_count(sigar); } return SIGAR_OK; } #define rt_s_addr(sa) ((struct sockaddr_in *)(sa))->sin_addr.s_addr #ifndef SA_SIZE #define SA_SIZE(sa) \ ( (!(sa) || ((struct sockaddr *)(sa))->sa_len == 0) ? \ sizeof(long) : \ 1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) ) #endif int sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist) { size_t needed; int bit; char *buf, *next, *lim; struct rt_msghdr *rtm; int mib[6] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 }; if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) { return errno; } #if __FreeBSD_version >= 800000 if (needed == 0) { return SIGAR_ENOTIMPL; /*XXX hoping this is an 8.0beta bug*/ } #endif buf = malloc(needed); if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) { free(buf); return errno; } sigar_net_route_list_create(routelist); lim = buf + needed; for (next = buf; next < lim; next += rtm->rtm_msglen) { struct sockaddr *sa; sigar_net_route_t *route; rtm = (struct rt_msghdr *)next; if (rtm->rtm_type != RTM_GET) { continue; } sa = (struct sockaddr *)(rtm + 1); if (sa->sa_family != AF_INET) { continue; } SIGAR_NET_ROUTE_LIST_GROW(routelist); route = &routelist->data[routelist->number++]; SIGAR_ZERO(route); route->flags = rtm->rtm_flags; if_indextoname(rtm->rtm_index, route->ifname); for (bit=RTA_DST; bit && ((char *)sa < lim); bit <<= 1) { if ((rtm->rtm_addrs & bit) == 0) { continue; } switch (bit) { case RTA_DST: sigar_net_address_set(route->destination, rt_s_addr(sa)); break; case RTA_GATEWAY: if (sa->sa_family == AF_INET) { sigar_net_address_set(route->gateway, rt_s_addr(sa)); } break; case RTA_NETMASK: sigar_net_address_set(route->mask, rt_s_addr(sa)); break; case RTA_IFA: break; } sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa)); } } free(buf); return SIGAR_OK; } typedef enum { IFMSG_ITER_LIST, IFMSG_ITER_GET } ifmsg_iter_e; typedef struct { const char *name; ifmsg_iter_e type; union { sigar_net_interface_list_t *iflist; struct if_msghdr *ifm; } data; } ifmsg_iter_t; static int sigar_ifmsg_init(sigar_t *sigar) { int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_IFLIST, 0 }; size_t len; if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) { return errno; } if (sigar->ifconf_len < len) { sigar->ifconf_buf = realloc(sigar->ifconf_buf, len); sigar->ifconf_len = len; } if (sysctl(mib, NMIB(mib), sigar->ifconf_buf, &len, NULL, 0) < 0) { return errno; } return SIGAR_OK; } /** * @param name name of the interface * @param name_len length of name (w/o \0) */ static int has_ifaddr(char *name, size_t name_len) { int sock, status; struct ifreq ifr; if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { return errno; } strncpy(ifr.ifr_name, name, MIN(sizeof(ifr.ifr_name) - 1, name_len)); ifr.ifr_name[MIN(sizeof(ifr.ifr_name) - 1, name_len)] = '\0'; if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) { status = SIGAR_OK; } else { status = errno; } close(sock); return status; } static int sigar_ifmsg_iter(sigar_t *sigar, ifmsg_iter_t *iter) { char *end = sigar->ifconf_buf + sigar->ifconf_len; char *ptr = sigar->ifconf_buf; if (iter->type == IFMSG_ITER_LIST) { sigar_net_interface_list_create(iter->data.iflist); } while (ptr < end) { char *name; struct sockaddr_dl *sdl; struct if_msghdr *ifm = (struct if_msghdr *)ptr; if (ifm->ifm_type != RTM_IFINFO) { break; } ptr += ifm->ifm_msglen; while (ptr < end) { struct if_msghdr *next = (struct if_msghdr *)ptr; if (next->ifm_type != RTM_NEWADDR) { break; } ptr += next->ifm_msglen; } sdl = (struct sockaddr_dl *)(ifm + 1); if (sdl->sdl_family != AF_LINK) { continue; } switch (iter->type) { case IFMSG_ITER_LIST: if (sdl->sdl_type == IFT_OTHER) { if (has_ifaddr(sdl->sdl_data, sdl->sdl_nlen) != SIGAR_OK) { break; } } else if (!((sdl->sdl_type == IFT_ETHER) || (sdl->sdl_type == IFT_LOOP))) { break; /* XXX deal w/ other weirdo interfaces */ } SIGAR_NET_IFLIST_GROW(iter->data.iflist); /* sdl_data doesn't include a trailing \0, it is only sdl_nlen long */ name = malloc(sdl->sdl_nlen+1); memcpy(name, sdl->sdl_data, sdl->sdl_nlen); name[sdl->sdl_nlen] = '\0'; /* add the missing \0 */ iter->data.iflist->data[iter->data.iflist->number++] = name; break; case IFMSG_ITER_GET: if (strlen(iter->name) == sdl->sdl_nlen && 0 == memcmp(iter->name, sdl->sdl_data, sdl->sdl_nlen)) { iter->data.ifm = ifm; return SIGAR_OK; } } } switch (iter->type) { case IFMSG_ITER_LIST: return SIGAR_OK; case IFMSG_ITER_GET: default: return ENXIO; } } int sigar_net_interface_list_get(sigar_t *sigar, sigar_net_interface_list_t *iflist) { int status; ifmsg_iter_t iter; if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) { return status; } iter.type = IFMSG_ITER_LIST; iter.data.iflist = iflist; return sigar_ifmsg_iter(sigar, &iter); } int sigar_net_interface_config_get(sigar_t *sigar, const char *name, sigar_net_interface_config_t *ifconfig) { int sock; int status; ifmsg_iter_t iter; struct if_msghdr *ifm; struct sockaddr_dl *sdl; struct ifreq ifr; if (!name) { return sigar_net_interface_config_primary_get(sigar, ifconfig); } if (sigar->ifconf_len == 0) { if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) { return status; } } SIGAR_ZERO(ifconfig); iter.type = IFMSG_ITER_GET; iter.name = name; if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) { return status; } if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { return errno; } ifm = iter.data.ifm; SIGAR_SSTRCPY(ifconfig->name, name); sdl = (struct sockaddr_dl *)(ifm + 1); sigar_net_address_mac_set(ifconfig->hwaddr, LLADDR(sdl), sdl->sdl_alen); ifconfig->flags = ifm->ifm_flags; ifconfig->mtu = ifm->ifm_data.ifi_mtu; ifconfig->metric = ifm->ifm_data.ifi_metric; SIGAR_SSTRCPY(ifr.ifr_name, name); #define ifr_s_addr(ifr) \ ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr if (!ioctl(sock, SIOCGIFADDR, &ifr)) { sigar_net_address_set(ifconfig->address, ifr_s_addr(ifr)); } if (!ioctl(sock, SIOCGIFNETMASK, &ifr)) { sigar_net_address_set(ifconfig->netmask, ifr_s_addr(ifr)); } if (ifconfig->flags & IFF_LOOPBACK) { sigar_net_address_set(ifconfig->destination, ifconfig->address.addr.in); sigar_net_address_set(ifconfig->broadcast, 0); SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_LOOPBACK); } else { if (!ioctl(sock, SIOCGIFDSTADDR, &ifr)) { sigar_net_address_set(ifconfig->destination, ifr_s_addr(ifr)); } if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) { sigar_net_address_set(ifconfig->broadcast, ifr_s_addr(ifr)); } SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_ETHERNET); } close(sock); /* XXX can we get a better description like win32? */ SIGAR_SSTRCPY(ifconfig->description, ifconfig->name); return SIGAR_OK; } int sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { int status; ifmsg_iter_t iter; struct if_msghdr *ifm; if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) { return status; } iter.type = IFMSG_ITER_GET; iter.name = name; if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) { return status; } ifm = iter.data.ifm; ifstat->rx_bytes = ifm->ifm_data.ifi_ibytes; ifstat->rx_packets = ifm->ifm_data.ifi_ipackets; ifstat->rx_errors = ifm->ifm_data.ifi_ierrors; ifstat->rx_dropped = ifm->ifm_data.ifi_iqdrops; ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->rx_frame = SIGAR_FIELD_NOTIMPL; ifstat->tx_bytes = ifm->ifm_data.ifi_obytes; ifstat->tx_packets = ifm->ifm_data.ifi_opackets; ifstat->tx_errors = ifm->ifm_data.ifi_oerrors; ifstat->tx_collisions = ifm->ifm_data.ifi_collisions; ifstat->tx_dropped = SIGAR_FIELD_NOTIMPL; ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL; ifstat->speed = ifm->ifm_data.ifi_baudrate; return SIGAR_OK; } static int net_connection_state_get(int state) { switch (state) { case TCPS_CLOSED: return SIGAR_TCP_CLOSE; case TCPS_LISTEN: return SIGAR_TCP_LISTEN; case TCPS_SYN_SENT: return SIGAR_TCP_SYN_SENT; case TCPS_SYN_RECEIVED: return SIGAR_TCP_SYN_RECV; case TCPS_ESTABLISHED: return SIGAR_TCP_ESTABLISHED; case TCPS_CLOSE_WAIT: return SIGAR_TCP_CLOSE_WAIT; case TCPS_FIN_WAIT_1: return SIGAR_TCP_FIN_WAIT1; case TCPS_CLOSING: return SIGAR_TCP_CLOSING; case TCPS_LAST_ACK: return SIGAR_TCP_LAST_ACK; case TCPS_FIN_WAIT_2: return SIGAR_TCP_FIN_WAIT2; case TCPS_TIME_WAIT: return SIGAR_TCP_TIME_WAIT; default: return SIGAR_TCP_UNKNOWN; } } #if defined(__OpenBSD__) || defined(__NetBSD__) static int net_connection_get(sigar_net_connection_walker_t *walker, int proto) { int status; int istcp = 0, type; int flags = walker->flags; struct inpcbtable table; struct inpcb *head, *next, *prev; sigar_t *sigar = walker->sigar; u_long offset; switch (proto) { case IPPROTO_TCP: offset = sigar->koffsets[KOFFSET_TCBTABLE]; istcp = 1; type = SIGAR_NETCONN_TCP; break; case IPPROTO_UDP: default: return SIGAR_ENOTIMPL; } status = kread(sigar, &table, sizeof(table), offset); if (status != SIGAR_OK) { return status; } prev = head = (struct inpcb *)&CIRCLEQ_FIRST(&((struct inpcbtable *)offset)->inpt_queue); next = (struct inpcb *)CIRCLEQ_FIRST(&table.inpt_queue); while (next != head) { struct inpcb inpcb; struct tcpcb tcpcb; struct socket socket; status = kread(sigar, &inpcb, sizeof(inpcb), (long)next); prev = next; next = (struct inpcb *)CIRCLEQ_NEXT(&inpcb, inp_queue); kread(sigar, &socket, sizeof(socket), (u_long)inpcb.inp_socket); if ((((flags & SIGAR_NETCONN_SERVER) && socket.so_qlimit) || ((flags & SIGAR_NETCONN_CLIENT) && !socket.so_qlimit))) { sigar_net_connection_t conn; SIGAR_ZERO(&conn); if (istcp) { kread(sigar, &tcpcb, sizeof(tcpcb), (u_long)inpcb.inp_ppcb); } #ifdef __NetBSD__ if (inpcb.inp_af == AF_INET6) { /*XXX*/ continue; } #else if (inpcb.inp_flags & INP_IPV6) { sigar_net_address6_set(conn.local_address, &inpcb.inp_laddr6.s6_addr); sigar_net_address6_set(conn.remote_address, &inpcb.inp_faddr6.s6_addr); } #endif else { sigar_net_address_set(conn.local_address, inpcb.inp_laddr.s_addr); sigar_net_address_set(conn.remote_address, inpcb.inp_faddr.s_addr); } conn.local_port = ntohs(inpcb.inp_lport); conn.remote_port = ntohs(inpcb.inp_fport); conn.receive_queue = socket.so_rcv.sb_cc; conn.send_queue = socket.so_snd.sb_cc; conn.uid = socket.so_pgid; conn.type = type; if (!istcp) { conn.state = SIGAR_TCP_UNKNOWN; if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } continue; } conn.state = net_connection_state_get(tcpcb.t_state); if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } } return SIGAR_OK; } #else static int net_connection_get(sigar_net_connection_walker_t *walker, int proto) { int flags = walker->flags; int type, istcp = 0; char *buf; const char *mibvar; struct tcpcb *tp = NULL; struct inpcb *inp; struct xinpgen *xig, *oxig; struct xsocket *so; size_t len; switch (proto) { case IPPROTO_TCP: mibvar = "net.inet.tcp.pcblist"; istcp = 1; type = SIGAR_NETCONN_TCP; break; case IPPROTO_UDP: mibvar = "net.inet.udp.pcblist"; type = SIGAR_NETCONN_UDP; break; default: mibvar = "net.inet.raw.pcblist"; type = SIGAR_NETCONN_RAW; break; } len = 0; if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) { return errno; } if ((buf = malloc(len)) == 0) { return errno; } if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) { free(buf); return errno; } oxig = xig = (struct xinpgen *)buf; for (xig = (struct xinpgen *)((char *)xig + xig->xig_len); xig->xig_len > sizeof(struct xinpgen); xig = (struct xinpgen *)((char *)xig + xig->xig_len)) { if (istcp) { struct xtcpcb *cb = (struct xtcpcb *)xig; tp = &cb->xt_tp; inp = &cb->xt_inp; so = &cb->xt_socket; } else { struct xinpcb *cb = (struct xinpcb *)xig; inp = &cb->xi_inp; so = &cb->xi_socket; } if (so->xso_protocol != proto) { continue; } if (inp->inp_gencnt > oxig->xig_gen) { continue; } if ((((flags & SIGAR_NETCONN_SERVER) && so->so_qlimit) || ((flags & SIGAR_NETCONN_CLIENT) && !so->so_qlimit))) { sigar_net_connection_t conn; SIGAR_ZERO(&conn); if (inp->inp_vflag & INP_IPV6) { sigar_net_address6_set(conn.local_address, &inp->in6p_laddr.s6_addr); sigar_net_address6_set(conn.remote_address, &inp->in6p_faddr.s6_addr); } else { sigar_net_address_set(conn.local_address, inp->inp_laddr.s_addr); sigar_net_address_set(conn.remote_address, inp->inp_faddr.s_addr); } conn.local_port = ntohs(inp->inp_lport); conn.remote_port = ntohs(inp->inp_fport); conn.receive_queue = so->so_rcv.sb_cc; conn.send_queue = so->so_snd.sb_cc; conn.uid = so->so_pgid; conn.type = type; if (!istcp) { conn.state = SIGAR_TCP_UNKNOWN; if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } continue; } conn.state = net_connection_state_get(tp->t_state); if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } } free(buf); return SIGAR_OK; } #endif int sigar_net_connection_walk(sigar_net_connection_walker_t *walker) { int flags = walker->flags; int status; if (flags & SIGAR_NETCONN_TCP) { status = net_connection_get(walker, IPPROTO_TCP); if (status != SIGAR_OK) { return status; } } if (flags & SIGAR_NETCONN_UDP) { status = net_connection_get(walker, IPPROTO_UDP); if (status != SIGAR_OK) { return status; } } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp) { struct tcpstat mib; #if !defined(TCPCTL_STATS) && (defined(__OpenBSD__) || defined(__NetBSD__)) int status = kread(sigar, &mib, sizeof(mib), sigar->koffsets[KOFFSET_TCPSTAT]); if (status != SIGAR_OK) { return status; } #else int var[4] = { CTL_NET, PF_INET, IPPROTO_TCP, TCPCTL_STATS }; size_t len = sizeof(mib); if (sysctl(var, NMIB(var), &mib, &len, NULL, 0) < 0) { return errno; } #endif tcp->active_opens = mib.tcps_connattempt; tcp->passive_opens = mib.tcps_accepts; tcp->attempt_fails = mib.tcps_conndrops; tcp->estab_resets = mib.tcps_drops; if (sigar_tcp_curr_estab(sigar, tcp) != SIGAR_OK) { tcp->curr_estab = -1; } tcp->in_segs = mib.tcps_rcvtotal; tcp->out_segs = mib.tcps_sndtotal - mib.tcps_sndrexmitpack; tcp->retrans_segs = mib.tcps_sndrexmitpack; tcp->in_errs = mib.tcps_rcvbadsum + mib.tcps_rcvbadoff + mib.tcps_rcvmemdrop + mib.tcps_rcvshort; tcp->out_rsts = -1; /* XXX mib.tcps_sndctrl - mib.tcps_closed; ? */ return SIGAR_OK; } #ifndef SIGAR_FREEBSD5_NFSSTAT static int get_nfsstats(struct nfsstats *stats) { size_t len = sizeof(*stats); int mib[] = { CTL_VFS, 2, NFS_NFSSTATS }; if (sysctl(mib, NMIB(mib), stats, &len, NULL, 0) < 0) { return errno; } else { return SIGAR_OK; } } #endif #if defined(__OpenBSD__) typedef uint64_t rpc_cnt_t; #else typedef int rpc_cnt_t; #endif static void map_nfs_stats(sigar_nfs_v3_t *nfs, rpc_cnt_t *rpc) { nfs->null = rpc[NFSPROC_NULL]; nfs->getattr = rpc[NFSPROC_GETATTR]; nfs->setattr = rpc[NFSPROC_SETATTR]; nfs->lookup = rpc[NFSPROC_LOOKUP]; nfs->access = rpc[NFSPROC_ACCESS]; nfs->readlink = rpc[NFSPROC_READLINK]; nfs->read = rpc[NFSPROC_READ]; nfs->write = rpc[NFSPROC_WRITE]; nfs->create = rpc[NFSPROC_CREATE]; nfs->mkdir = rpc[NFSPROC_MKDIR]; nfs->symlink = rpc[NFSPROC_SYMLINK]; nfs->mknod = rpc[NFSPROC_MKNOD]; nfs->remove = rpc[NFSPROC_REMOVE]; nfs->rmdir = rpc[NFSPROC_RMDIR]; nfs->rename = rpc[NFSPROC_RENAME]; nfs->link = rpc[NFSPROC_LINK]; nfs->readdir = rpc[NFSPROC_READDIR]; nfs->readdirplus = rpc[NFSPROC_READDIRPLUS]; nfs->fsstat = rpc[NFSPROC_FSSTAT]; nfs->fsinfo = rpc[NFSPROC_FSINFO]; nfs->pathconf = rpc[NFSPROC_PATHCONF]; nfs->commit = rpc[NFSPROC_COMMIT]; } int sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs) { return SIGAR_ENOTIMPL; } int sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs) { return SIGAR_ENOTIMPL; } int sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs) { #ifdef SIGAR_FREEBSD5_NFSSTAT struct nfsstats stats; size_t size = sizeof(stats); if (sysctlbyname("vfs.nfs.nfsstats", &stats, &size, NULL, 0) == -1) { return errno; } map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.rpccnt[0]); #else int status; struct nfsstats stats; if ((status = get_nfsstats(&stats)) != SIGAR_OK) { return status; } map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.rpccnt[0]); #endif return SIGAR_OK; } int sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs) { #ifdef SIGAR_FREEBSD5_NFSSTAT struct nfsrvstats stats; size_t size = sizeof(stats); if (sysctlbyname("vfs.nfsrv.nfsrvstats", &stats, &size, NULL, 0) == -1) { return errno; } map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.srvrpccnt[0]); #else int status; struct nfsstats stats; if ((status = get_nfsstats(&stats)) != SIGAR_OK) { return status; } map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.srvrpccnt[0]); #endif return SIGAR_OK; } #if defined(__FreeBSD__) && /*XXX*/ (__FreeBSD_version < 800000) #define _KERNEL #include #undef _KERNEL /* derived from * /usr/ports/security/pidentd/work/pidentd-3.0.16/src/k_freebsd2.c */ int sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid) { struct nlist nl[2]; struct inpcbhead tcb; struct socket *sockp = NULL; struct kinfo_proc *pinfo; struct inpcb *head, pcbp; int i, nentries, status; if (protocol != SIGAR_NETCONN_TCP) { return SIGAR_ENOTIMPL; } if (!sigar->kmem) { return SIGAR_EPERM_KMEM; } nl[0].n_name = "_tcb"; /* XXX cache */ nl[1].n_name = ""; if (kvm_nlist(sigar->kmem, nl) < 0) { return errno; } status = kread(sigar, &tcb, sizeof(tcb), nl[0].n_value); if (status != SIGAR_OK) { return status; } for (head = tcb.lh_first; head != NULL; head = pcbp.inp_list.le_next) { status = kread(sigar, &pcbp, sizeof(pcbp), (long)head); if (status != SIGAR_OK) { return status; } if (!(pcbp.inp_vflag & INP_IPV4)) { continue; } if (pcbp.inp_fport != 0) { continue; } if (ntohs(pcbp.inp_lport) == port) { sockp = pcbp.inp_socket; break; } } if (!sockp) { return ENOENT; } pinfo = kvm_getprocs(sigar->kmem, KERN_PROC_PROC, 0, &nentries); if (!pinfo) { return errno; } for (i=0; ilibproc) { return SIGAR_ENOTIMPL; } status = sigar_proc_list_get(sigar, &pids); if (status != SIGAR_OK) { return status; } for (i=0; iifconf_buf; for (n=0; nproc_fdtype != PROX_FDTYPE_SOCKET) { continue; } rsize = sigar->proc_pidfdinfo(pids.data[i], fdp->proc_fd, PROC_PIDFDSOCKETINFO, &si, sizeof(si)); if (rsize != sizeof(si)) { continue; } if (si.psi.soi_kind != SOCKINFO_TCP) { continue; } if (si.psi.soi_proto.pri_tcp.tcpsi_state != TSI_S_LISTEN) { continue; } family = si.psi.soi_family; if (!((family == AF_INET) || (family == AF_INET6))) { continue; } lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport); if (lport == port) { *pid = pids.data[i]; found = 1; break; } } } sigar_proc_list_destroy(sigar, &pids); return found ? SIGAR_OK : ENOENT; } #else int sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid) { return SIGAR_ENOTIMPL; } #endif int sigar_os_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo) { #ifdef DARWIN char *codename = NULL; SInt32 version, version_major, version_minor, version_fix; SIGAR_SSTRCPY(sysinfo->name, "MacOSX"); SIGAR_SSTRCPY(sysinfo->vendor_name, "Mac OS X"); SIGAR_SSTRCPY(sysinfo->vendor, "Apple"); if (Gestalt(gestaltSystemVersion, &version) == noErr) { if (version >= 0x00001040) { Gestalt('sys1' /*gestaltSystemVersionMajor*/, &version_major); Gestalt('sys2' /*gestaltSystemVersionMinor*/, &version_minor); Gestalt('sys3' /*gestaltSystemVersionBugFix*/, &version_fix); } else { version_fix = version & 0xf; version >>= 4; version_minor = version & 0xf; version >>= 4; version_major = version - (version >> 4) * 6; } } else { return SIGAR_ENOTIMPL; } snprintf(sysinfo->vendor_version, sizeof(sysinfo->vendor_version), "%d.%d", (int)version_major, (int)version_minor); snprintf(sysinfo->version, sizeof(sysinfo->version), "%s.%d", sysinfo->vendor_version, (int)version_fix); if (version_major == 10) { switch (version_minor) { case 2: codename = "Jaguar"; break; case 3: codename = "Panther"; break; case 4: codename = "Tiger"; break; case 5: codename = "Leopard"; break; case 6: codename = "Snow Leopard"; break; default: codename = "Unknown"; break; } } else { return SIGAR_ENOTIMPL; } SIGAR_SSTRCPY(sysinfo->vendor_code_name, codename); snprintf(sysinfo->description, sizeof(sysinfo->description), "%s %s", sysinfo->vendor_name, sysinfo->vendor_code_name); #else char *ptr; #if defined(__FreeBSD__) SIGAR_SSTRCPY(sysinfo->name, "FreeBSD"); #elif defined(__OpenBSD__) SIGAR_SSTRCPY(sysinfo->name, "OpenBSD"); #elif defined(__NetBSD__) SIGAR_SSTRCPY(sysinfo->name, "NetBSD"); #else SIGAR_SSTRCPY(sysinfo->name, "Unknown"); #endif SIGAR_SSTRCPY(sysinfo->vendor_name, sysinfo->name); SIGAR_SSTRCPY(sysinfo->vendor, sysinfo->name); SIGAR_SSTRCPY(sysinfo->vendor_version, sysinfo->version); if ((ptr = strstr(sysinfo->vendor_version, "-"))) { /* STABLE, RELEASE, CURRENT */ *ptr++ = '\0'; SIGAR_SSTRCPY(sysinfo->vendor_code_name, ptr); } snprintf(sysinfo->description, sizeof(sysinfo->description), "%s %s", sysinfo->name, sysinfo->version); #endif return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/os/darwin/sigar_os.h000066400000000000000000000036421210132627500216660ustar00rootroot00000000000000/* * Copyright (c) 2004-2006, 2008 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. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #ifdef DARWIN #include #include #ifdef DARWIN_HAS_LIBPROC_H #include #include typedef int (*proc_pidinfo_func_t)(int, int, uint64_t, void *, int); typedef int (*proc_pidfdinfo_func_t)(int, int, int, void *, int); #endif #else #include #endif #ifdef __NetBSD__ #include #endif #include enum { KOFFSET_CPUINFO, KOFFSET_VMMETER, #if defined(__OpenBSD__) || defined(__NetBSD__) KOFFSET_TCPSTAT, KOFFSET_TCBTABLE, #endif KOFFSET_MAX }; #if defined(__OpenBSD__) || defined(__NetBSD__) typedef struct kinfo_proc2 bsd_pinfo_t; #else typedef struct kinfo_proc bsd_pinfo_t; #endif struct sigar_t { SIGAR_T_BASE; int pagesize; time_t last_getprocs; sigar_pid_t last_pid; bsd_pinfo_t *pinfo; int lcpu; size_t argmax; #ifdef DARWIN mach_port_t mach_port; # ifdef DARWIN_HAS_LIBPROC_H void *libproc; proc_pidinfo_func_t proc_pidinfo; proc_pidfdinfo_func_t proc_pidfdinfo; # endif #else kvm_t *kmem; /* offsets for seeking on kmem */ unsigned long koffsets[KOFFSET_MAX]; int proc_mounted; #endif }; #define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES) #define SIGAR_EPROC_NOENT (SIGAR_OS_START_ERROR+2) #endif /* SIGAR_OS_H */ hyperic-sigar-1.6.4+dfsg/src/os/hpux/000077500000000000000000000000001210132627500174025ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/hpux/hpux_sigar.c000066400000000000000000000745341210132627500217340ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #include #ifndef __ia64__ #include #endif #include #include #ifdef _PSTAT64 typedef int64_t pstat_int_t; #else typedef int32_t pstat_int_t; #endif int sigar_os_open(sigar_t **sigar) { *sigar = malloc(sizeof(**sigar)); /* does not change while system is running */ pstat_getstatic(&(*sigar)->pstatic, sizeof((*sigar)->pstatic), 1, 0); (*sigar)->ticks = sysconf(_SC_CLK_TCK); (*sigar)->last_pid = -1; (*sigar)->pinfo = NULL; (*sigar)->mib = -1; return SIGAR_OK; } int sigar_os_close(sigar_t *sigar) { if (sigar->pinfo) { free(sigar->pinfo); } if (sigar->mib >= 0) { close_mib(sigar->mib); } free(sigar); return SIGAR_OK; } char *sigar_os_error_string(sigar_t *sigar, int err) { return NULL; } int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem) { struct pst_dynamic stats; struct pst_vminfo vminfo; sigar_uint64_t pagesize = sigar->pstatic.page_size; sigar_uint64_t kern; mem->total = sigar->pstatic.physical_memory * pagesize; pstat_getdynamic(&stats, sizeof(stats), 1, 0); mem->free = stats.psd_free * pagesize; mem->used = mem->total - mem->free; pstat_getvminfo(&vminfo, sizeof(vminfo), 1, 0); /* "kernel dynamic memory" */ kern = vminfo.psv_kern_dynmem * pagesize; mem->actual_free = mem->free + kern; mem->actual_used = mem->used - kern; sigar_mem_calc_ram(sigar, mem); return SIGAR_OK; } int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) { struct pst_swapinfo swapinfo; struct pst_vminfo vminfo; int i=0; swap->total = swap->free = 0; while (pstat_getswap(&swapinfo, sizeof(swapinfo), 1, i++) > 0) { swapinfo.pss_nfpgs *= 4; /* nfpgs is in 512 byte blocks */ if (swapinfo.pss_nblksenabled == 0) { swapinfo.pss_nblksenabled = swapinfo.pss_nfpgs; } swap->total += swapinfo.pss_nblksenabled; swap->free += swapinfo.pss_nfpgs; } swap->used = swap->total - swap->free; pstat_getvminfo(&vminfo, sizeof(vminfo), 1, 0); swap->page_in = vminfo.psv_spgin; swap->page_out = vminfo.psv_spgout; return SIGAR_OK; } static void get_cpu_metrics(sigar_t *sigar, sigar_cpu_t *cpu, pstat_int_t *cpu_time) { cpu->user = SIGAR_TICK2MSEC(cpu_time[CP_USER]); cpu->sys = SIGAR_TICK2MSEC(cpu_time[CP_SYS] + cpu_time[CP_SSYS]); cpu->nice = SIGAR_TICK2MSEC(cpu_time[CP_NICE]); cpu->idle = SIGAR_TICK2MSEC(cpu_time[CP_IDLE]); cpu->wait = SIGAR_TICK2MSEC(cpu_time[CP_SWAIT] + cpu_time[CP_BLOCK]); cpu->irq = SIGAR_TICK2MSEC(cpu_time[CP_INTR]); cpu->soft_irq = 0; /*N/A*/ cpu->stolen = 0; /*N/A*/ cpu->total = cpu->user + cpu->sys + cpu->nice + cpu->idle + cpu->wait + cpu->irq; } int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu) { struct pst_dynamic stats; pstat_getdynamic(&stats, sizeof(stats), 1, 0); sigar->ncpu = stats.psd_proc_cnt; get_cpu_metrics(sigar, cpu, stats.psd_cpu_time); return SIGAR_OK; } int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { int i; struct pst_dynamic stats; pstat_getdynamic(&stats, sizeof(stats), 1, 0); sigar->ncpu = stats.psd_proc_cnt; sigar_cpu_list_create(cpulist); for (i=0; incpu; i++) { sigar_cpu_t *cpu; struct pst_processor proc; if (pstat_getprocessor(&proc, sizeof(proc), 1, i) < 0) { continue; } SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; get_cpu_metrics(sigar, cpu, proc.psp_cpu_time); } return SIGAR_OK; } int sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime) { uptime->uptime = time(NULL) - sigar->pstatic.boot_time; return SIGAR_OK; } int sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg) { struct pst_dynamic stats; pstat_getdynamic(&stats, sizeof(stats), 1, 0); loadavg->loadavg[0] = stats.psd_avg_1_min; loadavg->loadavg[1] = stats.psd_avg_5_min; loadavg->loadavg[2] = stats.psd_avg_15_min; return SIGAR_OK; } #define PROC_ELTS 16 int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { int num, idx=0; struct pst_status proctab[PROC_ELTS]; while ((num = pstat_getproc(proctab, sizeof(proctab[0]), PROC_ELTS, idx)) > 0) { int i; for (i=0; idata[proclist->number++] = proctab[i].pst_pid; } idx = proctab[num-1].pst_idx + 1; } if (proclist->number == 0) { return errno; } return SIGAR_OK; } static int sigar_pstat_getproc(sigar_t *sigar, sigar_pid_t pid) { int status, num; time_t timenow = time(NULL); if (sigar->pinfo == NULL) { sigar->pinfo = malloc(sizeof(*sigar->pinfo)); } if (sigar->last_pid == pid) { if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) { return SIGAR_OK; } } sigar->last_pid = pid; sigar->last_getprocs = timenow; if (pstat_getproc(sigar->pinfo, sizeof(*sigar->pinfo), 0, pid) == -1) { return errno; } return SIGAR_OK; } int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem) { int pagesize = sigar->pstatic.page_size; int status = sigar_pstat_getproc(sigar, pid); struct pst_status *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } procmem->size = pinfo->pst_vtsize + /* text */ pinfo->pst_vdsize + /* data */ pinfo->pst_vssize + /* stack */ pinfo->pst_vshmsize + /* shared memory */ pinfo->pst_vmmsize + /* mem-mapped files */ pinfo->pst_vusize + /* U-Area & K-Stack */ pinfo->pst_viosize; /* I/O dev mapping */ procmem->size *= pagesize; procmem->resident = pinfo->pst_rssize * pagesize; procmem->share = pinfo->pst_vshmsize * pagesize; procmem->minor_faults = pinfo->pst_minorfaults; procmem->major_faults = pinfo->pst_majorfaults; procmem->page_faults = procmem->minor_faults + procmem->major_faults; return SIGAR_OK; } int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred) { int status = sigar_pstat_getproc(sigar, pid); struct pst_status *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } proccred->uid = pinfo->pst_uid; proccred->gid = pinfo->pst_gid; proccred->euid = pinfo->pst_euid; proccred->egid = pinfo->pst_egid; return SIGAR_OK; } int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime) { int status = sigar_pstat_getproc(sigar, pid); struct pst_status *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } proctime->start_time = pinfo->pst_start; proctime->start_time *= SIGAR_MSEC; proctime->user = pinfo->pst_utime * SIGAR_MSEC; proctime->sys = pinfo->pst_stime * SIGAR_MSEC; proctime->total = proctime->user + proctime->sys; return SIGAR_OK; } int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { int status = sigar_pstat_getproc(sigar, pid); struct pst_status *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } SIGAR_SSTRCPY(procstate->name, pinfo->pst_ucomm); procstate->ppid = pinfo->pst_ppid; procstate->tty = makedev(pinfo->pst_term.psd_major, pinfo->pst_term.psd_minor); procstate->priority = pinfo->pst_pri; procstate->nice = pinfo->pst_nice; procstate->threads = pinfo->pst_nlwps; procstate->processor = pinfo->pst_procnum; /* cast to prevent compiler warning: */ /* Case label too big for the type of the switch expression */ switch ((int32_t)pinfo->pst_stat) { case PS_SLEEP: procstate->state = 'S'; break; case PS_RUN: procstate->state = 'R'; break; case PS_STOP: procstate->state = 'T'; break; case PS_ZOMBIE: procstate->state = 'Z'; break; case PS_IDLE: procstate->state = 'D'; break; } return SIGAR_OK; } int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { char *args, *arg; #ifdef PSTAT_GETCOMMANDLINE char buf[1024]; /* kernel limit */ # ifdef pstat_getcommandline /* 11i v2 + */ if (pstat_getcommandline(buf, sizeof(buf), sizeof(buf[0]), pid) == -1) { return errno; } # else union pstun pu; pu.pst_command = buf; if (pstat(PSTAT_GETCOMMANDLINE, pu, sizeof(buf), sizeof(buf[0]), pid) == -1) { return errno; } # endif /* pstat_getcommandline */ args = buf; #else struct pst_status status; if (pstat_getproc(&status, sizeof(status), 0, pid) == -1) { return errno; } args = status.pst_cmd; #endif while (*args && (arg = sigar_getword(&args, ' '))) { SIGAR_PROC_ARGS_GROW(procargs); procargs->data[procargs->number++] = arg; } return SIGAR_OK; } int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { return SIGAR_ENOTIMPL; } int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd) { struct pst_status status; int idx=0, n; struct pst_fileinfo2 psf[16]; procfd->total = 0; if (pstat_getproc(&status, sizeof(status), 0, pid) == -1) { return errno; } /* HPUX 11.31 removed the deprecated pstat_getfile call */ while ((n = pstat_getfile2(psf, sizeof(psf[0]), sizeof(psf)/sizeof(psf[0]), idx, pid)) > 0) { procfd->total += n; idx = psf[n-1].psf_fd + 1; } if (n == -1) { return errno; } return SIGAR_OK; } int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { #ifdef __pst_fid /* 11.11+ */ int rc; struct pst_status status; if (pstat_getproc(&status, sizeof(status), 0, pid) == -1) { return errno; } rc = pstat_getpathname(procexe->cwd, sizeof(procexe->cwd), &status.pst_fid_cdir); if (rc == -1) { return errno; } rc = pstat_getpathname(procexe->name, sizeof(procexe->name), &status.pst_fid_text); if (rc == -1) { return errno; } rc = pstat_getpathname(procexe->root, sizeof(procexe->root), &status.pst_fid_rdir); if (rc == -1) { return errno; } return SIGAR_OK; #else return SIGAR_ENOTIMPL; /* 11.00 */ #endif } int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { return SIGAR_ENOTIMPL; } #define TIME_NSEC(t) \ (SIGAR_SEC2NANO((t).tv_sec) + (sigar_uint64_t)(t).tv_nsec) int sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu) { #ifdef __ia64__ /* XXX seems _lwp funcs were for solaris compat and dont exist * on itanium. hp docs claim that have equiv functions, * but wtf is it for _lwp_info? */ return SIGAR_ENOTIMPL; #else struct lwpinfo info; if (id != 0) { return SIGAR_ENOTIMPL; } _lwp_info(&info); cpu->user = TIME_NSEC(info.lwp_utime); cpu->sys = TIME_NSEC(info.lwp_stime); cpu->total = TIME_NSEC(info.lwp_utime) + TIME_NSEC(info.lwp_stime); return SIGAR_OK; #endif } #include int sigar_os_fs_type_get(sigar_file_system_t *fsp) { char *type = fsp->sys_type_name; switch (*type) { case 'h': if (strEQ(type, "hfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'c': if (strEQ(type, "cdfs")) { fsp->type = SIGAR_FSTYPE_CDROM; } break; } return fsp->type; } int sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist) { struct mntent *ent; FILE *fp; sigar_file_system_t *fsp; if (!(fp = setmntent(MNT_MNTTAB, "r"))) { return errno; } sigar_file_system_list_create(fslist); while ((ent = getmntent(fp))) { if ((*(ent->mnt_type) == 's') && strEQ(ent->mnt_type, "swap")) { /* * in this case, devname == "...", for * which statfs chokes on. so skip it. * also notice hpux df command has no swap info. */ continue; } SIGAR_FILE_SYSTEM_LIST_GROW(fslist); fsp = &fslist->data[fslist->number++]; SIGAR_SSTRCPY(fsp->dir_name, ent->mnt_dir); SIGAR_SSTRCPY(fsp->dev_name, ent->mnt_fsname); SIGAR_SSTRCPY(fsp->sys_type_name, ent->mnt_type); SIGAR_SSTRCPY(fsp->options, ent->mnt_opts); sigar_fs_type_init(fsp); } endmntent(fp); return SIGAR_OK; } static int create_fsdev_cache(sigar_t *sigar) { sigar_file_system_list_t fslist; int i; int status = sigar_file_system_list_get(sigar, &fslist); if (status != SIGAR_OK) { return status; } sigar->fsdev = sigar_cache_new(15); for (i=0; itype == SIGAR_FSTYPE_LOCAL_DISK) { sigar_cache_entry_t *ent; struct stat sb; if (stat(fsp->dir_name, &sb) < 0) { continue; } ent = sigar_cache_get(sigar->fsdev, SIGAR_FSDEV_ID(sb)); ent->value = strdup(fsp->dev_name); } } return SIGAR_OK; } int sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *usage) { return SIGAR_ENOTIMPL; } int sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { struct stat sb; int status = sigar_statvfs(sigar, dirname, fsusage); if (status != SIGAR_OK) { return status; } fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage); SIGAR_DISK_STATS_INIT(&fsusage->disk); if (!sigar->fsdev) { if (create_fsdev_cache(sigar) != SIGAR_OK) { return SIGAR_OK; } } if (stat(dirname, &sb) == 0) { sigar_cache_entry_t *ent; struct pst_lvinfo lv; struct stat devsb; char *devname; int retval; ent = sigar_cache_get(sigar->fsdev, SIGAR_FSDEV_ID(sb)); if (ent->value == NULL) { return SIGAR_OK; } if (stat((char *)ent->value, &devsb) < 0) { return SIGAR_OK; } retval = pstat_getlv(&lv, sizeof(lv), 0, (int)devsb.st_rdev); if (retval == 1) { fsusage->disk.reads = lv.psl_rxfer; fsusage->disk.writes = lv.psl_wxfer; fsusage->disk.read_bytes = lv.psl_rcount; fsusage->disk.write_bytes = lv.psl_wcount; fsusage->disk.queue = SIGAR_FIELD_NOTIMPL; } } return SIGAR_OK; } int sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { int i; struct pst_dynamic stats; pstat_getdynamic(&stats, sizeof(stats), 1, 0); sigar->ncpu = stats.psd_proc_cnt; sigar_cpu_info_list_create(cpu_infos); for (i=0; incpu; i++) { sigar_cpu_info_t *info; struct pst_processor proc; if (pstat_getprocessor(&proc, sizeof(proc), 1, i) < 0) { perror("pstat_getprocessor"); continue; } SIGAR_CPU_INFO_LIST_GROW(cpu_infos); info = &cpu_infos->data[cpu_infos->number++]; info->total_cores = sigar->ncpu; info->cores_per_socket = 1; /*XXX*/ info->total_sockets = sigar->ncpu; /*XXX*/ #ifdef __ia64__ SIGAR_SSTRCPY(info->vendor, "Intel"); /*XXX*/ SIGAR_SSTRCPY(info->model, "Itanium"); /*XXX*/ #else SIGAR_SSTRCPY(info->vendor, "HP"); /*XXX*/ SIGAR_SSTRCPY(info->model, "PA RISC"); /*XXX*/ #endif #ifdef PSP_MAX_CACHE_LEVELS /* 11.31+; see SIGAR-196 */ info->mhz = proc.psp_cpu_frequency / 1000000; #else info->mhz = sigar->ticks * proc.psp_iticksperclktick / 1000000; #endif info->cache_size = SIGAR_FIELD_NOTIMPL; /*XXX*/ } return SIGAR_OK; } static int sigar_get_mib_info(sigar_t *sigar, struct nmparms *parms) { if (sigar->mib < 0) { if ((sigar->mib = open_mib("/dev/ip", O_RDONLY, 0, 0)) < 0) { return errno; } } return get_mib_info(sigar->mib, parms); } /* wrapper around get_physical_stat() */ static int sigar_get_physical_stat(sigar_t *sigar, int *count) { int status; unsigned int len; struct nmparms parms; len = sizeof(*count); parms.objid = ID_ifNumber; parms.buffer = count; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { return status; } len = sizeof(nmapi_phystat) * *count; if (sigar->ifconf_len < len) { sigar->ifconf_buf = realloc(sigar->ifconf_buf, len); sigar->ifconf_len = len; } if (get_physical_stat(sigar->ifconf_buf, &len) < 0) { return errno; } else { return SIGAR_OK; } } #define SIGAR_IF_NAMESIZE 16 /* hpux if_indextoname() does not work as advertised in 11.11 */ static int sigar_if_indextoname(sigar_t *sigar, char *name, int index) { int i, status, count; nmapi_phystat *stat; if ((status = sigar_get_physical_stat(sigar, &count) != SIGAR_OK)) { return status; } for (i=0, stat = (nmapi_phystat *)sigar->ifconf_buf; iif_entry.ifIndex == index) { strncpy(name, stat->nm_device, SIGAR_IF_NAMESIZE); return SIGAR_OK; } } return ENXIO; } int sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist) { int status, count, i; unsigned int len; struct nmparms parms; mib_ipRouteEnt *routes; sigar_net_route_t *route; len = sizeof(count); parms.objid = ID_ipRouteNumEnt; parms.buffer = &count; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { return status; } len = count * sizeof(*routes); routes = malloc(len); parms.objid = ID_ipRouteTable; parms.buffer = routes; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { free(routes); return status; } routelist->size = routelist->number = 0; sigar_net_route_list_create(routelist); for (i=0; idata[routelist->number++]; SIGAR_ZERO(route); /* XXX: other fields */ sigar_net_address_set(route->destination, ent->Dest); sigar_net_address_set(route->mask, ent->Mask); sigar_net_address_set(route->gateway, ent->NextHop); sigar_if_indextoname(sigar, route->ifname, ent->IfIndex); route->flags = SIGAR_RTF_UP; if ((ent->Dest == 0) && (ent->Mask == 0)) { route->flags |= SIGAR_RTF_GATEWAY; } } free(routes); return SIGAR_OK; } static int get_mib_ifstat(sigar_t *sigar, const char *name, mib_ifEntry *mib) { int i, status, count; nmapi_phystat *stat; if ((status = sigar_get_physical_stat(sigar, &count) != SIGAR_OK)) { return status; } for (i=0, stat = (nmapi_phystat *)sigar->ifconf_buf; inm_device, name)) { memcpy(mib, &stat->if_entry, sizeof(*mib)); return SIGAR_OK; } } return ENXIO; } int sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { int status; mib_ifEntry mib; status = get_mib_ifstat(sigar, name, &mib); if (status != SIGAR_OK) { return status; } ifstat->rx_bytes = mib.ifInOctets; ifstat->rx_packets = mib.ifInUcastPkts + mib.ifInNUcastPkts; ifstat->rx_errors = mib.ifInErrors; ifstat->rx_dropped = mib.ifInDiscards; ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->rx_frame = SIGAR_FIELD_NOTIMPL; ifstat->tx_bytes = mib.ifOutOctets; ifstat->tx_packets = mib.ifOutUcastPkts + mib.ifOutNUcastPkts; ifstat->tx_errors = mib.ifOutErrors; ifstat->tx_dropped = mib.ifOutDiscards; ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->tx_collisions = SIGAR_FIELD_NOTIMPL; ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL; ifstat->speed = mib.ifSpeed; return SIGAR_OK; } static int net_conn_get_udp_listen(sigar_net_connection_walker_t *walker) { sigar_t *sigar = walker->sigar; int flags = walker->flags; int status, count, i; unsigned int len; mib_udpLsnEnt *entries; struct nmparms parms; len = sizeof(count); parms.objid = ID_udpLsnNumEnt; parms.buffer = &count; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { return status; } if (count <= 0) { return ENOENT; } len = count * sizeof(*entries); entries = malloc(len); parms.objid = ID_udpLsnTable; parms.buffer = entries; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { free(entries); return status; } for (i=0; iLocalPort; conn.remote_port = 0; sigar_net_address_set(conn.local_address, entry->LocalAddress); sigar_net_address_set(conn.remote_address, 0); conn.send_queue = conn.receive_queue = SIGAR_FIELD_NOTIMPL; if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } free(entries); return SIGAR_OK; } static int net_conn_get_udp(sigar_net_connection_walker_t *walker) { int status = SIGAR_OK; if (walker->flags & SIGAR_NETCONN_SERVER) { status = net_conn_get_udp_listen(walker); } return status; } #define IS_TCP_SERVER(state, flags) \ ((flags & SIGAR_NETCONN_SERVER) && (state == TCLISTEN)) #define IS_TCP_CLIENT(state, flags) \ ((flags & SIGAR_NETCONN_CLIENT) && (state != TCLISTEN)) static int net_conn_get_tcp(sigar_net_connection_walker_t *walker) { sigar_t *sigar = walker->sigar; int flags = walker->flags; int status, count, i; unsigned int len; mib_tcpConnEnt *entries; struct nmparms parms; len = sizeof(count); parms.objid = ID_tcpConnNumEnt; parms.buffer = &count; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { return status; } if (count <= 0) { return ENOENT; } len = count * sizeof(*entries); entries = malloc(len); parms.objid = ID_tcpConnTable; parms.buffer = entries; parms.len = &len; if ((status = sigar_get_mib_info(sigar, &parms)) != SIGAR_OK) { free(entries); return status; } for (i=0; iState; if (!(IS_TCP_SERVER(state, flags) || IS_TCP_CLIENT(state, flags))) { continue; } SIGAR_ZERO(&conn); switch (state) { case TCCLOSED: conn.state = SIGAR_TCP_CLOSE; break; case TCLISTEN: conn.state = SIGAR_TCP_LISTEN; break; case TCSYNSENT: conn.state = SIGAR_TCP_SYN_SENT; break; case TCSYNRECEIVE: conn.state = SIGAR_TCP_SYN_RECV; break; case TCESTABLISED: conn.state = SIGAR_TCP_ESTABLISHED; break; case TCFINWAIT1: conn.state = SIGAR_TCP_FIN_WAIT1; break; case TCFINWAIT2: conn.state = SIGAR_TCP_FIN_WAIT2; break; case TCCLOSEWAIT: conn.state = SIGAR_TCP_CLOSE_WAIT; break; case TCCLOSING: conn.state = SIGAR_TCP_CLOSING; break; case TCLASTACK: conn.state = SIGAR_TCP_LAST_ACK; break; case TCTIMEWAIT: conn.state = SIGAR_TCP_TIME_WAIT; break; case TCDELETETCB: default: conn.state = SIGAR_TCP_UNKNOWN; break; } conn.local_port = (unsigned short)entry->LocalPort; conn.remote_port = (unsigned short)entry->RemPort; conn.type = SIGAR_NETCONN_TCP; sigar_net_address_set(conn.local_address, entry->LocalAddress); sigar_net_address_set(conn.remote_address, entry->RemAddress); conn.send_queue = conn.receive_queue = SIGAR_FIELD_NOTIMPL; if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } free(entries); return SIGAR_OK; } int sigar_net_connection_walk(sigar_net_connection_walker_t *walker) { int status; if (walker->flags & SIGAR_NETCONN_TCP) { status = net_conn_get_tcp(walker); if (status != SIGAR_OK) { return status; } } if (walker->flags & SIGAR_NETCONN_UDP) { status = net_conn_get_udp(walker); if (status != SIGAR_OK) { return status; } } return SIGAR_OK; } #define tcpsoff(x) sigar_offsetof(sigar_tcp_t, x) static struct { unsigned int id; size_t offset; } tcps_lu[] = { #if 0 { ID_tcpRtoAlgorithm, tcpsoff(xxx) }, { ID_tcpRtoMin, tcpsoff(xxx) }, { ID_tcpRtoMax, tcpsoff(xxx) }, { ID_tcpMaxConn, tcpsoff(max_conn) }, #endif { ID_tcpActiveOpens, tcpsoff(active_opens) }, { ID_tcpPassiveOpens, tcpsoff(passive_opens) }, { ID_tcpAttemptFails, tcpsoff(attempt_fails) }, { ID_tcpEstabResets, tcpsoff(estab_resets) }, { ID_tcpCurrEstab, tcpsoff(curr_estab) }, { ID_tcpInSegs, tcpsoff(in_segs) }, { ID_tcpOutSegs, tcpsoff(out_segs) }, { ID_tcpRetransSegs, tcpsoff(retrans_segs) }, { ID_tcpInErrs, tcpsoff(in_errs) }, { ID_tcpOutRsts, tcpsoff(out_rsts) } }; SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp) { int i; for (i=0; iarch, arch); SIGAR_SSTRCPY(sysinfo->name, "HPUX"); SIGAR_SSTRCPY(sysinfo->vendor, "Hewlett-Packard"); if (strstr(sysinfo->version, ".11.")) { vendor_version = "11"; } else { vendor_version = sysinfo->version; } SIGAR_SSTRCPY(sysinfo->vendor_version, vendor_version); snprintf(sysinfo->description, sizeof(sysinfo->description), "%s %s", sysinfo->vendor_name, sysinfo->vendor_version); return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/os/hpux/sigar_os.h000066400000000000000000000021361210132627500213630ustar00rootroot00000000000000/* * Copyright (c) 2004-2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #if defined(__ia64) && !defined(__ia64__) #define __ia64__ #endif #ifdef __ia64__ #ifndef _LP64 #define _LP64 #endif #endif #define _PSTAT64 #include #include #include #include struct sigar_t { SIGAR_T_BASE; struct pst_static pstatic; time_t last_getprocs; sigar_pid_t last_pid; struct pst_status *pinfo; int mib; }; int hpux_get_mib_ifentry(int ppa, mib_ifEntry *mib); #endif /* SIGAR_OS_H */ hyperic-sigar-1.6.4+dfsg/src/os/linux/000077500000000000000000000000001210132627500175555ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/linux/linux_sigar.c000066400000000000000000002035231210132627500222520ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 #include #include #include #include #include #include #include #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #define pageshift(x) ((x) << sigar->pagesize) #define PROC_MEMINFO PROC_FS_ROOT "meminfo" #define PROC_VMSTAT PROC_FS_ROOT "vmstat" #define PROC_MTRR PROC_FS_ROOT "mtrr" #define PROC_STAT PROC_FS_ROOT "stat" #define PROC_UPTIME PROC_FS_ROOT "uptime" #define PROC_LOADAVG PROC_FS_ROOT "loadavg" #define PROC_PSTAT "/stat" #define PROC_PSTATUS "/status" #define SYS_BLOCK "/sys/block" #define PROC_PARTITIONS PROC_FS_ROOT "partitions" #define PROC_DISKSTATS PROC_FS_ROOT "diskstats" /* * /proc/self/stat fields: * 1 - pid * 2 - comm * 3 - state * 4 - ppid * 5 - pgrp * 6 - session * 7 - tty_nr * 8 - tpgid * 9 - flags * 10 - minflt * 11 - cminflt * 12 - majflt * 13 - cmajflt * 14 - utime * 15 - stime * 16 - cutime * 17 - cstime * 18 - priority * 19 - nice * 20 - 0 (removed field) * 21 - itrealvalue * 22 - starttime * 23 - vsize * 24 - rss * 25 - rlim * 26 - startcode * 27 - endcode * 28 - startstack * 29 - kstkesp * 30 - kstkeip * 31 - signal * 32 - blocked * 33 - sigignore * 34 - sigcache * 35 - wchan * 36 - nswap * 37 - cnswap * 38 - exit_signal <-- looking for this. * 39 - processor * ... more for newer RH */ #define PROC_SIGNAL_IX 38 static int get_proc_signal_offset(void) { char buffer[BUFSIZ], *ptr=buffer; int fields = 0; int status = sigar_file2str(PROCP_FS_ROOT "self/stat", buffer, sizeof(buffer)); if (status != SIGAR_OK) { return 1; } while (*ptr) { if (*ptr++ == ' ') { fields++; } } return (fields - PROC_SIGNAL_IX) + 1; } sigar_pid_t sigar_pid_get(sigar_t *sigar) { /* XXX cannot safely cache getpid unless using nptl */ /* we can however, cache it for optimizations in the * case of proc_env_get for example. */ sigar->pid = getpid(); return sigar->pid; } static int sigar_boot_time_get(sigar_t *sigar) { FILE *fp; char buffer[BUFSIZ], *ptr; int found = 0; if (!(fp = fopen(PROC_STAT, "r"))) { return errno; } while ((ptr = fgets(buffer, sizeof(buffer), fp))) { if (strnEQ(ptr, "btime", 5)) { if ((ptr = sigar_skip_token(ptr))) { sigar->boot_time = sigar_strtoul(ptr); found = 1; } break; } } fclose(fp); if (!found) { /* should never happen */ sigar->boot_time = time(NULL); } return SIGAR_OK; } int sigar_os_open(sigar_t **sigar) { int i, status; int kernel_rev, has_nptl; struct stat sb; struct utsname name; *sigar = malloc(sizeof(**sigar)); (*sigar)->pagesize = 0; i = getpagesize(); while ((i >>= 1) > 0) { (*sigar)->pagesize++; } status = sigar_boot_time_get(*sigar); if (status != SIGAR_OK) { return status; } (*sigar)->ticks = sysconf(_SC_CLK_TCK); (*sigar)->ram = -1; (*sigar)->proc_signal_offset = -1; (*sigar)->last_proc_stat.pid = -1; (*sigar)->lcpu = -1; if (stat(PROC_DISKSTATS, &sb) == 0) { (*sigar)->iostat = IOSTAT_DISKSTATS; } else if (stat(SYS_BLOCK, &sb) == 0) { (*sigar)->iostat = IOSTAT_SYS; } else if (stat(PROC_PARTITIONS, &sb) == 0) { /* XXX file exists does not mean is has the fields */ (*sigar)->iostat = IOSTAT_PARTITIONS; } else { (*sigar)->iostat = IOSTAT_NONE; } /* hook for using mirrored /proc/net/tcp file */ (*sigar)->proc_net = getenv("SIGAR_PROC_NET"); uname(&name); /* 2.X.y.z -> just need X (unless there is ever a kernel version 3!) */ kernel_rev = atoi(&name.release[2]); if (kernel_rev >= 6) { has_nptl = 1; } else { has_nptl = getenv("SIGAR_HAS_NPTL") ? 1 : 0; } (*sigar)->has_nptl = has_nptl; return SIGAR_OK; } int sigar_os_close(sigar_t *sigar) { free(sigar); return SIGAR_OK; } char *sigar_os_error_string(sigar_t *sigar, int err) { return NULL; } static int sigar_cpu_total_count(sigar_t *sigar) { sigar->ncpu = (int)sysconf(_SC_NPROCESSORS_CONF); sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu] ncpu=%d\n", sigar->ncpu); return sigar->ncpu; } static int get_ram(sigar_t *sigar, sigar_mem_t *mem) { char buffer[BUFSIZ], *ptr; FILE *fp; int total = 0; sigar_uint64_t sys_total = (mem->total / (1024 * 1024)); if (sigar->ram > 0) { /* return cached value */ mem->ram = sigar->ram; return SIGAR_OK; } if (sigar->ram == 0) { return ENOENT; } /* * Memory Type Range Registers * write-back registers add up to the total. * Well, they are supposed to add up, but seen * at least one configuration where that is not the * case. */ if (!(fp = fopen(PROC_MTRR, "r"))) { return errno; } while ((ptr = fgets(buffer, sizeof(buffer), fp))) { if (!(ptr = strstr(ptr, "size="))) { continue; } if (!strstr(ptr, "write-back")) { continue; } ptr += 5; while (sigar_isspace(*ptr)) { ++ptr; } total += atoi(ptr); } fclose(fp); if ((total - sys_total) > 256) { /* mtrr write-back registers are way off * kernel should not be using more that 256MB of mem */ total = 0; /* punt */ } if (total == 0) { return ENOENT; } mem->ram = sigar->ram = total; return SIGAR_OK; } #define MEMINFO_PARAM(a) a ":", SSTRLEN(a ":") static SIGAR_INLINE sigar_uint64_t sigar_meminfo(char *buffer, char *attr, int len) { sigar_uint64_t val = 0; char *ptr, *tok; if ((ptr = strstr(buffer, attr))) { ptr += len; val = strtoull(ptr, &tok, 0); while (*tok == ' ') { ++tok; } if (*tok == 'k') { val *= 1024; } else if (*tok == 'M') { val *= (1024 * 1024); } } return val; } int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem) { sigar_uint64_t buffers, cached, kern; char buffer[BUFSIZ]; int status = sigar_file2str(PROC_MEMINFO, buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } mem->total = sigar_meminfo(buffer, MEMINFO_PARAM("MemTotal")); mem->free = sigar_meminfo(buffer, MEMINFO_PARAM("MemFree")); mem->used = mem->total - mem->free; buffers = sigar_meminfo(buffer, MEMINFO_PARAM("Buffers")); cached = sigar_meminfo(buffer, MEMINFO_PARAM("Cached")); kern = buffers + cached; mem->actual_free = mem->free + kern; mem->actual_used = mem->used - kern; sigar_mem_calc_ram(sigar, mem); if (get_ram(sigar, mem) != SIGAR_OK) { /* XXX other options on failure? */ } return SIGAR_OK; } int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) { char buffer[BUFSIZ], *ptr; /* XXX: we open/parse the same file here as sigar_mem_get */ int status = sigar_file2str(PROC_MEMINFO, buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } swap->total = sigar_meminfo(buffer, MEMINFO_PARAM("SwapTotal")); swap->free = sigar_meminfo(buffer, MEMINFO_PARAM("SwapFree")); swap->used = swap->total - swap->free; swap->page_in = swap->page_out = -1; status = sigar_file2str(PROC_VMSTAT, buffer, sizeof(buffer)); if (status == SIGAR_OK) { /* 2.6+ kernel */ if ((ptr = strstr(buffer, "\npswpin"))) { ptr = sigar_skip_token(ptr); swap->page_in = sigar_strtoull(ptr); ptr = sigar_skip_token(ptr); swap->page_out = sigar_strtoull(ptr); } } else { /* 2.2, 2.4 kernels */ status = sigar_file2str(PROC_STAT, buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } if ((ptr = strstr(buffer, "\nswap"))) { ptr = sigar_skip_token(ptr); swap->page_in = sigar_strtoull(ptr); swap->page_out = sigar_strtoull(ptr); } } return SIGAR_OK; } static void get_cpu_metrics(sigar_t *sigar, sigar_cpu_t *cpu, char *line) { char *ptr = sigar_skip_token(line); /* "cpu%d" */ cpu->user += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); cpu->nice += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); cpu->sys += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); cpu->idle += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); if (*ptr == ' ') { /* 2.6+ kernels only */ cpu->wait += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); cpu->irq += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); cpu->soft_irq += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); } if (*ptr == ' ') { /* 2.6.11+ kernels only */ cpu->stolen += SIGAR_TICK2MSEC(sigar_strtoull(ptr)); } cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle + cpu->wait + cpu->irq + cpu->soft_irq + cpu->stolen; } int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu) { char buffer[BUFSIZ]; int status = sigar_file2str(PROC_STAT, buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } SIGAR_ZERO(cpu); get_cpu_metrics(sigar, cpu, buffer); return SIGAR_OK; } int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { FILE *fp; char buffer[BUFSIZ], cpu_total[BUFSIZ], *ptr; int core_rollup = sigar_cpu_core_rollup(sigar), i=0; sigar_cpu_t *cpu; if (!(fp = fopen(PROC_STAT, "r"))) { return errno; } /* skip first line */ (void)fgets(cpu_total, sizeof(cpu_total), fp); sigar_cpu_list_create(cpulist); /* XXX: merge times of logical processors if hyperthreading */ while ((ptr = fgets(buffer, sizeof(buffer), fp))) { if (!strnEQ(ptr, "cpu", 3)) { break; } if (core_rollup && (i % sigar->lcpu)) { /* merge times of logical processors */ cpu = &cpulist->data[cpulist->number-1]; } else { SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; SIGAR_ZERO(cpu); } get_cpu_metrics(sigar, cpu, ptr); i++; } fclose(fp); if (cpulist->number == 0) { /* likely older kernel where cpu\d is not present */ cpu = &cpulist->data[cpulist->number++]; SIGAR_ZERO(cpu); get_cpu_metrics(sigar, cpu, cpu_total); } return SIGAR_OK; } int sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime) { char buffer[BUFSIZ], *ptr = buffer; int status = sigar_file2str(PROC_UPTIME, buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } uptime->uptime = strtod(buffer, &ptr); return SIGAR_OK; } int sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg) { char buffer[BUFSIZ], *ptr = buffer; int status = sigar_file2str(PROC_LOADAVG, buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } loadavg->loadavg[0] = strtod(buffer, &ptr); loadavg->loadavg[1] = strtod(ptr, &ptr); loadavg->loadavg[2] = strtod(ptr, &ptr); return SIGAR_OK; } /* * seems the easiest/fastest way to tell if a process listed in /proc * is a thread is to check the "exit signal" flag in /proc/num/stat. * any value other than SIGCHLD seems to be a thread. this make hulk mad. * redhat's procps patch (named "threadbadhack.pat") does not use * this flag to filter out threads. instead does much more expensive * comparisions. their patch also bubbles up thread cpu times to the main * process. functionality we currently lack. * when nptl is in use, this is not the case and all threads spawned from * a process have the same pid. however, it seems both old-style linux * threads and nptl threads can be run on the same machine. * there is also the "Tgid" field in /proc/self/status which could be used * to detect threads, but this is not available in older kernels. */ static SIGAR_INLINE int proc_isthread(sigar_t *sigar, char *pidstr, int len) { char buffer[BUFSIZ], *ptr=buffer; int fd, n, offset=sigar->proc_signal_offset; /* sprintf(buffer, "/proc/%s/stat", pidstr) */ memcpy(ptr, PROCP_FS_ROOT, SSTRLEN(PROCP_FS_ROOT)); ptr += SSTRLEN(PROCP_FS_ROOT); memcpy(ptr, pidstr, len); ptr += len; memcpy(ptr, PROC_PSTAT, SSTRLEN(PROC_PSTAT)); ptr += SSTRLEN(PROC_PSTAT); *ptr = '\0'; if ((fd = open(buffer, O_RDONLY)) < 0) { /* unlikely if pid was from readdir proc */ return 0; } n = read(fd, buffer, sizeof(buffer)); close(fd); if (n < 0) { return 0; /* chances: slim..none */ } buffer[n--] = '\0'; /* exit_signal is the second to last field so we look backwards. * XXX if newer kernels drop more turds in this file we'll need * to go the other way. luckily linux has no real api for this shit. */ /* skip trailing crap */ while ((n > 0) && !isdigit(buffer[n--])) ; while (offset-- > 0) { /* skip last field */ while ((n > 0) && isdigit(buffer[n--])) ; /* skip whitespace */ while ((n > 0) && !isdigit(buffer[n--])) ; } if (n < 3) { return 0; /* hulk smashed /proc? */ } ptr = &buffer[n]; /* * '17' == SIGCHLD == real process. * '33' and '0' are threads */ if ((*ptr++ == '1') && (*ptr++ == '7') && (*ptr++ == ' ')) { return 0; } return 1; } int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { DIR *dirp = opendir(PROCP_FS_ROOT); struct dirent *ent, dbuf; register const int threadbadhack = !sigar->has_nptl; if (!dirp) { return errno; } if (threadbadhack && (sigar->proc_signal_offset == -1)) { sigar->proc_signal_offset = get_proc_signal_offset(); } while (readdir_r(dirp, &dbuf, &ent) == 0) { if (!ent) { break; } if (!sigar_isdigit(*ent->d_name)) { continue; } if (threadbadhack && proc_isthread(sigar, ent->d_name, strlen(ent->d_name))) { continue; } /* XXX: more sanity checking */ SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = strtoul(ent->d_name, NULL, 10); } closedir(dirp); return SIGAR_OK; } static int proc_stat_read(sigar_t *sigar, sigar_pid_t pid) { char buffer[BUFSIZ], *ptr=buffer, *tmp; unsigned int len; linux_proc_stat_t *pstat = &sigar->last_proc_stat; int status; time_t timenow = time(NULL); /* * short-lived cache read/parse of last /proc/pid/stat * as this info is spread out across a few functions. */ if (pstat->pid == pid) { if ((timenow - pstat->mtime) < SIGAR_LAST_PROC_EXPIRE) { return SIGAR_OK; } } pstat->pid = pid; pstat->mtime = timenow; status = SIGAR_PROC_FILE2STR(buffer, pid, PROC_PSTAT); if (status != SIGAR_OK) { return status; } if (!(ptr = strchr(ptr, '('))) { return EINVAL; } if (!(tmp = strrchr(++ptr, ')'))) { return EINVAL; } len = tmp-ptr; if (len >= sizeof(pstat->name)) { len = sizeof(pstat->name)-1; } /* (1,2) */ memcpy(pstat->name, ptr, len); pstat->name[len] = '\0'; ptr = tmp+1; SIGAR_SKIP_SPACE(ptr); pstat->state = *ptr++; /* (3) */ SIGAR_SKIP_SPACE(ptr); pstat->ppid = sigar_strtoul(ptr); /* (4) */ ptr = sigar_skip_token(ptr); /* (5) pgrp */ ptr = sigar_skip_token(ptr); /* (6) session */ pstat->tty = sigar_strtoul(ptr); /* (7) */ ptr = sigar_skip_token(ptr); /* (8) tty pgrp */ ptr = sigar_skip_token(ptr); /* (9) flags */ pstat->minor_faults = sigar_strtoull(ptr); /* (10) */ ptr = sigar_skip_token(ptr); /* (11) cmin flt */ pstat->major_faults = sigar_strtoull(ptr); /* (12) */ ptr = sigar_skip_token(ptr); /* (13) cmaj flt */ pstat->utime = SIGAR_TICK2MSEC(sigar_strtoull(ptr)); /* (14) */ pstat->stime = SIGAR_TICK2MSEC(sigar_strtoull(ptr)); /* (15) */ ptr = sigar_skip_token(ptr); /* (16) cutime */ ptr = sigar_skip_token(ptr); /* (17) cstime */ pstat->priority = sigar_strtoul(ptr); /* (18) */ pstat->nice = sigar_strtoul(ptr); /* (19) */ ptr = sigar_skip_token(ptr); /* (20) timeout */ ptr = sigar_skip_token(ptr); /* (21) it_real_value */ pstat->start_time = sigar_strtoul(ptr); /* (22) */ pstat->start_time /= sigar->ticks; pstat->start_time += sigar->boot_time; /* seconds */ pstat->start_time *= 1000; /* milliseconds */ pstat->vsize = sigar_strtoull(ptr); /* (23) */ pstat->rss = pageshift(sigar_strtoull(ptr)); /* (24) */ ptr = sigar_skip_token(ptr); /* (25) rlim */ ptr = sigar_skip_token(ptr); /* (26) startcode */ ptr = sigar_skip_token(ptr); /* (27) endcode */ ptr = sigar_skip_token(ptr); /* (28) startstack */ ptr = sigar_skip_token(ptr); /* (29) kstkesp */ ptr = sigar_skip_token(ptr); /* (30) kstkeip */ ptr = sigar_skip_token(ptr); /* (31) signal */ ptr = sigar_skip_token(ptr); /* (32) blocked */ ptr = sigar_skip_token(ptr); /* (33) sigignore */ ptr = sigar_skip_token(ptr); /* (34) sigcache */ ptr = sigar_skip_token(ptr); /* (35) wchan */ ptr = sigar_skip_token(ptr); /* (36) nswap */ ptr = sigar_skip_token(ptr); /* (37) cnswap */ ptr = sigar_skip_token(ptr); /* (38) exit_signal */ pstat->processor = sigar_strtoul(ptr); /* (39) */ return SIGAR_OK; } int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem) { char buffer[BUFSIZ], *ptr=buffer; int status = proc_stat_read(sigar, pid); linux_proc_stat_t *pstat = &sigar->last_proc_stat; procmem->minor_faults = pstat->minor_faults; procmem->major_faults = pstat->major_faults; procmem->page_faults = procmem->minor_faults + procmem->major_faults; status = SIGAR_PROC_FILE2STR(buffer, pid, "/statm"); if (status != SIGAR_OK) { return status; } procmem->size = pageshift(sigar_strtoull(ptr)); procmem->resident = pageshift(sigar_strtoull(ptr)); procmem->share = pageshift(sigar_strtoull(ptr)); return SIGAR_OK; } #define NO_ID_MSG "[proc_cred] /proc/%lu" PROC_PSTATUS " missing " int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred) { char buffer[BUFSIZ], *ptr; int status = SIGAR_PROC_FILE2STR(buffer, pid, PROC_PSTATUS); if (status != SIGAR_OK) { return status; } if ((ptr = strstr(buffer, "\nUid:"))) { ptr = sigar_skip_token(ptr); proccred->uid = sigar_strtoul(ptr); proccred->euid = sigar_strtoul(ptr); } else { sigar_log_printf(sigar, SIGAR_LOG_WARN, NO_ID_MSG "Uid", pid); return ENOENT; } if ((ptr = strstr(ptr, "\nGid:"))) { ptr = sigar_skip_token(ptr); proccred->gid = sigar_strtoul(ptr); proccred->egid = sigar_strtoul(ptr); } else { sigar_log_printf(sigar, SIGAR_LOG_WARN, NO_ID_MSG "Gid", pid); return ENOENT; } return SIGAR_OK; } int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime) { int status = proc_stat_read(sigar, pid); linux_proc_stat_t *pstat = &sigar->last_proc_stat; if (status != SIGAR_OK) { return status; } proctime->user = pstat->utime; proctime->sys = pstat->stime; proctime->total = proctime->user + proctime->sys; proctime->start_time = pstat->start_time; return SIGAR_OK; } static int proc_status_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { char buffer[BUFSIZ], *ptr; int status = SIGAR_PROC_FILE2STR(buffer, pid, PROC_PSTATUS); if (status != SIGAR_OK) { return status; } ptr = strstr(buffer, "\nThreads:"); if (ptr) { /* 2.6+ kernel only */ ptr = sigar_skip_token(ptr); procstate->threads = sigar_strtoul(ptr); } else { procstate->threads = SIGAR_FIELD_NOTIMPL; } return SIGAR_OK; } int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { int status = proc_stat_read(sigar, pid); linux_proc_stat_t *pstat = &sigar->last_proc_stat; if (status != SIGAR_OK) { return status; } memcpy(procstate->name, pstat->name, sizeof(procstate->name)); procstate->state = pstat->state; procstate->ppid = pstat->ppid; procstate->tty = pstat->tty; procstate->priority = pstat->priority; procstate->nice = pstat->nice; procstate->processor = pstat->processor; if (sigar_cpu_core_rollup(sigar)) { procstate->processor /= sigar->lcpu; } proc_status_get(sigar, pid, procstate); return SIGAR_OK; } int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { return sigar_procfs_args_get(sigar, pid, procargs); } /* glibc 2.8 XXX use sysconf(_SC_ARG_MAX) */ #ifndef ARG_MAX #define ARG_MAX 131072 #endif int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { int fd; char buffer[ARG_MAX]; /* XXX: ARG_MAX == 130k */ char name[BUFSIZ]; size_t len; char *ptr, *end; /* optimize if pid == $$ and type == ENV_KEY */ SIGAR_PROC_ENV_KEY_LOOKUP(); (void)SIGAR_PROC_FILENAME(name, pid, "/environ"); if ((fd = open(name, O_RDONLY)) < 0) { if (errno == ENOENT) { return ESRCH; } return errno; } len = read(fd, buffer, sizeof(buffer)); close(fd); buffer[len] = '\0'; ptr = buffer; end = buffer + len; while (ptr < end) { char *val = strchr(ptr, '='); int klen, vlen, status; char key[128]; /* XXX is there a max key size? */ if (val == NULL) { /* not key=val format */ break; } klen = val - ptr; SIGAR_SSTRCPY(key, ptr); key[klen] = '\0'; ++val; vlen = strlen(val); status = procenv->env_getter(procenv->data, key, klen, val, vlen); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } ptr += (klen + 1 + vlen + 1); } return SIGAR_OK; } int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd) { int status = sigar_proc_fd_count(sigar, pid, &procfd->total); return status; } int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { int len; char name[BUFSIZ]; (void)SIGAR_PROC_FILENAME(name, pid, "/cwd"); if ((len = readlink(name, procexe->cwd, sizeof(procexe->cwd)-1)) < 0) { return errno; } procexe->cwd[len] = '\0'; (void)SIGAR_PROC_FILENAME(name, pid, "/exe"); if ((len = readlink(name, procexe->name, sizeof(procexe->name)-1)) < 0) { return errno; } procexe->name[len] = '\0'; (void)SIGAR_PROC_FILENAME(name, pid, "/root"); if ((len = readlink(name, procexe->root, sizeof(procexe->root)-1)) < 0) { return errno; } procexe->root[len] = '\0'; return SIGAR_OK; } int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { FILE *fp; char buffer[BUFSIZ], *ptr; unsigned long inode, last_inode = 0; (void)SIGAR_PROC_FILENAME(buffer, pid, "/maps"); if (!(fp = fopen(buffer, "r"))) { return errno; } while ((ptr = fgets(buffer, sizeof(buffer), fp))) { int len, status; /* skip region, flags, offset, dev */ ptr = sigar_skip_multiple_token(ptr, 4); inode = sigar_strtoul(ptr); if ((inode == 0) || (inode == last_inode)) { last_inode = 0; continue; } last_inode = inode; SIGAR_SKIP_SPACE(ptr); len = strlen(ptr); ptr[len-1] = '\0'; /* chop \n */ status = procmods->module_getter(procmods->data, ptr, len-1); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } } fclose(fp); return SIGAR_OK; } int sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu) { struct tms now; if (id != 0) { return SIGAR_ENOTIMPL; } times(&now); cpu->user = SIGAR_TICK2NSEC(now.tms_utime); cpu->sys = SIGAR_TICK2NSEC(now.tms_stime); cpu->total = SIGAR_TICK2NSEC(now.tms_utime + now.tms_stime); return SIGAR_OK; } #include int sigar_os_fs_type_get(sigar_file_system_t *fsp) { char *type = fsp->sys_type_name; switch (*type) { case 'e': if (strnEQ(type, "ext", 3)) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'g': if (strEQ(type, "gfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'h': if (strEQ(type, "hpfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'j': if (strnEQ(type, "jfs", 3)) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'o': if (strnEQ(type, "ocfs", 4)) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'p': if (strnEQ(type, "psfs", 4)) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'r': if (strEQ(type, "reiserfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'v': if (strEQ(type, "vzfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'x': if (strEQ(type, "xfs") || strEQ(type, "xiafs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; } return fsp->type; } int sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist) { struct mntent ent; char buf[1025]; /* buffer for strings within ent */ FILE *fp; sigar_file_system_t *fsp; if (!(fp = setmntent(MOUNTED, "r"))) { return errno; } sigar_file_system_list_create(fslist); while (getmntent_r(fp, &ent, buf, sizeof(buf))) { SIGAR_FILE_SYSTEM_LIST_GROW(fslist); fsp = &fslist->data[fslist->number++]; fsp->type = SIGAR_FSTYPE_UNKNOWN; /* unknown, will be set later */ SIGAR_SSTRCPY(fsp->dir_name, ent.mnt_dir); SIGAR_SSTRCPY(fsp->dev_name, ent.mnt_fsname); SIGAR_SSTRCPY(fsp->sys_type_name, ent.mnt_type); SIGAR_SSTRCPY(fsp->options, ent.mnt_opts); sigar_fs_type_get(fsp); } endmntent(fp); return SIGAR_OK; } #define ST_MAJOR(sb) major((sb).st_rdev) #define ST_MINOR(sb) minor((sb).st_rdev) static int get_iostat_sys(sigar_t *sigar, const char *dirname, sigar_disk_usage_t *disk, sigar_iodev_t **iodev) { char stat[1025], dev[1025]; char *name, *ptr, *fsdev; int partition, status; if (!(*iodev = sigar_iodev_get(sigar, dirname))) { return ENXIO; } name = fsdev = (*iodev)->name; if (SIGAR_NAME_IS_DEV(name)) { name += SSTRLEN(SIGAR_DEV_PREFIX); /* strip "/dev/" */ } while (!sigar_isdigit(*fsdev)) { fsdev++; } partition = strtoul(fsdev, NULL, 0); *fsdev = '\0'; snprintf(stat, sizeof(stat), SYS_BLOCK "/%s/%s%d/stat", name, name, partition); status = sigar_file2str(stat, dev, sizeof(dev)); if (status != SIGAR_OK) { return status; } ptr = dev; ptr = sigar_skip_token(ptr); disk->reads = sigar_strtoull(ptr); ptr = sigar_skip_token(ptr); disk->writes = sigar_strtoull(ptr); disk->read_bytes = SIGAR_FIELD_NOTIMPL; disk->write_bytes = SIGAR_FIELD_NOTIMPL; disk->queue = SIGAR_FIELD_NOTIMPL; return SIGAR_OK; } static int get_iostat_proc_dstat(sigar_t *sigar, const char *dirname, sigar_disk_usage_t *disk, sigar_iodev_t **iodev, sigar_disk_usage_t *device_usage) { FILE *fp; char buffer[1025]; char *ptr; struct stat sb; int status=ENOENT; SIGAR_DISK_STATS_INIT(device_usage); if (!(*iodev = sigar_iodev_get(sigar, dirname))) { return ENXIO; } if (stat((*iodev)->name, &sb) < 0) { return errno; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, PROC_DISKSTATS " %s -> %s [%d,%d]", dirname, (*iodev)->name, ST_MAJOR(sb), ST_MINOR(sb)); } if (!(fp = fopen(PROC_DISKSTATS, "r"))) { return errno; } while ((ptr = fgets(buffer, sizeof(buffer), fp))) { unsigned long major, minor; major = sigar_strtoul(ptr); minor = sigar_strtoul(ptr); if ((major == ST_MAJOR(sb)) && ((minor == ST_MINOR(sb)) || (minor == 0))) { int num; unsigned long rio, rmerge, rsect, ruse, wio, wmerge, wsect, wuse, running, use, aveq; ptr = sigar_skip_token(ptr); /* name */ num = sscanf(ptr, "%lu %lu %lu %lu " "%lu %lu %lu %lu " "%lu %lu %lu", &rio, /* 1 # reads issued */ &rmerge, /* 2 # reads merged */ &rsect, /* 3 # sectors read */ &ruse, /* 4 # millis spent reading */ &wio, /* 5 # writes completed */ &wmerge, /* 6 # writes merged */ &wsect, /* 7 # sectors written */ &wuse, /* 8 # millis spent writing */ &running, /* 9 # I/Os currently in progress */ &use, /* 10 # millis spent doing I/Os */ &aveq); /* 11 # of millis spent doing I/Os (weighted) */ if (num == 11) { disk->rtime = ruse; disk->wtime = wuse; disk->time = use; disk->qtime = aveq; } else if (num == 4) { wio = rsect; rsect = rmerge; wsect = ruse; disk->time = disk->qtime = SIGAR_FIELD_NOTIMPL; } else { status = ENOENT; } disk->reads = rio; disk->writes = wio; disk->read_bytes = rsect; disk->write_bytes = wsect; /* convert sectors to bytes (512 is fixed size in 2.6 kernels) */ disk->read_bytes *= 512; disk->write_bytes *= 512; if (minor == ST_MINOR(sb)) { status = SIGAR_OK; break; } else if (minor == 0) { memcpy(device_usage, disk, sizeof(*device_usage)); } } } fclose(fp); return status; } static int get_iostat_procp(sigar_t *sigar, const char *dirname, sigar_disk_usage_t *disk, sigar_iodev_t **iodev) { FILE *fp; char buffer[1025]; char *ptr; struct stat sb; if (!(*iodev = sigar_iodev_get(sigar, dirname))) { return ENXIO; } if (stat((*iodev)->name, &sb) < 0) { return errno; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, PROC_PARTITIONS " %s -> %s [%d,%d]", dirname, (*iodev)->name, ST_MAJOR(sb), ST_MINOR(sb)); } if (!(fp = fopen(PROC_PARTITIONS, "r"))) { return errno; } (void)fgets(buffer, sizeof(buffer), fp); /* skip header */ while ((ptr = fgets(buffer, sizeof(buffer), fp))) { unsigned long major, minor; major = sigar_strtoul(ptr); minor = sigar_strtoul(ptr); if ((major == ST_MAJOR(sb)) && (minor == ST_MINOR(sb))) { ptr = sigar_skip_token(ptr); /* blocks */ ptr = sigar_skip_token(ptr); /* name */ disk->reads = sigar_strtoull(ptr); /* rio */ ptr = sigar_skip_token(ptr); /* rmerge */ disk->read_bytes = sigar_strtoull(ptr); /* rsect */ disk->rtime = sigar_strtoull(ptr); /* ruse */ disk->writes = sigar_strtoull(ptr); /* wio */ ptr = sigar_skip_token(ptr); /* wmerge */ disk->write_bytes = sigar_strtoull(ptr); /* wsect */ disk->wtime = sigar_strtoull(ptr); /* wuse */ ptr = sigar_skip_token(ptr); /* running */ disk->time = sigar_strtoull(ptr); /* use */ disk->qtime = sigar_strtoull(ptr); /* aveq */ /* convert sectors to bytes (512 is fixed size in 2.6 kernels) */ disk->read_bytes *= 512; disk->write_bytes *= 512; fclose(fp); return SIGAR_OK; } } fclose(fp); return ENOENT; } int sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *disk) { int status; sigar_iodev_t *iodev = NULL; sigar_disk_usage_t device_usage; SIGAR_DISK_STATS_INIT(disk); /* * 2.2 has metrics /proc/stat, but wtf is the device mapping? * 2.4 has /proc/partitions w/ the metrics. * 2.6 has /proc/partitions w/o the metrics. * instead the metrics are within the /proc-like /sys filesystem. * also has /proc/diskstats */ switch (sigar->iostat) { case IOSTAT_SYS: status = get_iostat_sys(sigar, name, disk, &iodev); break; case IOSTAT_DISKSTATS: status = get_iostat_proc_dstat(sigar, name, disk, &iodev, &device_usage); break; case IOSTAT_PARTITIONS: status = get_iostat_procp(sigar, name, disk, &iodev); break; /* * case IOSTAT_SOME_OTHER_WIERD_THING: * break; */ case IOSTAT_NONE: default: status = ENOENT; break; } if ((status == SIGAR_OK) && iodev) { sigar_uptime_t uptime; sigar_uint64_t interval, ios; double tput, util; sigar_disk_usage_t *partition_usage=NULL; sigar_uptime_get(sigar, &uptime); if (iodev->is_partition && (sigar->iostat == IOSTAT_DISKSTATS)) { /* 2.6 kernels do not have per-partition times */ partition_usage = disk; disk = &device_usage; } disk->snaptime = uptime.uptime; if (iodev->disk.snaptime) { interval = disk->snaptime - iodev->disk.snaptime; } else { interval = disk->snaptime; } ios = (disk->reads - iodev->disk.reads) + (disk->writes - iodev->disk.writes); if (disk->time == SIGAR_FIELD_NOTIMPL) { disk->service_time = SIGAR_FIELD_NOTIMPL; } else { tput = ((double)ios) * HZ / interval; util = ((double)(disk->time - iodev->disk.time)) / interval * HZ; disk->service_time = tput ? util / tput : 0.0; } if (disk->qtime == SIGAR_FIELD_NOTIMPL) { disk->queue = SIGAR_FIELD_NOTIMPL; } else { util = ((double)(disk->qtime - iodev->disk.qtime)) / interval; disk->queue = util / 1000.0; } memcpy(&iodev->disk, disk, sizeof(iodev->disk)); if (partition_usage) { partition_usage->service_time = disk->service_time; partition_usage->queue = disk->queue; } } return status; } int sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { int status = sigar_statvfs(sigar, dirname, fsusage); if (status != SIGAR_OK) { return status; } fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage); (void)sigar_disk_usage_get(sigar, dirname, &fsusage->disk); return SIGAR_OK; } static SIGAR_INLINE char *cpu_info_strval(char *ptr) { if ((ptr = strchr(ptr, ':'))) { ptr++; while (isspace (*ptr)) ptr++; return ptr; } return NULL; } static SIGAR_INLINE void cpu_info_strcpy(char *ptr, char *buf, int len) { int slen; ptr = cpu_info_strval(ptr); if (!ptr) { return; } slen = strlen(ptr); strncpy(buf, ptr, len); buf[len] = '\0'; if (slen < len) { buf[slen-1] = '\0'; /* rid \n */ } } static int get_cpu_info(sigar_t *sigar, sigar_cpu_info_t *info, FILE *fp) { char buffer[BUFSIZ], *ptr; int found = 0; /* UML vm wont have "cpu MHz" or "cache size" fields */ info->mhz = 0; info->cache_size = 0; #ifdef __powerpc64__ SIGAR_SSTRCPY(info->vendor, "IBM"); #endif while ((ptr = fgets(buffer, sizeof(buffer), fp))) { switch (*ptr) { case 'p': /* processor : 0 */ if (strnEQ(ptr, "processor", 9)) { found = 1; } break; case 'v': /* "vendor_id" or "vendor" */ if (strnEQ(ptr, "vendor", 6)) { cpu_info_strcpy(ptr, info->vendor, sizeof(info->vendor)); if (strEQ(info->vendor, "GenuineIntel")) { SIGAR_SSTRCPY(info->vendor, "Intel"); } else if (strEQ(info->vendor, "AuthenticAMD")) { SIGAR_SSTRCPY(info->vendor, "AMD"); } } break; case 'f': if (strnEQ(ptr, "family", 6)) { /* IA64 version of "model name" */ cpu_info_strcpy(ptr, info->model, sizeof(info->model)); sigar_cpu_model_adjust(sigar, info); } break; case 'm': if (strnEQ(ptr, "model name", 10)) { cpu_info_strcpy(ptr, info->model, sizeof(info->model)); sigar_cpu_model_adjust(sigar, info); } break; case 'c': if (strnEQ(ptr, "cpu MHz", 7)) { ptr = cpu_info_strval(ptr); info->mhz = atoi(ptr); } else if (strnEQ(ptr, "cache size", 10)) { ptr = cpu_info_strval(ptr); info->cache_size = sigar_strtoul(ptr); } #ifdef __powerpc64__ /* each /proc/cpuinfo entry looks like so: * processor : 0 * cpu : POWER5 (gr) * clock : 1656.392000MHz * revision : 2.2 */ else if (strnEQ(ptr, "clock", 5)) { ptr = cpu_info_strval(ptr); info->mhz = atoi(ptr); } else if (strnEQ(ptr, "cpu", 3)) { cpu_info_strcpy(ptr, info->model, sizeof(info->model)); if ((ptr = strchr(info->model, ' '))) { /* "POWER5 (gr)" -> "POWER5" */ *ptr = '\0'; } } #endif break; /* lone \n means end of info for this processor */ case '\n': return found; } } return found; } /* /proc/cpuinfo MHz will change w/ AMD + PowerNow */ static void get_cpuinfo_max_freq(sigar_cpu_info_t *cpu_info, int num) { int status; char max_freq[PATH_MAX]; snprintf(max_freq, sizeof(max_freq), "/sys/devices/system/cpu/cpu%d" "/cpufreq/cpuinfo_max_freq", num); status = sigar_file2str(max_freq, max_freq, sizeof(max_freq)-1); if (status == SIGAR_OK) { cpu_info->mhz = atoi(max_freq) / 1000; } } int sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { FILE *fp; int core_rollup = sigar_cpu_core_rollup(sigar), i=0; if (!(fp = fopen(PROC_FS_ROOT "cpuinfo", "r"))) { return errno; } (void)sigar_cpu_total_count(sigar); sigar_cpu_info_list_create(cpu_infos); while (get_cpu_info(sigar, &cpu_infos->data[cpu_infos->number], fp)) { sigar_cpu_info_t *info; if (core_rollup && (i++ % sigar->lcpu)) { continue; /* fold logical processors */ } info = &cpu_infos->data[cpu_infos->number]; get_cpuinfo_max_freq(info, cpu_infos->number); info->total_cores = sigar->ncpu; info->cores_per_socket = sigar->lcpu; info->total_sockets = sigar_cpu_socket_count(sigar); ++cpu_infos->number; SIGAR_CPU_INFO_LIST_GROW(cpu_infos); } fclose(fp); return SIGAR_OK; } static SIGAR_INLINE unsigned int hex2int(const char *x, int len) { int i; unsigned int j; for (i=0, j=0; isize = routelist->number = 0; if (!(fp = fopen(PROC_FS_ROOT "net/route", "r"))) { return errno; } sigar_net_route_list_create(routelist); (void)fgets(buffer, sizeof(buffer), fp); /* skip header */ while (fgets(buffer, sizeof(buffer), fp)) { int num; SIGAR_NET_ROUTE_LIST_GROW(routelist); route = &routelist->data[routelist->number++]; /* XXX rid sscanf */ num = sscanf(buffer, ROUTE_FMT, route->ifname, net_addr, gate_addr, &flags, &route->refcnt, &route->use, &route->metric, mask_addr, &route->mtu, &route->window, &route->irtt); if ((num < 10) || !(flags & RTF_UP)) { --routelist->number; continue; } route->flags = flags; sigar_net_address_set(route->destination, hex2int(net_addr, HEX_ENT_LEN)); sigar_net_address_set(route->gateway, hex2int(gate_addr, HEX_ENT_LEN)); sigar_net_address_set(route->mask, hex2int(mask_addr, HEX_ENT_LEN)); } fclose(fp); return SIGAR_OK; } int sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { int found = 0; char buffer[BUFSIZ]; FILE *fp = fopen(PROC_FS_ROOT "net/dev", "r"); if (!fp) { return errno; } /* skip header */ fgets(buffer, sizeof(buffer), fp); fgets(buffer, sizeof(buffer), fp); while (fgets(buffer, sizeof(buffer), fp)) { char *ptr, *dev; dev = buffer; while (isspace(*dev)) { dev++; } if (!(ptr = strchr(dev, ':'))) { continue; } *ptr++ = 0; if (!strEQ(dev, name)) { continue; } found = 1; ifstat->rx_bytes = sigar_strtoull(ptr); ifstat->rx_packets = sigar_strtoull(ptr); ifstat->rx_errors = sigar_strtoull(ptr); ifstat->rx_dropped = sigar_strtoull(ptr); ifstat->rx_overruns = sigar_strtoull(ptr); ifstat->rx_frame = sigar_strtoull(ptr); /* skip: compressed multicast */ ptr = sigar_skip_multiple_token(ptr, 2); ifstat->tx_bytes = sigar_strtoull(ptr); ifstat->tx_packets = sigar_strtoull(ptr); ifstat->tx_errors = sigar_strtoull(ptr); ifstat->tx_dropped = sigar_strtoull(ptr); ifstat->tx_overruns = sigar_strtoull(ptr); ifstat->tx_collisions = sigar_strtoull(ptr); ifstat->tx_carrier = sigar_strtoull(ptr); ifstat->speed = SIGAR_FIELD_NOTIMPL; break; } fclose(fp); return found ? SIGAR_OK : ENXIO; } static SIGAR_INLINE void convert_hex_address(sigar_net_address_t *address, char *ptr, int len) { if (len > HEX_ENT_LEN) { int i; for (i=0; i<=3; i++, ptr+=HEX_ENT_LEN) { address->addr.in6[i] = hex2int(ptr, HEX_ENT_LEN); } address->family = SIGAR_AF_INET6; } else { address->addr.in = (len == HEX_ENT_LEN) ? hex2int(ptr, HEX_ENT_LEN) : 0; address->family = SIGAR_AF_INET; } } typedef struct { sigar_net_connection_list_t *connlist; sigar_net_connection_t *conn; unsigned long port; } net_conn_getter_t; static int proc_net_walker(sigar_net_connection_walker_t *walker, sigar_net_connection_t *conn) { net_conn_getter_t *getter = (net_conn_getter_t *)walker->data; if (getter->connlist) { SIGAR_NET_CONNLIST_GROW(getter->connlist); memcpy(&getter->connlist->data[getter->connlist->number++], conn, sizeof(*conn)); } else { if ((getter->port == conn->local_port) && (conn->remote_port == 0)) { memcpy(getter->conn, conn, sizeof(*conn)); return !SIGAR_OK; /* break loop */ } } return SIGAR_OK; /* continue loop */ } #define SKIP_WHILE(p, c) while (*p == c) p++ #define SKIP_PAST(p, c) \ while(*p && (*p != c)) p++; \ SKIP_WHILE(p, c) static int proc_net_read(sigar_net_connection_walker_t *walker, const char *fname, int type) { FILE *fp = NULL; char buffer[8192]; sigar_t *sigar = walker->sigar; char *ptr = sigar->proc_net; int flags = walker->flags; if (ptr) { snprintf(buffer, sizeof(buffer), "%s/%s", ptr, fname + sizeof(PROC_FS_ROOT)-1); if ((fp = fopen(buffer, "r"))) { if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[proc_net] using %s", buffer); } } else if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[proc_net] cannot open %s", buffer); } } if (!(fp || (fp = fopen(fname, "r")))) { return errno; } fgets(buffer, sizeof(buffer), fp); /* skip header */ while ((ptr = fgets(buffer, sizeof(buffer), fp))) { sigar_net_connection_t conn; char *laddr, *raddr; int laddr_len=0, raddr_len=0; int more; /* skip leading space */ SKIP_WHILE(ptr, ' '); /* skip "%d: " */ SKIP_PAST(ptr, ' '); laddr = ptr; while (*ptr && (*ptr != ':')) { laddr_len++; ptr++; } SKIP_WHILE(ptr, ':'); conn.local_port = (strtoul(ptr, &ptr, 16) & 0xffff); SKIP_WHILE(ptr, ' '); raddr = ptr; while (*ptr && (*ptr != ':')) { raddr_len++; ptr++; } SKIP_WHILE(ptr, ':'); conn.remote_port = (strtoul(ptr, &ptr, 16) & 0xffff); SKIP_WHILE(ptr, ' '); if (!((conn.remote_port && (flags & SIGAR_NETCONN_CLIENT)) || (!conn.remote_port && (flags & SIGAR_NETCONN_SERVER)))) { continue; } conn.type = type; convert_hex_address(&conn.local_address, laddr, laddr_len); convert_hex_address(&conn.remote_address, raddr, raddr_len); /* SIGAR_TCP_* currently matches TCP_* in linux/tcp.h */ conn.state = hex2int(ptr, 2); ptr += 2; SKIP_WHILE(ptr, ' '); conn.send_queue = hex2int(ptr, HEX_ENT_LEN); ptr += HEX_ENT_LEN+1; /* tx + ':' */; conn.receive_queue = hex2int(ptr, HEX_ENT_LEN); ptr += HEX_ENT_LEN; SKIP_WHILE(ptr, ' '); SKIP_PAST(ptr, ' '); /* tr:tm->whem */ SKIP_PAST(ptr, ' '); /* retrnsmt */ conn.uid = sigar_strtoul(ptr); SKIP_WHILE(ptr, ' '); SKIP_PAST(ptr, ' '); /* timeout */ conn.inode = sigar_strtoul(ptr); more = walker->add_connection(walker, &conn); if (more != SIGAR_OK) { fclose(fp); return SIGAR_OK; } } fclose(fp); return SIGAR_OK; } int sigar_net_connection_walk(sigar_net_connection_walker_t *walker) { int flags = walker->flags; int status; if (flags & SIGAR_NETCONN_TCP) { status = proc_net_read(walker, PROC_FS_ROOT "net/tcp", SIGAR_NETCONN_TCP); if (status != SIGAR_OK) { return status; } status = proc_net_read(walker, PROC_FS_ROOT "net/tcp6", SIGAR_NETCONN_TCP); if (!((status == SIGAR_OK) || (status == ENOENT))) { return status; } } if (flags & SIGAR_NETCONN_UDP) { status = proc_net_read(walker, PROC_FS_ROOT "net/udp", SIGAR_NETCONN_UDP); if (status != SIGAR_OK) { return status; } status = proc_net_read(walker, PROC_FS_ROOT "net/udp6", SIGAR_NETCONN_UDP); if (!((status == SIGAR_OK) || (status == ENOENT))) { return status; } } if (flags & SIGAR_NETCONN_RAW) { status = proc_net_read(walker, PROC_FS_ROOT "net/raw", SIGAR_NETCONN_RAW); if (status != SIGAR_OK) { return status; } status = proc_net_read(walker, PROC_FS_ROOT "net/raw6", SIGAR_NETCONN_RAW); if (!((status == SIGAR_OK) || (status == ENOENT))) { return status; } } /* XXX /proc/net/unix */ return SIGAR_OK; } int sigar_net_connection_list_get(sigar_t *sigar, sigar_net_connection_list_t *connlist, int flags) { int status; sigar_net_connection_walker_t walker; net_conn_getter_t getter; sigar_net_connection_list_create(connlist); getter.conn = NULL; getter.connlist = connlist; walker.sigar = sigar; walker.flags = flags; walker.data = &getter; walker.add_connection = proc_net_walker; status = sigar_net_connection_walk(&walker); if (status != SIGAR_OK) { sigar_net_connection_list_destroy(sigar, connlist); } return status; } static int sigar_net_connection_get(sigar_t *sigar, sigar_net_connection_t *netconn, unsigned long port, int flags) { int status; sigar_net_connection_walker_t walker; net_conn_getter_t getter; getter.conn = netconn; getter.connlist = NULL; getter.port = port; walker.sigar = sigar; walker.flags = flags; walker.data = &getter; walker.add_connection = proc_net_walker; status = sigar_net_connection_walk(&walker); return status; } #define SNMP_TCP_PREFIX "Tcp: " SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp) { FILE *fp; char buffer[1024], *ptr=buffer; int status = SIGAR_ENOENT; if (!(fp = fopen(PROC_FS_ROOT "net/snmp", "r"))) { return errno; } while (fgets(buffer, sizeof(buffer), fp)) { if (strnEQ(buffer, SNMP_TCP_PREFIX, sizeof(SNMP_TCP_PREFIX)-1)) { if (fgets(buffer, sizeof(buffer), fp)) { status = SIGAR_OK; break; } } } fclose(fp); if (status == SIGAR_OK) { /* assuming field order, same in 2.2, 2.4 and 2.6 kernels */ /* Tcp: RtoAlgorithm RtoMin RtoMax MaxConn */ ptr = sigar_skip_multiple_token(ptr, 5); tcp->active_opens = sigar_strtoull(ptr); tcp->passive_opens = sigar_strtoull(ptr); tcp->attempt_fails = sigar_strtoull(ptr); tcp->estab_resets = sigar_strtoull(ptr); tcp->curr_estab = sigar_strtoull(ptr); tcp->in_segs = sigar_strtoull(ptr); tcp->out_segs = sigar_strtoull(ptr); tcp->retrans_segs = sigar_strtoull(ptr); tcp->in_errs = sigar_strtoull(ptr); tcp->out_rsts = sigar_strtoull(ptr); } return status; } static int sigar_proc_nfs_gets(char *file, char *tok, char *buffer, size_t size) { int status = ENOENT; int len = strlen(tok); FILE *fp = fopen(file, "r"); if (!fp) { return SIGAR_ENOTIMPL; } while (fgets(buffer, size, fp)) { if (strnEQ(buffer, tok, len)) { status = SIGAR_OK; break; } } fclose(fp); return status; } static int sigar_nfs_v2_get(char *file, sigar_nfs_v2_t *nfs) { char buffer[BUFSIZ], *ptr=buffer; int status = sigar_proc_nfs_gets(file, "proc2", buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } ptr = sigar_skip_multiple_token(ptr, 2); nfs->null = sigar_strtoull(ptr); nfs->getattr = sigar_strtoull(ptr); nfs->setattr = sigar_strtoull(ptr); nfs->root = sigar_strtoull(ptr); nfs->lookup = sigar_strtoull(ptr); nfs->readlink = sigar_strtoull(ptr); nfs->read = sigar_strtoull(ptr); nfs->writecache = sigar_strtoull(ptr); nfs->write = sigar_strtoull(ptr); nfs->create = sigar_strtoull(ptr); nfs->remove = sigar_strtoull(ptr); nfs->rename = sigar_strtoull(ptr); nfs->link = sigar_strtoull(ptr); nfs->symlink = sigar_strtoull(ptr); nfs->mkdir = sigar_strtoull(ptr); nfs->rmdir = sigar_strtoull(ptr); nfs->readdir = sigar_strtoull(ptr); nfs->fsstat = sigar_strtoull(ptr); return SIGAR_OK; } int sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs) { return sigar_nfs_v2_get(PROC_FS_ROOT "net/rpc/nfs", (sigar_nfs_v2_t *)nfs); } int sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs) { return sigar_nfs_v2_get(PROC_FS_ROOT "net/rpc/nfsd", (sigar_nfs_v2_t *)nfs); } static int sigar_nfs_v3_get(char *file, sigar_nfs_v3_t *nfs) { char buffer[BUFSIZ], *ptr=buffer; int status = sigar_proc_nfs_gets(file, "proc3", buffer, sizeof(buffer)); if (status != SIGAR_OK) { return status; } ptr = sigar_skip_multiple_token(ptr, 2); nfs->null = sigar_strtoull(ptr); nfs->getattr = sigar_strtoull(ptr); nfs->setattr = sigar_strtoull(ptr); nfs->lookup = sigar_strtoull(ptr); nfs->access = sigar_strtoull(ptr); nfs->readlink = sigar_strtoull(ptr); nfs->read = sigar_strtoull(ptr); nfs->write = sigar_strtoull(ptr); nfs->create = sigar_strtoull(ptr); nfs->mkdir = sigar_strtoull(ptr); nfs->symlink = sigar_strtoull(ptr); nfs->mknod = sigar_strtoull(ptr); nfs->remove = sigar_strtoull(ptr); nfs->rmdir = sigar_strtoull(ptr); nfs->rename = sigar_strtoull(ptr); nfs->link = sigar_strtoull(ptr); nfs->readdir = sigar_strtoull(ptr); nfs->readdirplus = sigar_strtoull(ptr); nfs->fsstat = sigar_strtoull(ptr); nfs->fsinfo = sigar_strtoull(ptr); nfs->pathconf = sigar_strtoull(ptr); nfs->commit = sigar_strtoull(ptr); return SIGAR_OK; } int sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs) { return sigar_nfs_v3_get(PROC_FS_ROOT "net/rpc/nfs", (sigar_nfs_v3_t *)nfs); } int sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs) { return sigar_nfs_v3_get(PROC_FS_ROOT "net/rpc/nfsd", (sigar_nfs_v3_t *)nfs); } int sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid) { int status; sigar_net_connection_t netconn; DIR *dirp; struct dirent *ent, dbuf; SIGAR_ZERO(&netconn); *pid = 0; status = sigar_net_connection_get(sigar, &netconn, port, SIGAR_NETCONN_SERVER|protocol); if (status != SIGAR_OK) { return status; } if (netconn.local_port != port) { return SIGAR_OK; /* XXX or ENOENT? */ } if (!(dirp = opendir(PROCP_FS_ROOT))) { return errno; } while (readdir_r(dirp, &dbuf, &ent) == 0) { DIR *fd_dirp; struct dirent *fd_ent, fd_dbuf; struct stat sb; char fd_name[BUFSIZ], pid_name[BUFSIZ]; int len, slen; if (ent == NULL) { break; } if (!sigar_isdigit(*ent->d_name)) { continue; } /* sprintf(pid_name, "/proc/%s", ent->d_name) */ memcpy(&pid_name[0], PROCP_FS_ROOT, SSTRLEN(PROCP_FS_ROOT)); len = SSTRLEN(PROCP_FS_ROOT); pid_name[len++] = '/'; slen = strlen(ent->d_name); memcpy(&pid_name[len], ent->d_name, slen); len += slen; pid_name[len] = '\0'; if (stat(pid_name, &sb) < 0) { continue; } if (sb.st_uid != netconn.uid) { continue; } /* sprintf(fd_name, "%s/fd", pid_name) */ memcpy(&fd_name[0], pid_name, len); memcpy(&fd_name[len], "/fd", 3); fd_name[len+=3] = '\0'; if (!(fd_dirp = opendir(fd_name))) { continue; } while (readdir_r(fd_dirp, &fd_dbuf, &fd_ent) == 0) { char fd_ent_name[BUFSIZ]; if (fd_ent == NULL) { break; } if (!sigar_isdigit(*fd_ent->d_name)) { continue; } /* sprintf(fd_ent_name, "%s/%s", fd_name, fd_ent->d_name) */ slen = strlen(fd_ent->d_name); memcpy(&fd_ent_name[0], fd_name, len); fd_ent_name[len] = '/'; memcpy(&fd_ent_name[len+1], fd_ent->d_name, slen); fd_ent_name[len+1+slen] = '\0'; if (stat(fd_ent_name, &sb) < 0) { continue; } if (sb.st_ino == netconn.inode) { closedir(fd_dirp); closedir(dirp); *pid = strtoul(ent->d_name, NULL, 10); return SIGAR_OK; } } closedir(fd_dirp); } closedir(dirp); return SIGAR_OK; } static void generic_vendor_parse(char *line, sigar_sys_info_t *info) { char *ptr; int len = 0; while (*line) { SIGAR_SKIP_SPACE(line); if (!isdigit(*line)) { ++line; continue; } ptr = line; while ((isdigit(*ptr) || (*ptr == '.'))) { ++ptr; ++len; } if (len) { /* sanity check */ if (len > sizeof(info->vendor_version)) { continue; } memcpy(info->vendor_version, line, len);/*XXX*/ info->vendor_version[len] = '\0'; return; } } } static void redhat_vendor_parse(char *line, sigar_sys_info_t *info) { char *start, *end; generic_vendor_parse(line, info); /* super.parse */ if ((start = strchr(line, '('))) { ++start; if ((end = strchr(start, ')'))) { int len = end-start; memcpy(info->vendor_code_name, start, len);/*XXX*/ info->vendor_code_name[len] = '\0'; } } #define RHEL_PREFIX "Red Hat Enterprise Linux " #define CENTOS_VENDOR "CentOS" #define SL_VENDOR "Scientific Linux" if (strnEQ(line, RHEL_PREFIX, sizeof(RHEL_PREFIX)-1)) { snprintf(info->vendor_version, sizeof(info->vendor_version), "Enterprise Linux %c", info->vendor_version[0]); } else if (strnEQ(line, CENTOS_VENDOR, sizeof(CENTOS_VENDOR)-1)) { SIGAR_SSTRCPY(info->vendor, CENTOS_VENDOR); } else if (strnEQ(line, SL_VENDOR, sizeof(SL_VENDOR)-1)) { SIGAR_SSTRCPY(info->vendor, SL_VENDOR); } } #define is_quote(c) ((c == '\'') || (c == '"')) static void kv_parse(char *data, sigar_sys_info_t *info, void (*func)(sigar_sys_info_t *, char *, char *)) { char *ptr = data; int len = strlen(data); char *end = data+len; while (ptr < end) { char *val = strchr(ptr, '='); int klen, vlen; char key[256], *ix; if (!val) { continue; } klen = val - ptr; SIGAR_SSTRCPY(key, ptr); key[klen] = '\0'; ++val; if ((ix = strchr(val, '\n'))) { *ix = '\0'; } vlen = strlen(val); if (is_quote(*val)) { if (is_quote(val[vlen-1])) { val[vlen-1] = '\0'; } ++val; } func(info, key, val); ptr += (klen + 1 + vlen + 1); } } static void lsb_parse(sigar_sys_info_t *info, char *key, char *val) { if (strEQ(key, "DISTRIB_ID")) { SIGAR_SSTRCPY(info->vendor, val); } else if (strEQ(key, "DISTRIB_RELEASE")) { SIGAR_SSTRCPY(info->vendor_version, val); } else if (strEQ(key, "DISTRIB_CODENAME")) { SIGAR_SSTRCPY(info->vendor_code_name, val); } } static void lsb_vendor_parse(char *data, sigar_sys_info_t *info) { kv_parse(data, info, lsb_parse); } static void xen_parse(sigar_sys_info_t *info, char *key, char *val) { if (strEQ(key, "PRODUCT_VERSION")) { SIGAR_SSTRCPY(info->vendor_version, val); } else if (strEQ(key, "KERNEL_VERSION")) { SIGAR_SSTRCPY(info->version, val); } } static void xen_vendor_parse(char *data, sigar_sys_info_t *info) { kv_parse(data, info, xen_parse); snprintf(info->description, sizeof(info->description), "XenServer %s", info->vendor_version); } typedef struct { const char *name; const char *file; void (*parse)(char *, sigar_sys_info_t *); } linux_vendor_info_t; static linux_vendor_info_t linux_vendors[] = { { "Fedora", "/etc/fedora-release", NULL }, { "SuSE", "/etc/SuSE-release", NULL }, { "Gentoo", "/etc/gentoo-release", NULL }, { "Slackware", "/etc/slackware-version", NULL }, { "Mandrake", "/etc/mandrake-release", NULL }, { "VMware", "/proc/vmware/version", NULL }, { "XenSource", "/etc/xensource-inventory", xen_vendor_parse }, { "Red Hat", "/etc/redhat-release", redhat_vendor_parse }, { "lsb", "/etc/lsb-release", lsb_vendor_parse }, { "Debian", "/etc/debian_version", NULL }, { NULL } }; static int get_linux_vendor_info(sigar_sys_info_t *info) { int i, status = ENOENT; /* env vars for testing */ const char *release_file = getenv("SIGAR_OS_RELEASE_FILE"); const char *vendor_name = getenv("SIGAR_OS_VENDOR_NAME"); char buffer[8192], *data; linux_vendor_info_t *vendor = NULL; for (i=0; linux_vendors[i].name; i++) { struct stat sb; vendor = &linux_vendors[i]; if (release_file && vendor_name) { if (!strEQ(vendor->name, vendor_name)) { continue; } } else { if (stat(vendor->file, &sb) < 0) { continue; } release_file = vendor->file; } status = sigar_file2str(release_file, buffer, sizeof(buffer)-1); break; } if (status != SIGAR_OK) { return status; } data = buffer; SIGAR_SSTRCPY(info->vendor, vendor->name); if (vendor->parse) { vendor->parse(data, info); } else { generic_vendor_parse(data, info); } if (info->description[0] == '\0') { snprintf(info->description, sizeof(info->description), "%s %s", info->vendor, info->vendor_version); } return SIGAR_OK; } int sigar_os_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo) { get_linux_vendor_info(sysinfo); return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/os/linux/sigar_os.h000066400000000000000000000036021210132627500215350ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 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. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #include #include #include #include #include #include #include #include #include #include typedef struct { sigar_pid_t pid; time_t mtime; sigar_uint64_t vsize; sigar_uint64_t rss; sigar_uint64_t minor_faults; sigar_uint64_t major_faults; sigar_uint64_t ppid; int tty; int priority; int nice; sigar_uint64_t start_time; sigar_uint64_t utime; sigar_uint64_t stime; char name[SIGAR_PROC_NAME_LEN]; char state; int processor; } linux_proc_stat_t; typedef enum { IOSTAT_NONE, IOSTAT_PARTITIONS, /* 2.4 */ IOSTAT_DISKSTATS, /* 2.6 */ IOSTAT_SYS /* 2.6 */ } linux_iostat_e; struct sigar_t { SIGAR_T_BASE; int pagesize; int ram; int proc_signal_offset; linux_proc_stat_t last_proc_stat; int lcpu; linux_iostat_e iostat; char *proc_net; /* Native POSIX Thread Library 2.6+ kernel */ int has_nptl; }; #define HAVE_STRERROR_R #ifndef __USE_XOPEN2K /* use gnu version of strerror_r */ #define HAVE_STRERROR_R_GLIBC #endif #define HAVE_READDIR_R #define HAVE_GETPWNAM_R #define HAVE_GETPWUID_R #define HAVE_GETGRGID_R #endif /* SIGAR_OS_H */ hyperic-sigar-1.6.4+dfsg/src/os/solaris/000077500000000000000000000000001210132627500200725ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/solaris/get_mib2.c000066400000000000000000000222361210132627500217330ustar00rootroot00000000000000/* * get_mib2() -- get MIB2 information from Solaris 2.[3-7] kernel * * V. Abell * Purdue University Computing Center */ /* * Copyright 1995 Purdue Research Foundation, West Lafayette, Indiana * 47907. All rights reserved. * * Written by Victor A. Abell * * This software is not subject to any license of the American Telephone * and Telegraph Company or the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. Neither Victor A Abell nor Purdue University are responsible for * any consequences of the use of this software. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Credit to Victor A. Abell and Purdue * University must appear in documentation and sources. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 4. This notice may not be removed or altered. */ /* * Altered for sigar: * - remove static stuff to make thread-safe by Doug MacEachern (3/11/05) */ #if 0 /*ndef lint -Wall -Werror*/ static char copyright[] = "@(#) Copyright 1995 Purdue Research Foundation.\nAll rights reserved.\n"; #endif #include "get_mib2.h" #include #include #include #include #include #include #ifdef DMALLOC #include #endif /* * close_mib2() - close MIB2 access * * return: * * exit = GET_MIB2_OK if close succeeded * GET_MIB2_* is the error code. */ int close_mib2(solaris_mib2_t *mib2) { if (mib2->sd < 0) { (void) strcpy(mib2->errmsg, "close_mib2: socket not open"); return(GET_MIB2_ERR_NOTOPEN); } if (close(mib2->sd)) { (void) sprintf(mib2->errmsg, "close_mib2: %s", strerror(errno)); return(GET_MIB2_ERR_CLOSE); } mib2->sd = -1; if (mib2->db_len && mib2->db) { mib2->db_len = 0; free((void *)mib2->db); mib2->db = NULL; } if (mib2->smb_len && mib2->smb) { mib2->smb_len = 0; free((void *)mib2->smb); mib2->smb = NULL; } return(GET_MIB2_OK); } /* * get_mib2() - get MIB2 data * * return: * * exit = GET_MIB2_OK if get succeeded, and: * *opt = opthdr structure address * *data = data buffer address * *datalen = size of data buffer * GET_MIB2_* is the error code for failure. */ int get_mib2(solaris_mib2_t *mib2, struct opthdr **opt, char **data, int *datalen) { struct strbuf d; /* streams data buffer */ int err; /* error code */ int f; /* flags */ int rc; /* reply code */ /* * If MIB2 access isn't open, open it and issue the preliminary stream * messages. */ if (mib2->sd < 0) { /* * Open access. Return on error. */ if ((err = open_mib2(mib2))) { return(err); } /* * Set up message request and option. */ mib2->req = (struct T_optmgmt_req *)mib2->smb; mib2->op = (struct opthdr *)&mib2->smb[sizeof(struct T_optmgmt_req)]; mib2->req->PRIM_type = T_OPTMGMT_REQ; mib2->req->OPT_offset = sizeof(struct T_optmgmt_req); mib2->req->OPT_length = sizeof(struct opthdr); #if defined(MI_T_CURRENT) mib2->req->MGMT_flags = MI_T_CURRENT; #else /* !defined(MI_T_CURRENT) */ # if defined(T_CURRENT) mib2->req->MGMT_flags = T_CURRENT; # else /* !defined(T_CURRENT) */ #error "Neither MI_T_CURRENT nor T_CURRENT are defined." # endif /* defined(T_CURRENT) */ #endif /* defined(MI_T_CURRENT) */ mib2->op->level = MIB2_IP; mib2->op->name = mib2->op->len = 0; mib2->ctlbuf.buf = mib2->smb; mib2->ctlbuf.len = mib2->req->OPT_offset + mib2->req->OPT_length; /* * Put the message. */ if (putmsg(mib2->sd, &mib2->ctlbuf, (struct strbuf *)NULL, 0) == -1) { (void) sprintf(mib2->errmsg, "get_mib2: putmsg request: %s", strerror(errno)); return(GET_MIB2_ERR_PUTMSG); } /* * Set up to process replies. */ mib2->op_ack = (struct T_optmgmt_ack *)mib2->smb; mib2->ctlbuf.maxlen = mib2->smb_len; mib2->err_ack = (struct T_error_ack *)mib2->smb; mib2->op = (struct opthdr *)&mib2->smb[sizeof(struct T_optmgmt_ack)]; } /* * Get the next (first) reply message. */ f = 0; if ((rc = getmsg(mib2->sd, &mib2->ctlbuf, NULL, &f)) < 0) { (void) sprintf(mib2->errmsg, "get_mib2: getmsg(reply): %s", strerror(errno)); return(GET_MIB2_ERR_GETMSGR); } /* * Check for end of data. */ if (rc == 0 && mib2->ctlbuf.len >= sizeof(struct T_optmgmt_ack) && mib2->op_ack->PRIM_type == T_OPTMGMT_ACK && mib2->op_ack->MGMT_flags == T_SUCCESS && mib2->op->len == 0) { err = close_mib2(mib2); if (err) { return(err); } return(GET_MIB2_EOD); } /* * Check for error. */ if (mib2->ctlbuf.len >= sizeof(struct T_error_ack) && mib2->err_ack->PRIM_type == T_ERROR_ACK) { (void) sprintf(mib2->errmsg, "get_mib2: T_ERROR_ACK: len=%d, TLI=%#x, UNIX=%#x", mib2->ctlbuf.len, (int)mib2->err_ack->TLI_error, (int)mib2->err_ack->UNIX_error); return(GET_MIB2_ERR_ACK); } /* * Check for no data. */ if (rc != MOREDATA || mib2->ctlbuf.len < sizeof(struct T_optmgmt_ack) || mib2->op_ack->PRIM_type != T_OPTMGMT_ACK || mib2->op_ack->MGMT_flags != T_SUCCESS) { (void) sprintf(mib2->errmsg, "get_mib2: T_OPTMGMT_ACK: " "rc=%d len=%d type=%#x flags=%#x", rc, mib2->ctlbuf.len, (int)mib2->op_ack->PRIM_type, (int)mib2->op_ack->MGMT_flags); return(GET_MIB2_ERR_NODATA); } /* * Allocate (or enlarge) the data buffer. */ if (mib2->op->len >= mib2->db_len) { mib2->db_len = mib2->op->len; if (mib2->db == NULL) { mib2->db = (char *)malloc(mib2->db_len); } else { mib2->db = (char *)realloc(mib2->db, mib2->db_len); } if (mib2->db == NULL) { (void) sprintf(mib2->errmsg, "get_mib2: no space for %d byte data buffer", mib2->db_len); return(GET_MIB2_ERR_NOSPC); } } /* * Get the data part of the message -- the MIB2 part. */ d.maxlen = mib2->op->len; d.buf = mib2->db; d.len = 0; f = 0; if ((rc = getmsg(mib2->sd, NULL, &d, &f)) < 0) { (void) sprintf(mib2->errmsg, "get_mib2: getmsg(data): %s", strerror(errno)); return(GET_MIB2_ERR_GETMSGD); } if (rc) { (void) sprintf(mib2->errmsg, "get_mib2: getmsg(data): rc=%d maxlen=%d len=%d: %s", rc, d.maxlen, d.len, strerror(errno)); return(GET_MIB2_ERR_GETMSGD); } /* * Compose a successful return. */ *opt = mib2->op; *data = mib2->db; *datalen = d.len; return(GET_MIB2_OK); } /* * open_mib2() - open access to MIB2 data * * return: * * exit = GET_MIB2_OK if open succeeded * GET_MIB2_* is the error code for failure. */ int open_mib2(solaris_mib2_t *mib2) { /* * It's an error if the stream device is already open. */ if (mib2->sd >= 0) { (void) strcpy(mib2->errmsg, "open_mib2: MIB2 access already open"); return(GET_MIB2_ERR_OPEN); } /* * Open the ARP stream device, push TCP and UDP on it. */ if ((mib2->sd = open(GET_MIB2_ARPDEV, O_RDWR, 0600)) < 0) { (void) sprintf(mib2->errmsg, "open_mib2: %s: %s", GET_MIB2_ARPDEV, strerror(errno)); return(GET_MIB2_ERR_ARPOPEN); } if (ioctl(mib2->sd, I_PUSH, GET_MIB2_TCPSTREAM) == -1) { (void) sprintf(mib2->errmsg, "open_mib2: push %s: %s", GET_MIB2_TCPSTREAM, strerror(errno)); return(GET_MIB2_ERR_TCPPUSH); } if (ioctl(mib2->sd, I_PUSH, GET_MIB2_UDPSTREAM) == -1) { (void) sprintf(mib2->errmsg, "open_mib2: push %s: %s", GET_MIB2_UDPSTREAM, strerror(errno)); return(GET_MIB2_ERR_UDPPUSH); } /* * Allocate a stream message buffer. */ mib2->smb_len = sizeof(struct opthdr) + sizeof(struct T_optmgmt_req); if (mib2->smb_len < (sizeof (struct opthdr) + sizeof(struct T_optmgmt_ack))) { mib2->smb_len = sizeof (struct opthdr) + sizeof(struct T_optmgmt_ack); } if (mib2->smb_len < sizeof(struct T_error_ack)) { mib2->smb_len = sizeof(struct T_error_ack); } if ((mib2->smb = (char *)malloc(mib2->smb_len)) == NULL) { (void) strcpy(mib2->errmsg, "open_mib2: no space for stream message buffer"); return(GET_MIB2_ERR_NOSPC); } /* * All is OK. Return that indication. */ return(GET_MIB2_OK); } hyperic-sigar-1.6.4+dfsg/src/os/solaris/get_mib2.h000066400000000000000000000076341210132627500217450ustar00rootroot00000000000000/* * get_mib2.h -- definitions for the get_mib2() function * * V. Abell * Purdue University Computing Center */ /* * Copyright 1995 Purdue Research Foundation, West Lafayette, Indiana * 47907. All rights reserved. * * Written by Victor A. Abell * * This software is not subject to any license of the American Telephone * and Telegraph Company or the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. Neither Victor A Abell nor Purdue University are responsible for * any consequences of the use of this software. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Credit to Victor A. Abell and Purdue * University must appear in documentation and sources. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 4. This notice may not be removed or altered. */ /* * Altered for sigar: * - remove static stuff to make thread-safe by Doug MacEachern (3/11/05) */ #if !defined(GET_MIB2_H) #define GET_MIB2_H /* * Required header files */ #include #include #include #include #include #include #include #include /* * Miscellaneous definitions */ #define GET_MIB2_ARPDEV "/dev/arp" /* ARP stream devi9ce */ #define GET_MIB2_ERRMSGL 1024 /* ErrMsg buffer length */ #define GET_MIB2_TCPSTREAM "tcp" /* TCP stream name */ #define GET_MIB2_UDPSTREAM "udp" /* UDP stream name */ /* * get_mib2() response codes * * -1 End of MIB2 information * 0 Next MIB2 structure returned * >0 Error code */ #define GET_MIB2_EOD -1 /* end of data */ #define GET_MIB2_OK 0 /* function succeeded */ #define GET_MIB2_ERR_ACK 1 /* getmsg() ACK error received */ #define GET_MIB2_ERR_ARPOPEN 2 /* error opening ARPDEV */ #define GET_MIB2_ERR_CLOSE 3 /* MIB2 access close error */ #define GET_MIB2_ERR_GETMSGD 4 /* error getting message data */ #define GET_MIB2_ERR_GETMSGR 5 /* error getting message reply */ #define GET_MIB2_ERR_NODATA 6 /* data expected; not received */ #define GET_MIB2_ERR_NOSPC 7 /* no malloc() space */ #define GET_MIB2_ERR_NOTOPEN 8 /* MIB2 access not open */ #define GET_MIB2_ERR_OPEN 9 /* MIB2 access open error */ #define GET_MIB2_ERR_PUTMSG 10 /* error putting request message */ #define GET_MIB2_ERR_TCPPUSH 11 /* error pushing TCPSTREAM */ #define GET_MIB2_ERR_UDPPUSH 12 /* error pushing UDPSTREAM */ #define GET_MIB2_ERR_MAX 13 /* maximum error number + 1 */ typedef struct { char *db; /* data buffer */ int db_len; /* data buffer length */ char *smb; /* stream message buffer */ size_t smb_len; /* size of Smb[] */ int sd; /* stream device descriptor */ char errmsg[GET_MIB2_ERRMSGL]; /* error message buffer */ struct T_optmgmt_ack *op_ack; /* message ACK pointer */ struct strbuf ctlbuf; /* streams control buffer */ struct T_error_ack *err_ack; /* message error pointer */ struct opthdr *op; /* message option pointer */ struct T_optmgmt_req *req; /* message request pointer */ } solaris_mib2_t; /* * Function prototypes */ int close_mib2( /* close acccess to MIB2 information */ solaris_mib2_t *mib2 ); int get_mib2( /* get MIB2 information */ solaris_mib2_t *mib2, struct opthdr **opt, /* opthdr pointer return (see * */ char **data, /* data buffer return address */ int *datalen /* data buffer length return * address */ ); int open_mib2( /* open acccess to MIB2 information */ solaris_mib2_t *mib2 ); #endif /* !defined(GET_MIB2_H) */ hyperic-sigar-1.6.4+dfsg/src/os/solaris/kstats.c000066400000000000000000000124551210132627500215560ustar00rootroot00000000000000/* * Copyright (c) 2004-2007 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" int sigar_get_kstats(sigar_t *sigar) { kstat_ctl_t *kc = sigar->kc; unsigned int i, id, ncpu = sysconf(_SC_NPROCESSORS_CONF); int is_debug = SIGAR_LOG_IS_DEBUG(sigar); if (ncpu != sigar->ncpu) { if (!sigar->ks.lcpu) { /* init */ sigar->ks.lcpu = ncpu; sigar->ks.cpu = malloc(sizeof(*(sigar->ks.cpu)) * ncpu); sigar->ks.cpu_info = malloc(sizeof(*(sigar->ks.cpu_info)) * ncpu); sigar->ks.cpuid = malloc(sizeof(*(sigar->ks.cpuid)) * ncpu); } else { sigar_log_printf(sigar, SIGAR_LOG_INFO, "ncpu changed from %d to %d", sigar->ncpu, ncpu); if (ncpu > sigar->ks.lcpu) { /* one or more cpus have been added */ sigar->ks.cpu = realloc(sigar->ks.cpu, sizeof(*(sigar->ks.cpu)) * ncpu); sigar->ks.cpu_info = realloc(sigar->ks.cpu_info, sizeof(*(sigar->ks.cpu_info)) * ncpu); sigar->ks.cpuid = realloc(sigar->ks.cpuid, sizeof(*(sigar->ks.cpuid)) * ncpu); sigar->ks.lcpu = ncpu; } /* else or more cpus have been removed */ } sigar->ncpu = ncpu; /* from man p_online: * ``Processor numbers are integers, * greater than or equal to 0, * and are defined by the hardware platform. * Processor numbers are not necessarily contiguous, * but "not too sparse."`` * so we maintain our own mapping in ks.cpuid[] */ /* lookup in order, which kstat chain may not be in */ for (i=0, id=0; iks.cpu_info[i] = cpu_info; sigar->ks.cpu[i] = cpu_stat; sigar->ks.cpuid[i] = id; if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "cpu %d id=%d", i, sigar->ks.cpuid[i]); } i++; } } sigar->ks.system = kstat_lookup(kc, "unix", -1, "system_misc"); sigar->ks.syspages = kstat_lookup(kc, "unix", -1, "system_pages"); sigar->ks.mempages = kstat_lookup(kc, "bunyip", -1, "mempages"); return SIGAR_OK; } SIGAR_INLINE kid_t sigar_kstat_update(sigar_t *sigar) { kid_t id = kstat_chain_update(sigar->kc); switch (id) { case -1: sigar_log_printf(sigar, SIGAR_LOG_ERROR, "kstat_chain_update error: %s", sigar_strerror(sigar, errno)); break; case 0: /* up-to-date */ break; default: sigar_get_kstats(sigar); sigar_log(sigar, SIGAR_LOG_DEBUG, "kstat chain updated"); break; } return id; } /* * bincompat is not possible with certain kstat data structures between * solaris 2.6, 2.7, 2.8, etc. alternative is to use kstat_data_lookup() * which means everytime we want a stat, must do a linear search * of ksp->ks_data. eek. so we meet half way and do the search for * each key once per sigar_t instance. once the initial search has * been done, we have a table of offsets to quickly access the stats via * ksp->ks_data + offset. this gives us bincompat without the overhead * of many kstat_data_lookup calls. */ static SIGAR_INLINE int kstat_named_offset(kstat_t *ksp, const char *name) { unsigned int i; kstat_named_t *kn; for (i=0, kn=ksp->ks_data; iks_ndata; i++, kn++) { if (strEQ(kn->name, name)) { return i; } } return -2; /* not found */ } static char *kstat_keys_system[] = { "boot_time", "avenrun_1min", "avenrun_5min", "avenrun_15min", NULL }; static char *kstat_keys_mempages[] = { "pages_anon", "pages_exec", "pages_vnode", NULL }; static char *kstat_keys_syspages[] = { "pagesfree", NULL }; static char **kstat_keys[] = { kstat_keys_system, kstat_keys_mempages, kstat_keys_syspages, }; void sigar_koffsets_lookup(kstat_t *ksp, int *offsets, int kidx) { int i; char **keys = kstat_keys[kidx]; for (i=0; keys[i]; i++) { offsets[i] = kstat_named_offset(ksp, keys[i]); } } hyperic-sigar-1.6.4+dfsg/src/os/solaris/procfs.c000066400000000000000000000043521210132627500215360ustar00rootroot00000000000000/* * Copyright (c) 2004, 2006 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. */ #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #define my_pread(fd, ptr, type, offset) \ (pread(fd, ptr, sizeof(type), offset) == sizeof(type)) int sigar_proc_psinfo_get(sigar_t *sigar, sigar_pid_t pid) { int fd, retval = SIGAR_OK; char buffer[BUFSIZ]; time_t timenow = time(NULL); if (sigar->pinfo == NULL) { sigar->pinfo = malloc(sizeof(*sigar->pinfo)); } if (sigar->last_pid == pid) { if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) { return SIGAR_OK; } } sigar->last_pid = pid; sigar->last_getprocs = timenow; (void)SIGAR_PROC_FILENAME(buffer, pid, "/psinfo"); if ((fd = open(buffer, O_RDONLY)) < 0) { return ESRCH; } if (!my_pread(fd, sigar->pinfo, psinfo_t, 0)) { retval = errno; } close(fd); return retval; } int sigar_proc_usage_get(sigar_t *sigar, prusage_t *prusage, sigar_pid_t pid) { int fd, retval = SIGAR_OK; char buffer[BUFSIZ]; (void)SIGAR_PROC_FILENAME(buffer, pid, "/usage"); if ((fd = open(buffer, O_RDONLY)) < 0) { return ESRCH; } if (!my_pread(fd, prusage, prusage_t, 0)) { retval = errno; } close(fd); return retval; } int sigar_proc_status_get(sigar_t *sigar, pstatus_t *pstatus, sigar_pid_t pid) { int fd, retval = SIGAR_OK; char buffer[BUFSIZ]; (void)SIGAR_PROC_FILENAME(buffer, pid, "/status"); if ((fd = open(buffer, O_RDONLY)) < 0) { return ESRCH; } if (!my_pread(fd, pstatus, pstatus_t, 0)) { retval = errno; } close(fd); return retval; } hyperic-sigar-1.6.4+dfsg/src/os/solaris/sigar_os.h000066400000000000000000000132201210132627500220470ustar00rootroot00000000000000/* * Copyright (c) 2004-2007 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #ifndef _POSIX_PTHREAD_SEMANTICS #define _POSIX_PTHREAD_SEMANTICS #endif typedef unsigned long long int u_int64_t; #include #include #ifndef DMALLOC #include #endif #include #include #include #include #include #include #include #include #include #include #include #include "get_mib2.h" /* avoid -Wall warning since solaris doesnt have a prototype for this */ int getdomainname(char *, int); typedef struct { kstat_t **ks; int num; char *name; int nlen; } kstat_list_t; SIGAR_INLINE kid_t sigar_kstat_update(sigar_t *sigar); int sigar_get_kstats(sigar_t *sigar); void sigar_init_multi_kstats(sigar_t *sigar); void sigar_free_multi_kstats(sigar_t *sigar); int sigar_get_multi_kstats(sigar_t *sigar, kstat_list_t *kl, const char *name, kstat_t **retval); void sigar_koffsets_lookup(kstat_t *ksp, int *offsets, int kidx); int sigar_proc_psinfo_get(sigar_t *sigar, sigar_pid_t pid); int sigar_proc_usage_get(sigar_t *sigar, prusage_t *prusage, sigar_pid_t pid); int sigar_proc_status_get(sigar_t *sigar, pstatus_t *pstatus, sigar_pid_t pid); #define CPU_ONLINE(n) \ (p_online(n, P_STATUS) == P_ONLINE) typedef enum { KSTAT_SYSTEM_BOOT_TIME, KSTAT_SYSTEM_LOADAVG_1, KSTAT_SYSTEM_LOADAVG_2, KSTAT_SYSTEM_LOADAVG_3, KSTAT_SYSTEM_MAX } kstat_system_off_e; typedef enum { KSTAT_MEMPAGES_ANON, KSTAT_MEMPAGES_EXEC, KSTAT_MEMPAGES_VNODE, KSTAT_MEMPAGES_MAX } kstat_mempages_off_e; typedef enum { KSTAT_SYSPAGES_FREE, KSTAT_SYSPAGES_MAX } kstat_syspages_off_e; enum { KSTAT_KEYS_system, KSTAT_KEYS_mempages, KSTAT_KEYS_syspages, } kstat_keys_e; typedef struct ps_prochandle * (*proc_grab_func_t)(pid_t, int, int *); typedef void (*proc_free_func_t)(struct ps_prochandle *); typedef int (*proc_create_agent_func_t)(struct ps_prochandle *); typedef void (*proc_destroy_agent_func_t)(struct ps_prochandle *); typedef void (*proc_objname_func_t)(struct ps_prochandle *, uintptr_t, const char *, size_t); typedef char * (*proc_dirname_func_t)(const char *, char *, size_t); typedef char * (*proc_exename_func_t)(struct ps_prochandle *, char *, size_t); typedef int (*proc_fstat64_func_t)(struct ps_prochandle *, int, void *); typedef int (*proc_getsockopt_func_t)(struct ps_prochandle *, int, int, int, void *, int *); typedef int (*proc_getsockname_func_t)(struct ps_prochandle *, int, struct sockaddr *, socklen_t *); struct sigar_t { SIGAR_T_BASE; int solaris_version; int use_ucb_ps; kstat_ctl_t *kc; /* kstat_lookup() as needed */ struct { kstat_t **cpu; kstat_t **cpu_info; processorid_t *cpuid; unsigned int lcpu; /* number malloced slots in the cpu array above */ kstat_t *system; kstat_t *syspages; kstat_t *mempages; } ks; struct { int system[KSTAT_SYSTEM_MAX]; int mempages[KSTAT_MEMPAGES_MAX]; int syspages[KSTAT_SYSPAGES_MAX]; } koffsets; int pagesize; time_t last_getprocs; sigar_pid_t last_pid; psinfo_t *pinfo; sigar_cpu_list_t cpulist; /* libproc.so interface */ void *plib; proc_grab_func_t pgrab; proc_free_func_t pfree; proc_create_agent_func_t pcreate_agent; proc_destroy_agent_func_t pdestroy_agent; proc_objname_func_t pobjname; proc_dirname_func_t pdirname; proc_exename_func_t pexename; proc_fstat64_func_t pfstat64; proc_getsockopt_func_t pgetsockopt; proc_getsockname_func_t pgetsockname; sigar_cache_t *pargs; solaris_mib2_t mib2; }; #ifdef SIGAR_64BIT #define KSTAT_UINT ui64 #else #define KSTAT_UINT ui32 #endif #define kSTAT_exists(v, type) \ (sigar->koffsets.type[v] != -2) #define kSTAT_ptr(v, type) \ ((kstat_named_t *)ksp->ks_data + sigar->koffsets.type[v]) #define kSTAT_uint(v, type) \ (kSTAT_exists(v, type) ? kSTAT_ptr(v, type)->value.KSTAT_UINT : 0) #define kSTAT_ui32(v, type) \ (kSTAT_exists(v, type) ? kSTAT_ptr(v, type)->value.ui32 : 0) #define kSYSTEM(v) kSTAT_ui32(v, system) #define kMEMPAGES(v) kSTAT_uint(v, mempages) #define kSYSPAGES(v) kSTAT_uint(v, syspages) #define sigar_koffsets_init(sigar, ksp, type) \ if (sigar->koffsets.type[0] == -1) \ sigar_koffsets_lookup(ksp, sigar->koffsets.type, KSTAT_KEYS_##type) #define sigar_koffsets_init_system(sigar, ksp) \ sigar_koffsets_init(sigar, ksp, system) #define sigar_koffsets_init_mempages(sigar, ksp) \ sigar_koffsets_init(sigar, ksp, mempages) #define sigar_koffsets_init_syspages(sigar, ksp) \ sigar_koffsets_init(sigar, ksp, syspages) #define HAVE_READDIR_R #define HAVE_GETPWNAM_R #define HAVE_GETPWUID_R #define SIGAR_EMIB2 (SIGAR_OS_START_ERROR+1) #endif /* SIGAR_OS_H */ hyperic-sigar-1.6.4+dfsg/src/os/solaris/solaris_sigar.c000066400000000000000000002062071210132627500231060ustar00rootroot00000000000000/* * Copyright (c) 2004-2008 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #include #include #include #include #include #include #include #include #include #include #include #define PROC_ERRNO ((errno == ENOENT) ? ESRCH : errno) #define SIGAR_USR_UCB_PS "/usr/ucb/ps" /* like kstat_lookup but start w/ ksp->ks_next instead of kc->kc_chain */ static kstat_t * kstat_next(kstat_t *ksp, char *ks_module, int ks_instance, char *ks_name) { if (ksp) { ksp = ksp->ks_next; } for (; ksp; ksp = ksp->ks_next) { if ((ks_module == NULL || strcmp(ksp->ks_module, ks_module) == 0) && (ks_instance == -1 || ksp->ks_instance == ks_instance) && (ks_name == NULL || strcmp(ksp->ks_name, ks_name) == 0)) return ksp; } errno = ENOENT; return NULL; } int sigar_os_open(sigar_t **sig) { kstat_ctl_t *kc; kstat_t *ksp; sigar_t *sigar; int i, status; struct utsname name; char *ptr; sigar = malloc(sizeof(*sigar)); *sig = sigar; sigar->log_level = -1; /* log nothing by default */ sigar->log_impl = NULL; sigar->log_data = NULL; uname(&name); if ((ptr = strchr(name.release, '.'))) { ptr++; sigar->solaris_version = atoi(ptr); } else { sigar->solaris_version = 6; } if ((ptr = getenv("SIGAR_USE_UCB_PS"))) { sigar->use_ucb_ps = strEQ(ptr, "true"); } else { struct stat sb; if (stat(SIGAR_USR_UCB_PS, &sb) < 0) { sigar->use_ucb_ps = 0; } else { sigar->use_ucb_ps = 1; } } sigar->pagesize = 0; i = sysconf(_SC_PAGESIZE); while ((i >>= 1) > 0) { sigar->pagesize++; } sigar->ticks = sysconf(_SC_CLK_TCK); sigar->kc = kc = kstat_open(); if (!kc) { return errno; } sigar->cpulist.size = 0; sigar->ncpu = 0; sigar->ks.cpu = NULL; sigar->ks.cpu_info = NULL; sigar->ks.cpuid = NULL; sigar->ks.lcpu = 0; sigar->koffsets.system[0] = -1; sigar->koffsets.mempages[0] = -1; sigar->koffsets.syspages[0] = -1; if ((status = sigar_get_kstats(sigar)) != SIGAR_OK) { fprintf(stderr, "status=%d\n", status); } sigar->boot_time = 0; if ((ksp = sigar->ks.system) && (kstat_read(kc, ksp, NULL) >= 0)) { sigar_koffsets_init_system(sigar, ksp); sigar->boot_time = kSYSTEM(KSTAT_SYSTEM_BOOT_TIME); } sigar->last_pid = -1; sigar->pinfo = NULL; sigar->plib = NULL; sigar->pgrab = NULL; sigar->pfree = NULL; sigar->pobjname = NULL; sigar->pargs = NULL; SIGAR_ZERO(&sigar->mib2); sigar->mib2.sd = -1; return SIGAR_OK; } int sigar_os_close(sigar_t *sigar) { kstat_close(sigar->kc); if (sigar->mib2.sd != -1) { close_mib2(&sigar->mib2); } if (sigar->ks.lcpu) { free(sigar->ks.cpu); free(sigar->ks.cpu_info); free(sigar->ks.cpuid); } if (sigar->pinfo) { free(sigar->pinfo); } if (sigar->cpulist.size != 0) { sigar_cpu_list_destroy(sigar, &sigar->cpulist); } if (sigar->plib) { dlclose(sigar->plib); } if (sigar->pargs) { sigar_cache_destroy(sigar->pargs); } free(sigar); return SIGAR_OK; } char *sigar_os_error_string(sigar_t *sigar, int err) { switch (err) { case SIGAR_EMIB2: return sigar->mib2.errmsg; default: return NULL; } } int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem) { kstat_ctl_t *kc = sigar->kc; kstat_t *ksp; sigar_uint64_t kern = 0; SIGAR_ZERO(mem); /* XXX: is mem hot swappable or can we just do this during open ? */ mem->total = sysconf(_SC_PHYS_PAGES); mem->total <<= sigar->pagesize; if (sigar_kstat_update(sigar) == -1) { return errno; } if ((ksp = sigar->ks.syspages) && kstat_read(kc, ksp, NULL) >= 0) { sigar_koffsets_init_syspages(sigar, ksp); mem->free = kSYSPAGES(KSTAT_SYSPAGES_FREE); mem->free <<= sigar->pagesize; mem->used = mem->total - mem->free; } if ((ksp = sigar->ks.mempages) && kstat_read(kc, ksp, NULL) >= 0) { sigar_koffsets_init_mempages(sigar, ksp); } /* XXX mdb ::memstat cachelist/freelist not available to kstat, see: */ /* http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=6821980 */ /* ZFS ARC cache. see: http://opensolaris.org/jive/thread.jspa?messageID=393695 */ if ((ksp = kstat_lookup(sigar->kc, "zfs", 0, "arcstats")) && (kstat_read(sigar->kc, ksp, NULL) != -1)) { kstat_named_t *kn; if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, "size"))) { kern = kn->value.i64; } if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, "c_min"))) { /* c_min cannot be reclaimed they say */ if (kern > kn->value.i64) { kern -= kn->value.i64; } } } mem->actual_free = mem->free + kern; mem->actual_used = mem->used - kern; sigar_mem_calc_ram(sigar, mem); return SIGAR_OK; } int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) { kstat_t *ksp; kstat_named_t *kn; swaptbl_t *stab; int num, i; char path[PATH_MAX+1]; /* {un,re}used */ /* see: man swapctl(2) */ if ((num = swapctl(SC_GETNSWP, NULL)) == -1) { return errno; } stab = malloc(num * sizeof(stab->swt_ent[0]) + sizeof(*stab)); stab->swt_n = num; for (i=0; iswt_ent[i].ste_path = path; } if ((num = swapctl(SC_LIST, stab)) == -1) { free(stab); return errno; } num = num < stab->swt_n ? num : stab->swt_n; swap->total = swap->free = 0; for (i=0; iswt_ent[i].ste_flags & ST_INDEL) { continue; /* swap file is being deleted */ } swap->total += stab->swt_ent[i].ste_pages; swap->free += stab->swt_ent[i].ste_free; } free(stab); swap->total <<= sigar->pagesize; swap->free <<= sigar->pagesize; swap->used = swap->total - swap->free; if (sigar_kstat_update(sigar) == -1) { return errno; } if (!(ksp = kstat_lookup(sigar->kc, "cpu", -1, "vm"))) { swap->page_in = swap->page_out = SIGAR_FIELD_NOTIMPL; return SIGAR_OK; } swap->page_in = swap->page_out = 0; /* XXX: these stats do not exist in this form on solaris 8 or 9. * they are in the raw cpu_stat struct, but thats not * binary compatible */ do { if (kstat_read(sigar->kc, ksp, NULL) < 0) { break; } if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, "pgin"))) { swap->page_in += kn->value.i64; /* vmstat -s | grep "page ins" */ } if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, "pgout"))) { swap->page_out += kn->value.i64; /* vmstat -s | grep "page outs" */ } } while ((ksp = kstat_next(ksp, "cpu", -1, "vm"))); return SIGAR_OK; } #ifndef KSTAT_NAMED_STR_PTR /* same offset as KSTAT_NAMED_STR_PTR(brand) */ #define KSTAT_NAMED_STR_PTR(n) (char *)((n)->value.i32) #endif static int get_chip_brand(sigar_t *sigar, int processor, sigar_cpu_info_t *info) { kstat_t *ksp = sigar->ks.cpu_info[processor]; kstat_named_t *brand; if (sigar->solaris_version < 10) { /* don't bother; doesn't exist. */ return 0; } if (ksp && (kstat_read(sigar->kc, ksp, NULL) != -1) && (brand = (kstat_named_t *)kstat_data_lookup(ksp, "brand"))) { char *name = KSTAT_NAMED_STR_PTR(brand); char *vendor = "Sun"; char *vendors[] = { "Intel", "AMD", NULL }; int i; if (!name) { return 0; } for (i=0; vendors[i]; i++) { if (strstr(name, vendors[i])) { vendor = vendors[i]; break; } } SIGAR_SSTRCPY(info->vendor, vendor); #if 0 SIGAR_SSTRCPY(info->model, name); sigar_cpu_model_adjust(sigar, info); #endif return 1; } else { return 0; } } static void free_chip_id(void *ptr) { /*noop*/ } static int get_chip_id(sigar_t *sigar, int processor) { kstat_t *ksp = sigar->ks.cpu_info[processor]; kstat_named_t *chipid; if (ksp && (kstat_read(sigar->kc, ksp, NULL) != -1) && (chipid = (kstat_named_t *)kstat_data_lookup(ksp, "chip_id"))) { return chipid->value.i32; } else { return -1; } } int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu) { int status, i; status = sigar_cpu_list_get(sigar, &sigar->cpulist); if (status != SIGAR_OK) { return status; } SIGAR_ZERO(cpu); for (i=0; icpulist.number; i++) { sigar_cpu_t *xcpu = &sigar->cpulist.data[i]; cpu->user += xcpu->user; cpu->sys += xcpu->sys; cpu->idle += xcpu->idle; cpu->nice += xcpu->nice; cpu->wait += xcpu->wait; cpu->total = xcpu->total; } return SIGAR_OK; } int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { kstat_ctl_t *kc = sigar->kc; kstat_t *ksp; uint_t cpuinfo[CPU_STATES]; unsigned int i; int is_debug = SIGAR_LOG_IS_DEBUG(sigar); sigar_cache_t *chips; if (sigar_kstat_update(sigar) == -1) { return errno; } if (cpulist == &sigar->cpulist) { if (sigar->cpulist.size == 0) { /* create once */ sigar_cpu_list_create(cpulist); } else { /* reset, re-using cpulist.data */ sigar->cpulist.number = 0; } } else { sigar_cpu_list_create(cpulist); } if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu_list] OS reports %d CPUs", sigar->ncpu); } chips = sigar_cache_new(16); chips->free_value = free_chip_id; for (i=0; incpu; i++) { sigar_cpu_t *cpu; char *buf; int chip_id; sigar_cache_entry_t *ent; if (!CPU_ONLINE(sigar->ks.cpuid[i])) { sigar_log_printf(sigar, SIGAR_LOG_INFO, "cpu %d (id=%d) is offline", i, sigar->ks.cpuid[i]); continue; } if (!(ksp = sigar->ks.cpu[i])) { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "NULL ksp for cpu %d (id=%d)", i, sigar->ks.cpuid[i]); continue; /* shouldnot happen */ } if (kstat_read(kc, ksp, NULL) < 0) { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "kstat_read failed for cpu %d (id=%d): %s", i, sigar->ks.cpuid[i], sigar_strerror(sigar, errno)); continue; /* shouldnot happen */ } /* * cpu_stat_t is not binary compatible between solaris versions. * since cpu_stat is a 'raw' kstat and not 'named' we cannot * use name based lookups as we do for others. * the start of the cpu_stat_t structure is binary compatible, * which looks like so: * typedef struct cpu_stat { * kmutex_t cpu_stat_lock; * cpu_sysinfo_t cpu_sysinfo; * ... * typedef struct cpu_sysinfo { * ulong cpu[CPU_STATES]; * ... * we just copy the piece we need below: */ buf = ksp->ks_data; buf += sizeof(kmutex_t); memcpy(&cpuinfo[0], buf, sizeof(cpuinfo)); chip_id = sigar->cpu_list_cores ? -1 : get_chip_id(sigar, i); if (chip_id == -1) { SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; SIGAR_ZERO(cpu); } else { /* merge times of logical processors */ ent = sigar_cache_get(chips, chip_id); if (ent->value) { cpu = &cpulist->data[(long)ent->value-1]; } else { SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; ent->value = (void *)(long)cpulist->number; SIGAR_ZERO(cpu); if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu_list] Merging times of" " logical processors for chip_id=%d", chip_id); } } } cpu->user += SIGAR_TICK2MSEC(cpuinfo[CPU_USER]); cpu->sys += SIGAR_TICK2MSEC(cpuinfo[CPU_KERNEL]); cpu->idle += SIGAR_TICK2MSEC(cpuinfo[CPU_IDLE]); cpu->wait += SIGAR_TICK2MSEC(cpuinfo[CPU_WAIT]); cpu->nice += 0; /* no cpu->nice */ cpu->total = cpu->user + cpu->sys + cpu->idle + cpu->wait; } sigar_cache_destroy(chips); return SIGAR_OK; } int sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime) { if (sigar->boot_time) { uptime->uptime = time(NULL) - sigar->boot_time; } else { uptime->uptime = 0; /* XXX: shouldn't happen */ } return SIGAR_OK; } static int loadavg_keys[] = { KSTAT_SYSTEM_LOADAVG_1, KSTAT_SYSTEM_LOADAVG_2, KSTAT_SYSTEM_LOADAVG_3 }; int sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg) { kstat_t *ksp; int i; if (sigar_kstat_update(sigar) == -1) { return errno; } if (!(ksp = sigar->ks.system)) { return -1; } if (kstat_read(sigar->kc, ksp, NULL) < 0) { return -1; } sigar_koffsets_init_system(sigar, ksp); for (i=0; i<3; i++) { loadavg->loadavg[i] = (double)kSYSTEM(loadavg_keys[i]) / FSCALE; } return SIGAR_OK; } #define LIBPROC "/usr/lib/libproc.so" #define CHECK_PSYM(s) \ if (!sigar->s) { \ sigar_log_printf(sigar, SIGAR_LOG_WARN, \ "[%s] Symbol not found: %s", \ SIGAR_FUNC, #s); \ dlclose(sigar->plib); \ sigar->plib = NULL; \ return SIGAR_ENOTIMPL; \ } static char *proc_readlink(const char *name, char *buffer, size_t size) { int len; if ((len = readlink(name, buffer, size-1)) < 0) { return NULL; } buffer[len] = '\0'; return buffer; } static int sigar_init_libproc(sigar_t *sigar) { if (sigar->plib) { return SIGAR_OK; } /* libproc.so ships with 5.8+ */ /* interface is undocumented, see libproc.h in the sun jdk sources */ sigar->plib = dlopen(LIBPROC, RTLD_LAZY); if (!sigar->plib) { sigar_log_printf(sigar, SIGAR_LOG_WARN, "[%s] dlopen(%s) = %s", SIGAR_FUNC, LIBPROC, dlerror()); return SIGAR_ENOTIMPL; } sigar->pgrab = (proc_grab_func_t)dlsym(sigar->plib, "Pgrab"); sigar->pfree = (proc_free_func_t)dlsym(sigar->plib, "Pfree"); sigar->pcreate_agent = (proc_create_agent_func_t)dlsym(sigar->plib, "Pcreate_agent"); sigar->pdestroy_agent = (proc_destroy_agent_func_t)dlsym(sigar->plib, "Pdestroy_agent"); sigar->pobjname = (proc_objname_func_t)dlsym(sigar->plib, "Pobjname"); sigar->pexename = (proc_exename_func_t)dlsym(sigar->plib, "Pexecname"); sigar->pdirname = (proc_dirname_func_t)dlsym(sigar->plib, "proc_dirname"); sigar->pfstat64 = (proc_fstat64_func_t)dlsym(sigar->plib, "pr_fstat64"); sigar->pgetsockopt = (proc_getsockopt_func_t)dlsym(sigar->plib, "pr_getsockopt"); sigar->pgetsockname = (proc_getsockname_func_t)dlsym(sigar->plib, "pr_getsockname"); CHECK_PSYM(pgrab); CHECK_PSYM(pfree); CHECK_PSYM(pobjname); return SIGAR_OK; } /* from libproc.h, not included w/ solaris distro */ /* Error codes from Pgrab(), Pfgrab_core(), and Pgrab_core() */ #define G_STRANGE -1 /* Unanticipated error, errno is meaningful */ #define G_NOPROC 1 /* No such process */ #define G_NOCORE 2 /* No such core file */ #define G_NOPROCORCORE 3 /* No such proc or core (for proc_arg_grab) */ #define G_NOEXEC 4 /* Cannot locate executable file */ #define G_ZOMB 5 /* Zombie process */ #define G_PERM 6 /* No permission */ #define G_BUSY 7 /* Another process has control */ #define G_SYS 8 /* System process */ #define G_SELF 9 /* Process is self */ #define G_INTR 10 /* Interrupt received while grabbing */ #define G_LP64 11 /* Process is _LP64, self is ILP32 */ #define G_FORMAT 12 /* File is not an ELF format core file */ #define G_ELF 13 /* Libelf error, elf_errno() is meaningful */ #define G_NOTE 14 /* Required PT_NOTE Phdr not present in core */ static int sigar_pgrab(sigar_t *sigar, sigar_pid_t pid, const char *func, struct ps_prochandle **phandle) { int pstatus; if (!(*phandle = sigar->pgrab(pid, 0x01, &pstatus))) { switch (pstatus) { case G_NOPROC: return ESRCH; case G_PERM: return EACCES; default: sigar_log_printf(sigar, SIGAR_LOG_ERROR, "[%s] Pgrab error=%d", func, pstatus); return ENOTSUP; /*XXX*/ } } return SIGAR_OK; } int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { return sigar_proc_list_procfs_get(sigar, proclist); } int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem) { int status = sigar_proc_psinfo_get(sigar, pid); psinfo_t *pinfo = sigar->pinfo; prusage_t usage; if (status != SIGAR_OK) { return status; } procmem->size = pinfo->pr_size << 10; procmem->resident = pinfo->pr_rssize << 10; procmem->share = SIGAR_FIELD_NOTIMPL; if (sigar_proc_usage_get(sigar, &usage, pid) == SIGAR_OK) { procmem->minor_faults = usage.pr_minf; procmem->major_faults = usage.pr_majf; procmem->page_faults = procmem->minor_faults + procmem->major_faults; } else { procmem->minor_faults = SIGAR_FIELD_NOTIMPL; procmem->major_faults = SIGAR_FIELD_NOTIMPL; procmem->page_faults = SIGAR_FIELD_NOTIMPL; } return SIGAR_OK; } int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred) { int status = sigar_proc_psinfo_get(sigar, pid); psinfo_t *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } proccred->uid = pinfo->pr_uid; proccred->gid = pinfo->pr_gid; proccred->euid = pinfo->pr_euid; proccred->egid = pinfo->pr_egid; return SIGAR_OK; } #define TIMESTRUCT_2MSEC(t) \ ((t.tv_sec * MILLISEC) + (t.tv_nsec / (NANOSEC/MILLISEC))) int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime) { prusage_t usage; int status; if ((status = sigar_proc_usage_get(sigar, &usage, pid)) != SIGAR_OK) { return status; } proctime->start_time = usage.pr_create.tv_sec + sigar->boot_time; proctime->start_time *= MILLISEC; if (usage.pr_utime.tv_sec < 0) { /* XXX wtf? seen on solaris 10, only for the self process */ pstatus_t pstatus; status = sigar_proc_status_get(sigar, &pstatus, pid); if (status != SIGAR_OK) { return status; } usage.pr_utime.tv_sec = pstatus.pr_utime.tv_sec; usage.pr_utime.tv_nsec = pstatus.pr_utime.tv_nsec; usage.pr_stime.tv_sec = pstatus.pr_stime.tv_sec; usage.pr_stime.tv_nsec = pstatus.pr_stime.tv_nsec; } proctime->user = TIMESTRUCT_2MSEC(usage.pr_utime); proctime->sys = TIMESTRUCT_2MSEC(usage.pr_stime); proctime->total = proctime->user + proctime->sys; return SIGAR_OK; } int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { int status = sigar_proc_psinfo_get(sigar, pid); psinfo_t *pinfo = sigar->pinfo; if (status != SIGAR_OK) { return status; } SIGAR_SSTRCPY(procstate->name, pinfo->pr_fname); procstate->ppid = pinfo->pr_ppid; procstate->tty = pinfo->pr_ttydev; procstate->priority = pinfo->pr_lwp.pr_pri; procstate->nice = pinfo->pr_lwp.pr_nice - NZERO; procstate->threads = pinfo->pr_nlwp; procstate->processor = pinfo->pr_lwp.pr_onpro; switch (pinfo->pr_lwp.pr_state) { case SONPROC: case SRUN: procstate->state = 'R'; break; case SZOMB: procstate->state = 'Z'; break; case SSLEEP: procstate->state = 'S'; break; case SSTOP: procstate->state = 'T'; break; case SIDL: procstate->state = 'D'; break; } return SIGAR_OK; } typedef struct { int timestamp; char *args; } pargs_t; static void pargs_free(void *value) { pargs_t *pargs = (pargs_t *)value; if (pargs->args != NULL) { free(pargs->args); } free(pargs); } static int ucb_ps_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs, int timestamp) { char buffer[9086], *args=NULL, *arg; sigar_cache_entry_t *ent; FILE *fp; pargs_t *pargs; if (!sigar->pargs) { sigar->pargs = sigar_cache_new(15); sigar->pargs->free_value = pargs_free; } ent = sigar_cache_get(sigar->pargs, pid); if (ent->value) { pargs = (pargs_t *)ent->value; if (pargs->timestamp != timestamp) { if (pargs->args) { free(pargs->args); pargs->args = NULL; } } } else { pargs = malloc(sizeof(*pargs)); pargs->args = NULL; ent->value = pargs; } pargs->timestamp = timestamp; if (pargs->args) { args = pargs->args; } else { snprintf(buffer, sizeof(buffer), SIGAR_USR_UCB_PS " -ww %ld", (long)pid); if (!(fp = popen(buffer, "r"))) { return errno; } /* skip header */ (void)fgets(buffer, sizeof(buffer), fp); if ((args = fgets(buffer, sizeof(buffer), fp))) { int len; /* skip PID,TT,S,TIME */ args = sigar_skip_multiple_token(args, 4); SIGAR_SKIP_SPACE(args); len = strlen(args); if (len > 0) { args[len-1] = '\0'; /* chop \n */ } pargs->args = malloc(len+1); memcpy(pargs->args, args, len); } pclose(fp); if (!args) { return ESRCH; } } while (*args && (arg = sigar_getword(&args, ' '))) { SIGAR_PROC_ARGS_GROW(procargs); procargs->data[procargs->number++] = arg; } return SIGAR_OK; } int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { psinfo_t *pinfo; int fd, status; char buffer[9086]; char *argvb[56]; char **argvp = argvb; int n; size_t nread = 0; unsigned int argv_size; if ((status = sigar_proc_psinfo_get(sigar, pid)) != SIGAR_OK) { return status; } pinfo = sigar->pinfo; if (pinfo->pr_argc == 0) { procargs->number = 0; return SIGAR_OK; } else if (pinfo->pr_dmodel != PR_MODEL_NATIVE) { /* we are compiled in 32bit mode * punt any 64bit native process, * sizeof our structures can't handle. */ if (sigar->use_ucb_ps) { return ucb_ps_args_get(sigar, pid, procargs, pinfo->pr_start.tv_sec); } else { return ENOTSUP; } } argv_size = sizeof(*argvp) * pinfo->pr_argc; (void)SIGAR_PROC_FILENAME(buffer, pid, "/as"); if ((fd = open(buffer, O_RDONLY)) < 0) { if ((errno == EACCES) && sigar->use_ucb_ps) { return ucb_ps_args_get(sigar, pid, procargs, pinfo->pr_start.tv_sec); } else { return PROC_ERRNO; } } if (argv_size > sizeof(argvb)) { argvp = malloc(argv_size); } if ((nread = pread(fd, argvp, argv_size, pinfo->pr_argv)) <= 0) { close(fd); if (argvp != argvb) { free(argvp); } return errno; } for (n = 0; n < pinfo->pr_argc; n++) { int alen; char *arg; if ((nread = pread(fd, buffer, sizeof(buffer)-1, (off_t)argvp[n])) <= 0) { close(fd); if (argvp != argvb) { free(argvp); } return errno; } buffer[nread] = '\0'; alen = strlen(buffer)+1; arg = malloc(alen); memcpy(arg, buffer, alen); SIGAR_PROC_ARGS_GROW(procargs); procargs->data[procargs->number++] = arg; } if (argvp != argvb) { free(argvp); } close(fd); return SIGAR_OK; } int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { psinfo_t *pinfo; int fd, status; char buffer[BUFSIZ], *offsets[512]; size_t nread; int n=0, max=sizeof(offsets)/sizeof(char *); if ((status = sigar_proc_psinfo_get(sigar, pid)) != SIGAR_OK) { return status; } pinfo = sigar->pinfo; (void)SIGAR_PROC_FILENAME(buffer, pid, "/as"); if ((fd = open(buffer, O_RDONLY)) < 0) { return PROC_ERRNO; } if ((nread = pread(fd, offsets, sizeof(offsets), pinfo->pr_envp)) <= 0) { close(fd); return errno; } while ((n < max) && offsets[n]) { char *val; int klen, vlen, status; char key[128]; /* XXX is there a max key size? */ if ((nread = pread(fd, buffer, sizeof(buffer), (off_t)offsets[n++])) <= 0) { close(fd); return errno; } val = strchr(buffer, '='); if (val == NULL) { break; /*XXX*/ } klen = val - buffer; SIGAR_SSTRCPY(key, buffer); key[klen] = '\0'; ++val; vlen = strlen(val); status = procenv->env_getter(procenv->data, key, klen, val, vlen); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } } close(fd); return SIGAR_OK; } int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd) { int status = sigar_proc_fd_count(sigar, pid, &procfd->total); return status; } static int sigar_proc_path_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { /* solaris 10+ */ char buffer[BUFSIZ]; (void)SIGAR_PROC_FILENAME(buffer, pid, "/path/a.out"); if (!proc_readlink(buffer, procexe->name, sizeof(procexe->name))) { procexe->name[0] = '\0'; } (void)SIGAR_PROC_FILENAME(buffer, pid, "/path/cwd"); if (!proc_readlink(buffer, procexe->cwd, sizeof(procexe->cwd))) { procexe->cwd[0] = '\0'; } (void)SIGAR_PROC_FILENAME(buffer, pid, "/path/root"); if (!proc_readlink(buffer, procexe->root, sizeof(procexe->root))) { procexe->root[0] = '\0'; } return SIGAR_OK; } static int proc_module_get_exe(void *data, char *name, int len) { sigar_proc_exe_t *procexe = (sigar_proc_exe_t *)data; SIGAR_STRNCPY(procexe->name, name, sizeof(procexe->name)); return !SIGAR_OK; /* break loop */ } static int sigar_which_exe_get(sigar_t *sigar, sigar_proc_exe_t *procexe) { char *path = getenv("PATH"); char exe[PATH_MAX]; if (path == NULL) { return EINVAL; } while (path) { char *ptr = strchr(path, ':'); if (!ptr) { break; } exe[0] = '\0'; strncat(exe, path, ptr-path); strncat(exe, "/", 1); strcat(exe, procexe->name); if (access(exe, X_OK) == 0) { SIGAR_STRNCPY(procexe->name, exe, sizeof(procexe->name)); break; } path = ptr+1; } return ENOENT; } int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { int status; char buffer[BUFSIZ]; struct ps_prochandle *phandle; if (sigar->solaris_version >= 10) { return sigar_proc_path_exe_get(sigar, pid, procexe); } if ((status = sigar_init_libproc(sigar)) != SIGAR_OK) { return status; } procexe->name[0] = '\0'; /* Pgrab would return G_SELF error */ if (pid == sigar_pid_get(sigar)) { sigar_proc_modules_t procmods; procmods.module_getter = proc_module_get_exe; procmods.data = procexe; status = sigar_dlinfo_modules(sigar, &procmods); if (status == SIGAR_OK) { if (procexe->name[0] != '/') { sigar_which_exe_get(sigar, procexe); } } } else { status = sigar_pgrab(sigar, pid, SIGAR_FUNC, &phandle); if (status == SIGAR_OK) { sigar->pexename(phandle, procexe->name, sizeof(procexe->name)); sigar->pfree(phandle); } } if (procexe->name[0] == '\0') { /*XXX*/ } (void)SIGAR_PROC_FILENAME(buffer, pid, "/cwd"); if (!sigar->pdirname(buffer, procexe->cwd, sizeof(procexe->cwd))) { procexe->cwd[0] = '\0'; } (void)SIGAR_PROC_FILENAME(buffer, pid, "/root"); if (!(sigar->pdirname(buffer, procexe->root, sizeof(procexe->root)))) { procexe->root[0] = '\0'; } return SIGAR_OK; } static int sigar_read_xmaps(sigar_t *sigar, prxmap_t *xmaps, int total, unsigned long *last_inode, struct ps_prochandle *phandle, sigar_proc_modules_t *procmods) { int status, i; unsigned long inode; char buffer[BUFSIZ]; for (i=0; ipobjname(phandle, xmaps[i].pr_vaddr, buffer, sizeof(buffer)); status = procmods->module_getter(procmods->data, buffer, strlen(buffer)); if (status != SIGAR_OK) { /* not an error; just stop iterating */ return status; } } return SIGAR_OK; } static int sigar_pgrab_modules(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { int fd, pstatus; off_t map_size, nread; unsigned long last_inode = 0; prxmap_t xmaps[15]; /* ~2K */ struct ps_prochandle *phandle; struct stat statbuf; char buffer[BUFSIZ]; (void)SIGAR_PROC_FILENAME(buffer, pid, "/xmap"); if ((fd = open(buffer, O_RDONLY)) < 0) { return errno; } if (fstat(fd, &statbuf) < 0) { close(fd); return errno; } map_size = statbuf.st_size; if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[%s] pid=%d, size=%d", SIGAR_FUNC, pid, map_size); } if ((pstatus = sigar_init_libproc(sigar)) != SIGAR_OK) { close(fd); return pstatus; } pstatus = sigar_pgrab(sigar, pid, SIGAR_FUNC, &phandle); if (pstatus != SIGAR_OK) { close(fd); return pstatus; } for (nread=0; nread sizeof(xmaps) ? sizeof(xmaps) : map_size; int total = wanted / sizeof(prxmap_t); if (pread(fd, xmaps, wanted, nread) != wanted) { close(fd); sigar->pfree(phandle); return errno; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[%s] nread=%d, map_size=%d, wanted=%d, total=%d", SIGAR_FUNC, nread, map_size, wanted, total); } if (sigar_read_xmaps(sigar, xmaps, total, &last_inode, phandle, procmods) != SIGAR_OK) { break; } nread += wanted; map_size -= wanted; } close(fd); sigar->pfree(phandle); return SIGAR_OK; } int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { if (pid == sigar_pid_get(sigar)) { /* Pgrab would return G_SELF, this is faster anyhow */ /* XXX one difference to Pgrab, first entry is not the exe name */ return sigar_dlinfo_modules(sigar, procmods); } else { return sigar_pgrab_modules(sigar, pid, procmods); } } #define TIME_NSEC(t) \ (SIGAR_SEC2NANO((t).tv_sec) + (sigar_uint64_t)(t).tv_nsec) int sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu) { struct lwpinfo info; if (id != 0) { return SIGAR_ENOTIMPL; } _lwp_info(&info); cpu->user = TIME_NSEC(info.lwp_utime); cpu->sys = TIME_NSEC(info.lwp_stime); cpu->total = TIME_NSEC(info.lwp_utime) + TIME_NSEC(info.lwp_stime); return SIGAR_OK; } #include int sigar_os_fs_type_get(sigar_file_system_t *fsp) { char *type = fsp->sys_type_name; switch (*type) { case 'u': if (strEQ(type, "ufs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; /* XXX */ } return fsp->type; } int sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist) { struct mnttab ent; sigar_file_system_t *fsp; FILE *fp = fopen(MNTTAB, "r"); if (!fp) { return errno; } sigar_file_system_list_create(fslist); while (getmntent(fp, &ent) == 0) { if (strstr(ent.mnt_mntopts, "ignore")) { continue; /* e.g. vold */ } SIGAR_FILE_SYSTEM_LIST_GROW(fslist); fsp = &fslist->data[fslist->number++]; SIGAR_SSTRCPY(fsp->dir_name, ent.mnt_mountp); SIGAR_SSTRCPY(fsp->dev_name, ent.mnt_special); SIGAR_SSTRCPY(fsp->sys_type_name, ent.mnt_fstype); SIGAR_SSTRCPY(fsp->options, ent.mnt_mntopts); sigar_fs_type_init(fsp); } fclose(fp); return SIGAR_OK; } typedef struct { char device[PATH_MAX]; char name[8]; int instance; } fsdev_path_t; typedef struct { char name[256]; int is_partition; sigar_disk_usage_t disk; } iodev_t; static fsdev_path_t *get_fsdev_paths(sigar_t *sigar, sigar_file_system_list_t *fslist) { int i, ndisk, size; char buffer[BUFSIZ], *ptr; char *dev, *inst, *drv; fsdev_path_t *paths, *mapping; FILE *fp = fopen("/etc/path_to_inst", "r"); if (!fp) { return NULL; } for (i=0, ndisk=0; inumber; i++) { sigar_file_system_t *fsp = &fslist->data[i]; if (fsp->type == SIGAR_FSTYPE_LOCAL_DISK) { ndisk++; } } size = sizeof(*paths) * (ndisk+1); mapping = paths = malloc(size); memset(mapping, '\0', size); while ((ptr = fgets(buffer, sizeof(buffer), fp))) { /* eat dust java */ char *q; SIGAR_SKIP_SPACE(ptr); if (*ptr == '#') { continue; } if (*ptr == '"') { ptr++; } dev = ptr; if (!(q = strchr(ptr, '"'))) { continue; } ptr = q+1; *q = '\0'; SIGAR_SKIP_SPACE(ptr); inst = ptr; while (sigar_isdigit(*ptr)) { ptr++; } *ptr = '\0'; ptr++; SIGAR_SKIP_SPACE(ptr); if (*ptr == '"') { ptr++; } drv = ptr; if (!(q = strchr(ptr, '"'))) { continue; } *q = '\0'; if (!(strEQ(drv, "sd") || strEQ(drv, "ssd") || strEQ(drv, "st") || strEQ(drv, "dad") || strEQ(drv, "cmdk"))) { continue; } paths->instance = atoi(inst); if (!kstat_lookup(sigar->kc, drv, paths->instance, NULL)) { continue; } SIGAR_SSTRCPY(paths->device, dev); SIGAR_SSTRCPY(paths->name, drv); if (--ndisk < 0) { /* XXX prevent overflow */ break; } paths++; } fclose(fp); return mapping; } static int create_fsdev_cache(sigar_t *sigar) { fsdev_path_t *paths, *mapping; sigar_file_system_list_t fslist; int i, j; int status; int debug = SIGAR_LOG_IS_DEBUG(sigar); sigar->fsdev = sigar_cache_new(15); status = sigar_file_system_list_get(sigar, &fslist); if (status != SIGAR_OK) { return status; } if (!(mapping = get_fsdev_paths(sigar, &fslist))) { sigar_file_system_list_destroy(sigar, &fslist); return ENOENT; } for (i=0; itype == SIGAR_FSTYPE_LOCAL_DISK) { char device[PATH_MAX+1], *ptr=device; int len = readlink(fsp->dev_name, device, sizeof(device)-1); char *s; char partition; if (len < 0) { continue; } device[len] = '\0'; if (debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fsdev] name=%s, dev=%s", fsp->dev_name, device); } while (strnEQ(ptr, "../", 3)) { ptr += 3; } if (strnEQ(ptr, "devices", 7)) { ptr += 7; } if ((s = strchr(ptr, ':'))) { partition = *(s+1); } else { continue; } for (j=0, paths=mapping; paths->name[0]; j++) { if (strnEQ(paths->device, ptr, strlen(paths->device))) { sigar_cache_entry_t *ent; struct stat sb; int retval = stat(fsp->dir_name, &sb); iodev_t *iodev; if (retval == 0) { iodev = malloc(sizeof(*iodev)); SIGAR_DISK_STATS_INIT(&iodev->disk); /* e.g. sd9,g * module == sd * instance == 9 * partition == 8 */ snprintf(iodev->name, sizeof(iodev->name), "%s%d,%c", paths->name, paths->instance, partition); ent = sigar_cache_get(sigar->fsdev, SIGAR_FSDEV_ID(sb)); ent->value = iodev; if (debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fsdev] map %s -> %s", fsp->dir_name, iodev->name); } } break; } paths++; } } } free(mapping); sigar_file_system_list_destroy(sigar, &fslist); return SIGAR_OK; } static int io_kstat_read(sigar_t *sigar, sigar_disk_usage_t *disk, kstat_t *ksp) { kstat_io_t *io; kstat_read(sigar->kc, ksp, NULL); io = (kstat_io_t *)ksp->ks_data; disk->reads = io->reads; disk->writes = io->writes; disk->read_bytes = io->nread; disk->write_bytes = io->nwritten; disk->qtime = io->wlentime; disk->rtime = io->rlentime; disk->wtime = io->wlentime; disk->time = disk->rtime + disk->wtime; disk->snaptime = ksp->ks_snaptime; return SIGAR_OK; } static int sigar_kstat_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *disk, kstat_t **kio) { kstat_t *ksp; if (sigar_kstat_update(sigar) == -1) { return errno; } for (ksp = sigar->kc->kc_chain; ksp; ksp = ksp->ks_next) { if (ksp->ks_type != KSTAT_TYPE_IO) { continue; } if (strEQ(ksp->ks_name, name)) { int status = io_kstat_read(sigar, disk, ksp); *kio = ksp; return status; } } return ENXIO; } static int simple_hash(const char *s) { int hash = 0; while (*s) { hash = 31*hash + *s++; } return hash; } int sigar_disk_usage_get(sigar_t *sigar, const char *name, sigar_disk_usage_t *disk) { kstat_t *ksp; int status; iodev_t *iodev = NULL; sigar_cache_entry_t *ent; sigar_uint64_t id; SIGAR_DISK_STATS_INIT(disk); if (!sigar->fsdev) { if (create_fsdev_cache(sigar) != SIGAR_OK) { return SIGAR_OK; } } if (*name == '/') { struct stat sb; if (stat(name, &sb) < 0) { return errno; } id = SIGAR_FSDEV_ID(sb); ent = sigar_cache_get(sigar->fsdev, id); if (ent->value == NULL) { return ENXIO; } iodev = (iodev_t *)ent->value; status = sigar_kstat_disk_usage_get(sigar, iodev->name, disk, &ksp); } else { status = sigar_kstat_disk_usage_get(sigar, name, disk, &ksp); if (status != SIGAR_OK) { return status; } id = simple_hash(name); /*XXX*/ ent = sigar_cache_get(sigar->fsdev, id); if (ent->value) { iodev = (iodev_t *)ent->value; } else { ent->value = iodev = malloc(sizeof(*iodev)); SIGAR_SSTRCPY(iodev->name, name); SIGAR_DISK_STATS_INIT(&iodev->disk); } } /* service_time formula derived from opensolaris.org:iostat.c */ if ((status == SIGAR_OK) && iodev) { sigar_uint64_t delta; double avw, avr, tps, mtps; double etime, hr_etime; if (iodev->disk.snaptime) { delta = disk->snaptime - iodev->disk.snaptime; } else { delta = ksp->ks_crtime - ksp->ks_snaptime; } hr_etime = (double)delta; if (hr_etime == 0.0) { hr_etime = (double)NANOSEC; } etime = hr_etime / (double)NANOSEC; tps = (((double)(disk->reads - iodev->disk.reads)) / etime) + (((double)(disk->writes - iodev->disk.writes)) / etime); delta = disk->wtime - iodev->disk.wtime; if (delta) { avw = (double)delta; avw /= hr_etime; } else { avw = 0.0; } delta = disk->rtime - iodev->disk.rtime; if (delta) { avr = (double)delta; avr /= hr_etime; } else { avr = 0.0; } disk->queue = avw; disk->service_time = 0.0; if (tps && (avw != 0.0 || avr != 0.0)) { mtps = 1000.0 / tps; if (avw != 0.0) { disk->service_time += avw * mtps; } if (avr != 0.0) { disk->service_time += avr * mtps; } } memcpy(&iodev->disk, disk, sizeof(iodev->disk)); } return status; } int sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { int status = sigar_statvfs(sigar, dirname, fsusage); if (status != SIGAR_OK) { return status; } fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage); sigar_disk_usage_get(sigar, dirname, &fsusage->disk); return SIGAR_OK; } int sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { processor_info_t stats; unsigned int i; int status = SIGAR_OK; int brand = -1; sigar_cache_t *chips; int is_debug = SIGAR_LOG_IS_DEBUG(sigar); int nsockets = 0; if (sigar_kstat_update(sigar) == -1) { /* for sigar->ncpu */ return errno; } /* * stats we care about will be the same for each * online processor, so just grab the first. */ for (i=0; incpu; i++) { processorid_t id = sigar->ks.cpuid[i]; if ((status = processor_info(id, &stats)) < 0) { continue; } else { status = SIGAR_OK; break; } } if (status != SIGAR_OK) { /* should never happen */ return ENOENT; } sigar_cpu_info_list_create(cpu_infos); chips = sigar_cache_new(16); chips->free_value = free_chip_id; for (i=0; incpu; i++) { sigar_cpu_info_t *info; int chip_id = get_chip_id(sigar, i); if (chip_id != -1) { sigar_cache_entry_t *ent = sigar_cache_get(chips, chip_id); if (ent->value) { if (!sigar->cpu_list_cores) { continue; } } else { ++nsockets; ent->value = chips; /*anything non-NULL*/ if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu_list] Merging info of" " logical processors for chip_id=%d", chip_id); } } } else { ++nsockets; } SIGAR_CPU_INFO_LIST_GROW(cpu_infos); info = &cpu_infos->data[cpu_infos->number++]; SIGAR_SSTRCPY(info->model, stats.pi_processor_type); if (brand == -1) { brand = get_chip_brand(sigar, i, info); } if (strEQ(info->model, "i386")) { if (!brand) { /* assume Intel on x86 */ SIGAR_SSTRCPY(info->vendor, "Intel"); } SIGAR_SSTRCPY(info->model, "x86"); } else { if (!brand) { /* assume Sun */ SIGAR_SSTRCPY(info->vendor, "Sun"); } /* s/sparc/Sparc/ */ info->model[0] = toupper(info->model[0]); } if (brand) { SIGAR_SSTRCPY(info->vendor, cpu_infos->data[0].vendor); } info->mhz = stats.pi_clock; info->cache_size = SIGAR_FIELD_NOTIMPL; /*XXX*/ } sigar_cache_destroy(chips); for (i=0; inumber; i++) { sigar_cpu_info_t *info = &cpu_infos->data[i]; info->total_sockets = nsockets; info->total_cores = sigar->ncpu; info->cores_per_socket = sigar->ncpu / nsockets; } return SIGAR_OK; } int sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist) { char *data; int len, rc; struct opthdr *op; size_t nread=0, size=0; const char *size_from; sigar_net_route_list_create(routelist); while ((rc = get_mib2(&sigar->mib2, &op, &data, &len)) == GET_MIB2_OK) { mib2_ipRouteEntry_t *entry; char *end; if (op->level != MIB2_IP) { continue; } if (op->name == 0) { /* we want to use this size for bincompat */ size = ((mib2_ip_t *)data)->ipRouteEntrySize; continue; } else if (op->name != MIB2_IP_21) { continue; } if (size == 0) { size_from = "sizeof"; size = sizeof(*entry); } else { size_from = "mib2_ip"; } if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[route_list] ipRouteEntrySize=%d (from %s)", size, size_from); } for (entry = (mib2_ipRouteEntry_t *)data, end = data + len; (char *)entry < end; nread+=size, entry = (mib2_ipRouteEntry_t *)((char *)data+nread)) { sigar_net_route_t *route; int type = entry->ipRouteInfo.re_ire_type; /* filter same as netstat -r */ if ((type == IRE_CACHE) || (type == IRE_BROADCAST) || (type == IRE_LOCAL)) { continue; } SIGAR_NET_ROUTE_LIST_GROW(routelist); route = &routelist->data[routelist->number++]; sigar_net_address_set(route->destination, entry->ipRouteDest); sigar_net_address_set(route->gateway, entry->ipRouteNextHop); sigar_net_address_set(route->mask, entry->ipRouteMask); route->refcnt = entry->ipRouteInfo.re_ref; route->irtt = entry->ipRouteInfo.re_rtt; route->metric = entry->ipRouteMetric1; SIGAR_SSTRCPY(route->ifname, entry->ipRouteIfIndex.o_bytes); route->flags = RTF_UP; if ((route->destination.addr.in == 0) && (route->mask.addr.in == 0)) { route->flags |= RTF_GATEWAY; } route->use = route->window = route->mtu = SIGAR_FIELD_NOTIMPL; /*XXX*/ } } if (rc != GET_MIB2_EOD) { close_mib2(&sigar->mib2); return SIGAR_EMIB2; } return SIGAR_OK; } static void ifstat_kstat_common(sigar_net_interface_stat_t *ifstat, kstat_named_t *data, int ndata) { int i; for (i=0; itx_collisions = value; } break; case 'd': if (strEQ(ptr, "drop")) { ifstat->rx_dropped = value; ifstat->tx_dropped = value; } break; case 'i': if (strEQ(ptr, "ipackets")) { if (ifstat->rx_packets == 0) { ifstat->rx_packets = value; } } else if (strEQ(ptr, "ipackets64")) { ifstat->rx_packets = data[i].value.ui64; } else if (strEQ(ptr, "ierrors")) { ifstat->rx_errors = value; } else if (strEQ(ptr, "ifspeed")) { ifstat->speed = value; } break; case 'f': if (strEQ(ptr, "framing")) { ifstat->rx_frame = value; } break; case 'm': if (strEQ(ptr, "missed")) { ifstat->rx_dropped = value; ifstat->tx_dropped = value; } break; case 'n': if (strEQ(ptr, "nocarrier")) { ifstat->tx_carrier = value; } break; case 'o': if (strEQ(ptr, "obytes")) { if (ifstat->tx_bytes == 0) { ifstat->tx_bytes = value; } } else if (strEQ(ptr, "obytes64")) { ifstat->tx_bytes = data[i].value.ui64; } else if (strEQ(ptr, "oerrors")) { ifstat->tx_errors = value; } else if (strEQ(ptr, "oflo")) { ifstat->tx_overruns = value; } else if (strEQ(ptr, "opackets")) { if (ifstat->tx_packets == 0) { ifstat->tx_packets = value; } } else if (strEQ(ptr, "opackets64")) { ifstat->tx_packets = data[i].value.ui64; } else if (strEQ(ptr, "toolong_errors")) { ifstat->tx_overruns = value; } break; case 'r': if (strEQ(ptr, "rbytes")) { if (ifstat->rx_bytes == 0) { ifstat->rx_bytes = value; } } else if (strEQ(ptr, "rbytes64")) { ifstat->rx_bytes = data[i].value.ui64; } else if (strEQ(ptr, "rx_overflow")) { ifstat->rx_overruns = value; } break; default: break; } } } static int sigar_net_ifstat_get_any(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { kstat_ctl_t *kc = sigar->kc; kstat_t *ksp; kstat_named_t *data; if (sigar_kstat_update(sigar) == -1) { return errno; } if (!(ksp = kstat_lookup(kc, NULL, -1, (char *)name))) { return ENXIO; } if (kstat_read(kc, ksp, NULL) < 0) { return ENOENT; } data = (kstat_named_t *)ksp->ks_data; ifstat_kstat_common(ifstat, data, ksp->ks_ndata); return SIGAR_OK; } /* loopback interface only has rx/tx packets */ static int sigar_net_ifstat_get_lo(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { ifstat->rx_packets = 0; ifstat->rx_bytes = SIGAR_FIELD_NOTIMPL; ifstat->rx_errors = SIGAR_FIELD_NOTIMPL; ifstat->rx_dropped = SIGAR_FIELD_NOTIMPL; ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->rx_frame = SIGAR_FIELD_NOTIMPL; ifstat->tx_packets = 0; ifstat->tx_bytes = SIGAR_FIELD_NOTIMPL; ifstat->tx_errors = SIGAR_FIELD_NOTIMPL; ifstat->tx_dropped = SIGAR_FIELD_NOTIMPL; ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->tx_collisions = SIGAR_FIELD_NOTIMPL; ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL; ifstat->speed = SIGAR_FIELD_NOTIMPL; return sigar_net_ifstat_get_any(sigar, name, ifstat); } int sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { ifstat->speed = SIGAR_FIELD_NOTIMPL; if (strnEQ(name, "lo", 2)) { return sigar_net_ifstat_get_lo(sigar, name, ifstat); } else { SIGAR_ZERO(ifstat); return sigar_net_ifstat_get_any(sigar, name, ifstat); } } #define TCPQ_SIZE(s) ((s) >= 0 ? (s) : 0) static int tcp_connection_get(sigar_net_connection_walker_t *walker, struct mib2_tcpConnEntry *entry, int len) { int flags = walker->flags; int status; char *end = (char *)entry + len; while ((char *)entry < end) { int state = entry->tcpConnEntryInfo.ce_state; if (((flags & SIGAR_NETCONN_SERVER) && (state == TCPS_LISTEN)) || ((flags & SIGAR_NETCONN_CLIENT) && (state != TCPS_LISTEN))) { sigar_net_connection_t conn; SIGAR_ZERO(&conn); sigar_net_address_set(conn.local_address, entry->tcpConnLocalAddress); sigar_net_address_set(conn.remote_address, entry->tcpConnRemAddress); conn.local_port = entry->tcpConnLocalPort; conn.remote_port = entry->tcpConnRemPort; conn.type = SIGAR_NETCONN_TCP; conn.send_queue = TCPQ_SIZE(entry->tcpConnEntryInfo.ce_snxt - entry->tcpConnEntryInfo.ce_suna - 1); conn.receive_queue = TCPQ_SIZE(entry->tcpConnEntryInfo.ce_rnxt - entry->tcpConnEntryInfo.ce_rack); switch (state) { case TCPS_CLOSED: conn.state = SIGAR_TCP_CLOSE; break; case TCPS_IDLE: conn.state = SIGAR_TCP_IDLE; break; case TCPS_BOUND: conn.state = SIGAR_TCP_BOUND; break; case TCPS_LISTEN: conn.state = SIGAR_TCP_LISTEN; break; case TCPS_SYN_SENT: conn.state = SIGAR_TCP_SYN_SENT; break; case TCPS_SYN_RCVD: conn.state = SIGAR_TCP_SYN_RECV; break; case TCPS_ESTABLISHED: conn.state = SIGAR_TCP_ESTABLISHED; break; case TCPS_CLOSE_WAIT: conn.state = SIGAR_TCP_CLOSE_WAIT; break; case TCPS_FIN_WAIT_1: conn.state = SIGAR_TCP_FIN_WAIT1; break; case TCPS_CLOSING: conn.state = SIGAR_TCP_CLOSING; break; case TCPS_LAST_ACK: conn.state = SIGAR_TCP_LAST_ACK; break; case TCPS_FIN_WAIT_2: conn.state = SIGAR_TCP_FIN_WAIT2; break; case TCPS_TIME_WAIT: conn.state = SIGAR_TCP_TIME_WAIT; break; default: conn.state = SIGAR_TCP_UNKNOWN; break; } status = walker->add_connection(walker, &conn); if (status != SIGAR_OK) { return status; } } entry++; } return SIGAR_OK; } static int udp_connection_get(sigar_net_connection_walker_t *walker, struct mib2_udpEntry *entry, int len) { int flags = walker->flags; int status; char *end = (char *)entry + len; while ((char *)entry < end) { int state = entry->udpEntryInfo.ue_state; /* XXX dunno if this state check is right */ if (((flags & SIGAR_NETCONN_SERVER) && (state == MIB2_UDP_idle)) || ((flags & SIGAR_NETCONN_CLIENT) && (state != MIB2_UDP_idle))) { sigar_net_connection_t conn; SIGAR_ZERO(&conn); sigar_net_address_set(conn.local_address, entry->udpLocalAddress); sigar_net_address_set(conn.remote_address, 0); conn.local_port = entry->udpLocalPort; conn.remote_port = 0; conn.type = SIGAR_NETCONN_UDP; status = walker->add_connection(walker, &conn); if (status != SIGAR_OK) { return status; } } entry++; } return SIGAR_OK; } int sigar_net_connection_walk(sigar_net_connection_walker_t *walker) { sigar_t *sigar = walker->sigar; int flags = walker->flags; int status; int want_tcp = flags & SIGAR_NETCONN_TCP; int want_udp = flags & SIGAR_NETCONN_UDP; char *data; int len; int rc; struct opthdr *op; while ((rc = get_mib2(&sigar->mib2, &op, &data, &len)) == GET_MIB2_OK) { if ((op->level == MIB2_TCP) && (op->name == MIB2_TCP_13) && want_tcp) { status = tcp_connection_get(walker, (struct mib2_tcpConnEntry *)data, len); } else if ((op->level == MIB2_UDP) && (op->name == MIB2_UDP_5) && want_udp) { status = udp_connection_get(walker, (struct mib2_udpEntry *)data, len); } else { status = SIGAR_OK; } if (status != SIGAR_OK) { break; } } if (rc != GET_MIB2_EOD) { close_mib2(&sigar->mib2); return SIGAR_EMIB2; } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp) { char *data; int len; int rc; struct opthdr *op; mib2_tcp_t *mib = NULL; while ((rc = get_mib2(&sigar->mib2, &op, &data, &len)) == GET_MIB2_OK) { if ((op->level == MIB2_TCP) && (op->name == 0)) { mib = (mib2_tcp_t *)data; break; } } if (mib) { tcp->active_opens = mib->tcpActiveOpens; tcp->passive_opens = mib->tcpPassiveOpens; tcp->attempt_fails = mib->tcpAttemptFails; tcp->estab_resets = mib->tcpEstabResets; tcp->curr_estab = mib->tcpCurrEstab; tcp->in_segs = mib->tcpInSegs; tcp->out_segs = mib->tcpOutSegs; tcp->retrans_segs = mib->tcpRetransSegs; tcp->in_errs = SIGAR_FIELD_NOTIMPL; /* XXX mib2_ip_t.tcpInErrs */ tcp->out_rsts = mib->tcpOutRsts; return SIGAR_OK; } else { return SIGAR_ENOTIMPL; } } static int sigar_nfs_get(sigar_t *sigar, char *type, char **names, char *nfs) { size_t offset; kstat_t *ksp; int i; if (sigar_kstat_update(sigar) == -1) { return errno; } if (!(ksp = kstat_lookup(sigar->kc, "nfs", 0, type))) { return SIGAR_ENOTIMPL; } if (kstat_read(sigar->kc, ksp, NULL) < 0) { return errno; } for (i=0, offset=0; names[i]; i++, offset+=sizeof(sigar_uint64_t)) { sigar_uint64_t val; kstat_named_t *kv = kstat_data_lookup(ksp, names[i]); if (kv) { val = kv->value.ui64; } else { val = -1; } *(sigar_uint64_t *)((char *)nfs + offset) = val; } return SIGAR_OK; } static char *nfs_v2_names[] = { "null", "getattr", "setattr", "root", "lookup", "readlink", "read", "wrcache", "write", "create", "remove", "rename", "link", "symlink", "mkdir", "rmdir", "readdir", "statfs", NULL }; int sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs) { return sigar_nfs_get(sigar, "rfsreqcnt_v2", nfs_v2_names, (char *)nfs); } int sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs) { return sigar_nfs_get(sigar, "rfsproccnt_v2", nfs_v2_names, (char *)nfs); } static char *nfs_v3_names[] = { "null", "getattr", "setattr", "lookup", "access", "readlink", "read", "write", "create", "mkdir", "symlink", "mknod", "remove", "rmdir", "rename", "link", "readdir", "readdirplus", "fsstat", "fsinfo", "pathconf", "commit", NULL }; int sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs) { return sigar_nfs_get(sigar, "rfsreqcnt_v3", nfs_v3_names, (char *)nfs); } int sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs) { return sigar_nfs_get(sigar, "rfsproccnt_v3", nfs_v3_names, (char *)nfs); } static int find_port(sigar_t *sigar, struct ps_prochandle *phandle, sigar_pid_t pid, unsigned long port) { DIR *dirp; struct dirent *ent; char pname[PATH_MAX]; struct stat64 statb; int found=0; sprintf(pname, "/proc/%d/fd", (int)pid); if (!(dirp = opendir(pname))) { return 0; } while ((ent = readdir(dirp))) { int fd; if (!sigar_isdigit(ent->d_name[0])) { continue; } fd = atoi(ent->d_name); if (sigar->pfstat64(phandle, fd, &statb) == -1) { continue; } if ((statb.st_mode & S_IFMT) == S_IFSOCK) { struct sockaddr_in sin; struct sockaddr *sa = (struct sockaddr *)&sin; socklen_t len = sizeof(sin); int opt, optsz, rc; optsz = sizeof(opt); rc = sigar->pgetsockopt(phandle, fd, SOL_SOCKET, SO_TYPE, &opt, &optsz); if (rc != 0) { continue; } if (opt != SOCK_STREAM) { continue; } optsz = sizeof(opt); rc = sigar->pgetsockopt(phandle, fd, SOL_SOCKET, SO_ACCEPTCONN, &opt, &optsz); if (rc != 0) { continue; } if (opt != SO_ACCEPTCONN) { continue; } rc = sigar->pgetsockname(phandle, fd, sa, &len); if (rc != 0) { continue; } if ((sa->sa_family == AF_INET) || (sa->sa_family == AF_INET6)) { if (ntohs(sin.sin_port) == port) { found = 1; break; } } } } closedir(dirp); return found; } /* derived from /usr/bin/pfiles.c */ int sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid) { sigar_proc_list_t pids; int i, status, found=0; if (sigar->solaris_version < 10) { return SIGAR_ENOTIMPL; } if ((status = sigar_init_libproc(sigar)) != SIGAR_OK) { return SIGAR_ENOTIMPL; } status = sigar_proc_list_get(sigar, &pids); if (status != SIGAR_OK) { return status; } for (i=0; ipcreate_agent(phandle) == 0) { found = find_port(sigar, phandle, ps_id, port); sigar->pdestroy_agent(phandle); } sigar->pfree(phandle); if (found) { *pid = ps_id; break; } } sigar_proc_list_destroy(sigar, &pids); return found ? SIGAR_OK : ENOENT; } int sigar_os_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sys_info) { char *vendor_version; sysinfo(SI_ARCHITECTURE, sys_info->arch, sizeof(sys_info->arch)); SIGAR_SSTRCPY(sys_info->name, "Solaris"); SIGAR_SSTRCPY(sys_info->vendor, "Sun Microsystems"); if (strEQ(sys_info->version, "5.6")) { vendor_version = "2.6"; } else { if ((vendor_version = strchr(sys_info->version, '.'))) { ++vendor_version; } else { vendor_version = sys_info->version; } } SIGAR_SSTRCPY(sys_info->vendor_version, vendor_version); snprintf(sys_info->description, sizeof(sys_info->description), "%s %s", sys_info->name, sys_info->vendor_version); return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/os/win32/000077500000000000000000000000001210132627500173605ustar00rootroot00000000000000hyperic-sigar-1.6.4+dfsg/src/os/win32/peb.c000066400000000000000000000123211210132627500202710ustar00rootroot00000000000000/* * Copyright (c) 2004, 2006-2008 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. */ /* * functions for getting info from the Process Environment Block */ #define UNICODE #define _UNICODE #include "sigar.h" #include "sigar_private.h" #include "sigar_os.h" #include void dllmod_init_ntdll(sigar_t *sigar); #define sigar_NtQueryInformationProcess \ sigar->ntdll.query_proc_info.func static int sigar_pbi_get(sigar_t *sigar, HANDLE proc, PEB *peb) { int status; PROCESS_BASIC_INFORMATION pbi; DWORD size=sizeof(pbi); dllmod_init_ntdll(sigar); if (!sigar_NtQueryInformationProcess) { return SIGAR_ENOTIMPL; } SIGAR_ZERO(&pbi); status = sigar_NtQueryInformationProcess(proc, ProcessBasicInformation, &pbi, size, NULL); if (status != ERROR_SUCCESS) { return status; } if (!pbi.PebBaseAddress) { /* likely we are 32-bit, pid process is 64-bit */ return ERROR_DATATYPE_MISMATCH; } size = sizeof(*peb); if (ReadProcessMemory(proc, pbi.PebBaseAddress, peb, size, NULL)) { return SIGAR_OK; } else { return GetLastError(); } } static int sigar_rtl_get(sigar_t *sigar, HANDLE proc, RTL_USER_PROCESS_PARAMETERS *rtl) { PEB peb; int status = sigar_pbi_get(sigar, proc, &peb); DWORD size=sizeof(*rtl); if (status != SIGAR_OK) { return status; } if (ReadProcessMemory(proc, peb.ProcessParameters, rtl, size, NULL)) { return SIGAR_OK; } else { return GetLastError(); } } #define rtl_bufsize(buf, uc) \ ((sizeof(buf) < uc.Length) ? sizeof(buf) : uc.Length) int sigar_proc_exe_peb_get(sigar_t *sigar, HANDLE proc, sigar_proc_exe_t *procexe) { int status; WCHAR buf[MAX_PATH+1]; RTL_USER_PROCESS_PARAMETERS rtl; DWORD size; procexe->name[0] = '\0'; procexe->cwd[0] = '\0'; if ((status = sigar_rtl_get(sigar, proc, &rtl)) != SIGAR_OK) { return status; } size = rtl_bufsize(buf, rtl.ImagePathName); memset(buf, '\0', sizeof(buf)); if ((size > 0) && ReadProcessMemory(proc, rtl.ImagePathName.Buffer, buf, size, NULL)) { SIGAR_W2A(buf, procexe->name, sizeof(procexe->name)); } size = rtl_bufsize(buf, rtl.CurrentDirectoryName); memset(buf, '\0', sizeof(buf)); if ((size > 0) && ReadProcessMemory(proc, rtl.CurrentDirectoryName.Buffer, buf, size, NULL)) { SIGAR_W2A(buf, procexe->cwd, sizeof(procexe->cwd)); } return SIGAR_OK; } int sigar_parse_proc_args(sigar_t *sigar, WCHAR *buf, sigar_proc_args_t *procargs) { char arg[SIGAR_CMDLINE_MAX]; LPWSTR *args; int num, i; if (!buf) { buf = GetCommandLine(); } args = CommandLineToArgvW(buf, &num); if (args == NULL) { return SIGAR_OK; } for (i=0; idata[procargs->number++] = sigar_strdup(arg); } GlobalFree(args); return SIGAR_OK; } int sigar_proc_args_peb_get(sigar_t *sigar, HANDLE proc, sigar_proc_args_t *procargs) { int status; WCHAR buf[SIGAR_CMDLINE_MAX]; RTL_USER_PROCESS_PARAMETERS rtl; DWORD size; if ((status = sigar_rtl_get(sigar, proc, &rtl)) != SIGAR_OK) { return status; } size = rtl_bufsize(buf, rtl.CommandLine); if (size <= 0) { return ERROR_DATATYPE_MISMATCH; /* fallback to wmi */ } memset(buf, '\0', sizeof(buf)); if (ReadProcessMemory(proc, rtl.CommandLine.Buffer, buf, size, NULL)) { return sigar_parse_proc_args(sigar, buf, procargs); } else { return GetLastError(); } } int sigar_proc_env_peb_get(sigar_t *sigar, HANDLE proc, WCHAR *buf, DWORD size) { int status; RTL_USER_PROCESS_PARAMETERS rtl; MEMORY_BASIC_INFORMATION info; if ((status = sigar_rtl_get(sigar, proc, &rtl)) != SIGAR_OK) { return status; } memset(buf, '\0', size); /* -2 to ensure \0\0 terminator */ size -= 2; if (VirtualQueryEx(proc, rtl.Environment, &info, sizeof(info))) { if (size > info.RegionSize) { /* ReadProcessMemory beyond region would fail */ size = info.RegionSize; } } if (ReadProcessMemory(proc, rtl.Environment, buf, size, NULL)) { return SIGAR_OK; } else { return GetLastError(); } } hyperic-sigar-1.6.4+dfsg/src/os/win32/sigar.rc.in000066400000000000000000000021571210132627500214250ustar00rootroot00000000000000#define SIGAR_VERSION_CSV \ @@VERSION_MAJOR@@,@@VERSION_MINOR@@,@@VERSION_MAINT@@,@@VERSION_BUILD@@ #define SIGAR_VERSION_STR \ "@@VERSION_MAJOR@@.@@VERSION_MINOR@@.@@VERSION_MAINT@@.@@VERSION_BUILD@@" #define SIGAR_ARCHLIB "@@ARCHLIB@@" 1 VERSIONINFO FILEVERSION SIGAR_VERSION_CSV PRODUCTVERSION SIGAR_VERSION_CSV FILEFLAGSMASK 0x3fL FILEFLAGS 0x00L #if defined(WINNT) || defined(WIN64) FILEOS 0x40004L #else FILEOS 0x4L #endif FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "Comments", "http://sigar.hyperic.com/\0" VALUE "CompanyName", "Hyperic, Inc.\0" VALUE "FileDescription", "System Information Gatherer And Reporter DLL\0" VALUE "FileVersion", SIGAR_VERSION_STR "\0" VALUE "InternalName", "sigar.dll\0" VALUE "LegalCopyright", "Copyright [@@COPYRIGHT_YEAR@@], Hyperic, Inc.\0" VALUE "OriginalFilename", SIGAR_ARCHLIB "\0" VALUE "ProductName", "Hyperic SIGAR\0" VALUE "ProductVersion", SIGAR_VERSION_STR "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END hyperic-sigar-1.6.4+dfsg/src/os/win32/sigar_os.h000066400000000000000000000441271210132627500213470ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #if _MSC_VER <= 1200 #define SIGAR_USING_MSC6 /* Visual Studio version 6 */ #endif #define WIN32_LEAN_AND_MEAN #include #include #include #include #include #include #include #include #include #include #include #include "sigar_util.h" #define INT64_C(val) val##i64 /* see apr/include/arch/win32/atime.h */ #define EPOCH_DELTA INT64_C(11644473600000000) #define SIGAR_CMDLINE_MAX 4096 /* XXX: support CP_UTF8 ? */ #define SIGAR_A2W(lpa, lpw, bytes) \ (lpw[0] = 0, MultiByteToWideChar(CP_ACP, 0, \ lpa, -1, lpw, (bytes/sizeof(WCHAR)))) #define SIGAR_W2A(lpw, lpa, chars) \ (lpa[0] = '\0', WideCharToMultiByte(CP_ACP, 0, \ lpw, -1, (LPSTR)lpa, chars, \ NULL, NULL)) /* iptypes.h from vc7, not available in vc6 */ /* copy from PSDK if using vc6 */ #include "iptypes.h" /* from wtsapi32.h not in vs6.0 */ typedef enum { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType, } WTS_INFO_CLASS; typedef enum _WTS_CONNECTSTATE_CLASS { WTSActive, WTSConnected, WTSConnectQuery, WTSShadow, WTSDisconnected, WTSIdle, WTSListen, WTSReset, WTSDown, WTSInit } WTS_CONNECTSTATE_CLASS; #define WTS_PROTOCOL_TYPE_CONSOLE 0 #define WTS_PROTOCOL_TYPE_ICA 1 #define WTS_PROTOCOL_TYPE_RDP 2 typedef struct _WTS_SESSION_INFO { DWORD SessionId; LPTSTR pWinStationName; DWORD State; } WTS_SESSION_INFO, *PWTS_SESSION_INFO; typedef struct _WTS_PROCESS_INFO { DWORD SessionId; DWORD ProcessId; LPSTR pProcessName; PSID pUserSid; } WTS_PROCESS_INFO, *PWTS_PROCESS_INFO; typedef struct _WTS_CLIENT_ADDRESS { DWORD AddressFamily; BYTE Address[20]; } WTS_CLIENT_ADDRESS, *PWTS_CLIENT_ADDRESS; /* the WINSTATION_INFO stuff here is undocumented * got the howto from google groups: * http://redirx.com/?31gy */ typedef enum _WINSTATION_INFO_CLASS { WinStationInformation = 8 } WINSTATION_INFO_CLASS; typedef struct _WINSTATION_INFO { BYTE Reserved1[72]; ULONG SessionId; BYTE Reserved2[4]; FILETIME ConnectTime; FILETIME DisconnectTime; FILETIME LastInputTime; FILETIME LoginTime; BYTE Reserved3[1096]; FILETIME CurrentTime; } WINSTATION_INFO, *PWINSTATION_INFO; /* end wtsapi32.h */ #ifdef SIGAR_USING_MSC6 /* from winbase.h not in vs6.0 */ typedef struct { DWORD dwLength; DWORD dwMemoryLoad; DWORDLONG ullTotalPhys; DWORDLONG ullAvailPhys; DWORDLONG ullTotalPageFile; DWORDLONG ullAvailPageFile; DWORDLONG ullTotalVirtual; DWORDLONG ullAvailVirtual; DWORDLONG ullAvailExtendedVirtual; } MEMORYSTATUSEX; /* service manager stuff not in vs6.0 */ typedef struct _SERVICE_STATUS_PROCESS { DWORD dwServiceType; DWORD dwCurrentState; DWORD dwControlsAccepted; DWORD dwWin32ExitCode; DWORD dwServiceSpecificExitCode; DWORD dwCheckPoint; DWORD dwWaitHint; DWORD dwProcessId; DWORD dwServiceFlags; } SERVICE_STATUS_PROCESS; typedef enum { SC_STATUS_PROCESS_INFO = 0 } SC_STATUS_TYPE; #ifndef ERROR_DATATYPE_MISMATCH #define ERROR_DATATYPE_MISMATCH 1629L #endif #endif /* _MSC_VER */ #include /* undocumented structures */ typedef struct { DWORD dwState; DWORD dwLocalAddr; DWORD dwLocalPort; DWORD dwRemoteAddr; DWORD dwRemotePort; DWORD dwProcessId; } MIB_TCPEXROW, *PMIB_TCPEXROW; typedef struct { DWORD dwNumEntries; MIB_TCPEXROW table[ANY_SIZE]; } MIB_TCPEXTABLE, *PMIB_TCPEXTABLE; typedef struct { DWORD dwLocalAddr; DWORD dwLocalPort; DWORD dwProcessId; } MIB_UDPEXROW, *PMIB_UDPEXROW; typedef struct { DWORD dwNumEntries; MIB_UDPEXROW table[ANY_SIZE]; } MIB_UDPEXTABLE, *PMIB_UDPEXTABLE; /* end undocumented structures */ /* no longer in the standard header files */ typedef struct { LARGE_INTEGER IdleTime; LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER DpcTime; LARGE_INTEGER InterruptTime; ULONG InterruptCount; } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; #define SystemProcessorPerformanceInformation 8 /* PEB decls from msdn docs w/ slight mods */ #define ProcessBasicInformation 0 typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef struct _PEB_LDR_DATA { BYTE Reserved1[8]; PVOID Reserved2[3]; LIST_ENTRY InMemoryOrderModuleList; } PEB_LDR_DATA, *PPEB_LDR_DATA; typedef struct RTL_DRIVE_LETTER_CURDIR { USHORT Flags; USHORT Length; ULONG TimeStamp; UNICODE_STRING DosPath; } RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR; /* from: http://source.winehq.org/source/include/winternl.h */ typedef struct _RTL_USER_PROCESS_PARAMETERS { ULONG AllocationSize; ULONG Size; ULONG Flags; ULONG DebugFlags; HANDLE hConsole; ULONG ProcessGroup; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; UNICODE_STRING CurrentDirectoryName; HANDLE CurrentDirectoryHandle; UNICODE_STRING DllPath; UNICODE_STRING ImagePathName; UNICODE_STRING CommandLine; PWSTR Environment; ULONG dwX; ULONG dwY; ULONG dwXSize; ULONG dwYSize; ULONG dwXCountChars; ULONG dwYCountChars; ULONG dwFillAttribute; ULONG dwFlags; ULONG wShowWindow; UNICODE_STRING WindowTitle; UNICODE_STRING Desktop; UNICODE_STRING ShellInfo; UNICODE_STRING RuntimeInfo; RTL_DRIVE_LETTER_CURDIR DLCurrentDirectory[0x20]; } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; /* from msdn docs typedef struct _RTL_USER_PROCESS_PARAMETERS { BYTE Reserved1[16]; PVOID Reserved2[10]; UNICODE_STRING ImagePathName; UNICODE_STRING CommandLine; } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; */ typedef struct _PEB { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; PVOID Reserved3[2]; PPEB_LDR_DATA Ldr; PRTL_USER_PROCESS_PARAMETERS ProcessParameters; BYTE Reserved4[104]; PVOID Reserved5[52]; /*PPS_POST_PROCESS_INIT_ROUTINE*/ PVOID PostProcessInitRoutine; BYTE Reserved6[128]; PVOID Reserved7[1]; ULONG SessionId; } PEB, *PPEB; typedef struct _PROCESS_BASIC_INFORMATION { PVOID Reserved1; PPEB PebBaseAddress; PVOID Reserved2[2]; /*ULONG_PTR*/ UINT_PTR UniqueProcessId; PVOID Reserved3; } PROCESS_BASIC_INFORMATION; typedef struct { sigar_pid_t pid; int ppid; int priority; time_t mtime; sigar_uint64_t size; sigar_uint64_t resident; char name[SIGAR_PROC_NAME_LEN]; char state; sigar_uint64_t handles; sigar_uint64_t threads; sigar_uint64_t page_faults; } sigar_win32_pinfo_t; typedef struct { const char *name; HINSTANCE handle; } sigar_dll_handle_t; typedef struct { const char *name; FARPROC func; } sigar_dll_func_t; typedef struct { const char *name; HINSTANCE handle; sigar_dll_func_t funcs[12]; } sigar_dll_module_t; /* wtsapi.dll */ typedef BOOL (CALLBACK *wtsapi_enum_sessions)(HANDLE, DWORD, DWORD, PWTS_SESSION_INFO *, DWORD *); typedef void (CALLBACK *wtsapi_free_mem)(PVOID); typedef BOOL (CALLBACK *wtsapi_query_session)(HANDLE, DWORD, WTS_INFO_CLASS, LPSTR *, DWORD *); /* iphlpapi.dll */ typedef DWORD (CALLBACK *iphlpapi_get_ipforward_table)(PMIB_IPFORWARDTABLE, PULONG, BOOL); typedef DWORD (CALLBACK *iphlpapi_get_ipaddr_table)(PMIB_IPADDRTABLE, PULONG, BOOL); typedef DWORD (CALLBACK *iphlpapi_get_if_table)(PMIB_IFTABLE, PULONG, BOOL); typedef DWORD (CALLBACK *iphlpapi_get_if_entry)(PMIB_IFROW); typedef DWORD (CALLBACK *iphlpapi_get_num_if)(PDWORD); typedef DWORD (CALLBACK *iphlpapi_get_tcp_table)(PMIB_TCPTABLE, PDWORD, BOOL); typedef DWORD (CALLBACK *iphlpapi_get_udp_table)(PMIB_UDPTABLE, PDWORD, BOOL); typedef DWORD (CALLBACK *iphlpapi_get_tcpx_table)(PMIB_TCPEXTABLE *, BOOL, HANDLE, DWORD, DWORD); typedef DWORD (CALLBACK *iphlpapi_get_udpx_table)(PMIB_UDPEXTABLE *, BOOL, HANDLE, DWORD, DWORD); typedef DWORD (CALLBACK *iphlpapi_get_tcp_stats)(PMIB_TCPSTATS); typedef DWORD (CALLBACK *iphlpapi_get_net_params)(PFIXED_INFO, PULONG); typedef DWORD (CALLBACK *iphlpapi_get_adapters_info)(PIP_ADAPTER_INFO, PULONG); typedef ULONG (CALLBACK *iphlpapi_get_adapters_addrs)(ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG); /* advapi32.dll */ typedef BOOL (CALLBACK *advapi_convert_string_sid)(LPCSTR, PSID *); typedef BOOL (CALLBACK *advapi_query_service_status)(SC_HANDLE, SC_STATUS_TYPE, LPBYTE, DWORD, LPDWORD); /* ntdll.dll */ typedef DWORD (CALLBACK *ntdll_query_sys_info)(DWORD, PVOID, ULONG, PULONG); typedef DWORD (CALLBACK *ntdll_query_proc_info)(HANDLE, DWORD, PVOID, ULONG, PULONG); /* psapi.dll */ typedef BOOL (CALLBACK *psapi_enum_modules)(HANDLE, HMODULE *, DWORD, LPDWORD); typedef DWORD (CALLBACK *psapi_get_module_name)(HANDLE, HMODULE, LPTSTR, DWORD); typedef BOOL (CALLBACK *psapi_enum_processes)(DWORD *, DWORD, DWORD *); /* winsta.dll */ typedef BOOLEAN (CALLBACK *winsta_query_info)(HANDLE, ULONG, WINSTATION_INFO_CLASS, PVOID, ULONG, PULONG); /* kernel32.dll */ typedef BOOL (CALLBACK *kernel_memory_status)(MEMORYSTATUSEX *); /* mpr.dll */ typedef BOOL (CALLBACK *mpr_get_net_connection)(LPCTSTR, LPTSTR, LPDWORD); #define SIGAR_DLLFUNC(api, name) \ struct { \ const char *name; \ ##api##_##name func; \ } ##name typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(wtsapi, enum_sessions); SIGAR_DLLFUNC(wtsapi, free_mem); SIGAR_DLLFUNC(wtsapi, query_session); sigar_dll_func_t end; } sigar_wtsapi_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(iphlpapi, get_ipforward_table); SIGAR_DLLFUNC(iphlpapi, get_ipaddr_table); SIGAR_DLLFUNC(iphlpapi, get_if_table); SIGAR_DLLFUNC(iphlpapi, get_if_entry); SIGAR_DLLFUNC(iphlpapi, get_num_if); SIGAR_DLLFUNC(iphlpapi, get_tcp_table); SIGAR_DLLFUNC(iphlpapi, get_udp_table); SIGAR_DLLFUNC(iphlpapi, get_tcpx_table); SIGAR_DLLFUNC(iphlpapi, get_udpx_table); SIGAR_DLLFUNC(iphlpapi, get_tcp_stats); SIGAR_DLLFUNC(iphlpapi, get_net_params); SIGAR_DLLFUNC(iphlpapi, get_adapters_info); SIGAR_DLLFUNC(iphlpapi, get_adapters_addrs); sigar_dll_func_t end; } sigar_iphlpapi_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(advapi, convert_string_sid); SIGAR_DLLFUNC(advapi, query_service_status); sigar_dll_func_t end; } sigar_advapi_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(ntdll, query_sys_info); SIGAR_DLLFUNC(ntdll, query_proc_info); sigar_dll_func_t end; } sigar_ntdll_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(psapi, enum_modules); SIGAR_DLLFUNC(psapi, enum_processes); SIGAR_DLLFUNC(psapi, get_module_name); sigar_dll_func_t end; } sigar_psapi_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(winsta, query_info); sigar_dll_func_t end; } sigar_winsta_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(kernel, memory_status); sigar_dll_func_t end; } sigar_kernel_t; typedef struct { sigar_dll_handle_t handle; SIGAR_DLLFUNC(mpr, get_net_connection); sigar_dll_func_t end; } sigar_mpr_t; struct sigar_t { SIGAR_T_BASE; char *machine; int using_wide; long pagesize; HKEY handle; char *perfbuf; DWORD perfbuf_size; sigar_wtsapi_t wtsapi; sigar_iphlpapi_t iphlpapi; sigar_advapi_t advapi; sigar_ntdll_t ntdll; sigar_psapi_t psapi; sigar_winsta_t winsta; sigar_kernel_t kernel; sigar_mpr_t mpr; sigar_win32_pinfo_t pinfo; sigar_cache_t *netif_adapters; sigar_cache_t *netif_mib_rows; sigar_cache_t *netif_addr_rows; sigar_cache_t *netif_names; /* dwIndex -> net_interface_config.name */ WORD ws_version; int ws_error; int ht_enabled; int lcpu; //number of logical cpus int winnt; }; #ifdef __cplusplus extern "C" { #endif sigar_uint64_t sigar_FileTimeToTime(FILETIME *ft); int sigar_wsa_init(sigar_t *sigar); int sigar_proc_exe_peb_get(sigar_t *sigar, HANDLE proc, sigar_proc_exe_t *procexe); int sigar_proc_args_peb_get(sigar_t *sigar, HANDLE proc, sigar_proc_args_t *procargs); int sigar_proc_env_peb_get(sigar_t *sigar, HANDLE proc, WCHAR *env, DWORD envlen); int sigar_proc_args_wmi_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs); int sigar_proc_exe_wmi_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe); int sigar_parse_proc_args(sigar_t *sigar, WCHAR *buf, sigar_proc_args_t *procargs); int sigar_service_pid_get(sigar_t *sigar, char *name, sigar_pid_t *pid); typedef struct { DWORD size; DWORD count; ENUM_SERVICE_STATUS *services; SC_HANDLE handle; } sigar_services_status_t; int sigar_services_status_get(sigar_services_status_t *ss, DWORD state); void sigar_services_status_close(sigar_services_status_t *ss); typedef struct sigar_services_walker_t sigar_services_walker_t; struct sigar_services_walker_t { sigar_t *sigar; int flags; void *data; /* user data */ int (*add_service)(sigar_services_walker_t *walker, char *name); }; int sigar_services_query(char *ptql, sigar_ptql_error_t *error, sigar_services_walker_t *walker); char *sigar_service_exe_get(char *path, char *buffer, int basename); typedef struct { WORD product_major; WORD product_minor; WORD product_build; WORD product_revision; WORD file_major; WORD file_minor; WORD file_build; WORD file_revision; } sigar_file_version_t; int sigar_file_version_get(sigar_file_version_t *version, char *name, sigar_proc_env_t *infocb); #ifdef __cplusplus } #endif #define SIGAR_NO_SUCH_PROCESS (SIGAR_OS_START_ERROR+1) #endif /* SIGAR_OS_H */ hyperic-sigar-1.6.4+dfsg/src/os/win32/sigar_pdh.h000066400000000000000000000030771210132627500215000ustar00rootroot00000000000000/* * Copyright (c) 2004, 2006 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. */ #ifndef SIGAR_PDH_H #define SIGAR_PDH_H /* performance data helpers */ #define PdhFirstObject(block) \ ((PERF_OBJECT_TYPE *)((BYTE *) block + block->HeaderLength)) #define PdhNextObject(object) \ ((PERF_OBJECT_TYPE *)((BYTE *) object + object->TotalByteLength)) #define PdhFirstCounter(object) \ ((PERF_COUNTER_DEFINITION *)((BYTE *) object + object->HeaderLength)) #define PdhNextCounter(counter) \ ((PERF_COUNTER_DEFINITION *)((BYTE *) counter + counter->ByteLength)) #define PdhGetCounterBlock(inst) \ ((PERF_COUNTER_BLOCK *)((BYTE *) inst + inst->ByteLength)) #define PdhFirstInstance(object) \ ((PERF_INSTANCE_DEFINITION *)((BYTE *) object + object->DefinitionLength)) #define PdhNextInstance(inst) \ ((PERF_INSTANCE_DEFINITION *)((BYTE *)inst + inst->ByteLength + \ PdhGetCounterBlock(inst)->ByteLength)) #define PdhInstanceName(inst) \ ((wchar_t *)((BYTE *)inst + inst->NameOffset)) #endif /* SIGAR_PDH_H */ hyperic-sigar-1.6.4+dfsg/src/os/win32/win32_sigar.c000066400000000000000000003061771210132627500216710ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009-2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.h" #include "sigar_private.h" #include "sigar_pdh.h" #include "sigar_os.h" #include "sigar_util.h" #include #define USING_WIDE_S(s) (s)->using_wide #define USING_WIDE() USING_WIDE_S(sigar) #define PERFBUF_SIZE 8192 #define PERF_TITLE_PROC 230 #define PERF_TITLE_SYS_KEY "2" #define PERF_TITLE_MEM_KEY "4" #define PERF_TITLE_PROC_KEY "230" #define PERF_TITLE_CPU_KEY "238" #define PERF_TITLE_DISK_KEY "236" #define PERF_TITLE_CPU_USER 142 #define PERF_TITLE_CPU_IDLE 1746 #define PERF_TITLE_CPU_SYS 144 #define PERF_TITLE_CPU_IRQ 698 typedef enum { PERF_IX_CPU_USER, PERF_IX_CPU_IDLE, PERF_IX_CPU_SYS, PERF_IX_CPU_IRQ, PERF_IX_CPU_MAX } perf_cpu_offsets_t; #define PERF_TITLE_CPUTIME 6 #define PERF_TITLE_PAGE_FAULTS 28 #define PERF_TITLE_MEM_VSIZE 174 #define PERF_TITLE_MEM_SIZE 180 #define PERF_TITLE_THREAD_CNT 680 #define PERF_TITLE_HANDLE_CNT 952 #define PERF_TITLE_PID 784 #define PERF_TITLE_PPID 1410 #define PERF_TITLE_PRIORITY 682 #define PERF_TITLE_START_TIME 684 typedef enum { PERF_IX_CPUTIME, PERF_IX_PAGE_FAULTS, PERF_IX_MEM_VSIZE, PERF_IX_MEM_SIZE, PERF_IX_THREAD_CNT, PERF_IX_HANDLE_CNT, PERF_IX_PID, PERF_IX_PPID, PERF_IX_PRIORITY, PERF_IX_START_TIME, PERF_IX_MAX } perf_proc_offsets_t; typedef enum { PERF_IX_DISK_TIME, PERF_IX_DISK_READ_TIME, PERF_IX_DISK_WRITE_TIME, PERF_IX_DISK_READ, PERF_IX_DISK_WRITE, PERF_IX_DISK_READ_BYTES, PERF_IX_DISK_WRITE_BYTES, PERF_IX_DISK_QUEUE, PERF_IX_DISK_MAX } perf_disk_offsets_t; #define PERF_TITLE_DISK_TIME 200 /* % Disk Time */ #define PERF_TITLE_DISK_READ_TIME 202 /* % Disk Read Time */ #define PERF_TITLE_DISK_WRITE_TIME 204 /* % Disk Write Time */ #define PERF_TITLE_DISK_READ 214 /* Disk Reads/sec */ #define PERF_TITLE_DISK_WRITE 216 /* Disk Writes/sec */ #define PERF_TITLE_DISK_READ_BYTES 220 /* Disk Read Bytes/sec */ #define PERF_TITLE_DISK_WRITE_BYTES 222 /* Disk Write Bytes/sec */ #define PERF_TITLE_DISK_QUEUE 198 /* Current Disk Queue Length */ /* * diff is: * ExW -> ExA * wcounter -> counter */ #define MyRegQueryValue() \ (USING_WIDE() ? \ RegQueryValueExW(sigar->handle, \ wcounter_key, NULL, &type, \ sigar->perfbuf, \ &bytes) : \ RegQueryValueExA(sigar->handle, \ counter_key, NULL, &type, \ sigar->perfbuf, \ &bytes)) #define PERF_VAL(ix) \ perf_offsets[ix] ? \ *((DWORD *)((BYTE *)counter_block + perf_offsets[ix])) : 0 /* 1/100ns units to milliseconds */ #define NS100_2MSEC(t) ((t) / 10000) #define PERF_VAL_CPU(ix) \ NS100_2MSEC(PERF_VAL(ix)) #define MS_LOOPBACK_ADAPTER "Microsoft Loopback Adapter" #define NETIF_LA "la" sigar_uint64_t sigar_FileTimeToTime(FILETIME *ft) { sigar_uint64_t time; time = ft->dwHighDateTime; time = time << 32; time |= ft->dwLowDateTime; time /= 10; time -= EPOCH_DELTA; return time; } static DWORD perfbuf_init(sigar_t *sigar) { if (!sigar->perfbuf) { sigar->perfbuf = malloc(PERFBUF_SIZE); sigar->perfbuf_size = PERFBUF_SIZE; } return sigar->perfbuf_size; } static DWORD perfbuf_grow(sigar_t *sigar) { sigar->perfbuf_size += PERFBUF_SIZE; sigar->perfbuf = realloc(sigar->perfbuf, sigar->perfbuf_size); return sigar->perfbuf_size; } static char *get_counter_name(char *key) { if (strEQ(key, PERF_TITLE_MEM_KEY)) { return "Memory"; } else if (strEQ(key, PERF_TITLE_PROC_KEY)) { return "Process"; } else if (strEQ(key, PERF_TITLE_CPU_KEY)) { return "Processor"; } else if (strEQ(key, PERF_TITLE_DISK_KEY)) { return "LogicalDisk"; } else { return key; } } static PERF_OBJECT_TYPE *get_perf_object_inst(sigar_t *sigar, char *counter_key, DWORD inst, DWORD *err) { DWORD retval, type, bytes; WCHAR wcounter_key[MAX_PATH+1]; PERF_DATA_BLOCK *block; PERF_OBJECT_TYPE *object; *err = SIGAR_OK; if (USING_WIDE()) { SIGAR_A2W(counter_key, wcounter_key, sizeof(wcounter_key)); } bytes = perfbuf_init(sigar); while ((retval = MyRegQueryValue()) != ERROR_SUCCESS) { if (retval == ERROR_MORE_DATA) { bytes = perfbuf_grow(sigar); } else { *err = retval; return NULL; } } block = (PERF_DATA_BLOCK *)sigar->perfbuf; if (block->NumObjectTypes == 0) { counter_key = get_counter_name(counter_key); sigar_strerror_printf(sigar, "No %s counters defined (disabled?)", counter_key); *err = -1; return NULL; } object = PdhFirstObject(block); /* * only seen on windows 2003 server when pdh.dll * functions are in use by the same process. * confucius say what the fuck. */ if (inst && (object->NumInstances == PERF_NO_INSTANCES)) { int i; for (i=0; iNumObjectTypes; i++) { if (object->NumInstances != PERF_NO_INSTANCES) { return object; } object = PdhNextObject(object); } return NULL; } else { return object; } } #define get_perf_object(sigar, counter_key, err) \ get_perf_object_inst(sigar, counter_key, 1, err) static int get_mem_counters(sigar_t *sigar, sigar_swap_t *swap, sigar_mem_t *mem) { int status; PERF_OBJECT_TYPE *object = get_perf_object_inst(sigar, PERF_TITLE_MEM_KEY, 0, &status); PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; BYTE *data; DWORD i; if (!object) { return status; } data = (BYTE *)((BYTE *)object + object->DefinitionLength); for (i=0, counter = PdhFirstCounter(object); iNumCounters; i++, counter = PdhNextCounter(counter)) { DWORD offset = counter->CounterOffset; switch (counter->CounterNameTitleIndex) { case 48: /* "Pages Output/sec" */ if (swap) swap->page_out = *((DWORD *)(data + offset)); break; case 76: /* "System Cache Resident Bytes" aka file cache */ if (mem) { sigar_uint64_t kern = *((DWORD *)(data + offset)); mem->actual_free = mem->free + kern; mem->actual_used = mem->used - kern; return SIGAR_OK; } case 822: /* "Pages Input/sec" */ if (swap) swap->page_in = *((DWORD *)(data + offset)); break; default: continue; } } return SIGAR_OK; } static void get_sysinfo(sigar_t *sigar) { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); sigar->ncpu = sysinfo.dwNumberOfProcessors; sigar->pagesize = sysinfo.dwPageSize; } /* for C# bindings */ SIGAR_DECLARE(sigar_t *) sigar_new(void) { sigar_t *sigar; if (sigar_open(&sigar) != SIGAR_OK) { return NULL; } return sigar; } static sigar_wtsapi_t sigar_wtsapi = { "wtsapi32.dll", NULL, { "WTSEnumerateSessionsA", NULL }, { "WTSFreeMemory", NULL }, { "WTSQuerySessionInformationA", NULL }, { NULL, NULL } }; static sigar_iphlpapi_t sigar_iphlpapi = { "iphlpapi.dll", NULL, { "GetIpForwardTable", NULL }, { "GetIpAddrTable", NULL }, { "GetIfTable", NULL }, { "GetIfEntry", NULL }, { "GetNumberOfInterfaces", NULL }, { "GetTcpTable", NULL }, { "GetUdpTable", NULL }, { "AllocateAndGetTcpExTableFromStack", NULL }, { "AllocateAndGetUdpExTableFromStack", NULL }, { "GetTcpStatistics", NULL }, { "GetNetworkParams", NULL }, { "GetAdaptersInfo", NULL }, { "GetAdaptersAddresses", NULL }, { NULL, NULL } }; static sigar_advapi_t sigar_advapi = { "advapi32.dll", NULL, { "ConvertStringSidToSidA", NULL }, { "QueryServiceStatusEx", NULL }, { NULL, NULL } }; static sigar_ntdll_t sigar_ntdll = { "ntdll.dll", NULL, { "NtQuerySystemInformation", NULL }, { "NtQueryInformationProcess", NULL }, { NULL, NULL } }; static sigar_psapi_t sigar_psapi = { "psapi.dll", NULL, { "EnumProcessModules", NULL }, { "EnumProcesses", NULL }, { "GetModuleFileNameExA", NULL }, { NULL, NULL } }; static sigar_psapi_t sigar_winsta = { "winsta.dll", NULL, { "WinStationQueryInformationW", NULL }, { NULL, NULL } }; static sigar_psapi_t sigar_kernel = { "kernel32.dll", NULL, { "GlobalMemoryStatusEx", NULL }, { NULL, NULL } }; static sigar_mpr_t sigar_mpr = { "mpr.dll", NULL, { "WNetGetConnectionA", NULL }, { NULL, NULL } }; #define DLLMOD_COPY(name) \ memcpy(&(sigar->##name), &sigar_##name, sizeof(sigar_##name)) #define DLLMOD_INIT(name, all) \ sigar_dllmod_init(sigar, (sigar_dll_module_t *)&(sigar->##name), all) #define DLLMOD_FREE(name) \ sigar_dllmod_free((sigar_dll_module_t *)&(sigar->##name)) static void sigar_dllmod_free(sigar_dll_module_t *module) { if (module->handle) { FreeLibrary(module->handle); module->handle = NULL; } } static int sigar_dllmod_init(sigar_t *sigar, sigar_dll_module_t *module, int all) { sigar_dll_func_t *funcs = &module->funcs[0]; int is_debug = SIGAR_LOG_IS_DEBUG(sigar); int rc, success; if (module->handle == INVALID_HANDLE_VALUE) { return ENOENT; /* XXX better rc */ } if (module->handle) { return SIGAR_OK; } module->handle = LoadLibrary(module->name); if (!(success = (module->handle ? TRUE : FALSE))) { rc = GetLastError(); /* dont try again */ module->handle = INVALID_HANDLE_VALUE; } if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "LoadLibrary(%s): %s", module->name, success ? "OK" : sigar_strerror(sigar, rc)); } if (!success) { return rc; } while (funcs->name) { funcs->func = GetProcAddress(module->handle, funcs->name); if (!(success = (funcs->func ? TRUE : FALSE))) { rc = GetLastError(); } if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetProcAddress(%s:%s): %s", module->name, funcs->name, success ? "OK" : sigar_strerror(sigar, rc)); } if (all && !success) { return rc; } funcs++; } return SIGAR_OK; } int sigar_wsa_init(sigar_t *sigar) { if (sigar->ws_version == 0) { WSADATA data; if (WSAStartup(MAKEWORD(2, 0), &data)) { sigar->ws_error = WSAGetLastError(); WSACleanup(); return sigar->ws_error; } sigar->ws_version = data.wVersion; } return SIGAR_OK; } static int sigar_enable_privilege(char *name) { int status; HANDLE handle; TOKEN_PRIVILEGES tok; SIGAR_ZERO(&tok); if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &handle)) { return GetLastError(); } if (LookupPrivilegeValue(NULL, name, &tok.Privileges[0].Luid)) { tok.PrivilegeCount = 1; tok.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (AdjustTokenPrivileges(handle, FALSE, &tok, 0, NULL, 0)) { status = SIGAR_OK; } else { status = GetLastError(); } } else { status = GetLastError(); } CloseHandle(handle); return status; } int sigar_os_open(sigar_t **sigar_ptr) { LONG result; HINSTANCE h; OSVERSIONINFO version; int i; sigar_t *sigar; *sigar_ptr = sigar = malloc(sizeof(*sigar)); sigar->machine = ""; /* local machine */ sigar->using_wide = 0; /*XXX*/ sigar->perfbuf = NULL; sigar->perfbuf_size = 0; version.dwOSVersionInfoSize = sizeof(version); GetVersionEx(&version); /* * 4 == NT 4.0 * 5 == 2000, XP, 2003 Server */ sigar->winnt = (version.dwMajorVersion == 4); if (USING_WIDE_S(sigar)) { WCHAR wmachine[MAX_PATH+1]; SIGAR_A2W(sigar->machine, wmachine, sizeof(wmachine)); result = RegConnectRegistryW(wmachine, HKEY_PERFORMANCE_DATA, &sigar->handle); } else { result = RegConnectRegistryA(sigar->machine, HKEY_PERFORMANCE_DATA, &sigar->handle); } get_sysinfo(sigar); DLLMOD_COPY(wtsapi); DLLMOD_COPY(iphlpapi); DLLMOD_COPY(advapi); DLLMOD_COPY(ntdll); DLLMOD_COPY(psapi); DLLMOD_COPY(winsta); DLLMOD_COPY(kernel); DLLMOD_COPY(mpr); sigar->log_level = -1; /* else below segfaults */ /* XXX init early for use by javasigar.c */ sigar_dllmod_init(sigar, (sigar_dll_module_t *)&sigar->advapi, FALSE); sigar->netif_mib_rows = NULL; sigar->netif_addr_rows = NULL; sigar->netif_adapters = NULL; sigar->netif_names = NULL; sigar->pinfo.pid = -1; sigar->ws_version = 0; sigar->lcpu = -1; /* increase process visibility */ sigar_enable_privilege(SE_DEBUG_NAME); return result; } void dllmod_init_ntdll(sigar_t *sigar) { DLLMOD_INIT(ntdll, FALSE); } int sigar_os_close(sigar_t *sigar) { int retval; DLLMOD_FREE(wtsapi); DLLMOD_FREE(iphlpapi); DLLMOD_FREE(advapi); DLLMOD_FREE(ntdll); DLLMOD_FREE(psapi); DLLMOD_FREE(winsta); DLLMOD_FREE(kernel); DLLMOD_FREE(mpr); if (sigar->perfbuf) { free(sigar->perfbuf); } retval = RegCloseKey(sigar->handle); if (sigar->ws_version != 0) { WSACleanup(); } if (sigar->netif_mib_rows) { sigar_cache_destroy(sigar->netif_mib_rows); } if (sigar->netif_addr_rows) { sigar_cache_destroy(sigar->netif_addr_rows); } if (sigar->netif_adapters) { sigar_cache_destroy(sigar->netif_adapters); } if (sigar->netif_names) { sigar_cache_destroy(sigar->netif_names); } free(sigar); return retval; } char *sigar_os_error_string(sigar_t *sigar, int err) { switch (err) { case SIGAR_NO_SUCH_PROCESS: return "No such process"; break; } return NULL; } #define sigar_GlobalMemoryStatusEx \ sigar->kernel.memory_status.func SIGAR_DECLARE(int) sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem) { DLLMOD_INIT(kernel, TRUE); if (sigar_GlobalMemoryStatusEx) { MEMORYSTATUSEX memstat; memstat.dwLength = sizeof(memstat); if (!sigar_GlobalMemoryStatusEx(&memstat)) { return GetLastError(); } mem->total = memstat.ullTotalPhys; mem->free = memstat.ullAvailPhys; } else { MEMORYSTATUS memstat; GlobalMemoryStatus(&memstat); mem->total = memstat.dwTotalPhys; mem->free = memstat.dwAvailPhys; } mem->used = mem->total - mem->free; mem->actual_free = mem->free; mem->actual_used = mem->used; /* set actual_{free,used} */ get_mem_counters(sigar, NULL, mem); sigar_mem_calc_ram(sigar, mem); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap) { int status; DLLMOD_INIT(kernel, TRUE); if (sigar_GlobalMemoryStatusEx) { MEMORYSTATUSEX memstat; memstat.dwLength = sizeof(memstat); if (!sigar_GlobalMemoryStatusEx(&memstat)) { return GetLastError(); } swap->total = memstat.ullTotalPageFile; swap->free = memstat.ullAvailPageFile; } else { MEMORYSTATUS memstat; GlobalMemoryStatus(&memstat); swap->total = memstat.dwTotalPageFile; swap->free = memstat.dwAvailPageFile; } swap->used = swap->total - swap->free; if (get_mem_counters(sigar, swap, NULL) != SIGAR_OK) { swap->page_in = SIGAR_FIELD_NOTIMPL; swap->page_out = SIGAR_FIELD_NOTIMPL; } return SIGAR_OK; } static PERF_INSTANCE_DEFINITION *get_cpu_instance(sigar_t *sigar, DWORD *perf_offsets, DWORD *num, DWORD *err) { PERF_OBJECT_TYPE *object = get_perf_object(sigar, PERF_TITLE_CPU_KEY, err); PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; DWORD i; if (!object) { return NULL; } for (i=0, counter = PdhFirstCounter(object); iNumCounters; i++, counter = PdhNextCounter(counter)) { DWORD offset = counter->CounterOffset; switch (counter->CounterNameTitleIndex) { case PERF_TITLE_CPU_SYS: perf_offsets[PERF_IX_CPU_SYS] = offset; break; case PERF_TITLE_CPU_USER: perf_offsets[PERF_IX_CPU_USER] = offset; break; case PERF_TITLE_CPU_IDLE: perf_offsets[PERF_IX_CPU_IDLE] = offset; break; case PERF_TITLE_CPU_IRQ: perf_offsets[PERF_IX_CPU_IRQ] = offset; break; } } if (num) { *num = object->NumInstances; } return PdhFirstInstance(object); } #define SPPI_MAX 128 /* XXX unhardcode; should move off this api anyhow */ #define sigar_NtQuerySystemInformation \ sigar->ntdll.query_sys_info.func static int get_idle_cpu(sigar_t *sigar, sigar_cpu_t *cpu, DWORD idx, PERF_COUNTER_BLOCK *counter_block, DWORD *perf_offsets) { cpu->idle = 0; if (perf_offsets[PERF_IX_CPU_IDLE]) { cpu->idle = PERF_VAL_CPU(PERF_IX_CPU_IDLE); } else { /* windows NT and 2000 do not have an Idle counter */ DLLMOD_INIT(ntdll, FALSE); if (sigar_NtQuerySystemInformation) { DWORD retval, num; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION info[SPPI_MAX]; /* into the lungs of hell */ sigar_NtQuerySystemInformation(SystemProcessorPerformanceInformation, &info, sizeof(info), &retval); if (!retval) { return GetLastError(); } num = retval/sizeof(info[0]); if (idx == -1) { int i; for (i=0; iidle += NS100_2MSEC(info[i].IdleTime.QuadPart); } } else if (idx < num) { cpu->idle = NS100_2MSEC(info[idx].IdleTime.QuadPart); } else { return ERROR_INVALID_DATA; } } else { return ERROR_INVALID_FUNCTION; } } return SIGAR_OK; } static int sigar_cpu_perflib_get(sigar_t *sigar, sigar_cpu_t *cpu) { int status; PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_BLOCK *counter_block; DWORD perf_offsets[PERF_IX_CPU_MAX], err; SIGAR_ZERO(cpu); memset(&perf_offsets, 0, sizeof(perf_offsets)); inst = get_cpu_instance(sigar, (DWORD*)&perf_offsets, 0, &err); if (!inst) { return err; } /* first instance is total, rest are per-cpu */ counter_block = PdhGetCounterBlock(inst); cpu->sys = PERF_VAL_CPU(PERF_IX_CPU_SYS); cpu->user = PERF_VAL_CPU(PERF_IX_CPU_USER); status = get_idle_cpu(sigar, cpu, -1, counter_block, perf_offsets); cpu->irq = PERF_VAL_CPU(PERF_IX_CPU_IRQ); cpu->nice = 0; /* no nice here */ cpu->wait = 0; /*N/A?*/ cpu->total = cpu->sys + cpu->user + cpu->idle + cpu->wait + cpu->irq; if (status != SIGAR_OK) { sigar_log_printf(sigar, SIGAR_LOG_WARN, "unable to determine idle cpu time: %s", sigar_strerror(sigar, status)); } return SIGAR_OK; } static int sigar_cpu_ntsys_get(sigar_t *sigar, sigar_cpu_t *cpu) { DWORD retval, num; int i; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION info[SPPI_MAX]; /* into the lungs of hell */ sigar_NtQuerySystemInformation(SystemProcessorPerformanceInformation, &info, sizeof(info), &retval); if (!retval) { return GetLastError(); } num = retval/sizeof(info[0]); SIGAR_ZERO(cpu); for (i=0; iidle += NS100_2MSEC(info[i].IdleTime.QuadPart); cpu->user += NS100_2MSEC(info[i].UserTime.QuadPart); cpu->sys += NS100_2MSEC(info[i].KernelTime.QuadPart - info[i].IdleTime.QuadPart); cpu->irq += NS100_2MSEC(info[i].InterruptTime.QuadPart); cpu->total += cpu->idle + cpu->user + cpu->sys; } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu) { DLLMOD_INIT(ntdll, FALSE); if (sigar_NtQuerySystemInformation) { return sigar_cpu_ntsys_get(sigar, cpu); } else { return sigar_cpu_perflib_get(sigar, cpu); } } static int sigar_cpu_list_perflib_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { int status, i, j; PERF_INSTANCE_DEFINITION *inst; DWORD perf_offsets[PERF_IX_CPU_MAX], num, err; int core_rollup = sigar_cpu_core_rollup(sigar); memset(&perf_offsets, 0, sizeof(perf_offsets)); /* first instance is total, rest are per-cpu */ inst = get_cpu_instance(sigar, (DWORD*)&perf_offsets, &num, &err); if (!inst) { return err; } if (!sigar->winnt) { /* skip Processor _Total instance (NT doesnt have one) */ --num; inst = PdhNextInstance(inst); } sigar_cpu_list_create(cpulist); /* verify there's a counter for each logical cpu */ if (core_rollup && (sigar->ncpu != num)) { core_rollup = 0; } for (i=0; ilcpu)) { /* merge times of logical processors */ cpu = &cpulist->data[cpulist->number-1]; } else { SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; SIGAR_ZERO(cpu); } counter_block = PdhGetCounterBlock(inst); cpu->sys += PERF_VAL_CPU(PERF_IX_CPU_SYS); cpu->user += PERF_VAL_CPU(PERF_IX_CPU_USER); cpu->irq += PERF_VAL_CPU(PERF_IX_CPU_IRQ); get_idle_cpu(sigar, cpu, i, counter_block, perf_offsets); cpu->nice = cpu->wait = 0; /*N/A*/ /*XXX adding up too much here if xeon, but not using this atm*/ cpu->total += cpu->sys + cpu->user + cpu->idle + cpu->irq; inst = PdhNextInstance(inst); } return SIGAR_OK; } static int sigar_cpu_list_ntsys_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { DWORD retval, num; int status, i, j; int core_rollup = sigar_cpu_core_rollup(sigar); SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION info[SPPI_MAX]; /* into the lungs of hell */ sigar_NtQuerySystemInformation(SystemProcessorPerformanceInformation, &info, sizeof(info), &retval); if (!retval) { return GetLastError(); } num = retval/sizeof(info[0]); sigar_cpu_list_create(cpulist); /* verify there's a counter for each logical cpu */ if (core_rollup && (sigar->ncpu != num)) { core_rollup = 0; } for (i=0; ilcpu)) { /* merge times of logical processors */ cpu = &cpulist->data[cpulist->number-1]; } else { SIGAR_CPU_LIST_GROW(cpulist); cpu = &cpulist->data[cpulist->number++]; SIGAR_ZERO(cpu); } idle = NS100_2MSEC(info[i].IdleTime.QuadPart); user = NS100_2MSEC(info[i].UserTime.QuadPart); sys = NS100_2MSEC(info[i].KernelTime.QuadPart - info[i].IdleTime.QuadPart); cpu->idle += idle; cpu->user += user; cpu->sys += sys; cpu->nice = cpu->wait = 0; /*N/A*/ cpu->total += idle + user + sys; } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist) { DLLMOD_INIT(ntdll, FALSE); if (sigar_NtQuerySystemInformation) { return sigar_cpu_list_ntsys_get(sigar, cpulist); } else { return sigar_cpu_list_perflib_get(sigar, cpulist); } } #define PERF_TITLE_UPTIME_KEY 674 /* System Up Time */ SIGAR_DECLARE(int) sigar_uptime_get(sigar_t *sigar, sigar_uptime_t *uptime) { int status; PERF_OBJECT_TYPE *object = get_perf_object_inst(sigar, PERF_TITLE_SYS_KEY, 0, &status); PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; BYTE *data; DWORD i; if (!object) { return status; } data = (BYTE *)((BYTE *)object + object->DefinitionLength); for (i=0, counter = PdhFirstCounter(object); iNumCounters; i++, counter = PdhNextCounter(counter)) { if (counter->CounterNameTitleIndex == PERF_TITLE_UPTIME_KEY) { DWORD offset = counter->CounterOffset; LONGLONG time = object->PerfTime.QuadPart; LONGLONG freq = object->PerfFreq.QuadPart; LONGLONG counter = *((LONGLONG *)(data + offset)); uptime->uptime = (time - counter) / freq; return SIGAR_OK; } } /* http://msdn.microsoft.com/en-us/library/ms724408.aspx */ return GetTickCount() / 1000; } /* * there is no api for this info. * closest i've seen is enumerating the entire process table * and calculating an average based on process times. */ SIGAR_DECLARE(int) sigar_loadavg_get(sigar_t *sigar, sigar_loadavg_t *loadavg) { return SIGAR_ENOTIMPL; } #define get_process_object(sigar, err) \ get_perf_object(sigar, PERF_TITLE_PROC_KEY, err) static int sigar_proc_list_get_perf(sigar_t *sigar, sigar_proc_list_t *proclist) { PERF_OBJECT_TYPE *object; PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; DWORD i, err; DWORD perf_offsets[PERF_IX_MAX]; perf_offsets[PERF_IX_PID] = 0; object = get_process_object(sigar, &err); if (!object) { return err; } /* * note we assume here: * block->NumObjectTypes == 1 * object->ObjectNameTitleIndex == PERF_TITLE_PROC * * which should always be the case. */ for (i=0, counter = PdhFirstCounter(object); iNumCounters; i++, counter = PdhNextCounter(counter)) { DWORD offset = counter->CounterOffset; switch (counter->CounterNameTitleIndex) { case PERF_TITLE_PID: perf_offsets[PERF_IX_PID] = offset; break; } } for (i=0, inst = PdhFirstInstance(object); iNumInstances; i++, inst = PdhNextInstance(inst)) { PERF_COUNTER_BLOCK *counter_block = PdhGetCounterBlock(inst); DWORD pid = PERF_VAL(PERF_IX_PID); if (pid == 0) { continue; /* dont include the system Idle process */ } SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = pid; } return SIGAR_OK; } #define sigar_EnumProcesses \ sigar->psapi.enum_processes.func int sigar_os_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { DLLMOD_INIT(psapi, FALSE); if (sigar_EnumProcesses) { DWORD retval, *pids; DWORD size = 0, i; do { /* re-use the perfbuf */ if (size == 0) { size = perfbuf_init(sigar); } else { size = perfbuf_grow(sigar); } if (!sigar_EnumProcesses((DWORD *)sigar->perfbuf, sigar->perfbuf_size, &retval)) { return GetLastError(); } } while (retval == sigar->perfbuf_size); //unlikely pids = (DWORD *)sigar->perfbuf; size = retval / sizeof(DWORD); for (i=0; idata[proclist->number++] = pid; } return SIGAR_OK; } else { return sigar_proc_list_get_perf(sigar, proclist); } } #define PROCESS_DAC (PROCESS_QUERY_INFORMATION|PROCESS_VM_READ) static HANDLE open_process(sigar_pid_t pid) { return OpenProcess(PROCESS_DAC, 0, (DWORD)pid); } /* * Pretty good explanation of counters: * http://www.semack.net/wiki/default.asp?db=SemackNetWiki&o=VirtualMemory */ SIGAR_DECLARE(int) sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_mem_t *procmem) { int status = get_proc_info(sigar, pid); sigar_win32_pinfo_t *pinfo = &sigar->pinfo; if (status != SIGAR_OK) { return status; } procmem->size = pinfo->size; /* "Virtual Bytes" */ procmem->resident = pinfo->resident; /* "Working Set" */ procmem->share = SIGAR_FIELD_NOTIMPL; procmem->page_faults = pinfo->page_faults; procmem->minor_faults = SIGAR_FIELD_NOTIMPL; procmem->major_faults = SIGAR_FIELD_NOTIMPL; return SIGAR_OK; } #define TOKEN_DAC (STANDARD_RIGHTS_READ | READ_CONTROL | TOKEN_QUERY) SIGAR_DECLARE(int) sigar_proc_cred_name_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_name_t *proccredname) { HANDLE proc, token; DWORD len; int success; TOKEN_USER *user = NULL; TOKEN_PRIMARY_GROUP *group = NULL; SID_NAME_USE type; char domain[SIGAR_CRED_NAME_MAX]; /* XXX cache lookup */ if (!(proc = open_process(pid))) { return GetLastError(); } if (!OpenProcessToken(proc, TOKEN_DAC, &token)) { CloseHandle(proc); return GetLastError(); } CloseHandle(proc); success = !GetTokenInformation(token, TokenUser, NULL, 0, &len) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && (user = malloc(len)) && GetTokenInformation(token, TokenUser, user, len, &len); if (success) { DWORD domain_len = sizeof(domain); DWORD user_len = sizeof(proccredname->user); success = LookupAccountSid(NULL, user->User.Sid, proccredname->user, &user_len, domain, &domain_len, &type); } if (user != NULL) { free(user); } if (!success) { CloseHandle(token); return GetLastError(); } success = !GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &len) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && (group = malloc(len)) && GetTokenInformation(token, TokenPrimaryGroup, group, len, &len); if (success) { DWORD domain_len = sizeof(domain); DWORD group_len = sizeof(proccredname->group); success = LookupAccountSid(NULL, group->PrimaryGroup, proccredname->group, &group_len, domain, &domain_len, &type); } if (group != NULL) { free(group); } CloseHandle(token); if (!success) { return GetLastError(); } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_t *proccred) { return SIGAR_ENOTIMPL; } #define FILETIME2MSEC(ft) \ NS100_2MSEC(((ft.dwHighDateTime << 32) | ft.dwLowDateTime)) sigar_int64_t sigar_time_now_millis(void) { SYSTEMTIME st; FILETIME time; GetSystemTime(&st); SystemTimeToFileTime(&st, &time); return sigar_FileTimeToTime(&time) / 1000; } SIGAR_DECLARE(int) sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *proctime) { HANDLE proc = open_process(pid); FILETIME start_time, exit_time, system_time, user_time; int status = ERROR_SUCCESS; if (!proc) { return GetLastError(); } if (!GetProcessTimes(proc, &start_time, &exit_time, &system_time, &user_time)) { status = GetLastError(); } CloseHandle(proc); if (status != ERROR_SUCCESS) { return status; } if (start_time.dwHighDateTime) { proctime->start_time = sigar_FileTimeToTime(&start_time) / 1000; } else { proctime->start_time = 0; } proctime->user = FILETIME2MSEC(user_time); proctime->sys = FILETIME2MSEC(system_time); proctime->total = proctime->user + proctime->sys; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_state_t *procstate) { int status = get_proc_info(sigar, pid); sigar_win32_pinfo_t *pinfo = &sigar->pinfo; if (status != SIGAR_OK) { return status; } memcpy(procstate->name, pinfo->name, sizeof(procstate->name)); procstate->state = pinfo->state; procstate->ppid = pinfo->ppid; procstate->priority = pinfo->priority; procstate->nice = SIGAR_FIELD_NOTIMPL; procstate->tty = SIGAR_FIELD_NOTIMPL; procstate->threads = pinfo->threads; procstate->processor = SIGAR_FIELD_NOTIMPL; return SIGAR_OK; } static int get_proc_info(sigar_t *sigar, sigar_pid_t pid) { PERF_OBJECT_TYPE *object; PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; DWORD i, err; DWORD perf_offsets[PERF_IX_MAX]; sigar_win32_pinfo_t *pinfo = &sigar->pinfo; time_t timenow = time(NULL); if (pinfo->pid == pid) { if ((timenow - pinfo->mtime) < SIGAR_LAST_PROC_EXPIRE) { return SIGAR_OK; } } memset(&perf_offsets, 0, sizeof(perf_offsets)); object = get_process_object(sigar, &err); if (object == NULL) { return err; } pinfo->pid = pid; pinfo->mtime = timenow; /* * note we assume here: * block->NumObjectTypes == 1 * object->ObjectNameTitleIndex == PERF_TITLE_PROC * * which should always be the case. */ for (i=0, counter = PdhFirstCounter(object); iNumCounters; i++, counter = PdhNextCounter(counter)) { DWORD offset = counter->CounterOffset; switch (counter->CounterNameTitleIndex) { case PERF_TITLE_CPUTIME: perf_offsets[PERF_IX_CPUTIME] = offset; break; case PERF_TITLE_PAGE_FAULTS: perf_offsets[PERF_IX_PAGE_FAULTS] = offset; break; case PERF_TITLE_MEM_VSIZE: perf_offsets[PERF_IX_MEM_VSIZE] = offset; break; case PERF_TITLE_MEM_SIZE: perf_offsets[PERF_IX_MEM_SIZE] = offset; break; case PERF_TITLE_THREAD_CNT: perf_offsets[PERF_IX_THREAD_CNT] = offset; break; case PERF_TITLE_HANDLE_CNT: perf_offsets[PERF_IX_HANDLE_CNT] = offset; break; case PERF_TITLE_PID: perf_offsets[PERF_IX_PID] = offset; break; case PERF_TITLE_PPID: perf_offsets[PERF_IX_PPID] = offset; break; case PERF_TITLE_PRIORITY: perf_offsets[PERF_IX_PRIORITY] = offset; break; case PERF_TITLE_START_TIME: perf_offsets[PERF_IX_START_TIME] = offset; break; } } for (i=0, inst = PdhFirstInstance(object); iNumInstances; i++, inst = PdhNextInstance(inst)) { PERF_COUNTER_BLOCK *counter_block = PdhGetCounterBlock(inst); sigar_pid_t this_pid = PERF_VAL(PERF_IX_PID); if (this_pid != pid) { continue; } pinfo->state = 'R'; /* XXX? */ SIGAR_W2A(PdhInstanceName(inst), pinfo->name, sizeof(pinfo->name)); pinfo->size = PERF_VAL(PERF_IX_MEM_VSIZE); pinfo->resident = PERF_VAL(PERF_IX_MEM_SIZE); pinfo->ppid = PERF_VAL(PERF_IX_PPID); pinfo->priority = PERF_VAL(PERF_IX_PRIORITY); pinfo->handles = PERF_VAL(PERF_IX_HANDLE_CNT); pinfo->threads = PERF_VAL(PERF_IX_THREAD_CNT); pinfo->page_faults = PERF_VAL(PERF_IX_PAGE_FAULTS); return SIGAR_OK; } return SIGAR_NO_SUCH_PROCESS; } static int sigar_remote_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { int status; char cmdline[SIGAR_CMDLINE_MAX], *ptr = cmdline, *arg; HANDLE proc = open_process(pid); if (proc) { status = sigar_proc_args_peb_get(sigar, proc, procargs); CloseHandle(proc); if (status == SIGAR_OK) { return status; } } /* likely we are 32-bit, pid process is 64-bit */ status = sigar_proc_args_wmi_get(sigar, pid, procargs); if (status == ERROR_NOT_FOUND) { status = SIGAR_NO_SUCH_PROCESS; } return status; } int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { if (pid == sigar->pid) { return sigar_parse_proc_args(sigar, NULL, procargs); } else { return sigar_remote_proc_args_get(sigar, pid, procargs); } } static int sigar_proc_env_parse(UCHAR *ptr, sigar_proc_env_t *procenv, int multi) { while (*ptr) { char *val; int klen, vlen, status; char key[128]; /* XXX is there a max key size? */ if (*ptr == '=') { ptr += strlen(ptr)+1; continue; } val = strchr(ptr, '='); if (val == NULL) { break; /*XXX*/ } klen = val - ptr; SIGAR_SSTRCPY(key, ptr); key[klen] = '\0'; ++val; vlen = strlen(val); status = procenv->env_getter(procenv->data, key, klen, val, vlen); if (status != SIGAR_OK) { /* not an error; just stop iterating */ return status; } if (!multi) { break; /* caller only provided 1 key=val pair */ } ptr += klen + 1 + vlen + 1; } return SIGAR_OK; } static int sigar_local_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { UCHAR *env = (UCHAR*)GetEnvironmentStrings(); sigar_proc_env_parse(env, procenv, TRUE); FreeEnvironmentStrings(env); return SIGAR_OK; } static int sigar_remote_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { int status; HANDLE proc = open_process(pid); WCHAR env[4096]; if (!proc) { return GetLastError(); } status = sigar_proc_env_peb_get(sigar, proc, env, sizeof(env)); CloseHandle(proc); if (status == SIGAR_OK) { LPBYTE ptr = (LPBYTE)env; DWORD size = sizeof(env); UCHAR ent[4096]; while ((size > 0) && (*ptr != L'\0')) { DWORD len = (wcslen((LPWSTR)ptr) + 1) * sizeof(WCHAR); /* multi=FALSE so no need to: memset(ent, '\0', sizeof(ent)) */ SIGAR_W2A((WCHAR *)ptr, ent, sizeof(ent)); if (sigar_proc_env_parse(ent, procenv, FALSE) != SIGAR_OK) { break; } size -= len; ptr += len; } } return status; } SIGAR_DECLARE(int) sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_env_t *procenv) { if (pid == sigar->pid) { if (procenv->type == SIGAR_PROC_ENV_KEY) { char value[32767]; /* max size from msdn docs */ DWORD retval = GetEnvironmentVariable(procenv->key, value, sizeof(value)); if (retval == 0) { if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { return SIGAR_OK; } return GetLastError(); } else if (retval > sizeof(value)) { /* XXX shouldnt happen */ return GetLastError(); } procenv->env_getter(procenv->data, procenv->key, procenv->klen, value, retval); return SIGAR_OK; } else { return sigar_local_proc_env_get(sigar, pid, procenv); } } else { return sigar_remote_proc_env_get(sigar, pid, procenv); } } SIGAR_DECLARE(int) sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_fd_t *procfd) { int status; sigar_win32_pinfo_t *pinfo = &sigar->pinfo; pinfo->pid = -1; /* force update */ if ((status = get_proc_info(sigar, pid)) != SIGAR_OK) { return status; } procfd->total = pinfo->handles; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { int status = SIGAR_OK; HANDLE proc = open_process(pid); if (!proc) { return GetLastError(); } status = sigar_proc_exe_peb_get(sigar, proc, procexe); if (procexe->name[0] == '\0') { /* likely we are 32-bit, pid process is 64-bit */ /* procexe->cwd[0] = XXX where else can we try? */ status = sigar_proc_exe_wmi_get(sigar, pid, procexe); if (status == ERROR_NOT_FOUND) { status = SIGAR_NO_SUCH_PROCESS; } } if (procexe->cwd[0] != '\0') { /* strip trailing '\' */ int len = strlen(procexe->cwd); if (procexe->cwd[len-1] == '\\') { procexe->cwd[len-1] = '\0'; } /* uppercase driver letter */ procexe->cwd[0] = toupper(procexe->cwd[0]); /* e.g. C:\ */ strncpy(procexe->root, procexe->cwd, 3); procexe->root[3] = '\0'; } else { procexe->root[0] = '\0'; } if (procexe->name[0] != '\0') { /* uppercase driver letter */ procexe->name[0] = toupper(procexe->name[0]); } CloseHandle(proc); return status; } #define sigar_EnumProcessModules \ sigar->psapi.enum_modules.func #define sigar_GetModuleFileNameEx \ sigar->psapi.get_module_name.func SIGAR_DECLARE(int) sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_modules_t *procmods) { HANDLE proc; HMODULE modules[1024]; DWORD size = 0; unsigned int i; if (DLLMOD_INIT(psapi, TRUE) != SIGAR_OK) { return SIGAR_ENOTIMPL; } if (!(proc = open_process(pid))) { return GetLastError(); } if (!sigar_EnumProcessModules(proc, modules, sizeof(modules), &size)) { CloseHandle(proc); return GetLastError(); } for (i=0; i<(size/sizeof(HMODULE)); i++) { int status; char name[MAX_PATH]; if (!sigar_GetModuleFileNameEx(proc, modules[i], name, sizeof(name))) { continue; } status = procmods->module_getter(procmods->data, name, strlen(name)); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } } CloseHandle(proc); return SIGAR_OK; } #define FT2INT64(ft) \ ((__int64)((__int64)(ft).dwHighDateTime << 32 | \ (__int64)(ft).dwLowDateTime)) SIGAR_DECLARE(int) sigar_thread_cpu_get(sigar_t *sigar, sigar_uint64_t id, sigar_thread_cpu_t *cpu) { FILETIME start, exit, sys, user; DWORD retval; if (id != 0) { return SIGAR_ENOTIMPL; } retval = GetThreadTimes(GetCurrentThread(), &start, &exit, &sys, &user); if (retval == 0) { return GetLastError(); } cpu->user = FT2INT64(user) * 100; cpu->sys = FT2INT64(sys) * 100; cpu->total = (FT2INT64(user) + FT2INT64(sys)) * 100; return SIGAR_OK; } int sigar_os_fs_type_get(sigar_file_system_t *fsp) { return fsp->type; } #ifndef FILE_READ_ONLY_VOLUME #define FILE_READ_ONLY_VOLUME 0x00080000 #endif #ifndef FILE_NAMED_STREAMS #define FILE_NAMED_STREAMS 0x00040000 #endif #ifndef FILE_SEQUENTIAL_WRITE_ONCE #define FILE_SEQUENTIAL_WRITE_ONCE 0x00100000 #endif #ifndef FILE_SUPPORTS_TRANSACTIONS #define FILE_SUPPORTS_TRANSACTIONS 0x00200000 #endif static void get_fs_options(char *opts, int osize, long flags) { *opts = '\0'; if (flags & FILE_READ_ONLY_VOLUME) strncat(opts, "ro", osize); else strncat(opts, "rw", osize); #if 0 /*XXX*/ if (flags & FILE_CASE_PRESERVED_NAMES) strncat(opts, ",casepn", osize); if (flags & FILE_CASE_SENSITIVE_SEARCH) strncat(opts, ",casess", osize); if (flags & FILE_FILE_COMPRESSION) strncat(opts, ",fcomp", osize); if (flags & FILE_NAMED_STREAMS) strncat(opts, ",streams", osize); if (flags & FILE_PERSISTENT_ACLS) strncat(opts, ",acls", osize); if (flags & FILE_SEQUENTIAL_WRITE_ONCE) strncat(opts, ",wronce", osize); if (flags & FILE_SUPPORTS_ENCRYPTION) strncat(opts, ",efs", osize); if (flags & FILE_SUPPORTS_OBJECT_IDS) strncat(opts, ",oids", osize); if (flags & FILE_SUPPORTS_REPARSE_POINTS) strncat(opts, ",reparse", osize); if (flags & FILE_SUPPORTS_SPARSE_FILES) strncat(opts, ",sparse", osize); if (flags & FILE_SUPPORTS_TRANSACTIONS) strncat(opts, ",trans", osize); if (flags & FILE_UNICODE_ON_DISK) strncat(opts, ",unicode", osize); if (flags & FILE_VOLUME_IS_COMPRESSED) strncat(opts, ",vcomp", osize); if (flags & FILE_VOLUME_QUOTAS) strncat(opts, ",quota", osize); #endif } #define sigar_WNetGetConnection \ sigar->mpr.get_net_connection.func SIGAR_DECLARE(int) sigar_file_system_list_get(sigar_t *sigar, sigar_file_system_list_t *fslist) { char name[256]; char *ptr = name; /* XXX: hmm, Find{First,Next}Volume not available in my sdk */ DWORD len = GetLogicalDriveStringsA(sizeof(name), name); DLLMOD_INIT(mpr, TRUE); if (len == 0) { return GetLastError(); } sigar_file_system_list_create(fslist); while (*ptr) { sigar_file_system_t *fsp; DWORD flags, serialnum=0; char fsname[1024]; UINT drive_type = GetDriveType(ptr); int type; switch (drive_type) { case DRIVE_FIXED: type = SIGAR_FSTYPE_LOCAL_DISK; break; case DRIVE_REMOTE: type = SIGAR_FSTYPE_NETWORK; break; case DRIVE_CDROM: type = SIGAR_FSTYPE_CDROM; break; case DRIVE_RAMDISK: type = SIGAR_FSTYPE_RAM_DISK; break; case DRIVE_REMOVABLE: /* skip floppy, usb, etc. drives */ ptr += strlen(ptr)+1; continue; default: type = SIGAR_FSTYPE_NONE; break; } fsname[0] = '\0'; GetVolumeInformation(ptr, NULL, 0, &serialnum, NULL, &flags, fsname, sizeof(fsname)); if (!serialnum && (drive_type == DRIVE_FIXED)) { ptr += strlen(ptr)+1; continue; /* ignore unformatted partitions */ } SIGAR_FILE_SYSTEM_LIST_GROW(fslist); fsp = &fslist->data[fslist->number++]; fsp->type = type; SIGAR_SSTRCPY(fsp->dir_name, ptr); SIGAR_SSTRCPY(fsp->dev_name, ptr); if ((drive_type == DRIVE_REMOTE) && sigar_WNetGetConnection) { DWORD len = sizeof(fsp->dev_name); char drive[3] = {'\0', ':', '\0'}; /* e.g. "X:" w/o trailing "\" */ drive[0] = fsp->dir_name[0]; sigar_WNetGetConnection(drive, fsp->dev_name, &len); /* ignoring failure, leaving dev_name as dir_name */ } /* we set fsp->type, just looking up sigar.c:fstype_names[type] */ sigar_fs_type_get(fsp); if (*fsname == '\0') { SIGAR_SSTRCPY(fsp->sys_type_name, fsp->type_name); } else { SIGAR_SSTRCPY(fsp->sys_type_name, fsname); /* CDFS, NTFS, etc */ } get_fs_options(fsp->options, sizeof(fsp->options)-1, flags); ptr += strlen(ptr)+1; } return SIGAR_OK; } static PERF_INSTANCE_DEFINITION *get_disk_instance(sigar_t *sigar, DWORD *perf_offsets, DWORD *num, DWORD *err) { PERF_OBJECT_TYPE *object = get_perf_object(sigar, PERF_TITLE_DISK_KEY, err); PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; DWORD i, found=0; if (!object) { return NULL; } for (i=0, counter = PdhFirstCounter(object); iNumCounters; i++, counter = PdhNextCounter(counter)) { DWORD offset = counter->CounterOffset; switch (counter->CounterNameTitleIndex) { case PERF_TITLE_DISK_TIME: perf_offsets[PERF_IX_DISK_TIME] = offset; found = 1; break; case PERF_TITLE_DISK_READ_TIME: perf_offsets[PERF_IX_DISK_READ_TIME] = offset; found = 1; break; case PERF_TITLE_DISK_WRITE_TIME: perf_offsets[PERF_IX_DISK_WRITE_TIME] = offset; found = 1; break; case PERF_TITLE_DISK_READ: perf_offsets[PERF_IX_DISK_READ] = offset; found = 1; break; case PERF_TITLE_DISK_WRITE: perf_offsets[PERF_IX_DISK_WRITE] = offset; found = 1; break; case PERF_TITLE_DISK_READ_BYTES: perf_offsets[PERF_IX_DISK_READ_BYTES] = offset; found = 1; break; case PERF_TITLE_DISK_WRITE_BYTES: perf_offsets[PERF_IX_DISK_WRITE_BYTES] = offset; found = 1; break; case PERF_TITLE_DISK_QUEUE: perf_offsets[PERF_IX_DISK_QUEUE] = offset; found = 1; break; } } if (!found) { *err = ENOENT; return NULL; } if (num) { *num = object->NumInstances; } return PdhFirstInstance(object); } SIGAR_DECLARE(int) sigar_disk_usage_get(sigar_t *sigar, const char *dirname, sigar_disk_usage_t *disk) { DWORD i, err; PERF_OBJECT_TYPE *object = get_perf_object(sigar, PERF_TITLE_DISK_KEY, &err); PERF_INSTANCE_DEFINITION *inst; PERF_COUNTER_DEFINITION *counter; DWORD perf_offsets[PERF_IX_DISK_MAX]; SIGAR_DISK_STATS_INIT(disk); if (!object) { return err; } memset(&perf_offsets, 0, sizeof(perf_offsets)); inst = get_disk_instance(sigar, (DWORD*)&perf_offsets, 0, &err); if (!inst) { return err; } for (i=0, inst = PdhFirstInstance(object); iNumInstances; i++, inst = PdhNextInstance(inst)) { char drive[MAX_PATH]; PERF_COUNTER_BLOCK *counter_block = PdhGetCounterBlock(inst); wchar_t *name = (wchar_t *)((BYTE *)inst + inst->NameOffset); SIGAR_W2A(name, drive, sizeof(drive)); if (sigar_isdigit(*name)) { char *ptr = strchr(drive, ' '); /* 2000 Server "0 C:" */ if (ptr) { ++ptr; SIGAR_SSTRCPY(drive, ptr); } else { /* XXX NT is a number only "0", how to map? */ } } if (strnEQ(drive, dirname, 2)) { disk->time = PERF_VAL(PERF_IX_DISK_TIME); disk->rtime = PERF_VAL(PERF_IX_DISK_READ_TIME); disk->wtime = PERF_VAL(PERF_IX_DISK_WRITE_TIME); disk->reads = PERF_VAL(PERF_IX_DISK_READ); disk->writes = PERF_VAL(PERF_IX_DISK_WRITE); disk->read_bytes = PERF_VAL(PERF_IX_DISK_READ_BYTES); disk->write_bytes = PERF_VAL(PERF_IX_DISK_WRITE_BYTES); disk->queue = PERF_VAL(PERF_IX_DISK_QUEUE); return SIGAR_OK; } } return ENXIO; } SIGAR_DECLARE(int) sigar_file_system_usage_get(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { BOOL retval; ULARGE_INTEGER avail, total, free; int status; /* prevent dialog box if A:\ drive is empty */ UINT errmode = SetErrorMode(SEM_FAILCRITICALERRORS); retval = GetDiskFreeSpaceEx(dirname, &avail, &total, &free); /* restore previous error mode */ SetErrorMode(errmode); if (!retval) { return GetLastError(); } fsusage->total = total.QuadPart / 1024; fsusage->free = free.QuadPart / 1024; fsusage->avail = avail.QuadPart / 1024; fsusage->used = fsusage->total - fsusage->free; fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage); /* N/A */ fsusage->files = SIGAR_FIELD_NOTIMPL; fsusage->free_files = SIGAR_FIELD_NOTIMPL; status = sigar_disk_usage_get(sigar, dirname, &fsusage->disk); return SIGAR_OK; } static int sigar_cpu_info_get(sigar_t *sigar, sigar_cpu_info_t *info) { HKEY key, cpu; int i = 0; char id[MAX_PATH + 1]; DWORD size = 0, rc; RegOpenKey(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor", &key); //just lookup the first id, then assume all cpus are the same. rc = RegEnumKey(key, 0, id, sizeof(id)); if (rc != ERROR_SUCCESS) { RegCloseKey(key); return rc; } rc = RegOpenKey(key, id, &cpu); if (rc != ERROR_SUCCESS) { RegCloseKey(key); return rc; } size = sizeof(info->vendor); if (RegQueryValueEx(cpu, "VendorIdentifier", NULL, NULL, (LPVOID)&info->vendor, &size) || strEQ(info->vendor, "GenuineIntel")) { SIGAR_SSTRCPY(info->vendor, "Intel"); } else { if (strEQ(info->vendor, "AuthenticAMD")) { SIGAR_SSTRCPY(info->vendor, "AMD"); } } size = sizeof(info->model); if (RegQueryValueEx(cpu, "ProcessorNameString", NULL, NULL, (LPVOID)&info->model, &size)) { size = sizeof(info->model); if (RegQueryValueEx(cpu, "Identifier", NULL, NULL, (LPVOID)&info->model, &size)) { SIGAR_SSTRCPY(info->model, "x86"); } } else { sigar_cpu_model_adjust(sigar, info); } size = sizeof(info->mhz); // == sizeof(DWORD) if (RegQueryValueEx(cpu, "~MHz", NULL, NULL, (LPVOID)&info->mhz, &size)) { info->mhz = -1; } info->cache_size = -1; //XXX RegCloseKey(key); RegCloseKey(cpu); info->total_cores = sigar->ncpu; info->cores_per_socket = sigar->lcpu; info->total_sockets = sigar_cpu_socket_count(sigar); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_cpu_info_list_get(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { int i, status; sigar_cpu_info_t info; int core_rollup = sigar_cpu_core_rollup(sigar); sigar_cpu_info_list_create(cpu_infos); status = sigar_cpu_info_get(sigar, &info); if (status != SIGAR_OK) { return status; } for (i=0; incpu; i++) { SIGAR_CPU_INFO_LIST_GROW(cpu_infos); if (core_rollup && (i % sigar->lcpu)) { continue; /* fold logical processors */ } memcpy(&cpu_infos->data[cpu_infos->number++], &info, sizeof(info)); } return SIGAR_OK; } #define sigar_GetNetworkParams \ sigar->iphlpapi.get_net_params.func #define sigar_GetAdaptersInfo \ sigar->iphlpapi.get_adapters_info.func #define sigar_GetAdaptersAddresses \ sigar->iphlpapi.get_adapters_addrs.func #define sigar_GetNumberOfInterfaces \ sigar->iphlpapi.get_num_if.func static sigar_cache_t *sigar_netif_cache_new(sigar_t *sigar) { DWORD num = 0; DLLMOD_INIT(iphlpapi, FALSE); if (sigar_GetNumberOfInterfaces) { DWORD rc = sigar_GetNumberOfInterfaces(&num); if (rc == NO_ERROR) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetNumberOfInterfaces=%d", num); } else { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetNumberOfInterfaces failed: %s", sigar_strerror(sigar, rc)); } } if (num == 0) { num = 10; /* reasonable default */ } return sigar_cache_new(num); } static int sigar_get_adapters_info(sigar_t *sigar, PIP_ADAPTER_INFO *adapter) { ULONG size = sigar->ifconf_len; DWORD rc; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetAdaptersInfo) { return SIGAR_ENOTIMPL; } *adapter = (PIP_ADAPTER_INFO)sigar->ifconf_buf; rc = sigar_GetAdaptersInfo(*adapter, &size); if (rc == ERROR_BUFFER_OVERFLOW) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetAdaptersInfo " "realloc ifconf_buf old=%d, new=%d", sigar->ifconf_len, size); sigar->ifconf_len = size; sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len); *adapter = (PIP_ADAPTER_INFO)sigar->ifconf_buf; rc = sigar_GetAdaptersInfo(*adapter, &size); } if (rc != NO_ERROR) { return rc; } else { return SIGAR_OK; } } static int sigar_get_adapter_info(sigar_t *sigar, DWORD index, IP_ADAPTER_INFO **adapter) { sigar_cache_entry_t *entry; *adapter = NULL; if (sigar->netif_adapters) { entry = sigar_cache_get(sigar->netif_adapters, index); if (entry->value) { *adapter = (IP_ADAPTER_INFO *)entry->value; } } else { int status; IP_ADAPTER_INFO *info; sigar->netif_adapters = sigar_netif_cache_new(sigar); status = sigar_get_adapters_info(sigar, &info); if (status != SIGAR_OK) { return status; } while (info) { entry = sigar_cache_get(sigar->netif_adapters, info->Index); if (!entry->value) { entry->value = malloc(sizeof(*info)); } memcpy(entry->value, info, sizeof(*info)); if (info->Index == index) { *adapter = info; } info = info->Next; } } if (*adapter) { return SIGAR_OK; } else { return ENOENT; } } static int sigar_get_adapters_addresses(sigar_t *sigar, PIP_ADAPTER_ADDRESSES *addrs) { ULONG size = sigar->ifconf_len; ULONG rc; ULONG flags = GAA_FLAG_SKIP_DNS_SERVER|GAA_FLAG_SKIP_MULTICAST; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetAdaptersAddresses) { return SIGAR_ENOTIMPL; } *addrs = (PIP_ADAPTER_ADDRESSES)sigar->ifconf_buf; rc = sigar_GetAdaptersAddresses(AF_UNSPEC, flags, NULL, *addrs, &size); if (rc == ERROR_BUFFER_OVERFLOW) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetAdaptersAddresses " "realloc ifconf_buf old=%d, new=%d", sigar->ifconf_len, size); sigar->ifconf_len = size; sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len); *addrs = (PIP_ADAPTER_ADDRESSES)sigar->ifconf_buf; rc = sigar_GetAdaptersAddresses(AF_UNSPEC, flags, NULL, *addrs, &size); } if (rc != ERROR_SUCCESS) { return rc; } else { return SIGAR_OK; } } #define sigar_GetIpAddrTable \ sigar->iphlpapi.get_ipaddr_table.func static int sigar_get_ipaddr_table(sigar_t *sigar, PMIB_IPADDRTABLE *ipaddr) { ULONG size = sigar->ifconf_len; DWORD rc; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetIpAddrTable) { return SIGAR_ENOTIMPL; } *ipaddr = (PMIB_IPADDRTABLE)sigar->ifconf_buf; rc = sigar_GetIpAddrTable(*ipaddr, &size, FALSE); if (rc == ERROR_INSUFFICIENT_BUFFER) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetIpAddrTable " "realloc ifconf_buf old=%d, new=%d", sigar->ifconf_len, size); sigar->ifconf_len = size; sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len); *ipaddr = (PMIB_IPADDRTABLE)sigar->ifconf_buf; rc = sigar_GetIpAddrTable(*ipaddr, &size, FALSE); } if (rc != NO_ERROR) { return rc; } else { return SIGAR_OK; } } #ifndef MIB_IPADDR_PRIMARY #define MIB_IPADDR_PRIMARY 0x0001 #endif static int sigar_get_netif_ipaddr(sigar_t *sigar, DWORD index, MIB_IPADDRROW **ipaddr) { sigar_cache_entry_t *entry; *ipaddr = NULL; if (sigar->netif_addr_rows) { entry = sigar_cache_get(sigar->netif_addr_rows, index); if (entry->value) { *ipaddr = (MIB_IPADDRROW *)entry->value; } } else { int status, i; MIB_IPADDRTABLE *mib; sigar->netif_addr_rows = sigar_netif_cache_new(sigar); status = sigar_get_ipaddr_table(sigar, &mib); if (status != SIGAR_OK) { return status; } for (i=0; idwNumEntries; i++) { MIB_IPADDRROW *row = &mib->table[i]; short type; #ifdef SIGAR_USING_MSC6 type = row->unused2; #else type = row->wType; #endif if (!(type & MIB_IPADDR_PRIMARY)) { continue; } entry = sigar_cache_get(sigar->netif_addr_rows, row->dwIndex); if (!entry->value) { entry->value = malloc(sizeof(*row)); } memcpy(entry->value, row, sizeof(*row)); if (row->dwIndex == index) { *ipaddr = row; } } } if (*ipaddr) { return SIGAR_OK; } else { return ENOENT; } } SIGAR_DECLARE(int) sigar_net_info_get(sigar_t *sigar, sigar_net_info_t *netinfo) { PIP_ADAPTER_INFO adapter; FIXED_INFO *info; ULONG len = 0; IP_ADDR_STRING *ip; DWORD rc; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetNetworkParams) { return SIGAR_ENOTIMPL; } SIGAR_ZERO(netinfo); rc = sigar_GetNetworkParams(NULL, &len); if (rc != ERROR_BUFFER_OVERFLOW) { return rc; } info = malloc(len); rc = sigar_GetNetworkParams(info, &len); if (rc != NO_ERROR) { free(info); return rc; } SIGAR_SSTRCPY(netinfo->host_name, info->HostName); SIGAR_SSTRCPY(netinfo->domain_name, info->DomainName); SIGAR_SSTRCPY(netinfo->primary_dns, info->DnsServerList.IpAddress.String); if ((ip = info->DnsServerList.Next)) { SIGAR_SSTRCPY(netinfo->secondary_dns, ip->IpAddress.String); } free(info); if (sigar_get_adapters_info(sigar, &adapter) != SIGAR_OK) { return SIGAR_OK; } while (adapter) { /* should only be 1 */ if (adapter->GatewayList.IpAddress.String[0]) { SIGAR_SSTRCPY(netinfo->default_gateway, adapter->GatewayList.IpAddress.String); } #if 0 if (apapters->DhcpEnabled) { SIGAR_SSTRCPY(netinfo->dhcp_server, apdaters->DhcpServer.IpAddress.String); } #endif adapter = adapter->Next; } return SIGAR_OK; } #define sigar_GetIpForwardTable \ sigar->iphlpapi.get_ipforward_table.func SIGAR_DECLARE(int) sigar_net_route_list_get(sigar_t *sigar, sigar_net_route_list_t *routelist) { PMIB_IPFORWARDTABLE buffer = NULL; ULONG bufsize = 0; DWORD rc, i; MIB_IPFORWARDTABLE *ipt; sigar_net_route_t *route; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetIpForwardTable) { return SIGAR_ENOTIMPL; } rc = sigar_GetIpForwardTable(buffer, &bufsize, FALSE); if (rc != ERROR_INSUFFICIENT_BUFFER) { return GetLastError(); } buffer = malloc(bufsize); rc = sigar_GetIpForwardTable(buffer, &bufsize, FALSE); if (rc != NO_ERROR) { free(buffer); return GetLastError(); } if (!sigar->netif_names) { sigar_net_interface_list_get(sigar, NULL); } sigar_net_route_list_create(routelist); routelist->size = routelist->number = 0; ipt = buffer; for (i=0; idwNumEntries; i++) { MIB_IPFORWARDROW *ipr = ipt->table + i; sigar_cache_entry_t *entry; SIGAR_NET_ROUTE_LIST_GROW(routelist); route = &routelist->data[routelist->number++]; SIGAR_ZERO(route); /* XXX: other fields */ sigar_net_address_set(route->destination, ipr->dwForwardDest); sigar_net_address_set(route->mask, ipr->dwForwardMask); sigar_net_address_set(route->gateway, ipr->dwForwardNextHop); route->metric = ipr->dwForwardMetric1; route->flags = SIGAR_RTF_UP; if ((ipr->dwForwardDest == 0) && (ipr->dwForwardMask == 0)) { route->flags |= SIGAR_RTF_GATEWAY; } entry = sigar_cache_get(sigar->netif_names, ipr->dwForwardIfIndex); if (entry->value) { SIGAR_SSTRCPY(route->ifname, (char *)entry->value); } } free(buffer); return SIGAR_OK; } #define sigar_GetIfTable \ sigar->iphlpapi.get_if_table.func #define sigar_GetIfEntry \ sigar->iphlpapi.get_if_entry.func static int sigar_get_if_table(sigar_t *sigar, PMIB_IFTABLE *iftable) { ULONG size = sigar->ifconf_len; DWORD rc; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetIfTable) { return SIGAR_ENOTIMPL; } *iftable = (PMIB_IFTABLE)sigar->ifconf_buf; rc = sigar_GetIfTable(*iftable, &size, FALSE); if (rc == ERROR_INSUFFICIENT_BUFFER) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "GetIfTable " "realloc ifconf_buf old=%d, new=%d", sigar->ifconf_len, size); sigar->ifconf_len = size; sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len); *iftable = (PMIB_IFTABLE)sigar->ifconf_buf; rc = sigar_GetIfTable(*iftable, &size, FALSE); } if (rc != NO_ERROR) { return rc; } else { return SIGAR_OK; } } static int get_mib_ifrow(sigar_t *sigar, const char *name, MIB_IFROW **ifrp) { int status, key, cached=0; sigar_cache_entry_t *entry; if (sigar->netif_mib_rows) { cached = 1; } else { status = sigar_net_interface_list_get(sigar, NULL); if (status != SIGAR_OK) { return status; } } key = netif_hash(name); entry = sigar_cache_get(sigar->netif_mib_rows, key); if (!entry->value) { return ENOENT; } *ifrp = (MIB_IFROW *)entry->value; if (cached) { /* refresh */ if ((status = sigar_GetIfEntry(*ifrp)) != NO_ERROR) { return status; } } return SIGAR_OK; } static int netif_hash(char *s) { int hash = 0; while (*s) { hash = 31*hash + *s++; } return hash; } /* Vista and later, wireless network cards are reported as IF_TYPE_IEEE80211 */ #ifndef IF_TYPE_IEEE80211 #define IF_TYPE_IEEE80211 71 #endif SIGAR_DECLARE(int) sigar_net_interface_list_get(sigar_t *sigar, sigar_net_interface_list_t *iflist) { MIB_IFTABLE *ift; int i, status; int lo=0, eth=0, la=0; if (!sigar->netif_mib_rows) { sigar->netif_mib_rows = sigar_netif_cache_new(sigar); } if (!sigar->netif_names) { sigar->netif_names = sigar_netif_cache_new(sigar); } if ((status = sigar_get_if_table(sigar, &ift)) != SIGAR_OK) { return status; } if (iflist) { iflist->number = 0; iflist->size = ift->dwNumEntries; iflist->data = malloc(sizeof(*(iflist->data)) * iflist->size); } for (i=0; idwNumEntries; i++) { char name[16]; int key; MIB_IFROW *ifr = ift->table + i; sigar_cache_entry_t *entry; if (strEQ(ifr->bDescr, MS_LOOPBACK_ADAPTER)) { /* special-case */ sprintf(name, NETIF_LA "%d", la++); } else if (ifr->dwType == MIB_IF_TYPE_LOOPBACK) { sprintf(name, "lo%d", lo++); } else if ((ifr->dwType == MIB_IF_TYPE_ETHERNET) || (ifr->dwType == IF_TYPE_IEEE80211)) { sprintf(name, "eth%d", eth++); } else { continue; /*XXX*/ } if (iflist) { iflist->data[iflist->number++] = sigar_strdup(name); } key = netif_hash(name); entry = sigar_cache_get(sigar->netif_mib_rows, key); if (!entry->value) { entry->value = malloc(sizeof(*ifr)); } memcpy(entry->value, ifr, sizeof(*ifr)); /* save dwIndex -> name mapping for use by route_list */ entry = sigar_cache_get(sigar->netif_names, ifr->dwIndex); if (!entry->value) { entry->value = sigar_strdup(name); } } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_interface_config_get(sigar_t *sigar, const char *name, sigar_net_interface_config_t *ifconfig) { MIB_IFROW *ifr; MIB_IPADDRROW *ipaddr; int status; if (!name) { return sigar_net_interface_config_primary_get(sigar, ifconfig); } status = get_mib_ifrow(sigar, name, &ifr); if (status != SIGAR_OK) { return status; } SIGAR_ZERO(ifconfig); SIGAR_SSTRCPY(ifconfig->name, name); ifconfig->mtu = ifr->dwMtu; sigar_net_address_mac_set(ifconfig->hwaddr, ifr->bPhysAddr, SIGAR_IFHWADDRLEN); SIGAR_SSTRCPY(ifconfig->description, ifr->bDescr); if (ifr->dwOperStatus & MIB_IF_OPER_STATUS_OPERATIONAL) { ifconfig->flags |= SIGAR_IFF_UP|SIGAR_IFF_RUNNING; } status = sigar_get_netif_ipaddr(sigar, ifr->dwIndex, &ipaddr); if (status == SIGAR_OK) { sigar_net_address_set(ifconfig->address, ipaddr->dwAddr); sigar_net_address_set(ifconfig->netmask, ipaddr->dwMask); if (ifr->dwType != MIB_IF_TYPE_LOOPBACK) { if (ipaddr->dwBCastAddr) { long bcast = ipaddr->dwAddr & ipaddr->dwMask; bcast |= ~ipaddr->dwMask; ifconfig->flags |= SIGAR_IFF_BROADCAST; sigar_net_address_set(ifconfig->broadcast, bcast); } } } /* hack for MS_LOOPBACK_ADAPTER */ if (strnEQ(name, NETIF_LA, sizeof(NETIF_LA)-1)) { ifr->dwType = MIB_IF_TYPE_LOOPBACK; } if (ifr->dwType == MIB_IF_TYPE_LOOPBACK) { ifconfig->flags |= SIGAR_IFF_LOOPBACK; SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_LOOPBACK); } else { if (ipaddr) { ifconfig->flags |= SIGAR_IFF_MULTICAST; } SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_ETHERNET); } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_interface_stat_get(sigar_t *sigar, const char *name, sigar_net_interface_stat_t *ifstat) { MIB_IFROW *ifr; int status; status = get_mib_ifrow(sigar, name, &ifr); if (status != SIGAR_OK) { return status; } ifstat->rx_bytes = ifr->dwInOctets; ifstat->rx_packets = ifr->dwInUcastPkts + ifr->dwInNUcastPkts; ifstat->rx_errors = ifr->dwInErrors; ifstat->rx_dropped = ifr->dwInDiscards; ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->rx_frame = SIGAR_FIELD_NOTIMPL; ifstat->tx_bytes = ifr->dwOutOctets; ifstat->tx_packets = ifr->dwOutUcastPkts + ifr->dwOutNUcastPkts; ifstat->tx_errors = ifr->dwOutErrors; ifstat->tx_dropped = ifr->dwOutDiscards; ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL; ifstat->tx_collisions = SIGAR_FIELD_NOTIMPL; ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL; ifstat->speed = ifr->dwSpeed; return SIGAR_OK; } #define IS_TCP_SERVER(state, flags) \ ((flags & SIGAR_NETCONN_SERVER) && (state == MIB_TCP_STATE_LISTEN)) #define IS_TCP_CLIENT(state, flags) \ ((flags & SIGAR_NETCONN_CLIENT) && (state != MIB_TCP_STATE_LISTEN)) #define sigar_GetTcpTable \ sigar->iphlpapi.get_tcp_table.func static int net_conn_get_tcp(sigar_net_connection_walker_t *walker) { sigar_t *sigar = walker->sigar; int flags = walker->flags; int status, i; DWORD rc, size=0; PMIB_TCPTABLE tcp; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetTcpTable) { return SIGAR_ENOTIMPL; } rc = sigar_GetTcpTable(NULL, &size, FALSE); if (rc != ERROR_INSUFFICIENT_BUFFER) { return GetLastError(); } tcp = malloc(size); rc = sigar_GetTcpTable(tcp, &size, FALSE); if (rc) { free(tcp); return GetLastError(); } /* go in reverse to get LISTEN states first */ for (i = (tcp->dwNumEntries-1); i >= 0; i--) { sigar_net_connection_t conn; DWORD state = tcp->table[i].dwState; if (!(IS_TCP_SERVER(state, flags) || IS_TCP_CLIENT(state, flags))) { continue; } conn.local_port = htons((WORD)tcp->table[i].dwLocalPort); conn.remote_port = htons((WORD)tcp->table[i].dwRemotePort); conn.type = SIGAR_NETCONN_TCP; sigar_net_address_set(conn.local_address, tcp->table[i].dwLocalAddr); sigar_net_address_set(conn.remote_address, tcp->table[i].dwRemoteAddr); conn.send_queue = conn.receive_queue = SIGAR_FIELD_NOTIMPL; switch (state) { case MIB_TCP_STATE_CLOSED: conn.state = SIGAR_TCP_CLOSE; break; case MIB_TCP_STATE_LISTEN: conn.state = SIGAR_TCP_LISTEN; break; case MIB_TCP_STATE_SYN_SENT: conn.state = SIGAR_TCP_SYN_SENT; break; case MIB_TCP_STATE_SYN_RCVD: conn.state = SIGAR_TCP_SYN_RECV; break; case MIB_TCP_STATE_ESTAB: conn.state = SIGAR_TCP_ESTABLISHED; break; case MIB_TCP_STATE_FIN_WAIT1: conn.state = SIGAR_TCP_FIN_WAIT1; break; case MIB_TCP_STATE_FIN_WAIT2: conn.state = SIGAR_TCP_FIN_WAIT2; break; case MIB_TCP_STATE_CLOSE_WAIT: conn.state = SIGAR_TCP_CLOSE_WAIT; break; case MIB_TCP_STATE_CLOSING: conn.state = SIGAR_TCP_CLOSING; break; case MIB_TCP_STATE_LAST_ACK: conn.state = SIGAR_TCP_LAST_ACK; break; case MIB_TCP_STATE_TIME_WAIT: conn.state = SIGAR_TCP_TIME_WAIT; break; case MIB_TCP_STATE_DELETE_TCB: default: conn.state = SIGAR_TCP_UNKNOWN; break; } if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } free(tcp); return SIGAR_OK; } #define IS_UDP_SERVER(conn, flags) \ ((flags & SIGAR_NETCONN_SERVER) && !conn.remote_port) #define IS_UDP_CLIENT(state, flags) \ ((flags & SIGAR_NETCONN_CLIENT) && conn.remote_port) #define sigar_GetUdpTable \ sigar->iphlpapi.get_udp_table.func static int net_conn_get_udp(sigar_net_connection_walker_t *walker) { sigar_t *sigar = walker->sigar; int flags = walker->flags; int status; DWORD rc, size=0, i; PMIB_UDPTABLE udp; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetUdpTable) { return SIGAR_ENOTIMPL; } rc = sigar_GetUdpTable(NULL, &size, FALSE); if (rc != ERROR_INSUFFICIENT_BUFFER) { return GetLastError(); } udp = malloc(size); rc = sigar_GetUdpTable(udp, &size, FALSE); if (rc) { free(udp); return GetLastError(); } for (i = 0; i < udp->dwNumEntries; i++) { sigar_net_connection_t conn; if (!(IS_UDP_SERVER(conn, flags) || IS_UDP_CLIENT(conn, flags))) { continue; } conn.local_port = htons((WORD)udp->table[i].dwLocalPort); conn.remote_port = 0; conn.type = SIGAR_NETCONN_UDP; sigar_net_address_set(conn.local_address, udp->table[i].dwLocalAddr); sigar_net_address_set(conn.remote_address, 0); conn.send_queue = conn.receive_queue = SIGAR_FIELD_NOTIMPL; if (walker->add_connection(walker, &conn) != SIGAR_OK) { break; } } free(udp); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_connection_walk(sigar_net_connection_walker_t *walker) { int status; if (walker->flags & SIGAR_NETCONN_TCP) { status = net_conn_get_tcp(walker); if (status != SIGAR_OK) { return status; } } if (walker->flags & SIGAR_NETCONN_UDP) { status = net_conn_get_udp(walker); if (status != SIGAR_OK) { return status; } } return SIGAR_OK; } #define sigar_GetTcpStatistics \ sigar->iphlpapi.get_tcp_stats.func SIGAR_DECLARE(int) sigar_tcp_get(sigar_t *sigar, sigar_tcp_t *tcp) { MIB_TCPSTATS mib; int status; DLLMOD_INIT(iphlpapi, FALSE); if (!sigar_GetTcpStatistics) { return SIGAR_ENOTIMPL; } status = sigar_GetTcpStatistics(&mib); if (status != NO_ERROR) { return status; } tcp->active_opens = mib.dwActiveOpens; tcp->passive_opens = mib.dwPassiveOpens; tcp->attempt_fails = mib.dwAttemptFails; tcp->estab_resets = mib.dwEstabResets; tcp->curr_estab = mib.dwCurrEstab; tcp->in_segs = mib.dwInSegs; tcp->out_segs = mib.dwOutSegs; tcp->retrans_segs = mib.dwRetransSegs; tcp->in_errs = mib.dwInErrs; tcp->out_rsts = mib.dwOutRsts; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_nfs_client_v2_get(sigar_t *sigar, sigar_nfs_client_v2_t *nfs) { return SIGAR_ENOTIMPL; } SIGAR_DECLARE(int) sigar_nfs_server_v2_get(sigar_t *sigar, sigar_nfs_server_v2_t *nfs) { return SIGAR_ENOTIMPL; } SIGAR_DECLARE(int) sigar_nfs_client_v3_get(sigar_t *sigar, sigar_nfs_client_v3_t *nfs) { return SIGAR_ENOTIMPL; } SIGAR_DECLARE(int) sigar_nfs_server_v3_get(sigar_t *sigar, sigar_nfs_server_v3_t *nfs) { return SIGAR_ENOTIMPL; } #define sigar_GetTcpExTable \ sigar->iphlpapi.get_tcpx_table.func #define sigar_GetUdpExTable \ sigar->iphlpapi.get_udpx_table.func SIGAR_DECLARE(int) sigar_proc_port_get(sigar_t *sigar, int protocol, unsigned long port, sigar_pid_t *pid) { DWORD rc, i; DLLMOD_INIT(iphlpapi, FALSE); if (protocol == SIGAR_NETCONN_TCP) { PMIB_TCPEXTABLE tcp; if (!sigar_GetTcpExTable) { return SIGAR_ENOTIMPL; } rc = sigar_GetTcpExTable(&tcp, FALSE, GetProcessHeap(), 2, 2); if (rc) { return GetLastError(); } for (i=0; idwNumEntries; i++) { if (tcp->table[i].dwState != MIB_TCP_STATE_LISTEN) { continue; } if (htons((WORD)tcp->table[i].dwLocalPort) != port) { continue; } *pid = tcp->table[i].dwProcessId; return SIGAR_OK; } } else if (protocol == SIGAR_NETCONN_UDP) { PMIB_UDPEXTABLE udp; if (!sigar_GetUdpExTable) { return SIGAR_ENOTIMPL; } rc = sigar_GetUdpExTable(&udp, FALSE, GetProcessHeap(), 2, 2); if (rc) { return GetLastError(); } for (i=0; idwNumEntries; i++) { if (htons((WORD)udp->table[i].dwLocalPort) != port) { continue; } *pid = udp->table[i].dwProcessId; return SIGAR_OK; } } else { return SIGAR_ENOTIMPL; } return ENOENT; } #include static int sigar_who_net_sessions(sigar_t *sigar, sigar_who_list_t *wholist) { NET_API_STATUS status; LPSESSION_INFO_10 buffer=NULL, ptr; DWORD entries=0, total_entries=0; DWORD resume_handle=0; DWORD i; do { status = NetSessionEnum(NULL, /* server name */ NULL, /* client name */ NULL, /* user name */ 10, /* level */ (LPBYTE*)&buffer, MAX_PREFERRED_LENGTH, &entries, &total_entries, &resume_handle); if ((status == NERR_Success) || (status == ERROR_MORE_DATA)) { if ((ptr = buffer)) { for (i=0; idata[wholist->number++]; who->time = (time(NULL) - ptr->sesi10_time); SIGAR_W2A((LPCWSTR)ptr->sesi10_username, who->user, sizeof(who->user)); SIGAR_W2A((LPCWSTR)ptr->sesi10_cname, who->host, sizeof(who->host)); SIGAR_SSTRCPY(who->device, "network share"); ptr++; } } } else { break; } if (buffer) { NetApiBufferFree(buffer); buffer = NULL; } } while (status == ERROR_MORE_DATA); if (buffer) { NetApiBufferFree(buffer); } return SIGAR_OK; } static int get_logon_info(HKEY users, char *username, sigar_who_t *who) { DWORD status, size, type; HKEY key; char key_name[MAX_PATH]; char value[256]; FILETIME wtime; who->time = 0; sprintf(key_name, "%s\\Volatile Environment", username); if (RegOpenKey(users, key_name, &key) != ERROR_SUCCESS) { return ENOENT; } status = RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &wtime); if (status == ERROR_SUCCESS) { FileTimeToLocalFileTime(&wtime, &wtime); who->time = sigar_FileTimeToTime(&wtime) / 1000000; } size = sizeof(value); status = RegQueryValueEx(key, "CLIENTNAME", NULL, &type, value, &size); if (status == ERROR_SUCCESS) { if ((value[0] != '\0') && !strEQ(value, "Console")) { SIGAR_SSTRCPY(who->host, value); } } size = sizeof(value); status = RegQueryValueEx(key, "SESSIONNAME", NULL, &type, value, &size); if (status == ERROR_SUCCESS) { SIGAR_SSTRCPY(who->device, value); } RegCloseKey(key); return SIGAR_OK; } #define sigar_ConvertStringSidToSid \ sigar->advapi.convert_string_sid.func static int sigar_who_registry(sigar_t *sigar, sigar_who_list_t *wholist) { HKEY users; DWORD index=0, status; if (!sigar_ConvertStringSidToSid) { return ENOENT; } status = RegOpenKey(HKEY_USERS, NULL, &users); if (status != ERROR_SUCCESS) { return status; } while (1) { char subkey[MAX_PATH]; char username[SIGAR_CRED_NAME_MAX]; char domain[SIGAR_CRED_NAME_MAX]; DWORD subkey_len = sizeof(subkey); DWORD username_len = sizeof(username); DWORD domain_len = sizeof(domain); PSID sid; SID_NAME_USE type; status = RegEnumKeyEx(users, index, subkey, &subkey_len, NULL, NULL, NULL, NULL); if (status != ERROR_SUCCESS) { break; } index++; if ((subkey[0] == '.') || strstr(subkey, "_Classes")) { continue; } if (!sigar_ConvertStringSidToSid(subkey, &sid)) { continue; } if (LookupAccountSid(NULL, /* server */ sid, username, &username_len, domain, &domain_len, &type)) { sigar_who_t *who; SIGAR_WHO_LIST_GROW(wholist); who = &wholist->data[wholist->number++]; SIGAR_SSTRCPY(who->user, username); SIGAR_SSTRCPY(who->host, domain); SIGAR_SSTRCPY(who->device, "console"); get_logon_info(users, subkey, who); } LocalFree(sid); } RegCloseKey(users); return SIGAR_OK; } #define sigar_WTSEnumerateSessions \ sigar->wtsapi.enum_sessions.func #define sigar_WTSFreeMemory \ sigar->wtsapi.free_mem.func #define sigar_WTSQuerySessionInformation \ sigar->wtsapi.query_session.func #define sigar_WinStationQueryInformation \ sigar->winsta.query_info.func static int sigar_who_wts(sigar_t *sigar, sigar_who_list_t *wholist) { DWORD count=0, i; WTS_SESSION_INFO *sessions = NULL; if (DLLMOD_INIT(wtsapi, TRUE) != SIGAR_OK) { sigar_log(sigar, SIGAR_LOG_DEBUG, "Terminal Services api functions not available"); return ENOENT; } DLLMOD_INIT(winsta, FALSE); if (!sigar_WTSEnumerateSessions(0, 0, 1, &sessions, &count)) { return GetLastError(); } for (i=0; idata[wholist->number++]; SIGAR_SSTRCPY(who->device, sessions[i].pWinStationName); buffer = NULL; bytes = 0; if (sigar_WTSQuerySessionInformation(0, sessionId, WTSClientAddress, &buffer, &bytes)) { PWTS_CLIENT_ADDRESS client = (PWTS_CLIENT_ADDRESS)buffer; sprintf(who->host, "%u.%u.%u.%u", client->Address[2], client->Address[3], client->Address[4], client->Address[5]); sigar_WTSFreeMemory(buffer); } else { SIGAR_SSTRCPY(who->host, "unknown"); } buffer = NULL; bytes = 0; if (sigar_WTSQuerySessionInformation(0, sessionId, WTSUserName, &buffer, &bytes)) { SIGAR_SSTRCPY(who->user, buffer); sigar_WTSFreeMemory(buffer); } else { SIGAR_SSTRCPY(who->user, "unknown"); } buffer = NULL; bytes = 0; if (sigar_WinStationQueryInformation && sigar_WinStationQueryInformation(0, sessionId, WinStationInformation, &station_info, sizeof(station_info), &bytes)) { who->time = sigar_FileTimeToTime(&station_info.ConnectTime) / 1000000; } else { who->time = 0; } } sigar_WTSFreeMemory(sessions); return SIGAR_OK; } int sigar_who_list_get_win32(sigar_t *sigar, sigar_who_list_t *wholist) { sigar_who_net_sessions(sigar, wholist); sigar_who_registry(sigar, wholist); sigar_who_wts(sigar, wholist); return SIGAR_OK; } /* see: http://msdn2.microsoft.com/en-us/library/ms724833.aspx */ #ifndef VER_NT_WORKSTATION #define VER_NT_WORKSTATION 0x0000001 #endif #ifdef SIGAR_USING_MSC6 #define sigar_wProductType wReserved[1] #else #define sigar_wProductType wProductType #endif #ifdef _M_X64 #define SIGAR_ARCH "x64" #else #define SIGAR_ARCH "x86" #endif int sigar_os_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo) { OSVERSIONINFOEX version; char *vendor_name, *vendor_version, *code_name=NULL; version.dwOSVersionInfoSize = sizeof(version); GetVersionEx((OSVERSIONINFO *)&version); if (version.dwMajorVersion == 4) { vendor_name = "Windows NT"; vendor_version = "NT"; } else if (version.dwMajorVersion == 5) { switch (version.dwMinorVersion) { case 0: vendor_name = "Windows 2000"; vendor_version = "2000"; break; case 1: vendor_name = "Windows XP"; vendor_version = "XP"; code_name = "Whistler"; break; case 2: vendor_name = "Windows 2003"; vendor_version = "2003"; code_name = "Whistler Server"; break; default: vendor_name = "Windows Unknown"; break; } } else if (version.dwMajorVersion == 6) { if (version.sigar_wProductType == VER_NT_WORKSTATION) { if (version.dwMinorVersion == 0) { vendor_name = "Windows Vista"; vendor_version = "Vista"; code_name = "Longhorn"; } else { vendor_name = "Windows 7"; vendor_version = "7"; code_name = "Vienna"; } } else { vendor_name = "Windows 2008"; vendor_version = "2008"; code_name = "Longhorn Server"; } } SIGAR_SSTRCPY(sysinfo->name, "Win32"); SIGAR_SSTRCPY(sysinfo->vendor, "Microsoft"); SIGAR_SSTRCPY(sysinfo->vendor_name, vendor_name); SIGAR_SSTRCPY(sysinfo->vendor_version, vendor_version); if (code_name) { SIGAR_SSTRCPY(sysinfo->vendor_code_name, code_name); } SIGAR_SSTRCPY(sysinfo->arch, SIGAR_ARCH); sprintf(sysinfo->version, "%d.%d", version.dwMajorVersion, version.dwMinorVersion); SIGAR_SSTRCPY(sysinfo->patch_level, version.szCSDVersion); sprintf(sysinfo->description, "%s %s", sysinfo->vendor, sysinfo->vendor_name); return SIGAR_OK; } #define sigar_QueryServiceStatusEx \ sigar->advapi.query_service_status.func int sigar_service_pid_get(sigar_t *sigar, char *name, sigar_pid_t *pid) { DWORD rc = ERROR_SUCCESS, len; SC_HANDLE mgr; HANDLE svc; SERVICE_STATUS_PROCESS status; if (!sigar_QueryServiceStatusEx) { return SIGAR_ENOTIMPL; } mgr = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS); if (!mgr) { return GetLastError(); } if (!(svc = OpenService(mgr, name, SERVICE_ALL_ACCESS))) { CloseServiceHandle(mgr); return GetLastError(); } if (sigar_QueryServiceStatusEx(svc, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(status), &len)) { *pid = status.dwProcessId; } else { *pid = -1; rc = GetLastError(); } CloseServiceHandle(svc); CloseServiceHandle(mgr); return rc; } int sigar_services_status_get(sigar_services_status_t *ss, DWORD state) { DWORD bytes, resume=0; BOOL retval; if (!ss->handle) { ss->handle = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE); if (!ss->handle) { return GetLastError(); } } retval = EnumServicesStatus(ss->handle, SERVICE_WIN32, state, ss->services, ss->size, &bytes, &ss->count, &resume); if (retval == FALSE) { DWORD err = GetLastError(); if (err != ERROR_MORE_DATA) { return err; } ss->services = realloc(ss->services, bytes); ss->size = bytes; retval = EnumServicesStatus(ss->handle, SERVICE_WIN32, state, ss->services, ss->size, &bytes, &ss->count, &resume); if (retval == FALSE) { return GetLastError(); } } return SIGAR_OK; } void sigar_services_status_close(sigar_services_status_t *ss) { if (ss->handle) { CloseServiceHandle(ss->handle); } if (ss->size) { free(ss->services); } SIGAR_ZERO(ss); } /* extract exe from QUERY_SERVICE_CONFIG.lpBinaryPathName * leaves behind command-line arguments and quotes (if any) */ char *sigar_service_exe_get(char *path, char *buffer, int basename) { char *ptr; if (path) { strncpy(buffer, path, SIGAR_CMDLINE_MAX); } path = buffer; if (*path == '"') { ++path; if ((ptr = strchr(path, '"'))) { *ptr = '\0'; } } else { ptr = sigar_strcasestr(path, ".exe"); if (ptr) { *(ptr+4) = '\0'; } else { if ((ptr = strchr(path, ' '))) { *ptr = '\0'; } } } if (basename && (ptr = strrchr(path, '\\'))) { path = ++ptr; } return path; } static char *string_file_info_keys[] = { "Comments", "CompanyName", "FileDescription", "FileVersion", "InternalName", "LegalCopyright", "LegalTrademarks", "OriginalFilename", "ProductName", "ProductVersion", "PrivateBuild", "SpecialBuild", NULL }; int sigar_file_version_get(sigar_file_version_t *version, char *name, sigar_proc_env_t *infocb) { DWORD handle, len; LPTSTR data; VS_FIXEDFILEINFO *info; int status; if (!(len = GetFileVersionInfoSize(name, &handle))) { return GetLastError(); } if (len == 0) { return !SIGAR_OK; } data = malloc(len); if (GetFileVersionInfo(name, handle, len, data)) { if (VerQueryValue(data, "\\", &info, &len)) { version->product_major = HIWORD(info->dwProductVersionMS); version->product_minor = LOWORD(info->dwProductVersionMS); version->product_build = HIWORD(info->dwProductVersionLS); version->product_revision = LOWORD(info->dwProductVersionLS); version->file_major = HIWORD(info->dwFileVersionMS); version->file_minor = LOWORD(info->dwFileVersionMS); version->file_build = HIWORD(info->dwFileVersionLS); version->file_revision = LOWORD(info->dwFileVersionLS); status = SIGAR_OK; } else { status = GetLastError(); } } else { status = GetLastError(); } if (infocb && (status == SIGAR_OK)) { struct { WORD lang; WORD code_page; } *trans; if (VerQueryValue(data, "\\VarFileInfo\\Translation", &trans, &len)) { int i; char buf[1024]; void *ptr; for (i=0; string_file_info_keys[i]; i++) { char *key = string_file_info_keys[i]; sprintf(buf, "\\StringFileInfo\\%04x%04x\\%s", trans[0].lang, trans[0].code_page, key); if (VerQueryValue(data, buf, &ptr, &len)) { if (len == 0) { continue; } infocb->env_getter(infocb->data, key, strlen(key), (char *)ptr, len); } } } } free(data); return status; } hyperic-sigar-1.6.4+dfsg/src/sigar.c000066400000000000000000001637441210132627500172650ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 #include #ifndef WIN32 #include #include #include #endif #if defined(__OpenBSD__) || defined(__FreeBSD__) #include #endif #ifndef WIN32 #include #endif #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #include "sigar_format.h" SIGAR_DECLARE(int) sigar_open(sigar_t **sigar) { int status = sigar_os_open(sigar); if (status == SIGAR_OK) { /* use env to revert to old behavior */ (*sigar)->cpu_list_cores = getenv("SIGAR_CPU_LIST_SOCKETS") ? 0 : 1; (*sigar)->pid = 0; (*sigar)->ifconf_buf = NULL; (*sigar)->ifconf_len = 0; (*sigar)->log_level = -1; /* log nothing by default */ (*sigar)->log_impl = NULL; (*sigar)->log_data = NULL; (*sigar)->ptql_re_impl = NULL; (*sigar)->ptql_re_data = NULL; (*sigar)->self_path = NULL; (*sigar)->fsdev = NULL; (*sigar)->pids = NULL; (*sigar)->proc_cpu = NULL; (*sigar)->net_listen = NULL; (*sigar)->net_services_tcp = NULL; (*sigar)->net_services_udp = NULL; } return status; } SIGAR_DECLARE(int) sigar_close(sigar_t *sigar) { if (sigar->ifconf_buf) { free(sigar->ifconf_buf); } if (sigar->self_path) { free(sigar->self_path); } if (sigar->pids) { sigar_proc_list_destroy(sigar, sigar->pids); free(sigar->pids); } if (sigar->fsdev) { sigar_cache_destroy(sigar->fsdev); } if (sigar->proc_cpu) { sigar_cache_destroy(sigar->proc_cpu); } if (sigar->net_listen) { sigar_cache_destroy(sigar->net_listen); } if (sigar->net_services_tcp) { sigar_cache_destroy(sigar->net_services_tcp); } if (sigar->net_services_udp) { sigar_cache_destroy(sigar->net_services_udp); } return sigar_os_close(sigar); } #ifndef __linux__ /* linux has a special case */ SIGAR_DECLARE(sigar_pid_t) sigar_pid_get(sigar_t *sigar) { if (!sigar->pid) { sigar->pid = getpid(); } return sigar->pid; } #endif /* XXX: add clear() function */ /* XXX: check for stale-ness using start_time */ SIGAR_DECLARE(int) sigar_proc_cpu_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cpu_t *proccpu) { sigar_cache_entry_t *entry; sigar_proc_cpu_t *prev; sigar_uint64_t otime, time_now = sigar_time_now_millis(); sigar_uint64_t time_diff, total_diff; int status; if (!sigar->proc_cpu) { sigar->proc_cpu = sigar_cache_new(128); } entry = sigar_cache_get(sigar->proc_cpu, pid); if (entry->value) { prev = (sigar_proc_cpu_t *)entry->value; } else { prev = entry->value = malloc(sizeof(*prev)); SIGAR_ZERO(prev); } time_diff = time_now - prev->last_time; proccpu->last_time = prev->last_time = time_now; if (time_diff == 0) { /* we were just called within < 1 second ago. */ memcpy(proccpu, prev, sizeof(*proccpu)); return SIGAR_OK; } otime = prev->total; status = sigar_proc_time_get(sigar, pid, (sigar_proc_time_t *)proccpu); if (status != SIGAR_OK) { return status; } memcpy(prev, proccpu, sizeof(*prev)); if (proccpu->total < otime) { /* XXX this should not happen */ otime = 0; } if (otime == 0) { proccpu->percent = 0.0; /* first time called */ return SIGAR_OK; } total_diff = proccpu->total - otime; proccpu->percent = total_diff / (double)time_diff; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_stat_get(sigar_t *sigar, sigar_proc_stat_t *procstat) { int status, i; sigar_proc_list_t *pids; SIGAR_ZERO(procstat); procstat->threads = SIGAR_FIELD_NOTIMPL; if ((status = sigar_proc_list_get(sigar, NULL)) != SIGAR_OK) { return status; } pids = sigar->pids; procstat->total = pids->number; for (i=0; inumber; i++) { sigar_proc_state_t state; status = sigar_proc_state_get(sigar, pids->data[i], &state); if (status != SIGAR_OK) { continue; } if (state.threads != SIGAR_FIELD_NOTIMPL) { procstat->threads += state.threads; } switch (state.state) { case SIGAR_PROC_STATE_IDLE: procstat->idle++; break; case SIGAR_PROC_STATE_RUN: procstat->running++; break; case SIGAR_PROC_STATE_SLEEP: procstat->sleeping++; break; case SIGAR_PROC_STATE_STOP: procstat->stopped++; break; case SIGAR_PROC_STATE_ZOMBIE: procstat->zombie++; break; default: break; } } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_sys_info_get(sigar_t *sigar, sigar_sys_info_t *sysinfo) { SIGAR_ZERO(sysinfo); #ifndef WIN32 sigar_sys_info_get_uname(sysinfo); #endif sigar_os_sys_info_get(sigar, sysinfo); return SIGAR_OK; } #ifndef WIN32 #include int sigar_sys_info_get_uname(sigar_sys_info_t *sysinfo) { struct utsname name; uname(&name); SIGAR_SSTRCPY(sysinfo->version, name.release); SIGAR_SSTRCPY(sysinfo->vendor_name, name.sysname); SIGAR_SSTRCPY(sysinfo->name, name.sysname); SIGAR_SSTRCPY(sysinfo->machine, name.machine); SIGAR_SSTRCPY(sysinfo->arch, name.machine); SIGAR_SSTRCPY(sysinfo->patch_level, "unknown"); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_cred_name_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_cred_name_t *proccredname) { sigar_proc_cred_t cred; int status = sigar_proc_cred_get(sigar, pid, &cred); if (status != SIGAR_OK) { return status; } status = sigar_user_name_get(sigar, cred.uid, proccredname->user, sizeof(proccredname->user)); if (status != SIGAR_OK) { return status; } status = sigar_group_name_get(sigar, cred.gid, proccredname->group, sizeof(proccredname->group)); return status; } #endif /* WIN32 */ int sigar_proc_list_create(sigar_proc_list_t *proclist) { proclist->number = 0; proclist->size = SIGAR_PROC_LIST_MAX; proclist->data = malloc(sizeof(*(proclist->data)) * proclist->size); return SIGAR_OK; } int sigar_proc_list_grow(sigar_proc_list_t *proclist) { proclist->data = realloc(proclist->data, sizeof(*(proclist->data)) * (proclist->size + SIGAR_PROC_LIST_MAX)); proclist->size += SIGAR_PROC_LIST_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_list_destroy(sigar_t *sigar, sigar_proc_list_t *proclist) { if (proclist->size) { free(proclist->data); proclist->number = proclist->size = 0; } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_list_get(sigar_t *sigar, sigar_proc_list_t *proclist) { if (proclist == NULL) { /* internal re-use */ if (sigar->pids == NULL) { sigar->pids = malloc(sizeof(*sigar->pids)); sigar_proc_list_create(sigar->pids); } else { sigar->pids->number = 0; } proclist = sigar->pids; } else { sigar_proc_list_create(proclist); } return sigar_os_proc_list_get(sigar, proclist); } int sigar_proc_args_create(sigar_proc_args_t *procargs) { procargs->number = 0; procargs->size = SIGAR_PROC_ARGS_MAX; procargs->data = malloc(sizeof(*(procargs->data)) * procargs->size); return SIGAR_OK; } int sigar_proc_args_grow(sigar_proc_args_t *procargs) { procargs->data = realloc(procargs->data, sizeof(*(procargs->data)) * (procargs->size + SIGAR_PROC_ARGS_MAX)); procargs->size += SIGAR_PROC_ARGS_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_args_destroy(sigar_t *sigar, sigar_proc_args_t *procargs) { unsigned int i; if (procargs->size) { for (i=0; inumber; i++) { free(procargs->data[i]); } free(procargs->data); procargs->number = procargs->size = 0; } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_proc_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { int status; sigar_proc_args_create(procargs); status = sigar_os_proc_args_get(sigar, pid, procargs); if (status != SIGAR_OK) { sigar_proc_args_destroy(sigar, procargs); } return status; } int sigar_file_system_list_create(sigar_file_system_list_t *fslist) { fslist->number = 0; fslist->size = SIGAR_FS_MAX; fslist->data = malloc(sizeof(*(fslist->data)) * fslist->size); return SIGAR_OK; } int sigar_file_system_list_grow(sigar_file_system_list_t *fslist) { fslist->data = realloc(fslist->data, sizeof(*(fslist->data)) * (fslist->size + SIGAR_FS_MAX)); fslist->size += SIGAR_FS_MAX; return SIGAR_OK; } /* indexed with sigar_file_system_type_e */ static const char *fstype_names[] = { "unknown", "none", "local", "remote", "ram", "cdrom", "swap" }; static int sigar_common_fs_type_get(sigar_file_system_t *fsp) { char *type = fsp->sys_type_name; switch (*type) { case 'n': if (strEQ(type, "nfs")) { fsp->type = SIGAR_FSTYPE_NETWORK; } break; case 's': if (strEQ(type, "smbfs")) { /* samba */ fsp->type = SIGAR_FSTYPE_NETWORK; } else if (strEQ(type, "swap")) { fsp->type = SIGAR_FSTYPE_SWAP; } break; case 'a': if (strEQ(type, "afs")) { fsp->type = SIGAR_FSTYPE_NETWORK; } break; case 'i': if (strEQ(type, "iso9660")) { fsp->type = SIGAR_FSTYPE_CDROM; } break; case 'c': if (strEQ(type, "cvfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } else if (strEQ(type, "cifs")) { fsp->type = SIGAR_FSTYPE_NETWORK; } break; case 'm': if (strEQ(type, "msdos") || strEQ(type, "minix")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'h': if (strEQ(type, "hpfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'v': if (strEQ(type, "vxfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } else if (strEQ(type, "vfat")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; case 'z': if (strEQ(type, "zfs")) { fsp->type = SIGAR_FSTYPE_LOCAL_DISK; } break; } return fsp->type; } void sigar_fs_type_get(sigar_file_system_t *fsp) { if (!(fsp->type || /* already set */ sigar_os_fs_type_get(fsp) || /* try os specifics first */ sigar_common_fs_type_get(fsp))) /* try common ones last */ { fsp->type = SIGAR_FSTYPE_NONE; } if (fsp->type >= SIGAR_FSTYPE_MAX) { fsp->type = SIGAR_FSTYPE_NONE; } strcpy(fsp->type_name, fstype_names[fsp->type]); } SIGAR_DECLARE(int) sigar_file_system_list_destroy(sigar_t *sigar, sigar_file_system_list_t *fslist) { if (fslist->size) { free(fslist->data); fslist->number = fslist->size = 0; } return SIGAR_OK; } #ifndef NFS_PROGRAM #define NFS_PROGRAM 100003 #endif #ifndef NFS_VERSION #define NFS_VERSION 2 #endif SIGAR_DECLARE(int) sigar_file_system_ping(sigar_t *sigar, sigar_file_system_t *fs) { int status = SIGAR_OK; #ifndef WIN32 char *ptr; if ((fs->type == SIGAR_FSTYPE_NETWORK) && strEQ(fs->sys_type_name, "nfs") && (ptr = strchr(fs->dev_name, ':'))) { *ptr = '\0'; /* "hostname:/mount" -> "hostname" */ status = sigar_rpc_ping(fs->dev_name, SIGAR_NETCONN_UDP, NFS_PROGRAM, NFS_VERSION); if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fs_ping] %s -> %s: %s", fs->dir_name, fs->dev_name, ((status == SIGAR_OK) ? "OK" : sigar_rpc_strerror(status))); } *ptr = ':'; /* "hostname" -> "hostname:/mount" */ } #endif return status; } int sigar_cpu_info_list_create(sigar_cpu_info_list_t *cpu_infos) { cpu_infos->number = 0; cpu_infos->size = SIGAR_CPU_INFO_MAX; cpu_infos->data = malloc(sizeof(*(cpu_infos->data)) * cpu_infos->size); return SIGAR_OK; } int sigar_cpu_info_list_grow(sigar_cpu_info_list_t *cpu_infos) { cpu_infos->data = realloc(cpu_infos->data, sizeof(*(cpu_infos->data)) * (cpu_infos->size + SIGAR_CPU_INFO_MAX)); cpu_infos->size += SIGAR_CPU_INFO_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_cpu_info_list_destroy(sigar_t *sigar, sigar_cpu_info_list_t *cpu_infos) { if (cpu_infos->size) { free(cpu_infos->data); cpu_infos->number = cpu_infos->size = 0; } return SIGAR_OK; } int sigar_cpu_list_create(sigar_cpu_list_t *cpulist) { cpulist->number = 0; cpulist->size = SIGAR_CPU_INFO_MAX; cpulist->data = malloc(sizeof(*(cpulist->data)) * cpulist->size); return SIGAR_OK; } int sigar_cpu_list_grow(sigar_cpu_list_t *cpulist) { cpulist->data = realloc(cpulist->data, sizeof(*(cpulist->data)) * (cpulist->size + SIGAR_CPU_INFO_MAX)); cpulist->size += SIGAR_CPU_INFO_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_cpu_list_destroy(sigar_t *sigar, sigar_cpu_list_t *cpulist) { if (cpulist->size) { free(cpulist->data); cpulist->number = cpulist->size = 0; } return SIGAR_OK; } int sigar_net_route_list_create(sigar_net_route_list_t *routelist) { routelist->number = 0; routelist->size = SIGAR_NET_ROUTE_LIST_MAX; routelist->data = malloc(sizeof(*(routelist->data)) * routelist->size); return SIGAR_OK; } int sigar_net_route_list_grow(sigar_net_route_list_t *routelist) { routelist->data = realloc(routelist->data, sizeof(*(routelist->data)) * (routelist->size + SIGAR_NET_ROUTE_LIST_MAX)); routelist->size += SIGAR_NET_ROUTE_LIST_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_route_list_destroy(sigar_t *sigar, sigar_net_route_list_t *routelist) { if (routelist->size) { free(routelist->data); routelist->number = routelist->size = 0; } return SIGAR_OK; } int sigar_net_interface_list_create(sigar_net_interface_list_t *iflist) { iflist->number = 0; iflist->size = SIGAR_NET_IFLIST_MAX; iflist->data = malloc(sizeof(*(iflist->data)) * iflist->size); return SIGAR_OK; } int sigar_net_interface_list_grow(sigar_net_interface_list_t *iflist) { iflist->data = realloc(iflist->data, sizeof(*(iflist->data)) * (iflist->size + SIGAR_NET_IFLIST_MAX)); iflist->size += SIGAR_NET_IFLIST_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_interface_list_destroy(sigar_t *sigar, sigar_net_interface_list_t *iflist) { unsigned int i; if (iflist->size) { for (i=0; inumber; i++) { free(iflist->data[i]); } free(iflist->data); iflist->number = iflist->size = 0; } return SIGAR_OK; } int sigar_net_connection_list_create(sigar_net_connection_list_t *connlist) { connlist->number = 0; connlist->size = SIGAR_NET_CONNLIST_MAX; connlist->data = malloc(sizeof(*(connlist->data)) * connlist->size); return SIGAR_OK; } int sigar_net_connection_list_grow(sigar_net_connection_list_t *connlist) { connlist->data = realloc(connlist->data, sizeof(*(connlist->data)) * (connlist->size + SIGAR_NET_CONNLIST_MAX)); connlist->size += SIGAR_NET_CONNLIST_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_connection_list_destroy(sigar_t *sigar, sigar_net_connection_list_t *connlist) { if (connlist->size) { free(connlist->data); connlist->number = connlist->size = 0; } return SIGAR_OK; } #if !defined(__linux__) /* * implement sigar_net_connection_list_get using sigar_net_connection_walk * linux has its own list_get impl. */ static int net_connection_list_walker(sigar_net_connection_walker_t *walker, sigar_net_connection_t *conn) { sigar_net_connection_list_t *connlist = (sigar_net_connection_list_t *)walker->data; SIGAR_NET_CONNLIST_GROW(connlist); memcpy(&connlist->data[connlist->number++], conn, sizeof(*conn)); return SIGAR_OK; /* continue loop */ } SIGAR_DECLARE(int) sigar_net_connection_list_get(sigar_t *sigar, sigar_net_connection_list_t *connlist, int flags) { int status; sigar_net_connection_walker_t walker; sigar_net_connection_list_create(connlist); walker.sigar = sigar; walker.flags = flags; walker.data = connlist; walker.add_connection = net_connection_list_walker; status = sigar_net_connection_walk(&walker); if (status != SIGAR_OK) { sigar_net_connection_list_destroy(sigar, connlist); } return status; } #endif static void sigar_net_listen_address_add(sigar_t *sigar, sigar_net_connection_t *conn) { sigar_cache_entry_t *entry = sigar_cache_get(sigar->net_listen, conn->local_port); if (entry->value) { if (conn->local_address.family == SIGAR_AF_INET6) { return; /* prefer ipv4 */ } } else { entry->value = malloc(sizeof(conn->local_address)); } memcpy(entry->value, &conn->local_address, sizeof(conn->local_address)); } SIGAR_DECLARE(int) sigar_net_listen_address_get(sigar_t *sigar, unsigned long port, sigar_net_address_t *address) { if (!sigar->net_listen || !sigar_cache_find(sigar->net_listen, port)) { sigar_net_stat_t netstat; int status = sigar_net_stat_get(sigar, &netstat, SIGAR_NETCONN_SERVER|SIGAR_NETCONN_TCP); if (status != SIGAR_OK) { return status; } } if (sigar_cache_find(sigar->net_listen, port)) { void *value = sigar_cache_get(sigar->net_listen, port)->value; memcpy(address, value, sizeof(*address)); return SIGAR_OK; } else { return ENOENT; } } typedef struct { sigar_net_stat_t *netstat; sigar_net_connection_list_t *connlist; } net_stat_getter_t; static int net_stat_walker(sigar_net_connection_walker_t *walker, sigar_net_connection_t *conn) { int state = conn->state; sigar_cache_t *listen_ports = walker->sigar->net_listen; net_stat_getter_t *getter = (net_stat_getter_t *)walker->data; if (conn->type == SIGAR_NETCONN_TCP) { getter->netstat->tcp_states[state]++; /* XXX listen_ports may get stale */ if (state == SIGAR_TCP_LISTEN) { sigar_net_listen_address_add(walker->sigar, conn); } else { if (sigar_cache_find(listen_ports, conn->local_port)) { getter->netstat->tcp_inbound_total++; } else { getter->netstat->tcp_outbound_total++; } } } else if (conn->type == SIGAR_NETCONN_UDP) { /*XXX*/ } getter->netstat->all_inbound_total = getter->netstat->tcp_inbound_total; getter->netstat->all_outbound_total = getter->netstat->tcp_outbound_total; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_stat_get(sigar_t *sigar, sigar_net_stat_t *netstat, int flags) { sigar_net_connection_walker_t walker; net_stat_getter_t getter; if (!sigar->net_listen) { sigar->net_listen = sigar_cache_new(32); } SIGAR_ZERO(netstat); getter.netstat = netstat; walker.sigar = sigar; walker.data = &getter; walker.add_connection = net_stat_walker; walker.flags = flags; return sigar_net_connection_walk(&walker); } typedef struct { sigar_net_stat_t *netstat; sigar_net_address_t *address; unsigned long port; } net_stat_port_getter_t; static int net_stat_port_walker(sigar_net_connection_walker_t *walker, sigar_net_connection_t *conn) { net_stat_port_getter_t *getter = (net_stat_port_getter_t *)walker->data; sigar_net_stat_t *netstat = getter->netstat; if (conn->type == SIGAR_NETCONN_TCP) { if (conn->local_port == getter->port) { netstat->all_inbound_total++; if (sigar_net_address_equals(getter->address, &conn->local_address) == SIGAR_OK) { netstat->tcp_inbound_total++; } } else if (conn->remote_port == getter->port) { netstat->all_outbound_total++; if (sigar_net_address_equals(getter->address, &conn->remote_address) == SIGAR_OK) { netstat->tcp_outbound_total++; } } else { return SIGAR_OK; } netstat->tcp_states[conn->state]++; } else if (conn->type == SIGAR_NETCONN_UDP) { /*XXX*/ } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_stat_port_get(sigar_t *sigar, sigar_net_stat_t *netstat, int flags, sigar_net_address_t *address, unsigned long port) { sigar_net_connection_walker_t walker; net_stat_port_getter_t getter; SIGAR_ZERO(netstat); getter.netstat = netstat; getter.address = address; getter.port = port; walker.sigar = sigar; walker.data = &getter; walker.add_connection = net_stat_port_walker; walker.flags = flags; if (SIGAR_LOG_IS_DEBUG(sigar)) { char name[SIGAR_FQDN_LEN]; sigar_net_address_to_string(sigar, address, name); sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[net_stat_port] using address '%s:%d'", name, port); } return sigar_net_connection_walk(&walker); } static int tcp_curr_estab_count(sigar_net_connection_walker_t *walker, sigar_net_connection_t *conn) { if ((conn->state == SIGAR_TCP_ESTABLISHED) || (conn->state == SIGAR_TCP_CLOSE_WAIT)) { ((sigar_tcp_t *)walker->data)->curr_estab++; } return SIGAR_OK; } /* TCP-MIB::tcpCurrEstab */ int sigar_tcp_curr_estab(sigar_t *sigar, sigar_tcp_t *tcp) { sigar_net_connection_walker_t walker; walker.sigar = sigar; walker.data = tcp; walker.add_connection = tcp_curr_estab_count; walker.flags = SIGAR_NETCONN_CLIENT|SIGAR_NETCONN_TCP; tcp->curr_estab = 0; return sigar_net_connection_walk(&walker); } int sigar_who_list_create(sigar_who_list_t *wholist) { wholist->number = 0; wholist->size = SIGAR_WHO_LIST_MAX; wholist->data = malloc(sizeof(*(wholist->data)) * wholist->size); return SIGAR_OK; } int sigar_who_list_grow(sigar_who_list_t *wholist) { wholist->data = realloc(wholist->data, sizeof(*(wholist->data)) * (wholist->size + SIGAR_WHO_LIST_MAX)); wholist->size += SIGAR_WHO_LIST_MAX; return SIGAR_OK; } SIGAR_DECLARE(int) sigar_who_list_destroy(sigar_t *sigar, sigar_who_list_t *wholist) { if (wholist->size) { free(wholist->data); wholist->number = wholist->size = 0; } return SIGAR_OK; } #if defined(__sun) # include # define SIGAR_UTMP_FILE _UTMPX_FILE # define ut_time ut_tv.tv_sec #elif defined(WIN32) /* XXX may not be the default */ #define SIGAR_UTMP_FILE "C:\\cygwin\\var\\run\\utmp" #define UT_LINESIZE 16 #define UT_NAMESIZE 16 #define UT_HOSTSIZE 256 #define UT_IDLEN 2 #define ut_name ut_user struct utmp { short ut_type; int ut_pid; char ut_line[UT_LINESIZE]; char ut_id[UT_IDLEN]; time_t ut_time; char ut_user[UT_NAMESIZE]; char ut_host[UT_HOSTSIZE]; long ut_addr; }; #elif defined(NETWARE) static char *getpass(const char *prompt) { static char password[BUFSIZ]; fputs(prompt, stderr); fgets((char *)&password, sizeof(password), stdin); return (char *)&password; } #else # include # ifdef UTMP_FILE # define SIGAR_UTMP_FILE UTMP_FILE # else # define SIGAR_UTMP_FILE _PATH_UTMP # endif #endif #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(DARWIN) # define ut_user ut_name #endif #ifdef DARWIN /* XXX from utmpx.h; sizeof changed in 10.5 */ /* additionally, utmpx does not work on 10.4 */ #define SIGAR_HAS_UTMPX #define _PATH_UTMPX "/var/run/utmpx" #define _UTX_USERSIZE 256 /* matches MAXLOGNAME */ #define _UTX_LINESIZE 32 #define _UTX_IDSIZE 4 #define _UTX_HOSTSIZE 256 struct utmpx { char ut_user[_UTX_USERSIZE]; /* login name */ char ut_id[_UTX_IDSIZE]; /* id */ char ut_line[_UTX_LINESIZE]; /* tty name */ pid_t ut_pid; /* process id creating the entry */ short ut_type; /* type of this entry */ struct timeval ut_tv; /* time entry was created */ char ut_host[_UTX_HOSTSIZE]; /* host name */ __uint32_t ut_pad[16]; /* reserved for future use */ }; #define ut_xtime ut_tv.tv_sec #define UTMPX_USER_PROCESS 7 /* end utmpx.h */ #define SIGAR_UTMPX_FILE _PATH_UTMPX #endif #if !defined(NETWARE) && !defined(_AIX) #define WHOCPY(dest, src) \ SIGAR_SSTRCPY(dest, src); \ if (sizeof(src) < sizeof(dest)) \ dest[sizeof(src)] = '\0' #ifdef SIGAR_HAS_UTMPX static int sigar_who_utmpx(sigar_t *sigar, sigar_who_list_t *wholist) { FILE *fp; struct utmpx ut; if (!(fp = fopen(SIGAR_UTMPX_FILE, "r"))) { return errno; } while (fread(&ut, sizeof(ut), 1, fp) == 1) { sigar_who_t *who; if (*ut.ut_user == '\0') { continue; } #ifdef UTMPX_USER_PROCESS if (ut.ut_type != UTMPX_USER_PROCESS) { continue; } #endif SIGAR_WHO_LIST_GROW(wholist); who = &wholist->data[wholist->number++]; WHOCPY(who->user, ut.ut_user); WHOCPY(who->device, ut.ut_line); WHOCPY(who->host, ut.ut_host); who->time = ut.ut_xtime; } fclose(fp); return SIGAR_OK; } #endif static int sigar_who_utmp(sigar_t *sigar, sigar_who_list_t *wholist) { FILE *fp; #ifdef __sun /* use futmpx w/ pid32_t for sparc64 */ struct futmpx ut; #else struct utmp ut; #endif if (!(fp = fopen(SIGAR_UTMP_FILE, "r"))) { #ifdef SIGAR_HAS_UTMPX /* Darwin 10.5 */ return sigar_who_utmpx(sigar, wholist); #endif return errno; } while (fread(&ut, sizeof(ut), 1, fp) == 1) { sigar_who_t *who; if (*ut.ut_name == '\0') { continue; } #ifdef USER_PROCESS if (ut.ut_type != USER_PROCESS) { continue; } #endif SIGAR_WHO_LIST_GROW(wholist); who = &wholist->data[wholist->number++]; WHOCPY(who->user, ut.ut_user); WHOCPY(who->device, ut.ut_line); WHOCPY(who->host, ut.ut_host); who->time = ut.ut_time; } fclose(fp); return SIGAR_OK; } #endif /* NETWARE */ #if defined(WIN32) int sigar_who_list_get_win32(sigar_t *sigar, sigar_who_list_t *wholist); SIGAR_DECLARE(int) sigar_who_list_get(sigar_t *sigar, sigar_who_list_t *wholist) { sigar_who_list_create(wholist); /* cygwin ssh */ sigar_who_utmp(sigar, wholist); sigar_who_list_get_win32(sigar, wholist); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_resource_limit_get(sigar_t *sigar, sigar_resource_limit_t *rlimit) { MEMORY_BASIC_INFORMATION meminfo; memset(rlimit, 0x7fffffff, sizeof(*rlimit)); if (VirtualQuery((LPCVOID)&meminfo, &meminfo, sizeof(meminfo))) { rlimit->stack_cur = (DWORD)&meminfo - (DWORD)meminfo.AllocationBase; rlimit->stack_max = ((DWORD)meminfo.BaseAddress + meminfo.RegionSize) - (DWORD)meminfo.AllocationBase; } rlimit->virtual_memory_max = rlimit->virtual_memory_cur = 0x80000000UL; return SIGAR_OK; } #elif defined(NETWARE) int sigar_resource_limit_get(sigar_t *sigar, sigar_resource_limit_t *rlimit) { return SIGAR_ENOTIMPL; } int sigar_who_list_get(sigar_t *sigar, sigar_who_list_t *wholist) { return SIGAR_ENOTIMPL; } #else #ifndef _AIX int sigar_who_list_get(sigar_t *sigar, sigar_who_list_t *wholist) { int status; sigar_who_list_create(wholist); status = sigar_who_utmp(sigar, wholist); if (status != SIGAR_OK) { sigar_who_list_destroy(sigar, wholist); return status; } return SIGAR_OK; } #endif static int sigar_get_default_gateway(sigar_t *sigar, char *gateway) { int status, i; sigar_net_route_list_t routelist; status = sigar_net_route_list_get(sigar, &routelist); if (status != SIGAR_OK) { return status; } for (i=0; iprimary_dns[0]) { SIGAR_SSTRCPY(netinfo->primary_dns, ptr); } else if (!netinfo->secondary_dns[0]) { SIGAR_SSTRCPY(netinfo->secondary_dns, ptr); } else { break; } } fclose(fp); } /* else /etc/resolv.conf may not exist if unplugged (MacOSX) */ size = sizeof(netinfo->host_name)-1; if (gethostname(netinfo->host_name, size) == 0) { netinfo->host_name[size] = '\0'; } else { netinfo->host_name[0] = '\0'; } size = sizeof(netinfo->domain_name)-1; if (getdomainname(netinfo->domain_name, size) == 0) { netinfo->domain_name[size] = '\0'; } else { netinfo->domain_name[0] = '\0'; } sigar_get_default_gateway(sigar, netinfo->default_gateway); return SIGAR_OK; } #include #define OffsetOf(structure, field) \ (size_t)(&((structure *)NULL)->field) #define RlimitOffsets(field) \ OffsetOf(sigar_resource_limit_t, field##_cur), \ OffsetOf(sigar_resource_limit_t, field##_max) #define RlimitSet(structure, ptr, val) \ *(sigar_uint64_t *)((char *)structure + (int)(long)ptr) = val typedef struct { int resource; int factor; size_t cur; size_t max; } rlimit_field_t; #ifndef RLIMIT_RSS #define RLIMIT_RSS (RLIM_NLIMITS+1) #endif #ifndef RLIMIT_NPROC #define RLIMIT_NPROC (RLIM_NLIMITS+2) #endif #define RLIMIT_PSIZE (RLIM_NLIMITS+3) #ifndef RLIMIT_AS # if defined(RLIMIT_VMEM) # define RLIMIT_AS RLIMIT_VMEM # elif defined(RLIMIT_RSS) # define RLIMIT_AS RLIMIT_RSS # endif #endif static rlimit_field_t sigar_rlimits[] = { { RLIMIT_CPU, 1, RlimitOffsets(cpu) }, { RLIMIT_FSIZE, 1024, RlimitOffsets(file_size) }, { RLIMIT_DATA, 1024, RlimitOffsets(data) }, { RLIMIT_STACK, 1024, RlimitOffsets(stack) }, { RLIMIT_PSIZE, 512, RlimitOffsets(pipe_size) }, { RLIMIT_CORE, 1024, RlimitOffsets(core) }, { RLIMIT_RSS, 1024, RlimitOffsets(memory) }, { RLIMIT_NPROC, 1, RlimitOffsets(processes) }, { RLIMIT_NOFILE, 1, RlimitOffsets(open_files) }, { RLIMIT_AS, 1024, RlimitOffsets(virtual_memory) }, { -1 } }; #define RlimitScale(val) \ if (val != RLIM_INFINITY) val /= r->factor #define RlimitHS(val) \ rl.rlim_cur = rl.rlim_max = (val) int sigar_resource_limit_get(sigar_t *sigar, sigar_resource_limit_t *rlimit) { int i; for (i=0; sigar_rlimits[i].resource != -1; i++) { struct rlimit rl; rlimit_field_t *r = &sigar_rlimits[i]; if (r->resource > RLIM_NLIMITS) { switch (r->resource) { case RLIMIT_NPROC: RlimitHS(sysconf(_SC_CHILD_MAX)); break; case RLIMIT_PSIZE: RlimitHS(PIPE_BUF/512); break; default: RlimitHS(RLIM_INFINITY); break; } } else if (getrlimit(r->resource, &rl) != 0) { RlimitHS(RLIM_INFINITY); } else { RlimitScale(rl.rlim_cur); RlimitScale(rl.rlim_max); } RlimitSet(rlimit, r->cur, rl.rlim_cur); RlimitSet(rlimit, r->max, rl.rlim_max); } return SIGAR_OK; } #endif #if !defined(WIN32) && !defined(NETWARE) && !defined(DARWIN) && \ !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) /* XXX: prolly will be moving these stuffs into os_net.c */ #include #include #ifndef SIOCGIFCONF #include #endif #if defined(_AIX) || defined(__osf__) /* good buddies */ #include static void hwaddr_aix_lookup(sigar_t *sigar, sigar_net_interface_config_t *ifconfig) { char *ent, *end; struct ifreq *ifr; /* XXX: assumes sigar_net_interface_list_get has been called */ end = sigar->ifconf_buf + sigar->ifconf_len; for (ent = sigar->ifconf_buf; ent < end; ent += sizeof(*ifr)) { ifr = (struct ifreq *)ent; if (ifr->ifr_addr.sa_family != AF_LINK) { continue; } if (strEQ(ifr->ifr_name, ifconfig->name)) { struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr; sigar_net_address_mac_set(ifconfig->hwaddr, LLADDR(sdl), sdl->sdl_alen); return; } } sigar_hwaddr_set_null(ifconfig); } #elif !defined(SIOCGIFHWADDR) #include static void hwaddr_arp_lookup(sigar_net_interface_config_t *ifconfig, int sock) { struct arpreq areq; struct sockaddr_in *sa; memset(&areq, 0, sizeof(areq)); sa = (struct sockaddr_in *)&areq.arp_pa; sa->sin_family = AF_INET; sa->sin_addr.s_addr = ifconfig->address.addr.in; if (ioctl(sock, SIOCGARP, &areq) < 0) { /* ho-hum */ sigar_hwaddr_set_null(ifconfig); } else { sigar_net_address_mac_set(ifconfig->hwaddr, areq.arp_ha.sa_data, SIGAR_IFHWADDRLEN); } } #endif #ifdef __linux__ #include static void get_interface_type(sigar_net_interface_config_t *ifconfig, int family) { char *type; switch (family) { case ARPHRD_NETROM: type = SIGAR_NIC_NETROM; break; /* XXX more */ default: type = SIGAR_NIC_ETHERNET; break; } SIGAR_SSTRCPY(ifconfig->type, type); } #endif int sigar_net_interface_config_get(sigar_t *sigar, const char *name, sigar_net_interface_config_t *ifconfig) { int sock; struct ifreq ifr; if (!name) { return sigar_net_interface_config_primary_get(sigar, ifconfig); } SIGAR_ZERO(ifconfig); if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { return errno; } SIGAR_SSTRCPY(ifconfig->name, name); SIGAR_SSTRCPY(ifr.ifr_name, name); #define ifr_s_addr(ifr) \ ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr if (!ioctl(sock, SIOCGIFADDR, &ifr)) { sigar_net_address_set(ifconfig->address, ifr_s_addr(ifr)); } if (!ioctl(sock, SIOCGIFNETMASK, &ifr)) { sigar_net_address_set(ifconfig->netmask, ifr_s_addr(ifr)); } if (!ioctl(sock, SIOCGIFFLAGS, &ifr)) { sigar_uint64_t flags = ifr.ifr_flags; #ifdef __linux__ int is_mcast = flags & IFF_MULTICAST; int is_slave = flags & IFF_SLAVE; /* * XXX: should just define SIGAR_IFF_* * and test IFF_* bits on given platform. * this is the only diff between solaris/hpux/linux * for the flags we care about. * */ flags &= ~(IFF_MULTICAST|IFF_SLAVE); if (is_mcast) { flags |= SIGAR_IFF_MULTICAST; } if (is_slave) { flags |= SIGAR_IFF_SLAVE; } #endif ifconfig->flags = flags; } else { /* should always be able to get flags for existing device */ /* other ioctls may fail if device is not enabled: ok */ close(sock); return errno; } if (ifconfig->flags & IFF_LOOPBACK) { sigar_net_address_set(ifconfig->destination, ifconfig->address.addr.in); sigar_net_address_set(ifconfig->broadcast, 0); sigar_hwaddr_set_null(ifconfig); SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_LOOPBACK); } else { if (!ioctl(sock, SIOCGIFDSTADDR, &ifr)) { sigar_net_address_set(ifconfig->destination, ifr_s_addr(ifr)); } if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) { sigar_net_address_set(ifconfig->broadcast, ifr_s_addr(ifr)); } #if defined(SIOCGIFHWADDR) if (!ioctl(sock, SIOCGIFHWADDR, &ifr)) { get_interface_type(ifconfig, ifr.ifr_hwaddr.sa_family); sigar_net_address_mac_set(ifconfig->hwaddr, ifr.ifr_hwaddr.sa_data, IFHWADDRLEN); } #elif defined(_AIX) || defined(__osf__) hwaddr_aix_lookup(sigar, ifconfig); SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_ETHERNET); #else hwaddr_arp_lookup(ifconfig, sock); SIGAR_SSTRCPY(ifconfig->type, SIGAR_NIC_ETHERNET); #endif } #if defined(SIOCGLIFMTU) && !defined(__hpux) { struct lifreq lifr; SIGAR_SSTRCPY(lifr.lifr_name, name); if(!ioctl(sock, SIOCGLIFMTU, &lifr)) { ifconfig->mtu = lifr.lifr_mtu; } } #elif defined(SIOCGIFMTU) if (!ioctl(sock, SIOCGIFMTU, &ifr)) { # if defined(__hpux) ifconfig->mtu = ifr.ifr_metric; # else ifconfig->mtu = ifr.ifr_mtu; #endif } #else ifconfig->mtu = 0; /*XXX*/ #endif if (!ioctl(sock, SIOCGIFMETRIC, &ifr)) { ifconfig->metric = ifr.ifr_metric ? ifr.ifr_metric : 1; } close(sock); /* XXX can we get a better description like win32? */ SIGAR_SSTRCPY(ifconfig->description, ifconfig->name); return SIGAR_OK; } #ifdef _AIX # define MY_SIOCGIFCONF CSIOCGIFCONF #else # define MY_SIOCGIFCONF SIOCGIFCONF #endif #ifdef __osf__ static int sigar_netif_configured(sigar_t *sigar, char *name) { int status; sigar_net_interface_config_t ifconfig; status = sigar_net_interface_config_get(sigar, name, &ifconfig); return status == SIGAR_OK; } #endif #ifdef __linux__ static SIGAR_INLINE int has_interface(sigar_net_interface_list_t *iflist, char *name) { register int i; register int num = iflist->number; register char **data = iflist->data; for (i=0; idata[iflist->number++] = sigar_strdup(dev); } fclose(fp); return SIGAR_OK; } #endif int sigar_net_interface_list_get(sigar_t *sigar, sigar_net_interface_list_t *iflist) { int n, lastlen=0; struct ifreq *ifr; struct ifconf ifc; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { return errno; } for (;;) { if (!sigar->ifconf_buf || lastlen) { sigar->ifconf_len += sizeof(struct ifreq) * SIGAR_NET_IFLIST_MAX; sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len); } ifc.ifc_len = sigar->ifconf_len; ifc.ifc_buf = sigar->ifconf_buf; if (ioctl(sock, MY_SIOCGIFCONF, &ifc) < 0) { /* EINVAL should mean num_interfaces > ifc.ifc_len */ if ((errno != EINVAL) || (lastlen == ifc.ifc_len)) { free(ifc.ifc_buf); return errno; } } if (ifc.ifc_len < sigar->ifconf_len) { break; /* got em all */ } if (ifc.ifc_len != lastlen) { /* might be more */ lastlen = ifc.ifc_len; continue; } break; } close(sock); iflist->number = 0; iflist->size = ifc.ifc_len; iflist->data = malloc(sizeof(*(iflist->data)) * iflist->size); ifr = ifc.ifc_req; for (n = 0; n < ifc.ifc_len; n += sizeof(struct ifreq), ifr++) { #if defined(_AIX) || defined(__osf__) /* pass the bourbon */ if (ifr->ifr_addr.sa_family != AF_LINK) { /* XXX: dunno if this is right. * otherwise end up with two 'en0' and three 'lo0' * with the same ip address. */ continue; } # ifdef __osf__ /* weed out "sl0", "tun0" and the like */ /* XXX must be a better way to check this */ if (!sigar_netif_configured(sigar, ifr->ifr_name)) { continue; } # endif #endif iflist->data[iflist->number++] = sigar_strdup(ifr->ifr_name); } #ifdef __linux__ proc_net_interface_list_get(sigar, iflist); #endif return SIGAR_OK; } #endif /* WIN32 */ SIGAR_DECLARE(int) sigar_net_interface_config_primary_get(sigar_t *sigar, sigar_net_interface_config_t *ifconfig) { int i, status, found=0; sigar_net_interface_list_t iflist; sigar_net_interface_config_t possible_config; possible_config.flags = 0; if ((status = sigar_net_interface_list_get(sigar, &iflist)) != SIGAR_OK) { return status; } for (i=0; iflags & SIGAR_IFF_LOOPBACK) || !ifconfig->hwaddr.addr.in) /* no mac address */ { continue; } if (!possible_config.flags) { /* save for later for use if we're not connected to the net * or all interfaces are aliases (e.g. solaris zone) */ memcpy(&possible_config, ifconfig, sizeof(*ifconfig)); } if (!ifconfig->address.addr.in) { continue; /* no ip address */ } if (strchr(iflist.data[i], ':')) { continue; /* alias */ } found = 1; break; } sigar_net_interface_list_destroy(sigar, &iflist); if (found) { return SIGAR_OK; } else if (possible_config.flags) { memcpy(ifconfig, &possible_config, sizeof(*ifconfig)); return SIGAR_OK; } else { return SIGAR_ENXIO; } } static int fqdn_ip_get(sigar_t *sigar, char *name) { sigar_net_interface_config_t ifconfig; int status; status = sigar_net_interface_config_primary_get(sigar, &ifconfig); if (status != SIGAR_OK) { return status; } if (!ifconfig.address.addr.in) { return SIGAR_ENXIO; } sigar_net_address_to_string(sigar, &ifconfig.address, name); sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] using ip address '%s' for fqdn", name); return SIGAR_OK; } struct hostent *sigar_gethostbyname(const char *name, sigar_hostent_t *data) { struct hostent *hp = NULL; #if defined(__linux__) gethostbyname_r(name, &data->hs, data->buffer, sizeof(data->buffer), &hp, &data->error); #elif defined(__sun) hp = gethostbyname_r(name, &data->hs, data->buffer, sizeof(data->buffer), &data->error); #elif defined(SIGAR_HAS_HOSTENT_DATA) if (gethostbyname_r(name, &data->hs, &data->hd) == 0) { hp = &data->hs; } else { data->error = h_errno; } #else hp = gethostbyname(name); #endif return hp; } static struct hostent *sigar_gethostbyaddr(const char *addr, int len, int type, sigar_hostent_t *data) { struct hostent *hp = NULL; #if defined(__linux__) gethostbyaddr_r(addr, len, type, &data->hs, data->buffer, sizeof(data->buffer), &hp, &data->error); #elif defined(__sun) hp = gethostbyaddr_r(addr, len, type, &data->hs, data->buffer, sizeof(data->buffer), &data->error); #elif defined(SIGAR_HAS_HOSTENT_DATA) if (gethostbyaddr_r((char *)addr, len, type, &data->hs, &data->hd) == 0) { hp = &data->hs; } else { data->error = h_errno; } #else if (!(hp = gethostbyaddr(addr, len, type))) { data->error = h_errno; } #endif return hp; } #define IS_FQDN(name) \ (name && strchr(name, '.')) #define IS_FQDN_MATCH(lookup, name) \ (IS_FQDN(lookup) && strnEQ(lookup, name, strlen(name))) #define FQDN_SET(fqdn) \ SIGAR_STRNCPY(name, fqdn, namelen) SIGAR_DECLARE(int) sigar_fqdn_get(sigar_t *sigar, char *name, int namelen) { register int is_debug = SIGAR_LOG_IS_DEBUG(sigar); sigar_hostent_t data; struct hostent *p; char domain[SIGAR_FQDN_LEN + 1]; #ifdef WIN32 int status = sigar_wsa_init(sigar); if (status != SIGAR_OK) { return status; } #endif if (gethostname(name, namelen - 1) != 0) { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "[fqdn] gethostname failed: %s", sigar_strerror(sigar, errno)); return errno; } else { if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] gethostname()=='%s'", name); } } if (!(p = sigar_gethostbyname(name, &data))) { if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] gethostbyname(%s) failed: %s", name, sigar_strerror(sigar, errno)); } if (!IS_FQDN(name)) { fqdn_ip_get(sigar, name); } return SIGAR_OK; } if (IS_FQDN_MATCH(p->h_name, name)) { FQDN_SET(p->h_name); sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] resolved using gethostbyname.h_name"); return SIGAR_OK; } else { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] unresolved using gethostbyname.h_name"); } if (p->h_aliases) { int i; for (i=0; p->h_aliases[i]; i++) { if (IS_FQDN_MATCH(p->h_aliases[i], name)) { FQDN_SET(p->h_aliases[i]); sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] resolved using gethostbyname.h_aliases"); return SIGAR_OK; } else if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] gethostbyname(%s).alias[%d]=='%s'", name, i, p->h_aliases[i]); } } } sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] unresolved using gethostbyname.h_aliases"); if (p->h_addr_list) { int i,j; for (i=0; p->h_addr_list[i]; i++) { char addr[SIGAR_INET6_ADDRSTRLEN]; struct in_addr *in = (struct in_addr *)p->h_addr_list[i]; struct hostent *q = sigar_gethostbyaddr(p->h_addr_list[i], p->h_length, p->h_addrtype, &data); if (is_debug) { sigar_inet_ntoa(sigar, in->s_addr, addr); } if (!q) { if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] gethostbyaddr(%s) failed: %s", addr, sigar_strerror(sigar, errno)); } continue; } if (IS_FQDN_MATCH(q->h_name, name)) { FQDN_SET(q->h_name); sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] resolved using gethostbyaddr.h_name"); return SIGAR_OK; } else { if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] gethostbyaddr(%s)=='%s'", addr, q->h_name); } for (j=0; q->h_aliases[j]; j++) { if (IS_FQDN_MATCH(q->h_aliases[j], name)) { FQDN_SET(q->h_aliases[j]); sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] resolved using " "gethostbyaddr.h_aliases"); return SIGAR_OK; } else if (is_debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[fqdn] gethostbyaddr(%s).alias[%d]=='%s'", addr, j, q->h_aliases[j]); } } } } } sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] unresolved using gethostbyname.h_addr_list"); #if !defined(WIN32) && !defined(NETWARE) if (!IS_FQDN(name) && /* e.g. aix gethostname is already fqdn */ (getdomainname(domain, sizeof(domain) - 1) == 0) && (domain[0] != '\0') && (domain[0] != '(')) /* linux default is "(none)" */ { /* sprintf(name, "%s.%s", name, domain); */ char *ptr = name; int len = strlen(name); ptr += len; *ptr++ = '.'; namelen -= (len+1); SIGAR_STRNCPY(ptr, domain, namelen); sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] resolved using getdomainname"); } else { sigar_log(sigar, SIGAR_LOG_DEBUG, "[fqdn] getdomainname failed"); } #endif if (!IS_FQDN(name)) { fqdn_ip_get(sigar, name); } return SIGAR_OK; } #ifndef MAX_STRING_LEN #define MAX_STRING_LEN 8192 #endif #ifdef WIN32 /* The windows version of getPasswordNative was lifted from apr */ SIGAR_DECLARE(char *) sigar_password_get(const char *prompt) { static char password[MAX_STRING_LEN]; int n = 0; int ch; fputs(prompt, stderr); fflush(stderr); while ((ch = _getch()) != '\r') { if (ch == EOF) /* EOF */ { return NULL; } else if (ch == 0 || ch == 0xE0) { /* FN Keys (0 or E0) are a sentinal for a FN code */ ch = (ch << 4) | _getch(); /* Catch {DELETE}, {<--}, Num{DEL} and Num{<--} */ if ((ch == 0xE53 || ch == 0xE4B || ch == 0x053 || ch == 0x04b) && n) { password[--n] = '\0'; fputs("\b \b", stderr); fflush(stderr); } else { fputc('\a', stderr); fflush(stderr); } } else if ((ch == '\b' || ch == 127) && n) /* BS/DEL */ { password[--n] = '\0'; fputs("\b \b", stderr); fflush(stderr); } else if (ch == 3) /* CTRL+C */ { /* _getch() bypasses Ctrl+C but not Ctrl+Break detection! */ fputs("^C\n", stderr); fflush(stderr); exit(-1); } else if (ch == 26) /* CTRL+Z */ { fputs("^Z\n", stderr); fflush(stderr); return NULL; } else if (ch == 27) /* ESC */ { fputc('\n', stderr); fputs(prompt, stderr); fflush(stderr); n = 0; } else if ((n < sizeof(password) - 1) && !iscntrl(ch)) { password[n++] = ch; fputc(' ', stderr); fflush(stderr); } else { fputc('\a', stderr); fflush(stderr); } } fputc('\n', stderr); fflush(stderr); password[n] = '\0'; return password; } #else /* linux/hpux/solaris getpass() prototype lives here */ #include #include /* from apr_getpass.c */ #if defined(SIGAR_HPUX) # define getpass termios_getpass #elif defined(SIGAR_SOLARIS) # define getpass getpassphrase #endif #ifdef SIGAR_HPUX static char *termios_getpass(const char *prompt) { struct termios attr; static char password[MAX_STRING_LEN]; unsigned int n=0; fputs(prompt, stderr); fflush(stderr); if (tcgetattr(STDIN_FILENO, &attr) != 0) { return NULL; } attr.c_lflag &= ~(ECHO); if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &attr) != 0) { return NULL; } while ((password[n] = getchar()) != '\n') { if (n < (sizeof(password) - 1) && (password[n] >= ' ') && (password[n] <= '~')) { n++; } else { fprintf(stderr, "\n"); fputs(prompt, stderr); fflush(stderr); n = 0; } } password[n] = '\0'; printf("\n"); if (n > (MAX_STRING_LEN - 1)) { password[MAX_STRING_LEN - 1] = '\0'; } attr.c_lflag |= ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &attr); return (char *)&password; } #endif SIGAR_DECLARE(char *) sigar_password_get(const char *prompt) { char *buf = NULL; /* the linux version of getpass prints the prompt to the tty; ok. * the solaris version prints the prompt to stderr; not ok. * so print the prompt to /dev/tty ourselves if possible (always should be) */ FILE *tty = NULL; if ((tty = fopen("/dev/tty", "w"))) { fprintf(tty, "%s", prompt); fflush(tty); buf = getpass(tty ? "" : prompt); fclose(tty); } return buf; } #endif /* WIN32 */ hyperic-sigar-1.6.4+dfsg/src/sigar_cache.c000066400000000000000000000103241210132627500203710ustar00rootroot00000000000000/* * Copyright (c) 2004-2006 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. */ #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include /* * hash table to cache values where key is a unique number * such as: * pid -> some process data * uid -> user name * gid -> group name */ #define ENTRIES_SIZE(n) \ (sizeof(sigar_cache_entry_t *) * (n)) /* wrap free() for use w/ dmalloc */ static void free_value(void *ptr) { free(ptr); } sigar_cache_t *sigar_cache_new(int size) { sigar_cache_t *table = malloc(sizeof(*table)); table->count = 0; table->size = size; table->entries = malloc(ENTRIES_SIZE(size)); memset(table->entries, '\0', ENTRIES_SIZE(size)); table->free_value = free_value; return table; } #ifdef DEBUG_CACHE /* see how well entries are distributed */ static void sigar_cache_dump(sigar_cache_t *table) { int i; sigar_cache_entry_t **entries = table->entries; for (i=0; isize; i++) { sigar_cache_entry_t *entry = *entries++; printf("|"); while (entry) { printf("%lld", entry->id); if (entry->next) { printf(","); } entry = entry->next; } } printf("\n"); fflush(stdout); } #endif static void sigar_cache_rehash(sigar_cache_t *table) { int i; unsigned int new_size = table->size * 2 + 1; sigar_cache_entry_t **entries = table->entries; sigar_cache_entry_t **new_entries = malloc(ENTRIES_SIZE(new_size)); memset(new_entries, '\0', ENTRIES_SIZE(new_size)); for (i=0; isize; i++) { sigar_cache_entry_t *entry = *entries++; while (entry) { sigar_cache_entry_t *next = entry->next; sigar_uint64_t hash = entry->id % new_size; entry->next = new_entries[hash]; new_entries[hash] = entry; entry = next; } } free(table->entries); table->entries = new_entries; table->size = new_size; } #define SIGAR_CACHE_IX(t, k) \ t->entries + (k % t->size) sigar_cache_entry_t *sigar_cache_find(sigar_cache_t *table, sigar_uint64_t key) { sigar_cache_entry_t *entry, **ptr; for (ptr = SIGAR_CACHE_IX(table, key), entry = *ptr; entry; ptr = &entry->next, entry = *ptr) { if (entry->id == key) { return entry; } } return NULL; } /* create entry if it does not exist */ sigar_cache_entry_t *sigar_cache_get(sigar_cache_t *table, sigar_uint64_t key) { sigar_cache_entry_t *entry, **ptr; for (ptr = SIGAR_CACHE_IX(table, key), entry = *ptr; entry; ptr = &entry->next, entry = *ptr) { if (entry->id == key) { return entry; } } if (table->count++ > table->size) { sigar_cache_rehash(table); for (ptr = SIGAR_CACHE_IX(table, key), entry = *ptr; entry; ptr = &entry->next, entry = *ptr) { } } *ptr = entry = malloc(sizeof(*entry)); entry->id = key; entry->value = NULL; entry->next = NULL; return entry; } void sigar_cache_destroy(sigar_cache_t *table) { int i; sigar_cache_entry_t **entries = table->entries; #ifdef DEBUG_CACHE sigar_cache_dump(table); #endif for (i=0; isize; i++) { sigar_cache_entry_t *entry, *ptr; entry = *entries++; while (entry) { if (entry->value) { table->free_value(entry->value); } ptr = entry->next; free(entry); entry = ptr; } } free(table->entries); free(table); } hyperic-sigar-1.6.4+dfsg/src/sigar_fileinfo.c000066400000000000000000000522411210132627500211250ustar00rootroot00000000000000/* * Copyright (c) 2004-2005, 2007-2008 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ #ifndef WIN32 # ifdef _AIX # define _LARGE_FILES # else # define _FILE_OFFSET_BITS 64 # define _LARGEFILE64_SOURCE # endif #endif #include "sigar.h" #ifndef WIN32 #if defined(__FreeBSD__) || defined(__OpenBSD__) # include # include #else # include # define HAVE_STATVFS #endif #include #define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1) int sigar_statvfs(sigar_t *sigar, const char *dirname, sigar_file_system_usage_t *fsusage) { sigar_uint64_t val, bsize; #ifdef HAVE_STATVFS struct statvfs buf; int status = # if defined(__sun) && !defined(_LP64) /* http://bugs.opensolaris.org/view_bug.do?bug_id=4462986 */ statvfs(dirname, (void *)&buf); # else statvfs(dirname, &buf); # endif #else struct statfs buf; int status = statfs(dirname, &buf); #endif if (status != 0) { return errno; } #ifdef HAVE_STATVFS bsize = buf.f_frsize / 512; #else bsize = buf.f_bsize / 512; #endif val = buf.f_blocks; fsusage->total = SIGAR_FS_BLOCKS_TO_BYTES(val, bsize); val = buf.f_bfree; fsusage->free = SIGAR_FS_BLOCKS_TO_BYTES(val, bsize); val = buf.f_bavail; fsusage->avail = SIGAR_FS_BLOCKS_TO_BYTES(val, bsize); fsusage->used = fsusage->total - fsusage->free; fsusage->files = buf.f_files; fsusage->free_files = buf.f_ffree; return SIGAR_OK; } #endif /* * whittled down version of apr/file_info/{unix,win32}/filestat.c * to fillin sigar_fileattrs_t */ #include "sigar_fileinfo.h" #include "sigar_log.h" #ifndef SIGAR_ZERO #define SIGAR_ZERO(s) \ memset(s, '\0', sizeof(*(s))) #endif #ifdef WIN32 #include sigar_uint64_t sigar_FileTimeToTime(FILETIME *ft); #else #include #endif static const char* types[] = { "none", "regular", "directory", "character device", "block device", "pipe", "symbolic link", "socket", "unknown" }; SIGAR_DECLARE(const char *) sigar_file_attrs_type_string_get(sigar_file_type_e type) { if ((type < SIGAR_FILETYPE_NOFILE) || (type > SIGAR_FILETYPE_UNKFILE)) { type = SIGAR_FILETYPE_UNKFILE; } return types[type]; } static const sigar_uint64_t perm_modes[] = { SIGAR_UREAD, SIGAR_UWRITE, SIGAR_UEXECUTE, SIGAR_GREAD, SIGAR_GWRITE, SIGAR_GEXECUTE, SIGAR_WREAD, SIGAR_WWRITE, SIGAR_WEXECUTE }; static const char perm_chars[] = "rwx"; SIGAR_DECLARE(char *) sigar_file_attrs_permissions_string_get(sigar_uint64_t permissions, char *str) { char *ptr = str; int i=0, j=0; for (i=0; i<9; i+=3) { for (j=0; j<3; j++) { if (permissions & perm_modes[i+j]) { *ptr = perm_chars[j]; } else { *ptr = '-'; } ptr++; } } *ptr = '\0'; return str; } static const int perm_int[] = { 400, 200, 100, 40, 20, 10, 4, 2, 1 }; SIGAR_DECLARE(int)sigar_file_attrs_mode_get(sigar_uint64_t permissions) { int i=0; int perms = 0; /* no doubt there is some fancy bitshifting * to convert, but this works fine. */ for (i=0; i<9; i++) { if (permissions & perm_modes[i]) { perms += perm_int[i]; } } return perms; } #define IS_DOTDIR(dir) \ ((dir[0] == '.') && (!dir[1] || ((dir[1] == '.') && !dir[2]))) #define DIR_STAT_WARN() \ sigar_log_printf(sigar, SIGAR_LOG_WARN, \ "dir_stat: cannot stat `%s': %s", \ name, \ sigar_strerror(sigar, status)) #if defined(NETWARE) int sigar_dir_stat_get(sigar_t *sigar, const char *dir, sigar_dir_stat_t *dirstats) { return SIGAR_ENOTIMPL; } int sigar_file_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { return SIGAR_ENOTIMPL; } int sigar_link_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { return SIGAR_ENOTIMPL; } #elif defined(WIN32) #include #include static void fillin_fileattrs(sigar_file_attrs_t *finfo, WIN32_FILE_ATTRIBUTE_DATA *wininfo, int linkinfo) { DWORD *sizes = &wininfo->nFileSizeHigh; finfo->atime = sigar_FileTimeToTime(&wininfo->ftLastAccessTime) / 1000; finfo->ctime = sigar_FileTimeToTime(&wininfo->ftCreationTime) / 1000; finfo->mtime = sigar_FileTimeToTime(&wininfo->ftLastWriteTime) / 1000; finfo->size = (sigar_uint64_t)sizes[1] | ((sigar_uint64_t)sizes[0] << 32); if (linkinfo && (wininfo->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) { finfo->type = SIGAR_FILETYPE_LNK; } else if (wininfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { finfo->type = SIGAR_FILETYPE_DIR; } else { finfo->type = SIGAR_FILETYPE_REG; } } static sigar_uint64_t convert_perms(ACCESS_MASK acc, sigar_uint64_t scope) { sigar_uint64_t perms = 0; if (acc & FILE_EXECUTE) { perms |= SIGAR_WEXECUTE; } if (acc & FILE_WRITE_DATA) { perms |= SIGAR_WWRITE; } if (acc & FILE_READ_DATA) { perms |= SIGAR_WREAD; } return (perms << scope); } static int get_security_info(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { DWORD retval; PSID user = NULL, group = NULL, world = NULL; PACL dacl = NULL; PSECURITY_DESCRIPTOR pdesc = NULL; SECURITY_INFORMATION sinfo = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; TRUSTEE ident = {NULL, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID}; ACCESS_MASK acc; SID_IDENTIFIER_AUTHORITY auth = SECURITY_WORLD_SID_AUTHORITY; retval = GetNamedSecurityInfo((char *)file, SE_FILE_OBJECT, sinfo, &user, &group, &dacl, NULL, &pdesc); if (retval != ERROR_SUCCESS) { return retval; } if (!AllocateAndInitializeSid(&auth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &world)) { world = NULL; } ident.TrusteeType = TRUSTEE_IS_USER; ident.ptstrName = user; if (GetEffectiveRightsFromAcl(dacl, &ident, &acc) == ERROR_SUCCESS) { fileattrs->permissions |= convert_perms(acc, 8); } ident.TrusteeType = TRUSTEE_IS_GROUP; ident.ptstrName = group; if (GetEffectiveRightsFromAcl(dacl, &ident, &acc) == ERROR_SUCCESS) { fileattrs->permissions |= convert_perms(acc, 4); } if (world) { ident.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ident.ptstrName = world; if (GetEffectiveRightsFromAcl(dacl, &ident, &acc) == ERROR_SUCCESS) { fileattrs->permissions |= convert_perms(acc, 0); } } if (world) { FreeSid(world); } LocalFree(pdesc); return SIGAR_OK; } static int fileattrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs, int linkinfo) { BY_HANDLE_FILE_INFORMATION info; WIN32_FILE_ATTRIBUTE_DATA attrs; HANDLE handle; DWORD flags; SIGAR_ZERO(fileattrs); if (!GetFileAttributesExA(file, GetFileExInfoStandard, &attrs)) { return GetLastError(); } fillin_fileattrs(fileattrs, &attrs, linkinfo); flags = fileattrs->type == SIGAR_FILETYPE_DIR ? FILE_FLAG_BACKUP_SEMANTICS : FILE_ATTRIBUTE_NORMAL; /** * We need to set dwDesiredAccess to 0 to work in cases where GENERIC_READ can fail. * * see: http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx */ handle = CreateFile(file, 0, 0, NULL, OPEN_EXISTING, flags, NULL); if (handle != INVALID_HANDLE_VALUE) { if (GetFileInformationByHandle(handle, &info)) { fileattrs->inode = info.nFileIndexLow | (info.nFileIndexHigh << 32); fileattrs->device = info.dwVolumeSerialNumber; fileattrs->nlink = info.nNumberOfLinks; } CloseHandle(handle); } get_security_info(sigar, file, fileattrs); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_file_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { return fileattrs_get(sigar, file, fileattrs, 0); } SIGAR_DECLARE(int) sigar_link_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { return fileattrs_get(sigar, file, fileattrs, 1); } static __inline int file_type(char *file) { WIN32_FILE_ATTRIBUTE_DATA attrs; if (!GetFileAttributesExA(file, GetFileExInfoStandard, &attrs)) { return -1; } if (attrs.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { return SIGAR_FILETYPE_LNK; } else if (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { return SIGAR_FILETYPE_DIR; } else { return SIGAR_FILETYPE_REG; } } static int dir_stat_get(sigar_t *sigar, const char *dir, sigar_dir_stat_t *dirstats, int recurse) { int status; char name[SIGAR_PATH_MAX+1]; int len = strlen(dir); int max = sizeof(name)-len-1; char *ptr = name; WIN32_FIND_DATA data; HANDLE handle; DWORD error; char delim; if (file_type((char *)dir) != SIGAR_FILETYPE_DIR) { return ERROR_NO_MORE_FILES; } strncpy(name, dir, sizeof(name)); ptr += len; if (strchr(dir, '/')) { delim = '/'; } else { delim = '\\'; } if (name[len] != delim) { *ptr++ = delim; len++; max--; } /* e.g. "C:\sigar\*" */ name[len] = '*'; name[len+1] = '\0'; handle = FindFirstFile(name, &data); if (handle == INVALID_HANDLE_VALUE) { return GetLastError(); } do { /* skip '.' and '..' */ if (IS_DOTDIR(data.cFileName)) { continue; } dirstats->disk_usage += (data.nFileSizeHigh * (MAXDWORD+1)) + data.nFileSizeLow; /* e.g. "C:\sigar\lib" */ strncpy(ptr, data.cFileName, max); ptr[max] = '\0'; switch (file_type(name)) { case -1: break; case SIGAR_FILETYPE_REG: ++dirstats->files; break; case SIGAR_FILETYPE_DIR: ++dirstats->subdirs; if (recurse) { status = dir_stat_get(sigar, name, dirstats, recurse); if (status != SIGAR_OK) { DIR_STAT_WARN(); } } break; case SIGAR_FILETYPE_LNK: ++dirstats->symlinks; break; case SIGAR_FILETYPE_CHR: ++dirstats->chrdevs; break; case SIGAR_FILETYPE_BLK: ++dirstats->blkdevs; break; case SIGAR_FILETYPE_SOCK: ++dirstats->sockets; break; default: ++dirstats->total; } } while (FindNextFile(handle, &data)); error = GetLastError(); FindClose(handle); if (error != ERROR_NO_MORE_FILES) { return error; } dirstats->total = dirstats->files + dirstats->subdirs + dirstats->symlinks + dirstats->chrdevs + dirstats->blkdevs + dirstats->sockets; return SIGAR_OK; } #else #include #include #include #include static sigar_file_type_e filetype_from_mode(mode_t mode) { sigar_file_type_e type; switch (mode & S_IFMT) { case S_IFREG: type = SIGAR_FILETYPE_REG; break; case S_IFDIR: type = SIGAR_FILETYPE_DIR; break; case S_IFLNK: type = SIGAR_FILETYPE_LNK; break; case S_IFCHR: type = SIGAR_FILETYPE_CHR; break; case S_IFBLK: type = SIGAR_FILETYPE_BLK; break; #if defined(S_IFFIFO) case S_IFFIFO: type = SIGAR_FILETYPE_PIPE; break; #endif #if !defined(BEOS) && defined(S_IFSOCK) case S_IFSOCK: type = SIGAR_FILETYPE_SOCK; break; #endif default: /* Work around missing S_IFxxx values above * for Linux et al. */ #if !defined(S_IFFIFO) && defined(S_ISFIFO) if (S_ISFIFO(mode)) { type = SIGAR_FILETYPE_PIPE; } else #endif #if !defined(BEOS) && !defined(S_IFSOCK) && defined(S_ISSOCK) if (S_ISSOCK(mode)) { type = SIGAR_FILETYPE_SOCK; } else #endif type = SIGAR_FILETYPE_UNKFILE; } return type; } static sigar_uint64_t sigar_unix_mode2perms(mode_t mode) { sigar_uint64_t perms = 0; if (mode & S_IRUSR) perms |= SIGAR_UREAD; if (mode & S_IWUSR) perms |= SIGAR_UWRITE; if (mode & S_IXUSR) perms |= SIGAR_UEXECUTE; if (mode & S_IRGRP) perms |= SIGAR_GREAD; if (mode & S_IWGRP) perms |= SIGAR_GWRITE; if (mode & S_IXGRP) perms |= SIGAR_GEXECUTE; if (mode & S_IROTH) perms |= SIGAR_WREAD; if (mode & S_IWOTH) perms |= SIGAR_WWRITE; if (mode & S_IXOTH) perms |= SIGAR_WEXECUTE; return perms; } static void copy_stat_info(sigar_file_attrs_t *fileattrs, struct stat *info) { fileattrs->permissions = sigar_unix_mode2perms(info->st_mode); fileattrs->type = filetype_from_mode(info->st_mode); fileattrs->uid = info->st_uid; fileattrs->gid = info->st_gid; fileattrs->size = info->st_size; fileattrs->inode = info->st_ino; fileattrs->device = info->st_dev; fileattrs->nlink = info->st_nlink; fileattrs->atime = info->st_atime; fileattrs->mtime = info->st_mtime; fileattrs->ctime = info->st_ctime; fileattrs->atime *= 1000; fileattrs->mtime *= 1000; fileattrs->ctime *= 1000; } int sigar_file_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { struct stat info; if (stat(file, &info) == 0) { copy_stat_info(fileattrs, &info); return SIGAR_OK; } else { return errno; } } int sigar_link_attrs_get(sigar_t *sigar, const char *file, sigar_file_attrs_t *fileattrs) { struct stat info; if (lstat(file, &info) == 0) { copy_stat_info(fileattrs, &info); return SIGAR_OK; } else { return errno; } } static int dir_stat_get(sigar_t *sigar, const char *dir, sigar_dir_stat_t *dirstats, int recurse) { int status; char name[SIGAR_PATH_MAX+1]; int len = strlen(dir); int max = sizeof(name)-len-1; char *ptr = name; DIR *dirp = opendir(dir); struct dirent *ent; struct stat info; #ifdef HAVE_READDIR_R struct dirent dbuf; #endif if (!dirp) { return errno; } strncpy(name, dir, sizeof(name)); ptr += len; if (name[len] != '/') { *ptr++ = '/'; len++; max--; } #ifdef HAVE_READDIR_R while (readdir_r(dirp, &dbuf, &ent) == 0) { if (ent == NULL) { break; } #else while ((ent = readdir(dirp))) { #endif /* skip '.' and '..' */ if (IS_DOTDIR(ent->d_name)) { continue; } strncpy(ptr, ent->d_name, max); ptr[max] = '\0'; if (lstat(name, &info) != 0) { continue; } dirstats->disk_usage += info.st_size; switch (filetype_from_mode(info.st_mode)) { case SIGAR_FILETYPE_REG: ++dirstats->files; break; case SIGAR_FILETYPE_DIR: ++dirstats->subdirs; if (recurse) { status = dir_stat_get(sigar, name, dirstats, recurse); if (status != SIGAR_OK) { DIR_STAT_WARN(); } } break; case SIGAR_FILETYPE_LNK: ++dirstats->symlinks; break; case SIGAR_FILETYPE_CHR: ++dirstats->chrdevs; break; case SIGAR_FILETYPE_BLK: ++dirstats->blkdevs; break; case SIGAR_FILETYPE_SOCK: ++dirstats->sockets; break; default: ++dirstats->total; } } dirstats->total = dirstats->files + dirstats->subdirs + dirstats->symlinks + dirstats->chrdevs + dirstats->blkdevs + dirstats->sockets; closedir(dirp); return SIGAR_OK; } #endif SIGAR_DECLARE(int) sigar_dir_stat_get(sigar_t *sigar, const char *dir, sigar_dir_stat_t *dirstats) { SIGAR_ZERO(dirstats); return dir_stat_get(sigar, dir, dirstats, 0); } SIGAR_DECLARE(int) sigar_dir_usage_get(sigar_t *sigar, const char *dir, sigar_dir_usage_t *dirusage) { SIGAR_ZERO(dirusage); return dir_stat_get(sigar, dir, dirusage, 1); } hyperic-sigar-1.6.4+dfsg/src/sigar_format.c000066400000000000000000000374751210132627500206360ustar00rootroot00000000000000/* * Copyright (c) 2007-2008 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /* Utility functions to provide string formatting of SIGAR data */ #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #include "sigar_format.h" #include #include #ifndef WIN32 #include #include #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(_AIX) #include #endif #include #include /* sysconf(_SC_GET{PW,GR}_R_SIZE_MAX) */ #define R_SIZE_MAX 1024 int sigar_user_name_get(sigar_t *sigar, int uid, char *buf, int buflen) { struct passwd *pw = NULL; /* XXX cache lookup */ # ifdef HAVE_GETPWUID_R struct passwd pwbuf; char buffer[R_SIZE_MAX]; if (getpwuid_r(uid, &pwbuf, buffer, sizeof(buffer), &pw) != 0) { return errno; } if (!pw) { return ENOENT; } # else if ((pw = getpwuid(uid)) == NULL) { return errno; } # endif strncpy(buf, pw->pw_name, buflen); buf[buflen-1] = '\0'; return SIGAR_OK; } int sigar_group_name_get(sigar_t *sigar, int gid, char *buf, int buflen) { struct group *gr; /* XXX cache lookup */ # ifdef HAVE_GETGRGID_R struct group grbuf; char buffer[R_SIZE_MAX]; if (getgrgid_r(gid, &grbuf, buffer, sizeof(buffer), &gr) != 0) { return errno; } # else if ((gr = getgrgid(gid)) == NULL) { return errno; } # endif if (gr && gr->gr_name) { strncpy(buf, gr->gr_name, buflen); } else { /* seen on linux.. apache httpd.conf has: * Group #-1 * results in uid == -1 and gr == NULL. * wtf getgrgid_r doesnt fail instead? */ sprintf(buf, "%d", gid); } buf[buflen-1] = '\0'; return SIGAR_OK; } int sigar_user_id_get(sigar_t *sigar, const char *name, int *uid) { /* XXX cache lookup */ struct passwd *pw; # ifdef HAVE_GETPWNAM_R struct passwd pwbuf; char buf[R_SIZE_MAX]; if (getpwnam_r(name, &pwbuf, buf, sizeof(buf), &pw) != 0) { return errno; } # else if (!(pw = getpwnam(name))) { return errno; } # endif *uid = (int)pw->pw_uid; return SIGAR_OK; } #endif /* WIN32 */ static char *sigar_error_string(int err) { switch (err) { case SIGAR_ENOTIMPL: return "This function has not been implemented on this platform"; default: return "Error string not specified yet"; } } SIGAR_DECLARE(char *) sigar_strerror(sigar_t *sigar, int err) { char *buf; if (err < 0) { return sigar->errbuf; } if (err > SIGAR_OS_START_ERROR) { if ((buf = sigar_os_error_string(sigar, err)) != NULL) { return buf; } return "Unknown OS Error"; /* should never happen */ } if (err > SIGAR_START_ERROR) { return sigar_error_string(err); } return sigar_strerror_get(err, sigar->errbuf, sizeof(sigar->errbuf)); } char *sigar_strerror_get(int err, char *errbuf, int buflen) { char *buf = NULL; #ifdef WIN32 DWORD len; len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), /* force english */ (LPTSTR)errbuf, (DWORD)buflen, NULL); #else #if defined(HAVE_STRERROR_R) && defined(HAVE_STRERROR_R_GLIBC) /* * strerror_r man page says: * "The GNU version may, but need not, use the user supplied buffer" */ buf = strerror_r(err, errbuf, buflen); #elif defined(HAVE_STRERROR_R) if (strerror_r(err, errbuf, buflen) < 0) { buf = "Unknown Error"; } #else /* strerror() is thread safe on solaris and hpux */ buf = strerror(err); #endif if (buf != NULL) { SIGAR_STRNCPY(errbuf, buf, buflen); } #endif return errbuf; } void sigar_strerror_set(sigar_t *sigar, char *msg) { SIGAR_SSTRCPY(sigar->errbuf, msg); } #ifdef WIN32 #define vsnprintf _vsnprintf #endif void sigar_strerror_printf(sigar_t *sigar, const char *format, ...) { va_list args; va_start(args, format); vsnprintf(sigar->errbuf, sizeof(sigar->errbuf), format, args); va_end(args); } /* copy apr_strfsize */ SIGAR_DECLARE(char *) sigar_format_size(sigar_uint64_t size, char *buf) { const char ord[] = "KMGTPE"; const char *o = ord; int remain; if (size == SIGAR_FIELD_NOTIMPL) { buf[0] = '-'; buf[1] = '\0'; return buf; } if (size < 973) { sprintf(buf, "%3d ", (int) size); return buf; } do { remain = (int)(size & 1023); size >>= 10; if (size >= 973) { ++o; continue; } if (size < 9 || (size == 9 && remain < 973)) { if ((remain = ((remain * 5) + 256) / 512) >= 10) { ++size; remain = 0; } sprintf(buf, "%d.%d%c", (int) size, remain, *o); return buf; } if (remain >= 512) { ++size; } sprintf(buf, "%3d%c", (int) size, *o); return buf; } while (1); } SIGAR_DECLARE(int) sigar_uptime_string(sigar_t *sigar, sigar_uptime_t *uptime, char *buffer, int buflen) { char *ptr = buffer; int time = (int)uptime->uptime; int minutes, hours, days, offset = 0; /* XXX: get rid of sprintf and/or check for overflow */ days = time / (60*60*24); if (days) { offset += sprintf(ptr + offset, "%d day%s, ", days, (days > 1) ? "s" : ""); } minutes = time / 60; hours = minutes / 60; hours = hours % 24; minutes = minutes % 60; if (hours) { offset += sprintf(ptr + offset, "%2d:%02d", hours, minutes); } else { offset += sprintf(ptr + offset, "%d min", minutes); } return SIGAR_OK; } /* threadsafe alternative to inet_ntoa (inet_ntop4 from apr) */ int sigar_inet_ntoa(sigar_t *sigar, sigar_uint32_t address, char *addr_str) { char *next=addr_str; int n=0; const unsigned char *src = (const unsigned char *)&address; do { unsigned char u = *src++; if (u > 99) { *next++ = '0' + u/100; u %= 100; *next++ = '0' + u/10; u %= 10; } else if (u > 9) { *next++ = '0' + u/10; u %= 10; } *next++ = '0' + u; *next++ = '.'; n++; } while (n < 4); *--next = 0; return SIGAR_OK; } static int sigar_ether_ntoa(char *buff, unsigned char *ptr) { sprintf(buff, "%02X:%02X:%02X:%02X:%02X:%02X", (ptr[0] & 0xff), (ptr[1] & 0xff), (ptr[2] & 0xff), (ptr[3] & 0xff), (ptr[4] & 0xff), (ptr[5] & 0xff)); return SIGAR_OK; } SIGAR_DECLARE(int) sigar_net_address_equals(sigar_net_address_t *addr1, sigar_net_address_t *addr2) { if (addr1->family != addr2->family) { return EINVAL; } switch (addr1->family) { case SIGAR_AF_INET: return memcmp(&addr1->addr.in, &addr2->addr.in, sizeof(addr1->addr.in)); case SIGAR_AF_INET6: return memcmp(&addr1->addr.in6, &addr2->addr.in6, sizeof(addr1->addr.in6)); case SIGAR_AF_LINK: return memcmp(&addr1->addr.mac, &addr2->addr.mac, sizeof(addr1->addr.mac)); default: return EINVAL; } } #if !defined(WIN32) && !defined(NETWARE) && !defined(__hpux) #define sigar_inet_ntop inet_ntop #define sigar_inet_ntop_errno errno #else #define sigar_inet_ntop(af, src, dst, size) NULL #define sigar_inet_ntop_errno EINVAL #endif SIGAR_DECLARE(int) sigar_net_address_to_string(sigar_t *sigar, sigar_net_address_t *address, char *addr_str) { switch (address->family) { case SIGAR_AF_INET6: if (sigar_inet_ntop(AF_INET6, (const void *)&address->addr.in6, addr_str, SIGAR_INET6_ADDRSTRLEN)) { return SIGAR_OK; } else { return sigar_inet_ntop_errno; } case SIGAR_AF_INET: return sigar_inet_ntoa(sigar, address->addr.in, addr_str); case SIGAR_AF_UNSPEC: return sigar_inet_ntoa(sigar, 0, addr_str); /*XXX*/ case SIGAR_AF_LINK: return sigar_ether_ntoa(addr_str, &address->addr.mac[0]); default: return EINVAL; } } SIGAR_DECLARE(sigar_uint32_t) sigar_net_address_hash(sigar_net_address_t *address) { sigar_uint32_t hash = 0; unsigned char *data; int i=0, size, elts; switch (address->family) { case SIGAR_AF_UNSPEC: case SIGAR_AF_INET: return address->addr.in; case SIGAR_AF_INET6: data = (unsigned char *)&address->addr.in6; size = sizeof(address->addr.in6); elts = 4; break; case SIGAR_AF_LINK: data = (unsigned char *)&address->addr.mac; size = sizeof(address->addr.mac); elts = 2; break; default: return -1; } while (ivalue) { entry->value = strdup(name); } } fclose(fp); return SIGAR_OK; } SIGAR_DECLARE(char *)sigar_net_services_name_get(sigar_t *sigar, int protocol, unsigned long port) { sigar_cache_entry_t *entry; sigar_cache_t **names; char *pname; switch (protocol) { case SIGAR_NETCONN_TCP: names = &sigar->net_services_tcp; pname = "tcp"; break; case SIGAR_NETCONN_UDP: names = &sigar->net_services_udp; pname = "udp"; break; default: return NULL; } if (*names == NULL) { *names = sigar_cache_new(1024); net_services_parse(*names, pname); } if ((entry = sigar_cache_find(*names, port))) { return (char *)entry->value; } else { return NULL; } } SIGAR_DECLARE(int) sigar_cpu_perc_calculate(sigar_cpu_t *prev, sigar_cpu_t *curr, sigar_cpu_perc_t *perc) { double diff_user, diff_sys, diff_nice, diff_idle; double diff_wait, diff_irq, diff_soft_irq, diff_stolen; double diff_total; diff_user = curr->user - prev->user; diff_sys = curr->sys - prev->sys; diff_nice = curr->nice - prev->nice; diff_idle = curr->idle - prev->idle; diff_wait = curr->wait - prev->wait; diff_irq = curr->irq - prev->irq; diff_soft_irq = curr->soft_irq - prev->soft_irq; diff_stolen = curr->stolen - prev->stolen; diff_user = diff_user < 0 ? 0 : diff_user; diff_sys = diff_sys < 0 ? 0 : diff_sys; diff_nice = diff_nice < 0 ? 0 : diff_nice; diff_idle = diff_idle < 0 ? 0 : diff_idle; diff_wait = diff_wait < 0 ? 0 : diff_wait; diff_irq = diff_irq < 0 ? 0 : diff_irq; diff_soft_irq = diff_soft_irq < 0 ? 0 : diff_soft_irq; diff_stolen = diff_stolen < 0 ? 0 : diff_stolen; diff_total = diff_user + diff_sys + diff_nice + diff_idle + diff_wait + diff_irq + diff_soft_irq + diff_stolen; perc->user = diff_user / diff_total; perc->sys = diff_sys / diff_total; perc->nice = diff_nice / diff_total; perc->idle = diff_idle / diff_total; perc->wait = diff_wait / diff_total; perc->irq = diff_irq / diff_total; perc->soft_irq = diff_soft_irq / diff_total; perc->stolen = diff_stolen / diff_total; perc->combined = perc->user + perc->sys + perc->nice + perc->wait; return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/sigar_getline.c000066400000000000000000001600161210132627500207610ustar00rootroot00000000000000/* * Copyright (C) 1991, 1992 by Chris Thewalt (thewalt@ce.berkeley.edu) * * Permission to use, copy, modify, and distribute this software * for any purpose and without fee is hereby granted, provided * that the above copyright notices appear in all copies and that both the * copyright notice and this permission notice appear in supporting * documentation. This software is provided "as is" without express or * implied warranty. */ /* *************************** Motivation ********************************** Many interactive programs read input line by line, but would like to provide line editing and history functionality to the end-user that runs the program. The input-edit package provides that functionality. As far as the programmer is concerned, the program only asks for the next line of input. However, until the user presses the RETURN key they can use emacs-style line editing commands and can traverse the history of lines previously typed. Other packages, such as GNU's readline, have greater capability but are also substantially larger. Input-edit is small, since it uses neither stdio nor any termcap features, and is also quite portable. It only uses \b to backspace and \007 to ring the bell on errors. Since it cannot edit multiple lines it scrolls long lines left and right on the same line. Input edit uses classic (not ANSI) C, and should run on any Unix system (BSD or SYSV), PC's with the MSC compiler, or Vax/VMS (untested by me). Porting the package to new systems basicaly requires code to read a character when it is typed without echoing it, everything else should be OK. I have run the package on: DECstation 5000, Ultrix 4.2 with cc and gcc Sun Sparc 2, SunOS 4.1.1, with cc SGI Iris, IRIX System V.3, with cc PC, DRDOS 5.0, with MSC 6.0 The description below is broken into two parts, the end-user (editing) interface and the programmer interface. Send bug reports, fixes and enhancements to: Chris Thewalt (thewalt@ce.berkeley.edu) 2/4/92 PS: I don't have, and don't want to add, a vi mode, sorry. ************************** End-User Interface *************************** Entering printable keys generally inserts new text into the buffer (unless in overwrite mode, see below). Other special keys can be used to modify the text in the buffer. In the description of the keys below, ^n means Control-n, or holding the CONTROL key down while pressing "n". M-B means Meta-B (or Alt-B). Errors will ring the terminal bell. ^A/^E : Move cursor to beginning/end of the line. ^F/^B : Move cursor forward/backward one character. ^D : Delete the character under the cursor. ^H, DEL : Delete the character to the left of the cursor. ^K : Kill from the cursor to the end of line. ^L : Redraw current line. ^O : Toggle overwrite/insert mode. Initially in insert mode. Text added in overwrite mode (including yanks) overwrite existing text, while insert mode does not overwrite. ^P/^N : Move to previous/next item on history list. ^R/^S : Perform incremental reverse/forward search for string on the history list. Typing normal characters adds to the current search string and searches for a match. Typing ^R/^S marks the start of a new search, and moves on to the next match. Typing ^H or DEL deletes the last character from the search string, and searches from the starting location of the last search. Therefore, repeated DEL's appear to unwind to the match nearest the point at which the last ^R or ^S was typed. If DEL is repeated until the search string is empty the search location begins from the start of the history list. Typing ESC or any other editing character accepts the current match and loads it into the buffer, terminating the search. ^T : Toggle the characters under and to the left of the cursor. ^U : Kill from beginning to the end of the line. ^Y : Yank previously killed text back at current location. Note that this will overwrite or insert, depending on the current mode. M-F/M-B : Move cursor forward/backward one word. M-D : Delete the word under the cursor. ^SPC : Set mark. ^W : Kill from mark to point. ^X : Exchange mark and point. TAB : By default adds spaces to buffer to get to next TAB stop (just after every 8th column), although this may be rebound by the programmer, as described below. NL, CR : returns current buffer to the program. DOS and ANSI terminal arrow key sequences are recognized, and act like: up : same as ^P down : same as ^N left : same as ^B right : same as ^F ************************** Programmer Interface *************************** The programmer accesses input-edit through five functions, and optionally through three additional function pointer hooks. The five functions are: char *Getline(char *prompt) Prints the prompt and allows the user to edit the current line. A pointer to the line is returned when the user finishes by typing a newline or a return. Unlike GNU readline, the returned pointer points to a static buffer, so it should not be free'd, and the buffer contains the newline character. The user enters an end-of-file by typing ^D on an empty line, in which case the first character of the returned buffer is '\0'. Getline never returns a NULL pointer. The getline function sets terminal modes needed to make it work, and resets them before returning to the caller. The getline function also looks for characters that would generate a signal, and resets the terminal modes before raising the signal condition. If the signal handler returns to getline, the screen is automatically redrawn and editing can continue. Getline now requires both the input and output stream be connected to the terminal (not redirected) so the main program should check to make sure this is true. If input or output have been redirected the main program should use buffered IO (stdio) rather than the slow 1 character read()s that getline uses (note: this limitation has been removed). char *Getlinem(int mode, char *prompt) mode: -1 = init, 0 = line mode, 1 = one char at a time mode, 2 = cleanup More specialized version of the previous function. Depending on the mode, it behaves differently. Its main use is to allow character by character input from the input stream (useful when in an X eventloop). It will return NULL as long as no newline has been received. Its use is typically as follows: 1) In the program initialization part one calls: Getlinem(-1,"prompt>") 2) In the X inputhandler: if ((line = Getlinem(1,NULL))) { 3) In the termination routine: Getlinem(2,NULL) With mode=0 the function behaves exactly like the previous function. void Gl_config(const char *which, int value) Set some config options. Which can be: "noecho": do not echo characters (used for passwd input) "erase": do erase line after return (used for text scrollers) void Gl_setwidth(int width) Set the width of the terminal to the specified width. The default width is 80 characters, so this function need only be called if the width of the terminal is not 80. Since horizontal scrolling is controlled by this parameter it is important to get it right. void Gl_histinit(char *file) This function reads a history list from file. So lines from a previous session can be used again. void Gl_histadd(char *buf) The Gl_histadd function checks to see if the buf is not empty or whitespace, and also checks to make sure it is different than the last saved buffer to avoid repeats on the history list. If the buf is a new non-blank string a copy is made and saved on the history list, so the caller can re-use the specified buf. The main loop in testgl.c, included in this directory, shows how the input-edit package can be used: extern char *Getline(); extern void Gl_histadd(); main() { char *p; Gl_histinit(".hist"); do { p = Getline("PROMPT>>>> "); Gl_histadd(p); fputs(p, stdout); } while (*p != 0); } In order to allow the main program to have additional access to the buffer, to implement things such as completion or auto-indent modes, three function pointers can be bound to user functions to modify the buffer as described below. By default gl_in_hook and gl_out_hook are set to NULL, and gl_tab_hook is bound to a function that inserts spaces until the next logical tab stop is reached. The user can reassign any of these pointers to other functions. Each of the functions bound to these hooks receives the current buffer as the first argument, and must return the location of the leftmost change made in the buffer. If the buffer isn't modified the functions should return -1. When the hook function returns the screen is updated to reflect any changes made by the user function. int (*gl_in_hook)(char *buf) If gl_in_hook is non-NULL the function is called each time a new buffer is loaded. It is called when getline is entered, with an empty buffer, it is called each time a new buffer is loaded from the history with ^P or ^N, and it is called when an incremental search string is accepted (when the search is terminated). The buffer can be modified and will be redrawn upon return to Getline(). int (*gl_out_hook)(char *buf) If gl_out_hook is non-NULL it is called when a line has been completed by the user entering a newline or return. The buffer handed to the hook does not yet have the newline appended. If the buffer is modified the screen is redrawn before getline returns the buffer to the caller. int (*gl_tab_hook)(char *buf, int prompt_width, int *cursor_loc) If gl_tab_hook is non-NULL, it is called whenever a tab is typed. In addition to receiving the buffer, the current prompt width is given (needed to do tabbing right) and a pointer to the cursor offset is given, where a 0 offset means the first character in the line. Not only does the cursor_loc tell the programmer where the TAB was received, but it can be reset so that the cursor will end up at the specified location after the screen is redrawn. */ /* forward reference needed for gl_tab_hook */ static int gl_tab(char *buf, int offset, int *loc); /********************* exported interface ********************************/ static int (*gl_in_hook)(char *buf) = 0; static int (*gl_out_hook)(char *buf) = 0; static int (*gl_tab_hook)(char *buf, int prompt_width, int *loc) = gl_tab; /******************** imported interface *********************************/ #ifdef DMALLOC /* reports leaks, which is the history buffer. dont care */ #undef DMALLOC #endif #include "sigar_getline.h" #include "sigar_private.h" #include "sigar_util.h" #include #include #include #include #include #include /******************** internal interface *********************************/ static char *sigar_getlinem(int mode, char *prompt); /* allows reading char by char */ static void sigar_getline_config(const char *which, int value); /* set some options */ static void sigar_getline_clear_screen(void); #define BUF_SIZE 8096 static int gl_init_done = -1; /* terminal mode flag */ static int gl_notty = 0; /* 1 when not a tty */ static int gl_eof = 0; /* 1 when not a tty and read() == -1 */ static int gl_termw = 80; /* actual terminal width */ static int gl_scroll = 27; /* width of EOL scrolling region */ static int gl_width = 0; /* net size available for input */ static int gl_extent = 0; /* how far to redraw, 0 means all */ static int gl_overwrite = 0; /* overwrite mode */ static int gl_no_echo = 0; /* do not echo input characters */ static int gl_passwd = 0; /* do not echo input characters */ static int gl_erase_line = 0; /* erase line before returning */ static int gl_pos, gl_cnt = 0; /* position and size of input */ static char gl_buf[BUF_SIZE]; /* input buffer */ static char gl_killbuf[BUF_SIZE]=""; /* killed text */ static char *gl_prompt; /* to save the prompt string */ static char gl_intrc = 0; /* keyboard SIGINT char */ static char gl_quitc = 0; /* keyboard SIGQUIT char */ static char gl_suspc = 0; /* keyboard SIGTSTP char */ static char gl_dsuspc = 0; /* delayed SIGTSTP char */ static int gl_search_mode = 0; /* search mode flag */ static int gl_bell_enabled = 0; /* bell mode */ static int gl_savehist = 0; /* # of lines to save in hist file */ static char gl_histfile[256]; /* name of history file */ static void gl_init(); /* prepare to edit a line */ static void gl_bell(); /* ring bell */ static void gl_cleanup(); /* to undo gl_init */ static void gl_char_init(); /* get ready for no echo input */ static void gl_char_cleanup(); /* undo gl_char_init */ static void gl_addchar(int c); /* install specified char */ static void gl_del(int loc); /* del, either left (-1) or cur (0) */ static void gl_error(char *buf); /* write error msg and die */ static void gl_fixup(char *p, int c, int cur); /* fixup state variables and screen */ static int gl_getc(); /* read one char from terminal */ static void gl_kill(); /* delete to EOL */ static void gl_newline(); /* handle \n or \r */ static void gl_putc(int c); /* write one char to terminal */ static void gl_puts(char *buf); /* write a line to terminal */ static void gl_transpose(); /* transpose two chars */ static void gl_yank(); /* yank killed text */ static int is_whitespace(char c); /* "whitespace" very loosely interpreted */ static void gl_back_1_word(); /* move cursor back one word */ static void gl_kill_1_word(); /* kill to end of word */ static void gl_kill_region(int i, int j); /* kills from i to j */ static void gl_fwd_1_word(); /* move cursor forward one word */ static void gl_set_mark(); /* sets mark to be at point */ static void gl_exch(); /* exchanges point and mark */ static void gl_wipe(); /* kills from mark to point */ static int gl_mark = -1; /* position of mark. gl_mark<0 if not set */ static void hist_init(); /* initializes hist pointers */ static char *hist_next(); /* return ptr to next item */ static char *hist_prev(); /* return ptr to prev item */ static char *hist_save(char *p); /* makes copy of a string, without NL */ static void search_addchar(int c); /* increment search string */ static void search_term(); /* reset with current contents */ static void search_back(int s); /* look back for current string */ static void search_forw(int s); /* look forw for current string */ /************************ nonportable part *********************************/ #ifdef MSDOS #include #endif #ifdef WIN32 # define MSDOS # include # include #endif /* WIN32 */ #ifdef __MWERKS__ #define R__MWERKS #endif #ifdef R__MWERKS # include #endif #if defined(_AIX) || defined(__Lynx__) || defined(__APPLE__) #define unix #endif #if defined(__hpux) || defined(__osf__) /* W.Karig@gsi.de */ #ifndef unix #define unix #endif #endif #ifdef unix #include #if !defined(__osf__) && !defined(_AIX) /* W.Karig@gsi.de */ #include #endif #if defined(__linux__) && defined(__powerpc__) # define R__MKLINUX // = linux on PowerMac #endif #if defined(__linux__) && defined(__alpha__) # define R__ALPHALINUX // = linux on Alpha #endif #if defined(TIOCGETP) && !defined(__sgi) && !defined(R__MKLINUX) && \ !defined(R__ALPHALINUX) /* use BSD interface if possible */ #include static struct sgttyb new_tty, old_tty; static struct tchars tch; static struct ltchars ltch; #else #ifdef SIGTSTP /* need POSIX interface to handle SUSP */ #include #if defined(__sun) || defined(__sgi) || defined(R__MKLINUX) || \ defined(R__ALPHALINUX) #undef TIOCGETP /* Solaris and SGI define TIOCGETP in */ #undef TIOCSETP #endif static struct termios new_termios, old_termios; #else /* use SYSV interface */ #include static struct termio new_termio, old_termio; #endif #endif #endif /* unix */ #ifdef VMS #include #include #include #include #include #include unixio static int setbuff[2]; /* buffer to set terminal attributes */ static short chan = -1; /* channel to terminal */ struct dsc$descriptor_s descrip; /* VMS descriptor */ #endif static void sigar_getline_config(const char *which, int value) { if (strcmp(which, "noecho") == 0) gl_no_echo = value; else if (strcmp(which, "erase") == 0) gl_erase_line = value; else printf("gl_config: %s ?\n", which); } static void gl_char_init() /* turn off input echo */ { if (gl_notty) return; #ifdef unix #ifdef TIOCGETP /* BSD */ ioctl(0, TIOCGETC, &tch); ioctl(0, TIOCGLTC, <ch); gl_intrc = tch.t_intrc; gl_quitc = tch.t_quitc; gl_suspc = ltch.t_suspc; gl_dsuspc = ltch.t_dsuspc; ioctl(0, TIOCGETP, &old_tty); new_tty = old_tty; new_tty.sg_flags |= RAW; new_tty.sg_flags &= ~ECHO; ioctl(0, TIOCSETP, &new_tty); #else #ifdef SIGTSTP /* POSIX */ tcgetattr(0, &old_termios); gl_intrc = old_termios.c_cc[VINTR]; gl_quitc = old_termios.c_cc[VQUIT]; #ifdef VSUSP gl_suspc = old_termios.c_cc[VSUSP]; #endif #ifdef VDSUSP gl_dsuspc = old_termios.c_cc[VDSUSP]; #endif new_termios = old_termios; new_termios.c_iflag &= ~(BRKINT|ISTRIP|IXON|IXOFF); new_termios.c_iflag |= (IGNBRK|IGNPAR); new_termios.c_lflag &= ~(ICANON|ISIG|IEXTEN|ECHO); new_termios.c_cc[VMIN] = 1; new_termios.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &new_termios); #else /* SYSV */ ioctl(0, TCGETA, &old_termio); gl_intrc = old_termio.c_cc[VINTR]; gl_quitc = old_termio.c_cc[VQUIT]; new_termio = old_termio; new_termio.c_iflag &= ~(BRKINT|ISTRIP|IXON|IXOFF); new_termio.c_iflag |= (IGNBRK|IGNPAR); new_termio.c_lflag &= ~(ICANON|ISIG|ECHO); new_termio.c_cc[VMIN] = 1; new_termio.c_cc[VTIME] = 0; ioctl(0, TCSETA, &new_termio); #endif #endif #endif /* unix */ #ifdef MSDOS gl_intrc = 'C' - '@'; gl_quitc = 'Q' - '@'; // gl_suspc = ltch.t_suspc; #endif /* MSDOS */ #ifdef R__MWERKS gl_intrc = 'C' - '@'; gl_quitc = 'Q' - '@'; #endif #ifdef vms descrip.dsc$w_length = strlen("tt:"); descrip.dsc$b_dtype = DSC$K_DTYPE_T; descrip.dsc$b_class = DSC$K_CLASS_S; descrip.dsc$a_pointer = "tt:"; (void)sys$assign(&descrip,&chan,0,0); (void)sys$qiow(0,chan,IO$_SENSEMODE,0,0,0,setbuff,8,0,0,0,0); setbuff[1] |= TT$M_NOECHO; (void)sys$qiow(0,chan,IO$_SETMODE,0,0,0,setbuff,8,0,0,0,0); #endif /* vms */ } static void gl_char_cleanup() /* undo effects of gl_char_init */ { if (gl_notty) return; #ifdef unix #ifdef TIOCSETP /* BSD */ ioctl(0, TIOCSETP, &old_tty); #else #ifdef SIGTSTP /* POSIX */ tcsetattr(0, TCSANOW, &old_termios); #else /* SYSV */ ioctl(0, TCSETA, &old_termio); #endif #endif #endif /* unix */ #ifdef vms setbuff[1] &= ~TT$M_NOECHO; (void)sys$qiow(0,chan,IO$_SETMODE,0,0,0,setbuff,8,0,0,0,0); sys$dassgn(chan); chan = -1; #endif } #if defined(MSDOS) && !defined(WIN32) // +DECK, PAUSE, T=XCC, IF=WINNT. (from KERNDOS.CAR ) # include int pause_() { int first_char; first_char = _getch(); if (first_char == 0 || first_char == 0xE0) first_char = -_getch(); return first_char; } #endif #if defined(MSDOS) && defined(WIN32) //______________________________________________________________________________ int pause_() { static HANDLE hConsoleInput = NULL; static iCharCount = 0; static int chLastChar = 0; DWORD cRead; INPUT_RECORD pirBuffer; KEY_EVENT_RECORD *KeyEvent= (KEY_EVENT_RECORD *)&(pirBuffer.Event); if (!hConsoleInput) hConsoleInput = GetStdHandle(STD_INPUT_HANDLE); if (iCharCount) iCharCount--; // Whether several symbols had been read else { chLastChar = 0; while (chLastChar == 0) { if (!ReadConsoleInput(hConsoleInput, // handle of a console input buffer &pirBuffer, // address of the buffer for read data 1, // number of records to read &cRead // address of number of records read )) return 0; if (pirBuffer.EventType == KEY_EVENT && KeyEvent->bKeyDown == TRUE){ iCharCount = KeyEvent->wRepeatCount - 1; chLastChar = ((int) (KeyEvent->uChar).AsciiChar & 0xffff); if (chLastChar) OemToCharBuff((char const *)&chLastChar,(char *)&chLastChar,1); else chLastChar = - (KeyEvent->wVirtualScanCode); // chLastChar = - (KeyEvent->wVirtualKeyCode); } } } return chLastChar; } #endif static int gl_getc() /* get a character without echoing it to screen */ { #ifdef MSDOS # define k_ctrl_C 3 # define k_ctrl_Z 26 # define k_ctrl_Q 17 # define k_ctrl_K 11 # define k_rt_arr -77 # define k_lt_arr -75 # define k_up_arr -72 # define k_dn_arr -80 # define k_PGUP -73 # define k_PGDW -81 # define k_HOME -71 # define k_END -79 # define k_INS -82 # define k_DEL -83 # define k_ENTER 13 # define k_CR 13 # define k_BS 8 # define k_ESC 27 # define k_alt_H -35 # define k_beep 7 # ifndef WIN32 int get_cursor__(int *,int *); int display_off__(int *); int display_on__(); int locate_(int *,int *); int ixc, iyc; # endif int pause_(); #endif int c; #if defined(unix) unsigned char ch; while ((c = (read(0, &ch, 1) > 0) ? ch : -1) == -1 && errno == EINTR) errno = 0; #endif #if defined(R__MWERKS) c = getchar(); #endif #ifdef MSDOS c = pause_(); if (c < 0) { switch (c) { case k_up_arr: c = 'P' - '@'; /* up -> ^P = 16 */ break; case k_dn_arr: c = 'N' - '@'; /* down -> ^N = 14 */ break; case k_lt_arr: c = 'B' - '@'; /* left -> ^B =2 */ break; case k_rt_arr: c = 'F' - '@'; /* right -> ^F = 6*/ break; case k_INS: c = 'O' - '@'; /* right -> ^O = 15*/ break; case k_DEL: c = 'D' - '@'; /* Delete character under cursor = 4*/ break; case k_END: c = 'E' - '@'; /* Moves cursor to end of line * = 5 */ break; case k_HOME: c = 'A' - '@'; /* Moves cursor to beginning of line = 1*/ break; default: c = 0; /* make it garbage */ } } else { switch(c) { case k_ESC: c = 'U' - '@'; /* Clear full line -> ^U */ break; default: break; } } #endif #ifdef vms if(chan < 0) { c='\0'; } (void)sys$qiow(0,chan,IO$_TTYREADALL,0,0,0,&c,1,0,0,0,0); c &= 0177; /* get a char */ #endif return c; } static void gl_putc(int c) { char ch = c; if (gl_notty) return; if ( !gl_passwd || !isgraph(c)) { #ifdef WIN32 CharToOemBuff((char const *)&c,&ch,1); #endif sigar_write(1, &ch, 1); } #if defined(unix) || defined(MSDOS) || defined(WIN32) || defined(R__MWERKS) #ifdef TIOCSETP /* BSD in RAW mode, map NL to NL,CR */ if (ch == '\n') { ch = '\r'; sigar_write(1, &ch, 1); } #endif #endif } /******************** fairly portable part *********************************/ static void gl_puts(char *buf) { int len = strlen(buf); if (gl_notty) return; #ifdef WIN32 { char *OemBuf = (char *)malloc(2*len); CharToOemBuff(buf,OemBuf,len); sigar_write(1, OemBuf, len); free(OemBuf); } #else sigar_write(1, buf, len); #endif } static void gl_error(char *buf) { int len = strlen(buf); gl_cleanup(); #ifdef WIN32 { char *OemBuf = (char *)malloc(2*len); CharToOemBuff(buf,OemBuf,len); sigar_write(2, OemBuf, len); free(OemBuf); } #else sigar_write(2, buf, len); #endif exit(1); } static void gl_init() /* set up variables and terminal */ { if (gl_init_done < 0) { /* -1 only on startup */ hist_init(); } if (sigar_isatty(0) == 0 || sigar_isatty(1) == 0) gl_notty = 1; gl_char_init(); gl_init_done = 1; } static void gl_bell() { if (gl_bell_enabled) { gl_putc('\007'); } } static void gl_cleanup() /* undo effects of gl_init, as necessary */ { if (gl_init_done > 0) gl_char_cleanup(); gl_init_done = 0; } SIGAR_DECLARE(void) sigar_getline_setwidth(int w) { if (w > 20) { gl_termw = w; gl_scroll = w / 3; } else { gl_error("\n*** Error: minimum screen width is 21\n"); } } SIGAR_DECLARE(void) sigar_getline_windowchanged() { #ifdef TIOCGWINSZ if (sigar_isatty(0)) { static char lenv[32], cenv[32]; struct winsize wins; ioctl(0, TIOCGWINSZ, &wins); if (wins.ws_col == 0) wins.ws_col = 80; if (wins.ws_row == 0) wins.ws_row = 24; sigar_getline_setwidth(wins.ws_col); sprintf(lenv, "LINES=%d", wins.ws_row); putenv(lenv); sprintf(cenv, "COLUMNS=%d", wins.ws_col); putenv(cenv); } #endif } /* -1 = init, 0 = line mode, 1 = one char at a time mode, 2 = cleanup */ static char * sigar_getlinem(int mode, char *prompt) { int c, loc, tmp; int sig; if (mode == 2) { gl_cleanup(); return NULL; } if (mode < 1) { if (mode == -1) { sigar_getline_config("noecho", 0); sigar_getline_config("erase", 0); } gl_init(); gl_prompt = (prompt)? prompt : (char*)""; gl_buf[0] = 0; if (gl_in_hook) gl_in_hook(gl_buf); gl_fixup(gl_prompt, -2, BUF_SIZE); if (mode == -1) return NULL; } while ((c = gl_getc()) >= 0) { gl_extent = 0; /* reset to full extent */ #ifndef WIN32 if (isprint(c)) { #else if (c >= ' ') { #endif if (gl_search_mode) search_addchar(c); else gl_addchar(c); } else { if (gl_search_mode) { if (c == '\033' || c == '\016' || c == '\020') { search_term(); c = 0; /* ignore the character */ } else if (c == '\010' || c == '\177') { search_addchar(-1); /* unwind search string */ c = 0; } else if (c != '\022' && c != '\023') { search_term(); /* terminate and handle char */ } } /* NOTE: * sometimes M-x turns on bit 8 ( M-x --> 'x' + 128 ) * sometimes M-x prepends an escape character ( M-x --> '\033','x' ) * both cases are handled ... */ switch (c) { case 'b'+128: /* M-b */ case 'B'+128: /* M-B */ gl_back_1_word(); break; case 'd'+128: /* M-d */ case 'D'+128: /* M-D */ gl_kill_1_word(); break; case 'f'+128: /* M-f */ case 'F'+128: /* M-F */ gl_fwd_1_word(); break; case '\000': /* ^SPC */ gl_set_mark(); break; case '\027': /* ^W */ gl_wipe(); break; case '\030': /* ^X */ gl_exch(); break; case '\n': /* newline */ case '\r': gl_newline(); gl_cleanup(); return gl_buf; /*NOTREACHED*/ break; case '\001': gl_fixup(gl_prompt, -1, 0); /* ^A */ break; case '\002': gl_fixup(gl_prompt, -1, gl_pos-1); /* ^B */ break; case '\004': /* ^D */ if (gl_cnt == 0) { gl_buf[0] = 0; gl_cleanup(); gl_putc('\n'); return gl_buf; } else { gl_del(0); } break; case '\005': gl_fixup(gl_prompt, -1, gl_cnt); /* ^E */ break; case '\006': gl_fixup(gl_prompt, -1, gl_pos+1); /* ^F */ break; case '\010': case '\177': gl_del(-1); /* ^H and DEL */ break; case '\t': /* TAB */ if (gl_tab_hook) { tmp = gl_pos; loc = gl_tab_hook(gl_buf, strlen(gl_prompt), &tmp); if (loc >= 0 || tmp != gl_pos || loc == -2) gl_fixup(gl_prompt, loc, tmp); } break; case '\013': gl_kill(); /* ^K */ break; case '\014': sigar_getline_clear_screen(); /* ^L */ break; case '\016': /* ^N */ strcpy(gl_buf, hist_next()); if (gl_in_hook) gl_in_hook(gl_buf); gl_fixup(gl_prompt, 0, BUF_SIZE); break; case '\017': gl_overwrite = !gl_overwrite; /* ^O */ break; case '\020': /* ^P */ strcpy(gl_buf, hist_prev()); if (gl_in_hook) gl_in_hook(gl_buf); gl_fixup(gl_prompt, 0, BUF_SIZE); break; case '\022': search_back(1); /* ^R */ break; case '\023': search_forw(1); /* ^S */ break; case '\024': gl_transpose(); /* ^T */ break; case '\025': gl_fixup(gl_prompt,-1,0); gl_kill(); /* ^U */ break; case '\031': gl_yank(); /* ^Y */ break; case '\033': switch(c = gl_getc()) { case 'b': /* M-b */ case 'B': /* M-B */ gl_back_1_word(); break; case 'd': /* M-d */ case 'D': /* M-D */ gl_kill_1_word(); break; case 'f': /* M-f */ case 'F': /* M-F */ gl_fwd_1_word(); break; case '[': /* ansi arrow keys */ case 'O': /* xterm arrow keys */ switch(c = gl_getc()) { case 'A': /* up */ strcpy(gl_buf, hist_prev()); if (gl_in_hook) gl_in_hook(gl_buf); gl_fixup(gl_prompt, 0, BUF_SIZE); break; case 'B': /* down */ strcpy(gl_buf, hist_next()); if (gl_in_hook) gl_in_hook(gl_buf); gl_fixup(gl_prompt, 0, BUF_SIZE); break; case 'C': gl_fixup(gl_prompt, -1, gl_pos+1); /* right */ break; case 'D': gl_fixup(gl_prompt, -1, gl_pos-1); /* left */ break; default: /* who knows */ gl_bell(); break; } break; default: gl_bell(); } break; default: /* check for a terminal signal */ #if defined(unix) || defined(WIN32) || defined(R__MWERKS) if (c > 0) { /* ignore 0 (reset above) */ sig = 0; #ifdef SIGINT if (c == gl_intrc) sig = SIGINT; #endif #ifdef SIGQUIT if (c == gl_quitc) sig = SIGQUIT; #endif #ifdef SIGTSTP if (c == gl_suspc || c == gl_dsuspc) sig = SIGTSTP; #endif if (sig != 0) { gl_cleanup(); #if !defined(WIN32) raise(sig); #endif #ifdef WIN32 if (sig == SIGINT) GenerateConsoleCtrlEvent(CTRL_C_EVENT,0); else raise(sig); #endif gl_init(); sigar_getline_redraw(); c = 0; } } #endif /* unix */ if (c > 0) gl_bell(); break; } } if (mode == 1) return NULL; } if (c == -1 && gl_notty) gl_eof = 1; else gl_eof = 0; gl_cleanup(); gl_buf[0] = 0; return gl_buf; } SIGAR_DECLARE(int) sigar_getline_eof() { return gl_eof; } SIGAR_DECLARE(char *) sigar_getline(char *prompt) { return sigar_getlinem(0, prompt); } static void gl_addchar(int c) /* adds the character c to the input buffer at current location */ { int i; if (gl_cnt >= BUF_SIZE - 1) gl_error("\n*** Error: sigar_getline(): input buffer overflow\n"); if (gl_overwrite == 0 || gl_pos == gl_cnt) { for (i=gl_cnt; i >= gl_pos; i--) gl_buf[i+1] = gl_buf[i]; gl_buf[gl_pos] = c; gl_fixup(gl_prompt, gl_pos, gl_pos+1); } else { gl_buf[gl_pos] = c; gl_extent = 1; gl_fixup(gl_prompt, gl_pos, gl_pos+1); } } static void gl_yank() /* adds the kill buffer to the input buffer at current location */ { int i, len; len = strlen(gl_killbuf); if (len > 0) { gl_mark = gl_pos; if (gl_overwrite == 0) { if (gl_cnt + len >= BUF_SIZE - 1) gl_error("\n*** Error: sigar_getline(): input buffer overflow\n"); for (i=gl_cnt; i >= gl_pos; i--) gl_buf[i+len] = gl_buf[i]; for (i=0; i < len; i++) gl_buf[gl_pos+i] = gl_killbuf[i]; gl_fixup(gl_prompt, gl_pos, gl_pos+len); } else { if (gl_pos + len > gl_cnt) { if (gl_pos + len >= BUF_SIZE - 1) gl_error("\n*** Error: sigar_getline(): input buffer overflow\n"); gl_buf[gl_pos + len] = 0; } for (i=0; i < len; i++) gl_buf[gl_pos+i] = gl_killbuf[i]; gl_extent = len; gl_fixup(gl_prompt, gl_pos, gl_pos+len); } } else gl_bell(); } static void gl_transpose() /* switch character under cursor and to left of cursor */ { int c; if (gl_pos > 0 && gl_cnt > gl_pos) { c = gl_buf[gl_pos-1]; gl_buf[gl_pos-1] = gl_buf[gl_pos]; gl_buf[gl_pos] = c; gl_extent = 2; gl_fixup(gl_prompt, gl_pos-1, gl_pos); } else gl_bell(); } static void gl_newline() /* * Cleans up entire line before returning to caller. A \n is appended. * If line longer than screen, we redraw starting at beginning */ { int change = gl_cnt; int len = gl_cnt; int loc = gl_width - 5; /* shifts line back to start position */ if (gl_cnt >= BUF_SIZE - 1) gl_error("\n*** Error: sigar_getline(): input buffer overflow\n"); if (gl_out_hook) { change = gl_out_hook(gl_buf); len = strlen(gl_buf); } if (gl_erase_line) { char gl_buf0 = gl_buf[0]; gl_buf[0] = '\0'; gl_fixup("", 0, 0); gl_buf[0] = gl_buf0; } else { if (loc > len) loc = len; gl_fixup(gl_prompt, change, loc); /* must do this before appending \n */ gl_putc('\n'); } #if 0 gl_buf[len] = '\n'; gl_buf[len+1] = '\0'; #endif gl_mark = -1; } static void gl_del(int loc) /* * Delete a character. The loc variable can be: * -1 : delete character to left of cursor * 0 : delete character under cursor */ { int i; if ((loc == -1 && gl_pos > 0) || (loc == 0 && gl_pos < gl_cnt)) { for (i=gl_pos+loc; i < gl_cnt; i++) gl_buf[i] = gl_buf[i+1]; gl_fixup(gl_prompt, gl_pos+loc, gl_pos+loc); } else gl_bell(); } static void gl_kill() /* delete from current position to the end of line */ { if (gl_pos < gl_cnt) { strcpy(gl_killbuf, gl_buf + gl_pos); gl_buf[gl_pos] = '\0'; gl_fixup(gl_prompt, gl_pos, gl_pos); } else gl_bell(); } SIGAR_DECLARE(void) sigar_getline_redraw(void) /* emit a newline, reset and redraw prompt and current input line */ { if (gl_init_done > 0) { gl_putc('\n'); gl_fixup(gl_prompt, -2, gl_pos); } } #define CLEAR_SCREEN "\033[2J" static void sigar_getline_clear_screen(void) { if (gl_init_done > 0) { gl_putc('\n'); /* XXX what to do for non-ansi term? */ gl_puts(CLEAR_SCREEN); gl_fixup(gl_prompt, -2, gl_pos); } } SIGAR_DECLARE(void) sigar_getline_reset(void) { gl_fixup(gl_prompt,-1,0); gl_kill(); } static void gl_fixup(char *prompt, int change, int cursor) /* * This function is used both for redrawing when input changes or for * moving within the input line. The parameters are: * prompt: compared to last_prompt[] for changes; * change : the index of the start of changes in the input buffer, * with -1 indicating no changes, -2 indicating we're on * a new line, redraw everything. * cursor : the desired location of the cursor after the call. * A value of BUF_SIZE can be used to indicate the cursor should * move just past the end of the input line. */ { static int gl_shift; /* index of first on screen character */ static int off_right; /* true if more text right of screen */ static int off_left; /* true if more text left of screen */ static char last_prompt[BUF_SIZE] = ""; int left = 0, right = -1; /* bounds for redraw */ int padl; /* how much to erase at end of line */ int backup; /* how far to backup before fixing */ int new_shift; /* value of shift based on cursor */ int extra; /* adjusts when shift (scroll) happens */ int i; int new_right = -1; /* alternate right bound, using gl_extent */ int l1, l2; if (change == -2) { /* reset */ gl_pos = gl_cnt = gl_shift = off_right = off_left = 0; gl_passwd = 0; gl_puts(prompt); gl_passwd = gl_no_echo; strcpy(last_prompt, prompt); change = 0; gl_width = gl_termw - strlen(prompt); } else if (strcmp(prompt, last_prompt) != 0) { l1 = strlen(last_prompt); l2 = strlen(prompt); gl_cnt = gl_cnt + l1 - l2; strcpy(last_prompt, prompt); backup = gl_pos - gl_shift + l1; for (i=0; i < backup; i++) gl_putc('\b'); gl_passwd = 0; gl_puts(prompt); gl_passwd = gl_no_echo; gl_pos = gl_shift; gl_width = gl_termw - l2; change = 0; } padl = (off_right)? gl_width - 1 : gl_cnt - gl_shift; /* old length */ backup = gl_pos - gl_shift; if (change >= 0) { gl_cnt = strlen(gl_buf); if (change > gl_cnt) change = gl_cnt; } if (cursor > gl_cnt) { if (cursor != BUF_SIZE) /* BUF_SIZE means end of line */ gl_bell(); cursor = gl_cnt; } if (cursor < 0) { gl_bell(); cursor = 0; } if (off_right || (off_left && cursor < gl_shift + gl_width - gl_scroll / 2)) extra = 2; /* shift the scrolling boundary */ else extra = 0; new_shift = cursor + extra + gl_scroll - gl_width; if (new_shift > 0) { new_shift /= gl_scroll; new_shift *= gl_scroll; } else new_shift = 0; if (new_shift != gl_shift) { /* scroll occurs */ gl_shift = new_shift; off_left = (gl_shift)? 1 : 0; off_right = (gl_cnt > gl_shift + gl_width - 1)? 1 : 0; left = gl_shift; new_right = right = (off_right)? gl_shift + gl_width - 2 : gl_cnt; } else if (change >= 0) { /* no scroll, but text changed */ if (change < gl_shift + off_left) { left = gl_shift; } else { left = change; backup = gl_pos - change; } off_right = (gl_cnt > gl_shift + gl_width - 1)? 1 : 0; right = (off_right)? gl_shift + gl_width - 2 : gl_cnt; new_right = (gl_extent && (right > left + gl_extent))? left + gl_extent : right; } padl -= (off_right)? gl_width - 1 : gl_cnt - gl_shift; padl = (padl < 0)? 0 : padl; if (left <= right) { /* clean up screen */ for (i=0; i < backup; i++) gl_putc('\b'); if (left == gl_shift && off_left) { gl_putc('$'); left++; } for (i=left; i < new_right; i++) gl_putc(gl_buf[i]); gl_pos = new_right; if (off_right && new_right == right) { gl_putc('$'); gl_pos++; } else { for (i=0; i < padl; i++) /* erase remains of prev line */ gl_putc(' '); gl_pos += padl; } } i = gl_pos - cursor; /* move to final cursor location */ if (i > 0) { while (i--) gl_putc('\b'); } else { for (i=gl_pos; i < cursor; i++) gl_putc(gl_buf[i]); } gl_pos = cursor; } static int gl_tab(char *buf, int offset, int *loc) /* default tab handler, acts like tabstops every 8 cols */ { int i, count, len; len = strlen(buf); count = 8 - (offset + *loc) % 8; for (i=len; i >= *loc; i--) buf[i+count] = buf[i]; for (i=0; i < count; i++) buf[*loc+i] = ' '; i = *loc; *loc = i + count; return i; } /******************* History stuff **************************************/ #ifndef HIST_SIZE #define HIST_SIZE 100 #endif static int hist_pos = 0, hist_last = 0; static char *hist_buf[HIST_SIZE]; static void hist_init() { int i; if (gl_savehist) return; hist_buf[0] = ""; for (i=1; i < HIST_SIZE; i++) hist_buf[i] = (char *)0; } SIGAR_DECLARE(void) sigar_getline_completer_set(sigar_getline_completer_t func) { if (func) { gl_tab_hook = func; } else { gl_tab_hook = gl_tab; } } SIGAR_DECLARE(void) sigar_getline_histinit(char *file) { char line[256]; FILE *fp; int nline = 1; /* prevent from becoming 0 */ gl_savehist = 0; hist_init(); if (!strcmp(file, "-")) return; sprintf(gl_histfile, "%s", file); fp = fopen(gl_histfile, "r"); if (fp) while (fgets(line, 256, fp)) { nline++; sigar_getline_histadd(line); } else fp = fopen(gl_histfile, "w"); if (fp) fclose(fp); gl_savehist = nline; } SIGAR_DECLARE(void) sigar_getline_histadd(char *buf) { static char *prev = 0; char *p = buf; int len; while (*p == ' ' || *p == '\t' || *p == '\n') p++; if (*p) { len = strlen(buf); if (strchr(p, '\n')) /* previously line already has NL stripped */ len--; if (prev == 0 || strlen(prev) != len || strncmp(prev, buf, len) != 0) { hist_buf[hist_last] = hist_save(buf); prev = hist_buf[hist_last]; hist_last = (hist_last + 1) % HIST_SIZE; if (hist_buf[hist_last] && *hist_buf[hist_last]) { free(hist_buf[hist_last]); } hist_buf[hist_last] = ""; /* append command to history file */ if (gl_savehist) { FILE *fp; fp = fopen(gl_histfile, "a+"); if (fp) { fprintf(fp, "%s\n", prev); gl_savehist++; fclose(fp); } /* if more than HIST_SIZE lines, safe last 60 command and delete rest */ if (gl_savehist > HIST_SIZE) { FILE *ftmp; char tname[L_tmpnam]; char line[BUFSIZ]; fp = fopen(gl_histfile, "r"); tmpnam(tname); ftmp = fopen(tname, "w"); if (fp && ftmp) { int nline = 0; while (fgets(line, BUFSIZ, fp)) { nline++; gl_savehist = 1; /* prevent from becoming 0 */ if (nline > HIST_SIZE-60) { gl_savehist++; fprintf(ftmp, "%s", line); } } } if (fp) fclose(fp); if (ftmp) fclose(ftmp); /* copy back to history file */ fp = fopen(gl_histfile, "w"); ftmp = fopen(tname, "r"); if (fp && ftmp) while (fgets(line, BUFSIZ, ftmp)) fprintf(fp, "%s", line); if (fp) fclose(fp); if (ftmp) fclose(ftmp); remove(tname); } } } } hist_pos = hist_last; } static char * hist_prev() /* loads previous hist entry into input buffer, sticks on first */ { char *p = 0; int next = (hist_pos - 1 + HIST_SIZE) % HIST_SIZE; if (hist_buf[hist_pos] != 0 && next != hist_last) { hist_pos = next; p = hist_buf[hist_pos]; } if (p == 0) { p = ""; gl_bell(); } return p; } static char * hist_next() /* loads next hist entry into input buffer, clears on last */ { char *p = 0; if (hist_pos != hist_last) { hist_pos = (hist_pos+1) % HIST_SIZE; p = hist_buf[hist_pos]; } if (p == 0) { p = ""; gl_bell(); } return p; } static char * hist_save(char *p) /* makes a copy of the string */ { char *s = 0; int len = strlen(p); char *nl = strchr(p, '\n'); if (nl) { if ((s = (char *)malloc(len)) != 0) { strncpy(s, p, len-1); s[len-1] = 0; } } else { if ((s = (char *)malloc(len+1)) != 0) { strcpy(s, p); } } if (s == 0) gl_error("\n*** Error: hist_save() failed on malloc\n"); return s; } /******************* Search stuff **************************************/ static char search_prompt[101]; /* prompt includes search string */ static char search_string[100]; static int search_pos = 0; /* current location in search_string */ static int search_forw_flg = 0; /* search direction flag */ static int search_last = 0; /* last match found */ static void search_update(int c) { if (c == 0) { search_pos = 0; search_string[0] = 0; search_prompt[0] = '?'; search_prompt[1] = ' '; search_prompt[2] = 0; } else if (c > 0) { search_string[search_pos] = c; search_string[search_pos+1] = 0; search_prompt[search_pos] = c; search_prompt[search_pos+1] = '?'; search_prompt[search_pos+2] = ' '; search_prompt[search_pos+3] = 0; search_pos++; } else { if (search_pos > 0) { search_pos--; search_string[search_pos] = 0; search_prompt[search_pos] = '?'; search_prompt[search_pos+1] = ' '; search_prompt[search_pos+2] = 0; } else { gl_bell(); hist_pos = hist_last; } } } static void search_addchar(int c) { char *loc; search_update(c); if (c < 0) { if (search_pos > 0) { hist_pos = search_last; } else { gl_buf[0] = 0; hist_pos = hist_last; } strcpy(gl_buf, hist_buf[hist_pos]); } if ((loc = strstr(gl_buf, search_string)) != 0) { gl_fixup(search_prompt, 0, loc - gl_buf); } else if (search_pos > 0) { if (search_forw_flg) { search_forw(0); } else { search_back(0); } } else { gl_fixup(search_prompt, 0, 0); } } static void search_term() { gl_search_mode = 0; if (gl_buf[0] == 0) /* not found, reset hist list */ hist_pos = hist_last; if (gl_in_hook) gl_in_hook(gl_buf); gl_fixup(gl_prompt, 0, gl_pos); } static void search_back(int new_search) { int found = 0; char *p, *loc; search_forw_flg = 0; if (gl_search_mode == 0) { search_last = hist_pos = hist_last; search_update(0); gl_search_mode = 1; gl_buf[0] = 0; gl_fixup(search_prompt, 0, 0); } else if (search_pos > 0) { while (!found) { p = hist_prev(); if (*p == 0) { /* not found, done looking */ gl_buf[0] = 0; gl_fixup(search_prompt, 0, 0); found = 1; } else if ((loc = strstr(p, search_string)) != 0) { strcpy(gl_buf, p); gl_fixup(search_prompt, 0, loc - p); if (new_search) search_last = hist_pos; found = 1; } } } else { gl_bell(); } } static void search_forw(int new_search) { int found = 0; char *p, *loc; search_forw_flg = 1; if (gl_search_mode == 0) { search_last = hist_pos = hist_last; search_update(0); gl_search_mode = 1; gl_buf[0] = 0; gl_fixup(search_prompt, 0, 0); } else if (search_pos > 0) { while (!found) { p = hist_next(); if (*p == 0) { /* not found, done looking */ gl_buf[0] = 0; gl_fixup(search_prompt, 0, 0); found = 1; } else if ((loc = strstr(p, search_string)) != 0) { strcpy(gl_buf, p); gl_fixup(search_prompt, 0, loc - p); if (new_search) search_last = hist_pos; found = 1; } } } else { gl_bell(); } } #if 0 /*********************************************************************** * * * Strip blanks from both sides of a string. Space for the new * * string is allocated and a pointer to it is returned. * * * ***********************************************************************/ char *strip(char *s) { char *r, *t1, *t2; int l; l = strlen(s); r = (char *)calloc(l+1, 1); if (l == 0) { *r = '\0'; return r; } /* get rid of leading blanks */ t1 = s; while (*t1 == ' ') t1++; t2 = s + l - 1; while (*t2 == ' ' && t2 > s) t2--; if (t1 > t2) { *r = '\0'; return r; } strncpy(r, t1, (size_t) (t2-t1+1)); return r; } #endif /*****************************************************************************/ /* Extra routine provided by Christian Lacunza */ /*****************************************************************************/ /* move cursor back to beginning of _current_ word */ /* unless it's already at the beginning, */ /* in which case it moves back to the beginning */ /* of the _previous_ word. */ static void gl_back_1_word( void ) { int i = gl_pos; /* if we're at the beginning of a word, */ /* slip back into the preceeding whitespace */ if( i>0 && is_whitespace(gl_buf[i-1]) ) { i-=1; } /* now move back over all consecutive whitespace */ while( i>0 && is_whitespace(gl_buf[i]) ) { i-=1; } /* now keep moving back over all consecutive non-whitespace */ /* until we find the beginning of this word. */ /* ie. stop just before more whitespace shows up. */ while( i>0 && !is_whitespace(gl_buf[i-1]) ) { i-=1; } /* move the cursor here */ gl_fixup(gl_prompt, -1, i); } /* kills from current position to end of word */ static void gl_kill_1_word( void ) { int i = gl_pos; int j = gl_pos; /* delete this: */ #if 0 /* not sure what to do with "punctuation" */ if( is_whitespace(gl_buf[j]) && gl_buf[j]!=' ' ) { return; } /* first find a word */ while( j #ifdef SIGAR_HAS_PCRE #include "pcre.h" #endif /* See http://gcc.gnu.org/ml/libstdc++/2002-03/msg00164.html */ #if defined(WIN32) || (defined(__hpux) && defined(SIGAR_64BIT)) #define strtoull strtoul #elif (defined(__hpux) && !defined(SIGAR_64BIT)) #define strtoull __strtoull #else #include #endif #define SIGAR_CLEAR_ERRNO() errno = 0 #define strtonum_failed(src, ptr) \ ((src == ptr) || (errno == ERANGE) || (*ptr != '\0')) typedef struct ptql_parse_branch_t ptql_parse_branch_t; typedef struct ptql_branch_t ptql_branch_t; /* adhere to calling convention, else risk stack corruption */ #ifdef WIN32 #define SIGAPI WINAPI #else #define SIGAPI #endif typedef int (SIGAPI *ptql_get_t)(sigar_t *sigar, sigar_pid_t pid, void *data); typedef int (*ptql_branch_init_t)(ptql_parse_branch_t *parsed, ptql_branch_t *branch, sigar_ptql_error_t *error); typedef int (*ptql_op_ui64_t)(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle); typedef int (*ptql_op_ui32_t)(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle); typedef int (*ptql_op_dbl_t)(ptql_branch_t *branch, double haystack, double needle); typedef int (*ptql_op_str_t)(ptql_branch_t *branch, char *haystack, char *needle); typedef int (*ptql_op_chr_t)(ptql_branch_t *branch, char haystack, char needle); typedef enum { PTQL_VALUE_TYPE_UI64, PTQL_VALUE_TYPE_UI32, PTQL_VALUE_TYPE_DBL, PTQL_VALUE_TYPE_CHR, PTQL_VALUE_TYPE_STR, PTQL_VALUE_TYPE_ANY } ptql_value_type_t; typedef enum { PTQL_OP_EQ, PTQL_OP_NE, PTQL_OP_GT, PTQL_OP_GE, PTQL_OP_LT, PTQL_OP_LE, #define PTQL_OP_MAX_NSTR PTQL_OP_LE PTQL_OP_EW, /* rest are string only */ PTQL_OP_SW, PTQL_OP_RE, PTQL_OP_CT, PTQL_OP_MAX } ptql_op_name_t; #define PTQL_OP_FLAG_PARENT 1 #define PTQL_OP_FLAG_REF 2 #define PTQL_OP_FLAG_GLOB 4 #define PTQL_OP_FLAG_PID 8 #define PTQL_OP_FLAG_ICASE 16 struct ptql_parse_branch_t { char *name; char *attr; char *op; char *value; unsigned int op_flags; }; typedef struct { char *name; ptql_get_t get; size_t offset; unsigned int data_size; ptql_value_type_t type; ptql_branch_init_t init; } ptql_lookup_t; #define DATA_PTR(branch) \ ((char *)branch->data.ptr + branch->lookup->offset) #define IS_ICASE(branch) \ (branch->op_flags & PTQL_OP_FLAG_ICASE) #define branch_strcmp(branch, s1, s2) \ (IS_ICASE(branch) ? strcasecmp(s1, s2) : strcmp(s1, s2)) #define branch_strncmp(branch, s1, s2, n) \ (IS_ICASE(branch) ? strncasecmp(s1, s2, n) : strncmp(s1, s2, n)) #define branch_strEQ(branch, s1, s2) \ (branch_strcmp(branch, s1, s2) == 0) #define branch_strnEQ(branch, s1, s2, n) \ (branch_strncmp(branch, s1, s2, n) == 0) #define branch_strstr(branch, s1, s2) \ (IS_ICASE(branch) ? sigar_strcasestr(s1, s2) : strstr(s1, s2)) #define IS_PID_SERVICE_QUERY(branch) \ (branch->flags >= PTQL_PID_SERVICE_NAME) static void data_free(void *data) { free(data); } typedef union { sigar_pid_t pid; sigar_uint64_t ui64; sigar_uint32_t ui32; double dbl; char chr[4]; char *str; void *ptr; } any_value_t; struct ptql_branch_t { ptql_lookup_t *lookup; any_value_t data; unsigned int data_size; void (*data_free)(void *); unsigned int flags; unsigned int op_flags; ptql_op_name_t op_name; union { ptql_op_ui64_t ui64; ptql_op_ui32_t ui32; ptql_op_dbl_t dbl; ptql_op_chr_t chr; ptql_op_str_t str; } match; any_value_t value; void (*value_free)(void *); }; typedef struct { char *name; ptql_lookup_t *members; } ptql_entry_t; typedef struct { unsigned long number; unsigned long size; ptql_branch_t *data; } ptql_branch_list_t; struct sigar_ptql_query_t { ptql_branch_list_t branches; #ifdef PTQL_DEBUG char *ptql; #endif }; /* XXX optimize */ static ptql_op_name_t ptql_op_code_get(char *op) { if (strEQ(op, "eq")) { return PTQL_OP_EQ; } else if (strEQ(op, "ne")) { return PTQL_OP_NE; } else if (strEQ(op, "gt")) { return PTQL_OP_GT; } else if (strEQ(op, "ge")) { return PTQL_OP_GE; } else if (strEQ(op, "lt")) { return PTQL_OP_LT; } else if (strEQ(op, "le")) { return PTQL_OP_LE; } else if (strEQ(op, "ew")) { return PTQL_OP_EW; } else if (strEQ(op, "sw")) { return PTQL_OP_SW; } else if (strEQ(op, "re")) { return PTQL_OP_RE; } else if (strEQ(op, "ct")) { return PTQL_OP_CT; } else { return PTQL_OP_MAX; } } static int ptql_op_ui64_eq(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle) { return haystack == needle; } static int ptql_op_ui64_ne(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle) { return haystack != needle; } static int ptql_op_ui64_gt(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle) { return haystack > needle; } static int ptql_op_ui64_ge(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle) { return haystack >= needle; } static int ptql_op_ui64_lt(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle) { return haystack < needle; } static int ptql_op_ui64_le(ptql_branch_t *branch, sigar_uint64_t haystack, sigar_uint64_t needle) { return haystack <= needle; } static ptql_op_ui64_t ptql_op_ui64[] = { ptql_op_ui64_eq, ptql_op_ui64_ne, ptql_op_ui64_gt, ptql_op_ui64_ge, ptql_op_ui64_lt, ptql_op_ui64_le }; static int ptql_op_ui32_eq(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle) { return haystack == needle; } static int ptql_op_ui32_ne(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle) { return haystack != needle; } static int ptql_op_ui32_gt(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle) { return haystack > needle; } static int ptql_op_ui32_ge(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle) { return haystack >= needle; } static int ptql_op_ui32_lt(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle) { return haystack < needle; } static int ptql_op_ui32_le(ptql_branch_t *branch, sigar_uint32_t haystack, sigar_uint32_t needle) { return haystack <= needle; } static ptql_op_ui32_t ptql_op_ui32[] = { ptql_op_ui32_eq, ptql_op_ui32_ne, ptql_op_ui32_gt, ptql_op_ui32_ge, ptql_op_ui32_lt, ptql_op_ui32_le }; static int ptql_op_dbl_eq(ptql_branch_t *branch, double haystack, double needle) { return haystack == needle; } static int ptql_op_dbl_ne(ptql_branch_t *branch, double haystack, double needle) { return haystack != needle; } static int ptql_op_dbl_gt(ptql_branch_t *branch, double haystack, double needle) { return haystack > needle; } static int ptql_op_dbl_ge(ptql_branch_t *branch, double haystack, double needle) { return haystack >= needle; } static int ptql_op_dbl_lt(ptql_branch_t *branch, double haystack, double needle) { return haystack < needle; } static int ptql_op_dbl_le(ptql_branch_t *branch, double haystack, double needle) { return haystack <= needle; } static ptql_op_dbl_t ptql_op_dbl[] = { ptql_op_dbl_eq, ptql_op_dbl_ne, ptql_op_dbl_gt, ptql_op_dbl_ge, ptql_op_dbl_lt, ptql_op_dbl_le }; static int ptql_op_str_eq(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strEQ(branch, haystack, needle); } static int ptql_op_str_ne(ptql_branch_t *branch, char *haystack, char *needle) { return !branch_strEQ(branch, haystack, needle); } static int ptql_op_str_gt(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strcmp(branch, haystack, needle) > 0; } static int ptql_op_str_ge(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strcmp(branch, haystack, needle) >= 0; } static int ptql_op_str_lt(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strcmp(branch, haystack, needle) < 0; } static int ptql_op_str_le(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strcmp(branch, haystack, needle) <= 0; } static int ptql_op_str_ew(ptql_branch_t *branch, char *haystack, char *needle) { int nlen = strlen(needle); int hlen = strlen(haystack); int diff = hlen - nlen; if (diff < 0) { return 0; } return branch_strnEQ(branch, haystack + diff, needle, nlen); } static int ptql_op_str_sw(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strnEQ(branch, haystack, needle, strlen(needle)); } static int ptql_op_str_re(ptql_branch_t *branch, char *haystack, char *needle) { #ifdef SIGAR_HAS_PCRE pcre *re = (pcre *)branch->value.ptr; int len = strlen(haystack); int rc = pcre_exec(re, NULL, haystack, len, 0, 0, NULL, 0); return rc >= 0; #else return 0; #endif } static int ptql_op_str_ct(ptql_branch_t *branch, char *haystack, char *needle) { return branch_strstr(branch, haystack, needle) != NULL; } static ptql_op_str_t ptql_op_str[] = { ptql_op_str_eq, ptql_op_str_ne, ptql_op_str_gt, ptql_op_str_ge, ptql_op_str_lt, ptql_op_str_le, ptql_op_str_ew, ptql_op_str_sw, ptql_op_str_re, ptql_op_str_ct }; static int ptql_op_chr_eq(ptql_branch_t *branch, char haystack, char needle) { return haystack == needle; } static int ptql_op_chr_ne(ptql_branch_t *branch, char haystack, char needle) { return haystack != needle; } static int ptql_op_chr_gt(ptql_branch_t *branch, char haystack, char needle) { return haystack > needle; } static int ptql_op_chr_ge(ptql_branch_t *branch, char haystack, char needle) { return haystack >= needle; } static int ptql_op_chr_lt(ptql_branch_t *branch, char haystack, char needle) { return haystack < needle; } static int ptql_op_chr_le(ptql_branch_t *branch, char haystack, char needle) { return haystack <= needle; } static ptql_op_chr_t ptql_op_chr[] = { ptql_op_chr_eq, ptql_op_chr_ne, ptql_op_chr_gt, ptql_op_chr_ge, ptql_op_chr_lt, ptql_op_chr_le }; #define PTQL_BRANCH_LIST_MAX 3 #define PTQL_BRANCH_LIST_GROW(branches) \ if ((branches)->number >= (branches)->size) { \ ptql_branch_list_grow(branches); \ } static int ptql_branch_list_create(ptql_branch_list_t *branches) { branches->number = 0; branches->size = PTQL_BRANCH_LIST_MAX; branches->data = malloc(sizeof(*(branches->data)) * branches->size); return SIGAR_OK; } static int ptql_branch_list_grow(ptql_branch_list_t *branches) { branches->data = realloc(branches->data, sizeof(*(branches->data)) * (branches->size + PTQL_BRANCH_LIST_MAX)); branches->size += PTQL_BRANCH_LIST_MAX; return SIGAR_OK; } static int ptql_branch_list_destroy(ptql_branch_list_t *branches) { if (branches->size) { int i; for (i=0; inumber; i++) { ptql_branch_t *branch = &branches->data[i]; if (branch->data_size && branch->data.ptr) { branch->data_free(branch->data.ptr); } if (branch->lookup && ((branch->lookup->type == PTQL_VALUE_TYPE_STR) || (branch->lookup->type == PTQL_VALUE_TYPE_ANY)) && !(branch->op_flags & PTQL_OP_FLAG_REF)) { if (branch->value.str) { branch->value_free(branch->value.str); } } } free(branches->data); branches->number = branches->size = 0; } return SIGAR_OK; } #ifdef WIN32 #define vsnprintf _vsnprintf #endif #define PTQL_ERRNAN \ ptql_error(error, "Query value '%s' is not a number", parsed->value) static int ptql_error(sigar_ptql_error_t *error, const char *format, ...) { va_list args; if (error != NULL) { va_start(args, format); vsnprintf(error->message, sizeof(error->message), format, args); va_end(args); } return SIGAR_PTQL_MALFORMED_QUERY; } static int ptql_branch_init_any(ptql_parse_branch_t *parsed, ptql_branch_t *branch, sigar_ptql_error_t *error) { branch->data.str = sigar_strdup(parsed->attr); branch->data_size = strlen(parsed->attr); return SIGAR_OK; } static int ptql_str_match(sigar_t *sigar, ptql_branch_t *branch, char *value) { if (!branch->value.str) { return 0; } #ifndef SIGAR_HAS_PCRE if (branch->op_name == PTQL_OP_RE) { if (sigar->ptql_re_impl) { return sigar->ptql_re_impl(sigar->ptql_re_data, value, branch->value.str); } else { return 0; } } #endif return branch->match.str(branch, value, branch->value.str); } static int ptql_branch_match(ptql_branch_t *branch) { switch (branch->lookup->type) { case PTQL_VALUE_TYPE_UI64: return branch->match.ui64(branch, *(sigar_uint64_t *)DATA_PTR(branch), branch->value.ui64); case PTQL_VALUE_TYPE_UI32: return branch->match.ui32(branch, *(sigar_uint32_t *)DATA_PTR(branch), branch->value.ui32); case PTQL_VALUE_TYPE_DBL: return branch->match.dbl(branch, *(double *)DATA_PTR(branch), branch->value.dbl); case PTQL_VALUE_TYPE_CHR: return branch->match.chr(branch, *(char *)DATA_PTR(branch), branch->value.chr[0]); case PTQL_VALUE_TYPE_STR: case PTQL_VALUE_TYPE_ANY: if (!branch->value.str) { return 0; } return branch->match.str(branch, (char *)DATA_PTR(branch), branch->value.str); default: return 0; } } static int ptql_branch_match_ref(ptql_branch_t *branch, ptql_branch_t *ref) { switch (branch->lookup->type) { case PTQL_VALUE_TYPE_UI64: return branch->match.ui64(branch, *(sigar_uint64_t *)DATA_PTR(branch), *(sigar_uint64_t *)DATA_PTR(ref)); case PTQL_VALUE_TYPE_UI32: return branch->match.ui32(branch, *(sigar_uint32_t *)DATA_PTR(branch), *(sigar_uint32_t *)DATA_PTR(ref)); case PTQL_VALUE_TYPE_DBL: return branch->match.dbl(branch, *(double *)DATA_PTR(branch), *(double *)DATA_PTR(ref)); case PTQL_VALUE_TYPE_CHR: return branch->match.chr(branch, *(char *)DATA_PTR(branch), *(char *)DATA_PTR(ref)); case PTQL_VALUE_TYPE_STR: case PTQL_VALUE_TYPE_ANY: return branch->match.str(branch, (char *)DATA_PTR(branch), (char *)DATA_PTR(ref)); default: return 0; } } enum { PTQL_PID_PID, PTQL_PID_FILE, PTQL_PID_SUDO_FILE, PTQL_PID_TCP_PORT, PTQL_PID_UDP_PORT, PTQL_PID_SERVICE_NAME, PTQL_PID_SERVICE_DISPLAY, PTQL_PID_SERVICE_PATH, PTQL_PID_SERVICE_EXE }; #ifdef SIGAR_64BIT #define str2pid(value, ptr) strtoull(value, &ptr, 10) #define pid_branch_match(branch, pid, match_pid) \ ptql_op_ui64[branch->op_name](branch, pid, match_pid) #else #define str2pid(value, ptr) strtoul(value, &ptr, 10) #define pid_branch_match(branch, pid, match_pid) \ ptql_op_ui32[branch->op_name](branch, pid, match_pid) #endif #ifndef WIN32 #include int sigar_sudo_file2str(const char *fname, char *buffer, int buflen) { FILE *fp; struct stat sb; if (stat(fname, &sb) < 0) { return errno; } if (sb.st_size > buflen) { return ENOMEM; } snprintf(buffer, buflen, "sudo cat %s", fname); if (!(fp = popen(buffer, "r"))) { return errno; } (void)fgets(buffer, buflen, fp); pclose(fp); return SIGAR_OK; } #endif static int ptql_branch_init_service(ptql_parse_branch_t *parsed, ptql_branch_t *branch, sigar_ptql_error_t *error) { branch->op_flags |= PTQL_OP_FLAG_PID; if (strEQ(parsed->attr, "Name")) { branch->flags = PTQL_PID_SERVICE_NAME; } else if (strEQ(parsed->attr, "DisplayName")) { branch->flags = PTQL_PID_SERVICE_DISPLAY; } else if (strEQ(parsed->attr, "Path")) { branch->flags = PTQL_PID_SERVICE_PATH; } else if (strEQ(parsed->attr, "Exe")) { /* basename of Path */ branch->flags = PTQL_PID_SERVICE_EXE; } else { return ptql_error(error, "Unsupported %s attribute: %s", parsed->name, parsed->attr); } #ifdef WIN32 branch->data.str = sigar_strdup(parsed->value); branch->data_size = strlen(parsed->value); #endif return SIGAR_OK; } static int ptql_branch_init_pid(ptql_parse_branch_t *parsed, ptql_branch_t *branch, sigar_ptql_error_t *error) { int use_sudo = 0; branch->op_flags |= PTQL_OP_FLAG_PID; if (strEQ(parsed->attr, "Pid")) { branch->flags = PTQL_PID_PID; if (strEQ(parsed->value, "$$")) { branch->data.pid = getpid(); } else { char *ptr; SIGAR_CLEAR_ERRNO(); branch->data.pid = str2pid(parsed->value, ptr); if (strtonum_failed(parsed->value, ptr)) { return PTQL_ERRNAN; } } return SIGAR_OK; } else if (strEQ(parsed->attr, "PidFile") || (use_sudo = strEQ(parsed->attr, "SudoPidFile"))) { branch->flags = use_sudo ? PTQL_PID_SUDO_FILE : PTQL_PID_FILE; branch->data.str = sigar_strdup(parsed->value); branch->data_size = strlen(parsed->value); return SIGAR_OK; } return ptql_error(error, "Unsupported %s attribute: %s", parsed->name, parsed->attr); } #ifdef WIN32 #define QUERY_SC_SIZE 8192 static int ptql_service_query_config(SC_HANDLE scm_handle, char *name, LPQUERY_SERVICE_CONFIG config) { int status; DWORD bytes; SC_HANDLE handle = OpenService(scm_handle, name, SERVICE_QUERY_CONFIG); if (!handle) { return GetLastError(); } if (QueryServiceConfig(handle, config, QUERY_SC_SIZE, &bytes)) { status = SIGAR_OK; } else { status = GetLastError(); } CloseServiceHandle(handle); return status; } static int sigar_services_walk(sigar_services_walker_t *walker, ptql_branch_t *branch) { sigar_services_status_t ss; char buffer[QUERY_SC_SIZE]; char exe[SIGAR_CMDLINE_MAX]; LPQUERY_SERVICE_CONFIG config = (LPQUERY_SERVICE_CONFIG)buffer; DWORD i, status; SIGAR_ZERO(&ss); status = sigar_services_status_get(&ss, walker->flags); if (status != SIGAR_OK) { return status; } for (i=0; iadd_service(walker, name) != SIGAR_OK) { break; } continue; } switch (branch->flags) { case PTQL_PID_SERVICE_DISPLAY: value = ss.services[i].lpDisplayName; break; case PTQL_PID_SERVICE_PATH: case PTQL_PID_SERVICE_EXE: status = ptql_service_query_config(ss.handle, name, config); if (status == SIGAR_OK) { if (branch->flags == PTQL_PID_SERVICE_EXE) { value = sigar_service_exe_get(config->lpBinaryPathName, exe, 1); } else { value = config->lpBinaryPathName; } } else { continue; } break; case PTQL_PID_SERVICE_NAME: default: value = name; break; } if (ptql_str_match(walker->sigar, branch, value)) { if (walker->add_service(walker, name) != SIGAR_OK) { break; } } } sigar_services_status_close(&ss); return SIGAR_OK; } static int ptql_pid_service_add(sigar_services_walker_t *walker, char *name) { sigar_pid_t service_pid; sigar_proc_list_t *proclist = (sigar_proc_list_t *)walker->data; int status = sigar_service_pid_get(walker->sigar, name, &service_pid); if (status == SIGAR_OK) { SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = service_pid; } return SIGAR_OK; } static int ptql_pid_service_list_get(sigar_t *sigar, ptql_branch_t *branch, sigar_proc_list_t *proclist) { sigar_services_walker_t walker; walker.sigar = sigar; walker.flags = SERVICE_ACTIVE; walker.data = proclist; walker.add_service = ptql_pid_service_add; return sigar_services_walk(&walker, branch); } int sigar_services_query(char *ptql, sigar_ptql_error_t *error, sigar_services_walker_t *walker) { int status; sigar_ptql_query_t *query; if (ptql == NULL) { return sigar_services_walk(walker, NULL); } status = sigar_ptql_query_create(&query, (char *)ptql, error); if (status != SIGAR_OK) { return status; } if (query->branches.number == 1) { ptql_branch_t *branch = &query->branches.data[0]; if (IS_PID_SERVICE_QUERY(branch)) { status = sigar_services_walk(walker, branch); } else { ptql_error(error, "Invalid Service query: %s", ptql); status = SIGAR_PTQL_MALFORMED_QUERY; } } else { ptql_error(error, "Too many queries (%d), must be (1)", query->branches.number); status = SIGAR_PTQL_MALFORMED_QUERY; } sigar_ptql_query_destroy(query); return status; } #endif static int ptql_pid_port_get(sigar_t *sigar, ptql_branch_t *branch, sigar_pid_t *pid) { unsigned long port = branch->data.ui32; int status; int proto = branch->flags == PTQL_PID_UDP_PORT ? SIGAR_NETCONN_UDP : SIGAR_NETCONN_TCP; status = sigar_proc_port_get(sigar, proto, port, pid); return status; } static int ptql_pid_get(sigar_t *sigar, ptql_branch_t *branch, sigar_pid_t *pid) { if ((branch->flags == PTQL_PID_FILE) || (branch->flags == PTQL_PID_SUDO_FILE)) { char *ptr, buffer[SIGAR_PATH_MAX+1]; const char *fname = (const char *)branch->data.str; int status, len = sizeof(buffer)-1; if (branch->flags == PTQL_PID_FILE) { status = sigar_file2str(fname, buffer, len); } else { #ifdef WIN32 return SIGAR_ENOTIMPL; #else status = sigar_sudo_file2str(fname, buffer, len); #endif } if (status != SIGAR_OK) { return status; } SIGAR_CLEAR_ERRNO(); *pid = str2pid(buffer, ptr); if ((buffer == ptr) || (errno == ERANGE)) { return errno; } } else if (branch->flags == PTQL_PID_SERVICE_NAME) { #ifdef WIN32 int status = sigar_service_pid_get(sigar, branch->data.str, pid); if (status != SIGAR_OK) { return status; } #else return SIGAR_ENOTIMPL; #endif } else if ((branch->flags == PTQL_PID_UDP_PORT) || (branch->flags == PTQL_PID_TCP_PORT)) { int status = ptql_pid_port_get(sigar, branch, pid); if (status != SIGAR_OK) { return status; } } else { *pid = branch->data.pid; } return SIGAR_OK; } static int ptql_pid_list_get(sigar_t *sigar, ptql_branch_t *branch, sigar_proc_list_t *proclist) { int status, i; sigar_pid_t match_pid; if (IS_PID_SERVICE_QUERY(branch)) { if ((branch->flags > PTQL_PID_SERVICE_NAME) || (branch->op_name != PTQL_OP_EQ)) { #ifdef WIN32 return ptql_pid_service_list_get(sigar, branch, proclist); #else return SIGAR_OK; /* no matches */ #endif } } status = ptql_pid_get(sigar, branch, &match_pid); if (status != SIGAR_OK) { /* XXX treated as non-match but would be nice to propagate */ return SIGAR_OK; } status = sigar_proc_list_get(sigar, NULL); if (status != SIGAR_OK) { return status; } for (i=0; ipids->number; i++) { sigar_pid_t pid = sigar->pids->data[i]; if (pid_branch_match(branch, pid, match_pid)) { SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = pid; } } return SIGAR_OK; } static int SIGAPI ptql_pid_match(sigar_t *sigar, sigar_pid_t pid, void *data) { /* query already used to filter proc_list */ return SIGAR_OK; } static int ptql_args_branch_init(ptql_parse_branch_t *parsed, ptql_branch_t *branch, sigar_ptql_error_t *error) { if (strEQ(parsed->attr, "*")) { branch->op_flags |= PTQL_OP_FLAG_GLOB; } else { char *end; SIGAR_CLEAR_ERRNO(); branch->data.ui32 = strtol(parsed->attr, &end, 10); if (strtonum_failed(parsed->attr, end)) { /* conversion failed */ return ptql_error(error, "%s is not a number", parsed->attr); } } return SIGAR_OK; } static int SIGAPI ptql_args_match(sigar_t *sigar, sigar_pid_t pid, void *data) { ptql_branch_t *branch = (ptql_branch_t *)data; int status, matched=0; sigar_proc_args_t args; status = sigar_proc_args_get(sigar, pid, &args); if (status != SIGAR_OK) { return status; } if (branch->op_flags & PTQL_OP_FLAG_GLOB) { int i; for (i=0; idata.ui32; /* e.g. find last element of args: Args.-1.eq=weblogic.Server */ if (num < 0) { num += args.number; } if ((num >= 0) && (num < args.number)) { matched = ptql_str_match(sigar, branch, args.data[num]); } } sigar_proc_args_destroy(sigar, &args); return matched ? SIGAR_OK : !SIGAR_OK; } typedef struct { sigar_t *sigar; ptql_branch_t *branch; sigar_uint32_t ix; int matched; } proc_modules_match_t; static int proc_modules_match(void *data, char *name, int len) { proc_modules_match_t *matcher = (proc_modules_match_t *)data; ptql_branch_t *branch = matcher->branch; if (branch->op_flags & PTQL_OP_FLAG_GLOB) { /* Modules.*.ct=libc */ matcher->matched = ptql_str_match(matcher->sigar, branch, name); if (matcher->matched) { return !SIGAR_OK; /* stop iterating */ } } else { if (matcher->ix++ == branch->data.ui32) { /* Modules.3.ct=libc */ matcher->matched = ptql_str_match(matcher->sigar, branch, name); return !SIGAR_OK; /* stop iterating */ } } return SIGAR_OK; } static int SIGAPI ptql_modules_match(sigar_t *sigar, sigar_pid_t pid, void *data) { ptql_branch_t *branch = (ptql_branch_t *)data; int status; sigar_proc_modules_t procmods; proc_modules_match_t matcher; matcher.sigar = sigar; matcher.branch = branch; matcher.ix = 0; matcher.matched = 0; procmods.module_getter = proc_modules_match; procmods.data = &matcher; status = sigar_proc_modules_get(sigar, pid, &procmods); if (status != SIGAR_OK) { return status; } return matcher.matched ? SIGAR_OK : !SIGAR_OK; } typedef struct { const char *key; int klen; char *val; int vlen; } sigar_proc_env_entry_t; static int sigar_proc_env_get_key(void *data, const char *key, int klen, char *val, int vlen) { sigar_proc_env_entry_t *entry = (sigar_proc_env_entry_t *)data; if ((entry->klen == klen) && (strcmp(entry->key, key) == 0)) { entry->val = val; entry->vlen = vlen; return !SIGAR_OK; /* foundit; stop iterating */ } return SIGAR_OK; } static int SIGAPI ptql_env_match(sigar_t *sigar, sigar_pid_t pid, void *data) { ptql_branch_t *branch = (ptql_branch_t *)data; int status, matched=0; sigar_proc_env_t procenv; sigar_proc_env_entry_t entry; /* XXX ugh this is klunky */ entry.key = branch->data.str; entry.klen = branch->data_size; entry.val = NULL; procenv.type = SIGAR_PROC_ENV_KEY; procenv.key = branch->data.str; procenv.klen = branch->data_size; procenv.env_getter = sigar_proc_env_get_key; procenv.data = &entry; status = sigar_proc_env_get(sigar, pid, &procenv); if (status != SIGAR_OK) { return status; } else { if (entry.val) { matched = ptql_str_match(sigar, branch, entry.val); } } return matched ? SIGAR_OK : !SIGAR_OK; } static int ptql_branch_init_port(ptql_parse_branch_t *parsed, ptql_branch_t *branch, sigar_ptql_error_t *error) { char *ptr; /* only 'eq' is supported here */ if (branch->op_name != PTQL_OP_EQ) { return ptql_error(error, "%s requires 'eq' operator", parsed->name); } if (strEQ(parsed->attr, "tcp")) { branch->flags = PTQL_PID_TCP_PORT; } else if (strEQ(parsed->attr, "udp")) { branch->flags = PTQL_PID_TCP_PORT; } else { return ptql_error(error, "Unsupported %s protocol: %s", parsed->name, parsed->attr); } branch->op_flags |= PTQL_OP_FLAG_PID; SIGAR_CLEAR_ERRNO(); branch->data.ui32 = strtoul(parsed->value, &ptr, 10); if (strtonum_failed(parsed->value, ptr)) { return PTQL_ERRNAN; } return SIGAR_OK; } #define PTQL_LOOKUP_ENTRY(cname, member, type) \ (ptql_get_t)sigar_##cname##_get, \ sigar_offsetof(sigar_##cname##_t, member), \ sizeof(sigar_##cname##_t), \ PTQL_VALUE_TYPE_##type, \ NULL /* XXX uid/pid can be larger w/ 64bit mode */ #define PTQL_VALUE_TYPE_PID PTQL_VALUE_TYPE_UI32 #define PTQL_VALUE_TYPE_UID PTQL_VALUE_TYPE_UI32 static ptql_lookup_t PTQL_Time[] = { { "StartTime", PTQL_LOOKUP_ENTRY(proc_time, start_time, UI64) }, { "User", PTQL_LOOKUP_ENTRY(proc_time, user, UI64) }, { "Sys", PTQL_LOOKUP_ENTRY(proc_time, sys, UI64) }, { "Total", PTQL_LOOKUP_ENTRY(proc_time, total, UI64) }, { NULL } }; static ptql_lookup_t PTQL_Cpu[] = { { "StartTime", PTQL_LOOKUP_ENTRY(proc_cpu, start_time, UI64) }, { "User", PTQL_LOOKUP_ENTRY(proc_cpu, user, UI64) }, { "Sys", PTQL_LOOKUP_ENTRY(proc_cpu, sys, UI64) }, { "Total", PTQL_LOOKUP_ENTRY(proc_cpu, total, UI64) }, { "Percent", PTQL_LOOKUP_ENTRY(proc_cpu, percent, DBL) }, { NULL } }; static ptql_lookup_t PTQL_CredName[] = { { "User", PTQL_LOOKUP_ENTRY(proc_cred_name, user, STR) }, { "Group", PTQL_LOOKUP_ENTRY(proc_cred_name, group, STR) }, { NULL } }; static ptql_lookup_t PTQL_Mem[] = { { "Size", PTQL_LOOKUP_ENTRY(proc_mem, size, UI64) }, { "Resident", PTQL_LOOKUP_ENTRY(proc_mem, resident, UI64) }, { "Share", PTQL_LOOKUP_ENTRY(proc_mem, share, UI64) }, { "MinorFaults", PTQL_LOOKUP_ENTRY(proc_mem, minor_faults, UI64) }, { "MajorFaults", PTQL_LOOKUP_ENTRY(proc_mem, major_faults, UI64) }, { "PageFaults", PTQL_LOOKUP_ENTRY(proc_mem, page_faults, UI64) }, { NULL } }; static ptql_lookup_t PTQL_Exe[] = { { "Name", PTQL_LOOKUP_ENTRY(proc_exe, name, STR) }, { "Cwd", PTQL_LOOKUP_ENTRY(proc_exe, cwd, STR) }, { NULL } }; static ptql_lookup_t PTQL_Cred[] = { { "Uid", PTQL_LOOKUP_ENTRY(proc_cred, uid, UID) }, { "Gid", PTQL_LOOKUP_ENTRY(proc_cred, gid, UID) }, { "Euid", PTQL_LOOKUP_ENTRY(proc_cred, euid, UID) }, { "Egid", PTQL_LOOKUP_ENTRY(proc_cred, egid, UID) }, { NULL } }; static ptql_lookup_t PTQL_State[] = { { "State", PTQL_LOOKUP_ENTRY(proc_state, state, CHR) }, { "Name", PTQL_LOOKUP_ENTRY(proc_state, name, STR) }, { "Ppid", PTQL_LOOKUP_ENTRY(proc_state, ppid, PID) }, { "Tty", PTQL_LOOKUP_ENTRY(proc_state, tty, UI32) }, { "Nice", PTQL_LOOKUP_ENTRY(proc_state, nice, UI32) }, { "Priority", PTQL_LOOKUP_ENTRY(proc_state, priority, UI32) }, { "Threads", PTQL_LOOKUP_ENTRY(proc_state, threads, UI64) }, { "Processor", PTQL_LOOKUP_ENTRY(proc_state, processor, UI32) }, { NULL } }; static ptql_lookup_t PTQL_Fd[] = { { "Total", PTQL_LOOKUP_ENTRY(proc_fd, total, UI64) }, { NULL } }; static ptql_lookup_t PTQL_Args[] = { { NULL, ptql_args_match, 0, 0, PTQL_VALUE_TYPE_ANY, ptql_args_branch_init } }; static ptql_lookup_t PTQL_Modules[] = { { NULL, ptql_modules_match, 0, 0, PTQL_VALUE_TYPE_ANY, ptql_args_branch_init } }; static ptql_lookup_t PTQL_Env[] = { { NULL, ptql_env_match, 0, 0, PTQL_VALUE_TYPE_ANY, ptql_branch_init_any } }; static ptql_lookup_t PTQL_Port[] = { { NULL, ptql_pid_match, 0, 0, PTQL_VALUE_TYPE_ANY, ptql_branch_init_port } }; static ptql_lookup_t PTQL_Pid[] = { { NULL, ptql_pid_match, 0, 0, PTQL_VALUE_TYPE_ANY, ptql_branch_init_pid } }; static ptql_lookup_t PTQL_Service[] = { { NULL, ptql_pid_match, 0, 0, PTQL_VALUE_TYPE_ANY, ptql_branch_init_service } }; static ptql_entry_t ptql_map[] = { { "Time", PTQL_Time }, { "Cpu", PTQL_Cpu }, { "CredName", PTQL_CredName }, { "Mem", PTQL_Mem }, { "Exe", PTQL_Exe }, { "Cred", PTQL_Cred }, { "State", PTQL_State }, { "Fd", PTQL_Fd }, { "Args", PTQL_Args }, { "Modules", PTQL_Modules }, { "Env", PTQL_Env }, { "Port", PTQL_Port }, { "Pid", PTQL_Pid }, { "Service", PTQL_Service }, { NULL } }; static int ptql_branch_parse(char *query, ptql_parse_branch_t *branch, sigar_ptql_error_t *error) { char *ptr = strchr(query, '='); if (!ptr) { return ptql_error(error, "Missing '='"); } branch->op_flags = 0; *ptr = '\0'; branch->value = ++ptr; if ((ptr = strchr(query, '.'))) { *ptr = '\0'; branch->name = query; query = ++ptr; } else { return ptql_error(error, "Missing '.'"); } if ((ptr = strchr(query, '.'))) { *ptr = '\0'; branch->attr = query; query = ++ptr; } else { return ptql_error(error, "Missing '.'"); } if (*query) { char flag; while (sigar_isupper((flag = *query))) { switch (flag) { case 'P': branch->op_flags |= PTQL_OP_FLAG_PARENT; break; case 'I': branch->op_flags |= PTQL_OP_FLAG_ICASE; break; default: return ptql_error(error, "Unsupported modifier: %c", flag); } ++query; } branch->op = query; } else { return ptql_error(error, "Missing query"); } /* Pid.Service -> Service.Name */ if (strEQ(branch->attr, "Service")) { branch->name = branch->attr; branch->attr = "Name"; } return SIGAR_OK; } static int ptql_branch_add(ptql_parse_branch_t *parsed, ptql_branch_list_t *branches, sigar_ptql_error_t *error) { ptql_branch_t *branch; ptql_entry_t *entry = NULL; ptql_lookup_t *lookup = NULL; int i, is_set=0; char *ptr; PTQL_BRANCH_LIST_GROW(branches); branch = &branches->data[branches->number++]; SIGAR_ZERO(branch); branch->data_free = data_free; branch->value_free = data_free; branch->op_flags = parsed->op_flags; branch->op_name = ptql_op_code_get(parsed->op); if (branch->op_name == PTQL_OP_MAX) { return ptql_error(error, "Unsupported operator: %s", parsed->op); } for (i=0; ptql_map[i].name; i++) { if (strEQ(ptql_map[i].name, parsed->name)) { entry = &ptql_map[i]; break; } } if (!entry) { return ptql_error(error, "Unsupported method: %s", parsed->name); } for (i=0; entry->members[i].name; i++) { if (strEQ(entry->members[i].name, parsed->attr)) { lookup = &entry->members[i]; break; } } if (!lookup) { if (entry->members[0].type == PTQL_VALUE_TYPE_ANY) { /* Args, Env, etc. */ lookup = &entry->members[0]; } else { return ptql_error(error, "Unsupported %s attribute: %s", parsed->name, parsed->attr); } } if (lookup->init) { int status = lookup->init(parsed, branch, error); if (status != SIGAR_OK) { return status; } } branch->lookup = lookup; if ((lookup->type < PTQL_VALUE_TYPE_STR) && (branch->op_name > PTQL_OP_MAX_NSTR)) { return ptql_error(error, "Unsupported operator '%s' for %s.%s", parsed->op, parsed->name, parsed->attr); } if (*parsed->value == '$') { is_set = 1; if (branch->op_name == PTQL_OP_RE) { /* not for use with .re */ return ptql_error(error, "Unsupported operator '%s' with variable %s", parsed->op, parsed->value); } if (sigar_isdigit(*(parsed->value+1))) { branch->op_flags |= PTQL_OP_FLAG_REF; parsed->op_flags = branch->op_flags; /* for use by caller */ branch->value.ui32 = atoi(parsed->value+1) - 1; if (branch->value.ui32 >= branches->number) { /* out-of-range */ return ptql_error(error, "Variable %s out of range (%d)", parsed->value, branches->number); } else if (branch->value.ui32 == branches->number-1) { /* self reference */ return ptql_error(error, "Variable %s self reference", parsed->value); } } else { if ((ptr = getenv(parsed->value+1))) { branch->value.str = sigar_strdup(ptr); } else { branch->value.str = NULL; } } } else if (branch->op_name == PTQL_OP_RE) { #ifdef SIGAR_HAS_PCRE const char *error; int offset; pcre *re = pcre_compile(parsed->value, 0, &error, &offset, NULL); if (!re) { /* XXX pcre_error ? */ return ptql_error(error, "Invalid regex"); } is_set = 1; branch->value.ptr = re; branch->value_free = pcre_free; #endif } switch (lookup->type) { case PTQL_VALUE_TYPE_UI64: branch->match.ui64 = ptql_op_ui64[branch->op_name]; if (!is_set) { SIGAR_CLEAR_ERRNO(); branch->value.ui64 = strtoull(parsed->value, &ptr, 10); if (strtonum_failed(parsed->value, ptr)) { return PTQL_ERRNAN; } } break; case PTQL_VALUE_TYPE_UI32: branch->match.ui32 = ptql_op_ui32[branch->op_name]; if (!is_set) { SIGAR_CLEAR_ERRNO(); branch->value.ui32 = strtoul(parsed->value, &ptr, 10); if (strtonum_failed(parsed->value, ptr)) { return PTQL_ERRNAN; } } break; case PTQL_VALUE_TYPE_DBL: branch->match.dbl = ptql_op_dbl[branch->op_name]; if (!is_set) { SIGAR_CLEAR_ERRNO(); branch->value.dbl = strtod(parsed->value, &ptr); if (strtonum_failed(parsed->value, ptr)) { return PTQL_ERRNAN; } } break; case PTQL_VALUE_TYPE_CHR: branch->match.chr = ptql_op_chr[branch->op_name]; if (!is_set) { if (strlen(parsed->value) != 1) { return ptql_error(error, "%s is not a char", parsed->value); } branch->value.chr[0] = parsed->value[0]; } break; case PTQL_VALUE_TYPE_STR: case PTQL_VALUE_TYPE_ANY: branch->match.str = ptql_op_str[branch->op_name]; if (!is_set) { branch->value.str = sigar_strdup(parsed->value); } break; } return SIGAR_OK; } static int ptql_branch_compare(const void *b1, const void *b2) { /* XXX can do better */ ptql_branch_t *branch1 = (ptql_branch_t *)b1; ptql_branch_t *branch2 = (ptql_branch_t *)b2; return branch1->lookup->type - branch2->lookup->type; } SIGAR_DECLARE(int) sigar_ptql_query_create(sigar_ptql_query_t **queryp, char *ptql, sigar_ptql_error_t *error) { char *ptr, *ptql_copy = sigar_strdup(ptql); int status = SIGAR_OK; int has_ref = 0; sigar_ptql_query_t *query = *queryp = malloc(sizeof(*query)); (void)ptql_error(error, "Malformed query"); #ifdef PTQL_DEBUG query->ptql = sigar_strdup(ptql); #endif ptql = ptql_copy; ptql_branch_list_create(&query->branches); do { ptql_parse_branch_t parsed; if ((ptr = strchr(ptql, ','))) { *ptr = '\0'; } status = ptql_branch_parse(ptql, &parsed, error); if (status == SIGAR_OK) { status = ptql_branch_add(&parsed, &query->branches, error); if (status != SIGAR_OK) { break; } if (parsed.op_flags & PTQL_OP_FLAG_REF) { has_ref = 1; } } else { break; } if (ptr) { ptql = ++ptr; } else { break; } } while (*ptql); free(ptql_copy); if (status != SIGAR_OK) { sigar_ptql_query_destroy(query); *queryp = NULL; } else if (!has_ref && (query->branches.number > 1)) { qsort(query->branches.data, query->branches.number, sizeof(query->branches.data[0]), ptql_branch_compare); } if (status == SIGAR_OK) { (void)ptql_error(error, "OK"); } return status; } SIGAR_DECLARE(int) sigar_ptql_query_destroy(sigar_ptql_query_t *query) { #ifdef PTQL_DEBUG free(query->ptql); #endif ptql_branch_list_destroy(&query->branches); free(query); return SIGAR_OK; } SIGAR_DECLARE(void) sigar_ptql_re_impl_set(sigar_t *sigar, void *data, sigar_ptql_re_impl_t impl) { sigar->ptql_re_data = data; sigar->ptql_re_impl = impl; } SIGAR_DECLARE(int) sigar_ptql_query_match(sigar_t *sigar, sigar_ptql_query_t *query, sigar_pid_t query_pid) { int i; for (i=0; ibranches.number; i++) { sigar_pid_t pid = query_pid; int status, matched=0; ptql_branch_t *branch = &query->branches.data[i]; ptql_lookup_t *lookup = branch->lookup; if (branch->op_flags & PTQL_OP_FLAG_PARENT) { sigar_proc_state_t state; status = sigar_proc_state_get(sigar, pid, &state); if (status != SIGAR_OK) { return status; } pid = state.ppid; } if (lookup->type == PTQL_VALUE_TYPE_ANY) { /* Args, Env, etc. */ status = lookup->get(sigar, pid, branch); if (status == SIGAR_OK) { matched = 1; } } else { /* standard sigar_proc_*_get / structptr + offset */ if (!branch->data.ptr) { branch->data_size = lookup->data_size; branch->data.ptr = malloc(branch->data_size); } status = lookup->get(sigar, pid, branch->data.ptr); if (status != SIGAR_OK) { return status; } if (branch->op_flags & PTQL_OP_FLAG_REF) { ptql_branch_t *ref = &query->branches.data[branch->value.ui32]; matched = ptql_branch_match_ref(branch, ref); } #ifndef SIGAR_HAS_PCRE else if (branch->lookup->type == PTQL_VALUE_TYPE_STR) { matched = ptql_str_match(sigar, branch, (char *)DATA_PTR(branch)); } #endif else { matched = ptql_branch_match(branch); } } if (!matched) { return 1; } } return SIGAR_OK; } static int ptql_proc_list_get(sigar_t *sigar, sigar_ptql_query_t *query, sigar_proc_list_t **proclist) { int status; int i; *proclist = NULL; for (i=0; ibranches.number; i++) { ptql_branch_t *branch = &query->branches.data[i]; if (branch->op_flags & PTQL_OP_FLAG_PID) { /* pre-filter pid list for Pid.* queries */ /* XXX multiple Pid.* may result in dups */ if (*proclist == NULL) { *proclist = malloc(sizeof(**proclist)); SIGAR_ZERO(*proclist); sigar_proc_list_create(*proclist); } status = ptql_pid_list_get(sigar, branch, *proclist); if (status != SIGAR_OK) { sigar_proc_list_destroy(sigar, *proclist); free(*proclist); return status; } } } if (*proclist) { return SIGAR_OK; } status = sigar_proc_list_get(sigar, NULL); if (status != SIGAR_OK) { return status; } *proclist = sigar->pids; return SIGAR_OK; } static int ptql_proc_list_destroy(sigar_t *sigar, sigar_proc_list_t *proclist) { if (proclist != sigar->pids) { sigar_proc_list_destroy(sigar, proclist); free(proclist); } return SIGAR_OK; } SIGAR_DECLARE(int) sigar_ptql_query_find_process(sigar_t *sigar, sigar_ptql_query_t *query, sigar_pid_t *pid) { int status; int i, matches=0; sigar_proc_list_t *pids; status = ptql_proc_list_get(sigar, query, &pids); if (status != SIGAR_OK) { return status; } for (i=0; inumber; i++) { int query_status = sigar_ptql_query_match(sigar, query, pids->data[i]); if (query_status == SIGAR_OK) { *pid = pids->data[i]; matches++; } else if (query_status == SIGAR_ENOTIMPL) { /* let caller know query is invalid. */ status = query_status; break; } /* else ok, e.g. permission denied */ } ptql_proc_list_destroy(sigar, pids); if (status != SIGAR_OK) { return status; } if (matches == 1) { return SIGAR_OK; } else if (matches == 0) { sigar_strerror_set(sigar, "Query did not match any processes"); } else { sigar_strerror_printf(sigar, "Query matched multiple processes (%d)", matches); } return -1; } SIGAR_DECLARE(int) sigar_ptql_query_find(sigar_t *sigar, sigar_ptql_query_t *query, sigar_proc_list_t *proclist) { int status; int i; sigar_proc_list_t *pids; status = ptql_proc_list_get(sigar, query, &pids); if (status != SIGAR_OK) { return status; } sigar_proc_list_create(proclist); for (i=0; inumber; i++) { int query_status = sigar_ptql_query_match(sigar, query, pids->data[i]); if (query_status == SIGAR_OK) { SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = pids->data[i]; } else if (query_status == SIGAR_ENOTIMPL) { /* let caller know query is invalid. */ status = query_status; break; } } ptql_proc_list_destroy(sigar, pids); if (status != SIGAR_OK) { sigar_proc_list_destroy(sigar, proclist); return status; } return SIGAR_OK; } hyperic-sigar-1.6.4+dfsg/src/sigar_signal.c000066400000000000000000000110631210132627500206040ustar00rootroot00000000000000/* * Copyright (c) 2007 Hyperic, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #ifdef WIN32 #include #endif #include #include SIGAR_DECLARE(int) sigar_proc_kill(sigar_pid_t pid, int signum) { #ifdef WIN32 int status = -1; HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, TRUE, (DWORD)pid); if (proc) { switch (signum) { case 0: status = SIGAR_OK; break; default: if (TerminateProcess(proc, signum)) { status = SIGAR_OK; } break; } CloseHandle(proc); if (status == SIGAR_OK) { return SIGAR_OK; } } return GetLastError(); #else if (kill(pid, signum) == -1) { return errno; } return SIGAR_OK; #endif } SIGAR_DECLARE(int) sigar_signum_get(char *name) { if (strnEQ(name, "SIG", 3)) { name += 3; } switch (*name) { case 'A': #ifdef SIGABRT if (strEQ(name, "ABRT")) return SIGABRT; #endif #ifdef SIGALRM if (strEQ(name, "ALRM")) return SIGALRM; #endif break; case 'B': #ifdef SIGBUS if (strEQ(name, "BUS")) return SIGBUS; #endif break; case 'C': #ifdef SIGCONT if (strEQ(name, "CONT")) return SIGCONT; #endif #ifdef SIGCHLD if (strEQ(name, "CHLD")) return SIGCHLD; #endif #ifdef SIGCLD if (strEQ(name, "CLD")) return SIGCLD; #endif break; case 'E': #ifdef SIGEMT if (strEQ(name, "EMT")) return SIGEMT; #endif break; case 'F': #ifdef SIGFPE if (strEQ(name, "FPE")) return SIGFPE; #endif break; case 'H': #ifdef SIGHUP if (strEQ(name, "HUP")) return SIGHUP; #endif break; case 'I': #ifdef SIGINT if (strEQ(name, "INT")) return SIGINT; #endif #ifdef SIGILL if (strEQ(name, "ILL")) return SIGILL; #endif #ifdef SIGIOT if (strEQ(name, "IOT")) return SIGIOT; #endif #ifdef SIGIO if (strEQ(name, "IO")) return SIGIO; #endif #ifdef SIGINFO if (strEQ(name, "INFO")) return SIGINFO; #endif break; case 'K': #ifdef SIGKILL if (strEQ(name, "KILL")) return SIGKILL; #endif break; case 'P': #ifdef SIGPOLL if (strEQ(name, "POLL")) return SIGPOLL; #endif #ifdef SIGPIPE if (strEQ(name, "PIPE")) return SIGPIPE; #endif #ifdef SIGPROF if (strEQ(name, "PROF")) return SIGPROF; #endif #ifdef SIGPWR if (strEQ(name, "PWR")) return SIGPWR; #endif break; case 'Q': #ifdef SIGQUIT if (strEQ(name, "QUIT")) return SIGQUIT; #endif break; case 'S': #ifdef SIGSEGV if (strEQ(name, "SEGV")) return SIGSEGV; #endif #ifdef SIGSYS if (strEQ(name, "SYS")) return SIGSYS; #endif #ifdef SIGSTOP if (strEQ(name, "STOP")) return SIGSTOP; #endif #ifdef SIGSTKFLT if (strEQ(name, "STKFLT")) return SIGSTKFLT; #endif break; case 'T': #ifdef SIGTRAP if (strEQ(name, "TRAP")) return SIGTRAP; #endif #ifdef SIGTERM if (strEQ(name, "TERM")) return SIGTERM; #endif #ifdef SIGTSTP if (strEQ(name, "TSTP")) return SIGTSTP; #endif #ifdef SIGTTIN if (strEQ(name, "TTIN")) return SIGTTIN; #endif #ifdef SIGTTOU if (strEQ(name, "TTOU")) return SIGTTOU; #endif break; case 'U': #ifdef SIGURG if (strEQ(name, "URG")) return SIGURG; #endif #ifdef SIGUSR1 if (strEQ(name, "USR1")) return SIGUSR1; #endif #ifdef SIGUSR2 if (strEQ(name, "USR2")) return SIGUSR2; #endif break; case 'V': #ifdef SIGVTALRM if (strEQ(name, "VTALRM")) return SIGVTALRM; #endif break; case 'W': #ifdef SIGWINCH if (strEQ(name, "WINCH")) return SIGWINCH; #endif break; case 'X': #ifdef SIGXCPU if (strEQ(name, "XCPU")) return SIGXCPU; #endif #ifdef SIGXFSZ if (strEQ(name, "XFSZ")) return SIGXFSZ; #endif break; default: break; } return -1; } hyperic-sigar-1.6.4+dfsg/src/sigar_util.c000066400000000000000000000611211210132627500203040ustar00rootroot00000000000000/* * Copyright (c) 2004-2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 #include #include #include #include #include "sigar.h" #include "sigar_private.h" #include "sigar_util.h" #include "sigar_os.h" #ifndef WIN32 #include #include SIGAR_INLINE char *sigar_uitoa(char *buf, unsigned int n, int *len) { char *start = buf + UITOA_BUFFER_SIZE - 1; *start = 0; do { *--start = '0' + (n % 10); ++*len; n /= 10; } while (n); return start; } SIGAR_INLINE char *sigar_skip_line(char *buffer, int buflen) { char *ptr = buflen ? (char *)memchr(buffer, '\n', buflen) : /* bleh */ strchr(buffer, '\n'); return ++ptr; } SIGAR_INLINE char *sigar_skip_token(char *p) { while (sigar_isspace(*p)) p++; while (*p && !sigar_isspace(*p)) p++; return p; } SIGAR_INLINE char *sigar_skip_multiple_token(char *p, int count) { int i; for (i = 0; i < count; i++) { p = sigar_skip_token(p); } return p; } char *sigar_getword(char **line, char stop) { char *pos = *line; int len; char *res; while ((*pos != stop) && *pos) { ++pos; } len = pos - *line; res = malloc(len + 1); memcpy(res, *line, len); res[len] = 0; if (stop) { while (*pos == stop) { ++pos; } } *line = pos; return res; } /* avoiding sprintf */ char *sigar_proc_filename(char *buffer, int buflen, sigar_pid_t bigpid, const char *fname, int fname_len) { int len = 0; char *ptr = buffer; unsigned int pid = (unsigned int)bigpid; /* XXX -- This isn't correct */ char pid_buf[UITOA_BUFFER_SIZE]; char *pid_str = sigar_uitoa(pid_buf, pid, &len); assert((unsigned int)buflen >= (SSTRLEN(PROCP_FS_ROOT) + UITOA_BUFFER_SIZE + fname_len + 1)); memcpy(ptr, PROCP_FS_ROOT, SSTRLEN(PROCP_FS_ROOT)); ptr += SSTRLEN(PROCP_FS_ROOT); memcpy(ptr, pid_str, len); ptr += len; memcpy(ptr, fname, fname_len); ptr += fname_len; *ptr = '\0'; return buffer; } int sigar_proc_file2str(char *buffer, int buflen, sigar_pid_t pid, const char *fname, int fname_len) { int retval; buffer = sigar_proc_filename(buffer, buflen, pid, fname, fname_len); retval = sigar_file2str(buffer, buffer, buflen); if (retval != SIGAR_OK) { switch (retval) { case ENOENT: retval = ESRCH; /* no such process */ default: break; } } return retval; } int sigar_proc_list_procfs_get(sigar_t *sigar, sigar_proc_list_t *proclist) { DIR *dirp = opendir("/proc"); struct dirent *ent; #ifdef HAVE_READDIR_R struct dirent dbuf; #endif if (!dirp) { return errno; } #ifdef HAVE_READDIR_R while (readdir_r(dirp, &dbuf, &ent) == 0) { if (ent == NULL) { break; } #else while ((ent = readdir(dirp))) { #endif if (!sigar_isdigit(*ent->d_name)) { continue; } /* XXX: more sanity checking */ SIGAR_PROC_LIST_GROW(proclist); proclist->data[proclist->number++] = strtoul(ent->d_name, NULL, 10); } closedir(dirp); return SIGAR_OK; } int sigar_proc_fd_count(sigar_t *sigar, sigar_pid_t pid, sigar_uint64_t *total) { DIR *dirp; struct dirent *ent; #ifdef HAVE_READDIR_R struct dirent dbuf; #endif char name[BUFSIZ]; (void)SIGAR_PROC_FILENAME(name, pid, "/fd"); *total = 0; if (!(dirp = opendir(name))) { return errno; } #ifdef HAVE_READDIR_R while (readdir_r(dirp, &dbuf, &ent) == 0) { if (ent == NULL) { break; } #else while ((ent = readdir(dirp))) { #endif if (!sigar_isdigit(*ent->d_name)) { continue; } (*total)++; } closedir(dirp); return SIGAR_OK; } int sigar_procfs_args_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { char buffer[9086], *buf=NULL, *ptr; int fd, len, total=0; (void)SIGAR_PROC_FILENAME(buffer, pid, "/cmdline"); if ((fd = open(buffer, O_RDONLY)) < 0) { if (errno == ENOENT) { return ESRCH; } return errno; } buffer[0] = '\0'; /* XXX: possible to get rid of some mallocs here. * but, unlikely this will be called often so it * might not even matter much. */ while ((len = read(fd, buffer, sizeof(buffer)-1)) > 0) { if (len == 0) { break; } buf = realloc(buf, total+len+1); memcpy(buf+total, buffer, len); total += len; } close(fd); /* e.g. /proc/2/cmdline */ if (total == 0) { procargs->number = 0; return SIGAR_OK; } buf[total] = '\0'; ptr = buf; while (total > 0) { int alen = strlen(ptr)+1; char *arg = malloc(alen); SIGAR_PROC_ARGS_GROW(procargs); memcpy(arg, ptr, alen); procargs->data[procargs->number++] = arg; total -= alen; if (total > 0) { ptr += alen; } } free(buf); return SIGAR_OK; } #endif /* WIN32 */ /* from httpd/server/util.c */ char *sigar_strcasestr(const char *s1, const char *s2) { char *p1, *p2; if (*s2 == '\0') { /* an empty s2 */ return((char *)s1); } while(1) { for ( ; (*s1 != '\0') && (sigar_tolower(*s1) != sigar_tolower(*s2)); s1++); if (*s1 == '\0') { return(NULL); } /* found first character of s2, see if the rest matches */ p1 = (char *)s1; p2 = (char *)s2; for (++p1, ++p2; sigar_tolower(*p1) == sigar_tolower(*p2); ++p1, ++p2) { if (*p1 == '\0') { /* both strings ended together */ return((char *)s1); } } if (*p2 == '\0') { /* second string ended, a match */ break; } /* didn't find a match here, try starting at next character in s1 */ s1++; } return((char *)s1); } int sigar_mem_calc_ram(sigar_t *sigar, sigar_mem_t *mem) { sigar_int64_t total = mem->total / 1024, diff; sigar_uint64_t lram = (mem->total / (1024 * 1024)); int ram = (int)lram; /* must cast after division */ int remainder = ram % 8; if (remainder > 0) { ram += (8 - remainder); } mem->ram = ram; diff = total - (mem->actual_free / 1024); mem->used_percent = (double)(diff * 100) / total; diff = total - (mem->actual_used / 1024); mem->free_percent = (double)(diff * 100) / total; return ram; } #ifndef WIN32 sigar_iodev_t *sigar_iodev_get(sigar_t *sigar, const char *dirname) { sigar_cache_entry_t *entry; struct stat sb; sigar_uint64_t id; sigar_file_system_list_t fslist; int i, status, is_dev=0; int debug = SIGAR_LOG_IS_DEBUG(sigar); char dev_name[SIGAR_FS_NAME_LEN]; if (!sigar->fsdev) { sigar->fsdev = sigar_cache_new(15); } if (*dirname != '/') { snprintf(dev_name, sizeof(dev_name), SIGAR_DEV_PREFIX "%s", dirname); dirname = dev_name; is_dev = 1; } else if (SIGAR_NAME_IS_DEV(dirname)) { is_dev = 1; } if (stat(dirname, &sb) < 0) { if (debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[iodev] stat(%s) failed", dirname); } return NULL; } id = SIGAR_FSDEV_ID(sb); entry = sigar_cache_get(sigar->fsdev, id); if (entry->value != NULL) { return (sigar_iodev_t *)entry->value; } if (is_dev) { sigar_iodev_t *iodev; entry->value = iodev = malloc(sizeof(*iodev)); SIGAR_ZERO(iodev); SIGAR_SSTRCPY(iodev->name, dirname); if (debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[iodev] %s is_dev=true", dirname); } return iodev; } status = sigar_file_system_list_get(sigar, &fslist); if (status != SIGAR_OK) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[iodev] file_system_list failed: %s", sigar_strerror(sigar, status)); return NULL; } for (i=0; itype == SIGAR_FSTYPE_LOCAL_DISK) { int retval = stat(fsp->dir_name, &sb); sigar_cache_entry_t *ent; if (retval < 0) { if (debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[iodev] inode stat(%s) failed", fsp->dir_name); } continue; /* cant cache w/o inode */ } ent = sigar_cache_get(sigar->fsdev, SIGAR_FSDEV_ID(sb)); if (ent->value) { continue; /* already cached */ } if (SIGAR_NAME_IS_DEV(fsp->dev_name)) { sigar_iodev_t *iodev; ent->value = iodev = malloc(sizeof(*iodev)); SIGAR_ZERO(iodev); iodev->is_partition = 1; SIGAR_SSTRCPY(iodev->name, fsp->dev_name); if (debug) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[iodev] map %s -> %s", fsp->dir_name, iodev->name); } } } } sigar_file_system_list_destroy(sigar, &fslist); if (entry->value && (((sigar_iodev_t *)entry->value)->name[0] != '\0')) { return (sigar_iodev_t *)entry->value; } else { return NULL; } } #endif double sigar_file_system_usage_calc_used(sigar_t *sigar, sigar_file_system_usage_t *fsusage) { /* * win32 will not convert __uint64 to double. * convert to KB then do unsigned long -> double. */ sigar_uint64_t b_used = (fsusage->total - fsusage->free) / 1024; sigar_uint64_t b_avail = fsusage->avail / 1024; unsigned long utotal = b_used + b_avail; unsigned long used = b_used; if (utotal != 0) { unsigned long u100 = used * 100; double pct = u100 / utotal + ((u100 % utotal != 0) ? 1 : 0); return pct / 100; } return 0; } typedef struct { sigar_uint32_t eax; sigar_uint32_t ebx; sigar_uint32_t ecx; sigar_uint32_t edx; } sigar_cpuid_t; #if defined(__GNUC__) && !defined(__sun) # if defined(__i386__) # define SIGAR_HAS_CPUID static void sigar_cpuid(sigar_uint32_t request, sigar_cpuid_t *id) { /* derived from: */ /* http://svn.red-bean.com/repos/minor/trunk/gc/barriers-ia-32.c */ asm volatile ("mov %%ebx, %%esi\n\t" "cpuid\n\t" "xchgl %%ebx, %%esi" : "=a" (id->eax), "=S" (id->ebx), "=c" (id->ecx), "=d" (id->edx) : "0" (request) : "memory"); } # elif defined(__amd64__) # define SIGAR_HAS_CPUID static void sigar_cpuid(sigar_uint32_t request, sigar_cpuid_t *id) { /* http://svn.red-bean.com/repos/minor/trunk/gc/barriers-amd64.c */ asm volatile ("cpuid\n\t" : "=a" (id->eax), "=b" (id->ebx), "=c" (id->ecx), "=d" (id->edx) : "0" (request) : "memory"); } # endif #elif defined(WIN32) # ifdef _M_X64 # include # define SIGAR_HAS_CPUID static void sigar_cpuid(sigar_uint32_t request, sigar_cpuid_t *id) { sigar_uint32_t info[4]; __cpuid(info, request); /* as of MSVC 7 */ memcpy(id, &info[0], sizeof(info)); } # else # define SIGAR_HAS_CPUID static void sigar_cpuid(sigar_uint32_t request, sigar_cpuid_t *id) { __asm { mov edi, id mov eax, [edi].eax mov ecx, [edi].ecx cpuid mov [edi].eax, eax mov [edi].ebx, ebx mov [edi].ecx, ecx mov [edi].edx, edx } } # endif #endif #define INTEL_ID 0x756e6547 #define AMD_ID 0x68747541 int sigar_cpu_core_count(sigar_t *sigar) { #if defined(SIGAR_HAS_CPUID) sigar_cpuid_t id; if (sigar->lcpu == -1) { sigar->lcpu = 1; sigar_cpuid(0, &id); if ((id.ebx == INTEL_ID) || (id.ebx == AMD_ID)) { sigar_cpuid(1, &id); if (id.edx & (1<<28)) { sigar->lcpu = (id.ebx & 0x00FF0000) >> 16; } } sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu] %d cores per socket", sigar->lcpu); } return sigar->lcpu; #elif defined(__sun) || defined(__hpux) || defined(_AIX) return 1; #else sigar->lcpu = 1; return sigar->lcpu; #endif } int sigar_cpu_core_rollup(sigar_t *sigar) { #ifdef SIGAR_HAS_CPUID int log_rollup = SIGAR_LOG_IS_DEBUG(sigar) && (sigar->lcpu == -1); (void)sigar_cpu_core_count(sigar); if (sigar->cpu_list_cores) { if (log_rollup && (sigar->lcpu > 1)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu] treating cores as-is"); } } else { if (log_rollup && (sigar->lcpu > 1)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "[cpu] rolling up cores to sockets"); return 1; } } #endif return 0; } #define IS_CPU_R(p) \ ((*p == '(') && (*(p+1) == 'R') && (*(p+2) == ')')) typedef struct { char *name; /* search */ int len; char *rname; /* replace */ int rlen; } cpu_model_str_t; /* to later replace 's' with 'r' */ #define CPU_MODEL_ENT_R(s, r) \ { s, sizeof(s)-1, r, sizeof(r) } #define CPU_MODEL_ENT(s) \ CPU_MODEL_ENT_R(s, s) /* after the vendor part of the string is removed, * looking for startsWith the entries below * to remove the crap after the model name, see * ../exp/intel_amd_cpu_models.txt */ static const cpu_model_str_t cpu_models[] = { /* intel */ CPU_MODEL_ENT("Xeon"), CPU_MODEL_ENT_R("XEON", "Xeon"), CPU_MODEL_ENT("Pentium III"), CPU_MODEL_ENT("Pentium II"), CPU_MODEL_ENT_R("Pentium(R) III", "Pentium III"), CPU_MODEL_ENT_R("Pentium(R) 4", "Pentium 4"), CPU_MODEL_ENT_R("Pentium(R) M", "Pentium M"), CPU_MODEL_ENT("Pentium Pro"), CPU_MODEL_ENT("Celeron"), /* amd */ CPU_MODEL_ENT("Opteron"), CPU_MODEL_ENT("Athlon"), CPU_MODEL_ENT("Duron"), CPU_MODEL_ENT_R("K6(tm)-III", "K6 III"), CPU_MODEL_ENT_R("K6(tm) 3D+", "K6 3D+"), { NULL } }; /* common to win32 and linux */ void sigar_cpu_model_adjust(sigar_t *sigar, sigar_cpu_info_t *info) { int len, i; char model[128], *ptr=model, *end; memcpy(model, info->model, sizeof(model)); /* trim leading and trailing spaces */ len = strlen(model); end = &model[len-1]; while (*ptr == ' ') ++ptr; while (*end == ' ') *end-- = '\0'; /* remove vendor from model name */ len = strlen(info->vendor); if (strnEQ(ptr, info->vendor, len)) { ptr += len; if (IS_CPU_R(ptr)) { ptr += 3; /* remove (R) */ } while (*ptr == ' ') ++ptr; } if (*ptr == '-') { ++ptr; /* e.g. was AMD-K6... */ } for (i=0; cpu_models[i].name; i++) { const cpu_model_str_t *cpu_model = &cpu_models[i]; if (strnEQ(ptr, cpu_model->name, cpu_model->len)) { memcpy(info->model, cpu_model->rname, cpu_model->rlen); return; } } strcpy(info->model, ptr); } /* attempt to derive MHz from model name * currently works for certain intel strings * see exp/intel_amd_cpu_models.txt */ int sigar_cpu_mhz_from_model(char *model) { int mhz = SIGAR_FIELD_NOTIMPL; char *ptr = model; while (*ptr && (ptr = strchr(ptr, ' '))) { while(*ptr && !sigar_isdigit(*ptr)) { ptr++; } mhz = sigar_strtoul(ptr); if (*ptr == '.') { /* e.g. "2.40GHz" */ ++ptr; mhz *= 100; mhz += sigar_strtoul(ptr); break; } else if (strnEQ(ptr, "GHz", 3) || strnEQ(ptr, "MHz", 3)) { /* e.g. "1500MHz" */ break; } else { mhz = SIGAR_FIELD_NOTIMPL; } } if (mhz != SIGAR_FIELD_NOTIMPL) { if (strnEQ(ptr, "GHz", 3)) { mhz *= 10; } } return mhz; } #if !defined(WIN32) && !defined(NETWARE) #include #include #include #include #ifdef SIGAR_HPUX #include #endif #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__sun) || defined(DARWIN) #include #endif #if defined(__sun) || defined(SIGAR_HPUX) #include #endif #if defined(_AIX) || defined(SIGAR_HPUX) || defined(__OpenBSD__) || defined(__NetBSD__) #include #endif static enum clnt_stat get_sockaddr(struct sockaddr_in *addr, char *host) { register struct hostent *hp; sigar_hostent_t data; memset(addr, 0, sizeof(struct sockaddr_in)); addr->sin_family = AF_INET; if ((addr->sin_addr.s_addr = inet_addr(host)) == -1) { if (!(hp = sigar_gethostbyname(host, &data))) { return RPC_UNKNOWNHOST; } memcpy(&addr->sin_addr, hp->h_addr, hp->h_length); } return RPC_SUCCESS; } char *sigar_rpc_strerror(int err) { return (char *)clnt_sperrno(err); } SIGAR_DECLARE(int) sigar_rpc_ping(char *host, int protocol, unsigned long program, unsigned long version) { CLIENT *client; struct sockaddr_in addr; int sock; struct timeval timeout; unsigned short port = 0; enum clnt_stat rpc_stat; rpc_stat = get_sockaddr(&addr, host); if (rpc_stat != RPC_SUCCESS) { return rpc_stat; } timeout.tv_sec = 2; timeout.tv_usec = 0; addr.sin_port = htons(port); sock = RPC_ANYSOCK; if (protocol == SIGAR_NETCONN_UDP) { client = clntudp_create(&addr, program, version, timeout, &sock); } else if (protocol == SIGAR_NETCONN_TCP) { client = clnttcp_create(&addr, program, version, &sock, 0, 0); } else { return RPC_UNKNOWNPROTO; } if (!client) { return rpc_createerr.cf_stat; } timeout.tv_sec = 10; timeout.tv_usec = 0; rpc_stat = clnt_call(client, NULLPROC, (xdrproc_t)xdr_void, NULL, (xdrproc_t)xdr_void, NULL, timeout); clnt_destroy(client); return rpc_stat; } #endif int sigar_file2str(const char *fname, char *buffer, int buflen) { int len, status; int fd = open(fname, O_RDONLY); if (fd < 0) { return ENOENT; } if ((len = read(fd, buffer, buflen)) < 0) { status = errno; } else { status = SIGAR_OK; buffer[len] = '\0'; } close(fd); return status; } #ifdef WIN32 #define vsnprintf _vsnprintf #endif #ifdef WIN32 # define rindex strrchr #endif static int proc_module_get_self(void *data, char *name, int len) { sigar_t *sigar = (sigar_t *)data; char *ptr = rindex(name, '/'); if (!ptr) { return SIGAR_OK; } if (strnEQ(ptr+1, "libsigar-", 9)) { int offset = ptr - name; sigar->self_path = sigar_strdup(name); *(sigar->self_path + offset) = '\0'; /* chop libsigar-*.so */ if (SIGAR_LOG_IS_DEBUG(sigar)) { sigar_log_printf(sigar, SIGAR_LOG_DEBUG, "detected sigar-lib='%s'", sigar->self_path); } return !SIGAR_OK; /* break loop */ } return SIGAR_OK; } char *sigar_get_self_path(sigar_t *sigar) { if (!sigar->self_path) { sigar_proc_modules_t procmods; char *self_path = getenv("SIGAR_PATH"); if (self_path) { sigar->self_path = sigar_strdup(self_path); return sigar->self_path; } procmods.module_getter = proc_module_get_self; procmods.data = sigar; sigar_proc_modules_get(sigar, sigar_pid_get(sigar), &procmods); if (!sigar->self_path) { /* dont try again */ sigar->self_path = sigar_strdup("."); } } return sigar->self_path; } #ifdef SIGAR_HAS_DLINFO_MODULES static int sigar_dlinfo_get(sigar_t *sigar, const char *func, void **handle, Link_map **map) { Dl_info dli; if (!dladdr((void *)((uintptr_t)sigar_dlinfo_get), &dli)) { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "[%s] dladdr(%s) = %s", func, SIGAR_FUNC, dlerror()); return ESRCH; } if (!(*handle = dlopen(dli.dli_fname, RTLD_LAZY))) { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "[%s] dlopen(%s) = %s", func, dli.dli_fname, dlerror()); return ESRCH; } dlinfo(*handle, RTLD_DI_LINKMAP, map); if (!map) { sigar_log_printf(sigar, SIGAR_LOG_ERROR, "[%s] dlinfo = %s", func, dlerror()); return ESRCH; } return SIGAR_OK; } int sigar_dlinfo_modules(sigar_t *sigar, sigar_proc_modules_t *procmods) { int status; void *handle; Link_map *map; status = sigar_dlinfo_get(sigar, SIGAR_FUNC, &handle, &map); if (status != SIGAR_OK) { return status; } while (map->l_prev != NULL) { map = map->l_prev; } do { int status = procmods->module_getter(procmods->data, (char *)map->l_name, strlen(map->l_name)); if (status != SIGAR_OK) { /* not an error; just stop iterating */ break; } } while ((map = map->l_next)); dlclose(handle); return SIGAR_OK; } #endif SIGAR_DECLARE(void) sigar_log_printf(sigar_t *sigar, int level, const char *format, ...) { va_list args; char buffer[8192]; if (level > sigar->log_level) { return; } if (!sigar->log_impl) { return; } va_start(args, format); vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); sigar->log_impl(sigar, sigar->log_data, level, buffer); } SIGAR_DECLARE(void) sigar_log(sigar_t *sigar, int level, char *message) { if (level > sigar->log_level) { return; } if (!sigar->log_impl) { return; } sigar->log_impl(sigar, sigar->log_data, level, message); } SIGAR_DECLARE(void) sigar_log_impl_set(sigar_t *sigar, void *data, sigar_log_impl_t impl) { sigar->log_data = data; sigar->log_impl = impl; } SIGAR_DECLARE(int) sigar_log_level_get(sigar_t *sigar) { return sigar->log_level; } static const char *log_levels[] = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE" }; SIGAR_DECLARE(const char *) sigar_log_level_string_get(sigar_t *sigar) { return log_levels[sigar->log_level]; } SIGAR_DECLARE(void) sigar_log_level_set(sigar_t *sigar, int level) { sigar->log_level = level; } SIGAR_DECLARE(void) sigar_log_impl_file(sigar_t *sigar, void *data, int level, char *message) { FILE *fp = (FILE*)data; fprintf(fp, "[%s] %s\n", log_levels[level], message); } #ifndef WIN32 sigar_int64_t sigar_time_now_millis(void) { struct timeval tv; gettimeofday(&tv, NULL); return ((tv.tv_sec * SIGAR_USEC) + tv.tv_usec) / SIGAR_MSEC; } #endif hyperic-sigar-1.6.4+dfsg/src/sigar_version.c.in000066400000000000000000000007501210132627500214220ustar00rootroot00000000000000#include "sigar.h" static sigar_version_t sigar_version = { "@@BUILD_DATE@@", "@@SCM_REVISION@@", "@@VERSION_STRING@@", "@@ARCHNAME@@", "@@ARCHLIB@@", "@@BINNAME@@", "SIGAR-@@VERSION_STRING@@, " "SCM revision @@SCM_REVISION@@, " "built @@BUILD_DATE@@ as @@ARCHLIB@@", @@VERSION_MAJOR@@, @@VERSION_MINOR@@, @@VERSION_MAINT@@, @@VERSION_BUILD@@ }; SIGAR_DECLARE(sigar_version_t *) sigar_version_get(void) { return &sigar_version; }