Initial commit

This commit is contained in:
Ziver Koc 2015-04-09 21:22:47 +00:00
commit aa4e110832
69 changed files with 17898 additions and 0 deletions

103
src/examples/CpuInfo.java Normal file
View file

@ -0,0 +1,103 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package test;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
/**
* 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<cpus.length; i++) {
println("CPU " + i + ".........");
output(cpus[i]);
}
println("Totals........");
output(this.sigar.getCpuPerc());
}
public static void main(String[] args) throws Exception {
new CpuInfo().processCommand(args);
}
}

164
src/examples/Df.java Normal file
View file

@ -0,0 +1,164 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package test;
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.NfsFileSystem;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
import org.hyperic.sigar.shell.FileCompleter;
import org.hyperic.sigar.util.GetlineCompleter;
/**
* Report filesytem disk space usage.
*/
public class Df extends SigarCommandBase {
private static final String OUTPUT_FORMAT =
"%-15s %4s %4s %5s %4s %-15s %s";
//like df -h -a
private static final String[] HEADER = new String[] {
"Filesystem",
"Size",
"Used",
"Avail",
"Use%",
"Mounted on",
"Type"
};
private GetlineCompleter completer;
public Df(Shell shell) {
super(shell);
setOutputFormat(OUTPUT_FORMAT);
this.completer = new FileCompleter(shell);
}
public Df() {
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 space usage";
}
public void printHeader() {
printf(HEADER);
}
public void output(String[] args) throws SigarException {
if (args.length == 1) {
FileSystemMap mounts = this.proxy.getFileSystemMap();
String name = FileCompleter.expand(args[0]);
FileSystem fs = mounts.getMountPoint(name);
if (fs != null) {
printHeader();
output(fs);
return;
}
throw new SigarException(args[0] +
" No such file or directory");
}
else {
FileSystem[] fslist = this.proxy.getFileSystemList();
printHeader();
for (int i=0; i<fslist.length; i++) {
output(fslist[i]);
}
}
}
public void output(FileSystem fs) throws SigarException {
long used, avail, total, pct;
try {
FileSystemUsage usage;
if (fs instanceof NfsFileSystem) {
NfsFileSystem nfs = (NfsFileSystem)fs;
if (!nfs.ping()) {
println(nfs.getUnreachableMessage());
return;
}
}
usage = this.sigar.getFileSystemUsage(fs.getDirName());
used = usage.getTotal() - usage.getFree();
avail = usage.getAvail();
total = usage.getTotal();
pct = (long)(usage.getUsePercent() * 100);
} catch (SigarException e) {
//e.g. on win32 D:\ fails with "Device not ready"
//if there is no cd in the drive.
used = avail = total = pct = 0;
}
String usePct;
if (pct == 0) {
usePct = "-";
}
else {
usePct = pct + "%";
}
ArrayList items = new ArrayList();
items.add(fs.getDevName());
items.add(formatSize(total));
items.add(formatSize(used));
items.add(formatSize(avail));
items.add(usePct);
items.add(fs.getDirName());
items.add(fs.getSysTypeName() + "/" + fs.getTypeName());
printf(items);
}
private static String formatSize(long size) {
return Sigar.formatSize(size * 1024);
}
public static void main(String[] args) throws Exception {
new Df().processCommand(args);
}
}

203
src/examples/Iostat.java Normal file
View file

@ -0,0 +1,203 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package test;
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.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
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<fslist.length; i++) {
if (fslist[i].getType() == FileSystem.TYPE_LOCAL_DISK) {
output(fslist[i]);
}
}
}
}
public void outputFileSystem(String arg) throws SigarException {
FileSystemMap mounts = this.proxy.getFileSystemMap();
String name = FileCompleter.expand(arg);
FileSystem fs = mounts.getMountPoint(name);
if (fs != null) {
printHeader();
output(fs);
return;
}
throw new SigarException(arg +
" No such file or directory");
}
public void outputDisk(String name) throws SigarException {
DiskUsage disk =
this.sigar.getDiskUsage(name);
ArrayList items = new ArrayList();
printHeader();
items.add(name);
items.add("-");
items.add(String.valueOf(disk.getReads()));
items.add(String.valueOf(disk.getWrites()));
if (disk.getReadBytes() == Sigar.FIELD_NOTIMPL) {
items.add("-");
items.add("-");
}
else {
items.add(Sigar.formatSize(disk.getReadBytes()));
items.add(Sigar.formatSize(disk.getWriteBytes()));
}
if (disk.getQueue() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(disk.getQueue()));
}
if (disk.getServiceTime() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(disk.getServiceTime()));
}
printf(items);
}
public void output(FileSystem fs) throws SigarException {
FileSystemUsage usage =
this.sigar.getFileSystemUsage(fs.getDirName());
ArrayList items = new ArrayList();
items.add(fs.getDevName());
items.add(fs.getDirName());
items.add(String.valueOf(usage.getDiskReads()));
items.add(String.valueOf(usage.getDiskWrites()));
if (usage.getDiskReadBytes() == Sigar.FIELD_NOTIMPL) {
items.add("-");
items.add("-");
}
else {
items.add(Sigar.formatSize(usage.getDiskReadBytes()));
items.add(Sigar.formatSize(usage.getDiskWriteBytes()));
}
if (usage.getDiskQueue() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(usage.getDiskQueue()));
}
if (usage.getDiskServiceTime() == Sigar.FIELD_NOTIMPL) {
items.add("-");
}
else {
items.add(svctm(usage.getDiskServiceTime()));
}
printf(items);
}
public static void main(String[] args) throws Exception {
new Iostat().processCommand(args);
}
}

261
src/examples/Netstat.java Normal file
View file

@ -0,0 +1,261 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package test;
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;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
/**
* 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<args.length; i++) {
String arg = args[i];
int j = 0;
while (j<arg.length()) {
switch (arg.charAt(j++)) {
case '-':
continue;
case 'l':
flags &= ~NetFlags.CONN_CLIENT;
flags |= NetFlags.CONN_SERVER;
break;
case 'a':
flags |= NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT;
break;
case 'n':
isNumeric = true;
break;
case 'p':
wantPid = true;
break;
case 's':
isStat = true;
break;
case 't':
proto_flags |= NetFlags.CONN_TCP;
break;
case 'u':
proto_flags |= NetFlags.CONN_UDP;
break;
case 'w':
proto_flags |= NetFlags.CONN_RAW;
break;
case 'x':
proto_flags |= NetFlags.CONN_UNIX;
break;
default:
System.err.println("unknown option");
}
}
}
if (proto_flags != 0) {
flags &= ~NetFlags.CONN_PROTOCOLS;
flags |= proto_flags;
}
return flags;
}
private String formatPort(int proto, long port) {
if (port == 0) {
return "*";
}
if (!isNumeric) {
String service = this.sigar.getNetServicesName(proto, port);
if (service != null) {
return service;
}
}
return String.valueOf(port);
}
private String formatAddress(int proto, String ip,
long portnum, int max) {
String port = formatPort(proto, portnum);
String address;
if (NetFlags.isAnyAddress(ip)) {
address = "*";
}
else if (isNumeric) {
address = ip;
}
else {
try {
address = InetAddress.getByName(ip).getHostName();
} catch (UnknownHostException e) {
address = ip;
}
}
max -= port.length() + 1;
if (address.length() > 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<connections.length; i++) {
NetConnection conn = connections[i];
String proto = conn.getTypeString();
String state;
if (conn.getType() == NetFlags.CONN_UDP) {
state = "";
}
else {
state = conn.getStateString();
}
ArrayList items = new ArrayList();
items.add(proto);
items.add(formatAddress(conn.getType(),
conn.getLocalAddress(),
conn.getLocalPort(),
LADDR_LEN));
items.add(formatAddress(conn.getType(),
conn.getRemoteAddress(),
conn.getRemotePort(),
RADDR_LEN));
items.add(state);
String process = null;
if (wantPid &&
//XXX only works w/ listen ports
(conn.getState() == NetFlags.TCP_LISTEN))
{
try {
long pid =
this.sigar.getProcPort(conn.getType(),
conn.getLocalPort());
if (pid != 0) { //XXX another bug
String name =
this.sigar.getProcState(pid).getName();
process = pid + "/" + name;
}
} catch (SigarException e) {
}
}
if (process == null) {
process = "";
}
items.add(process);
printf(items);
}
}
public static void main(String[] args) throws Exception {
new Netstat().processCommand(args);
}
}

View file

@ -0,0 +1,262 @@
package wa.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.NetRoute;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.Swap;
import org.hyperic.sigar.cmd.Shell;
/**
* Generates an XML with the status of the server, extended
* information can be obtained by adding a parameter extended
* in the GET request.
*
* @author Ziver
*/
public class ServerStatus extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
boolean extended = request.getParameter("extended") != null;
try {
Shell shell = new Shell();
Sigar sigar = shell.getSigar();
StringBuilder output = new StringBuilder();
output.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
output.append("<serverstatus>");
//****************** CPU **********************
CpuInfo cpu_info = sigar.getCpuInfoList()[0];
CpuPerc[] cpus = sigar.getCpuPercList();
output.append("<cpu>");
//output.append(cpu_info.getTotalCores());
for(int i=0; i<cpu_info.getTotalCores() ;i++){
output.append("<core id='");
output.append( i );
output.append("' load='");
output.append((int)(cpus[i].getCombined()*100));
output.append("' />");
}
output.append("</cpu>");
//***************** Memory *******************
Mem mem = sigar.getMem();
Swap swap = sigar.getSwap();
output.append("<memory total='");
output.append(mem.getRam());
output.append("' used='");
output.append( (int)format(mem.getUsed()) );
output.append("' />");
output.append("<swap total='");
output.append( (int)format(swap.getTotal()) );
output.append("' used='");
output.append( (int)format(swap.getUsed()) );
output.append("' />");
//**************** NETWORK ******************
output.append("<network>");
String[] net_intfs = sigar.getNetInterfaceList();
for( String intf : net_intfs ){
NetInterfaceStat net_stat = sigar.getNetInterfaceStat( intf );
NetInterfaceConfig net_conf = sigar.getNetInterfaceConfig( intf );
output.append("<interface name='");
output.append( intf );
output.append("' up='");
output.append( (net_conf.getFlags() & NetFlags.IFF_UP) > 0 );
output.append("' tx='");
output.append( format(net_stat.getTxBytes()) );
output.append("' rx='");
output.append( format(net_stat.getRxBytes()) );
output.append("' dropped='");
output.append( net_stat.getRxDropped()+net_stat.getTxDropped() );
output.append("' error='");
output.append( net_stat.getRxErrors()+net_stat.getTxErrors() );
if(extended){
output.append("' ip='");
output.append( net_conf.getAddress() );
output.append("' netmask='");
output.append( net_conf.getNetmask() );
output.append("' mac='");
output.append( net_conf.getHwaddr() );
output.append("' type='");
output.append( net_conf.getType() );
output.append("' flags='");
output.append( NetFlags.getIfFlagsString(net_conf.getFlags()) );
output.append("' description='");
output.append( net_conf.getDescription() );
}
output.append("' />");
}
output.append("</network>");
//***************** HDD ********************
FileSystem[] hdds = sigar.getFileSystemList();
output.append("<hdd>");
for(FileSystem hdd : hdds){
if( hdd.getType() != FileSystem.TYPE_LOCAL_DISK )
continue;
//System.out.println("HDD: "+hdd);
FileSystemUsage hdd_use = sigar.getFileSystemUsage(hdd.getDirName());
output.append("<disk name='");
output.append(new String(hdd.getDevName().getBytes(),"UTF-8"));
output.append("' total='");
output.append( format(hdd_use.getTotal()) );
output.append("' used='");
output.append( format(hdd_use.getTotal() - hdd_use.getFree()) );
output.append("' free='");
output.append( format(hdd_use.getFree()) );
//if(extended){
output.append("' type='");
output.append(hdd.getSysTypeName());
output.append("' mount='");
output.append(hdd.getDirName());
//}
output.append("' />");
}
output.append("</hdd>");
//******************************************************************
//*************************** EXTENDED ************************
if(extended){
//****************** ROUTING TABLE *************************
NetRoute[] routes = sigar.getNetRouteList();
output.append("<routing_table>");
for( NetRoute route : routes ) {
output.append("<route interface='");
output.append( route.getIfname() );
output.append("' destination='");
output.append( route.getDestination() );
output.append("' gateway='");
output.append( route.getGateway() );
output.append("' netmask='");
output.append( route.getMask() );
output.append("' flag='");
output.append( routing_flags(route.getFlags()) );
output.append("' metric='");
output.append( route.getMetric() );
output.append("' />");
}
output.append("</routing_table>");
//****************** APPLICATIONS *************************
long[] pids = Shell.getPids(sigar, new String[0]);
output.append("<applications>");
for( long pid : pids ) {
String app_user = "UNKNOWN";
long app_time = 0;
String app_load = "-";
try{
ProcCpu cpu = sigar.getProcCpu(pid);
app_load = CpuPerc.format(cpu.getPercent());
}catch(SigarException e){}
try{
app_user = sigar.getProcCredName(pid).getUser();
}catch(SigarException e){}
try{
app_time = sigar.getProcTime(pid).getTotal() / 1000;
}catch(SigarException e){}
output.append("<app pid='");
output.append( pid );
output.append("' user='");
output.append( app_user );
output.append("' size='");
output.append( format(sigar.getProcMem(pid).getSize()) );
output.append("' cputime='");
output.append( app_time/60 + ":" + app_time%60 );
output.append("' cpu='");
output.append( app_load );
output.append("' command='");
output.append( ProcUtil.getDescription(sigar, pid) );
output.append("' />");
}
output.append("</applications>");
//****************** UPTIME *************************
output.append("<uptime>");
output.append( formatUptime(sigar.getUptime().getUptime()) );
output.append("</uptime>");
//****************** HARDWARE INFO *************************
}
output.append("</serverstatus>");
out.println(output.toString());
} catch (SigarException e) {
e.printStackTrace();
}
}
private static String routing_flags(long flags) {
StringBuffer sb = new StringBuffer();
if ((flags & NetFlags.RTF_UP) != 0) {
sb.append('U');
}
if ((flags & NetFlags.RTF_GATEWAY) != 0) {
sb.append('G');
}
return sb.toString();
}
/**
* Formats a time to "Xdays Xh Xmin"
*/
private static String formatUptime(double uptime) {
StringBuilder ret = new StringBuilder();
int days = (int)uptime / (60*60*24);
int minutes, hours;
if (days != 0) {
ret.append(days);
if( days > 1 )
ret.append( " days " );
else
ret.append( " day " );
}
minutes = (int)uptime / 60;
hours = minutes / 60;
hours %= 24;
minutes %= 60;
if (hours != 0) {
ret.append( hours );
ret.append( "h " );
}
ret.append( minutes );
ret.append( "min " );
return ret.toString();
}
/**
* Takes in a size of B and returns MB
*/
private static double format(long size){
double tmp = ((double)size/(1024*1024));
tmp = (int)(tmp*10)/10.0;
return tmp;
}
}

147
src/examples/Version.java Normal file
View file

@ -0,0 +1,147 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package test;
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.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;
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);
}
}

View file

@ -0,0 +1,165 @@
<H2>Server Status</H2>
<center>
<table>
<tr><td></td><td></td></tr>
<tr>
<td>
<fieldset><legend>CPU</legend>
<div id="cpu_chart" style="width: 400px; height: 200px;"></div>
</fieldset>
</td>
<td>
<fieldset><legend>Memory</legend>
<div id="mem_chart" style="width: 400px; height: 200px;"></div>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset><legend>Network</legend>
<div id="net_chart" style="width: 400px; height: 200px;"></div>
</fieldset>
</td>
<td>
<fieldset><legend>HDD</legend>
<div id="hdd_chart" style="width: 400px; height: 200px;"></div>
</fieldset>
</td>
</tr>
</table>
</center>
<script language="javascript" type="text/javascript">
var MAX_POINTS = 20;
var index = 0;
var cpu_data = [];
var mem_data = [];
var mem_max = 0;
var swap_data = [];
$(function () {
update();
});
function update(){
$.ajax({
type: "GET",
url: "ServerStatus",
dataType: "xml",
success: function(data) {
update_cpu(data);
update_mem(data);
update_net(data);
update_hdd(data);
index++;
}
});
setTimeout('update()', 2000);
}
//***************** CPU ***********************
function update_cpu(data){
$(data).find("cpu").each(function() {
$(this).find("core").each(function() {
var cpu_nr = parseInt($(this).attr("id"));
if(cpu_data.length < (cpu_nr+1))
cpu_data.push( [] );
cpu_data[cpu_nr].push( [index, $(this).attr("load")] );
if(index>MAX_POINTS)
cpu_data[cpu_nr].shift();
});
});
var datasets = [];
for(i=0; i<cpu_data.length ;i++){
datasets[i] = {
label: "Cpu"+i,
data: cpu_data[i],
lines: { show: true },
points: { show: true }
};
}
var options = {
legend: { position: "ne" },
xaxis: { ticks: [] },
yaxis: { ticks: [0,20,40,60,80,100] }
};
$.plot($("#cpu_chart"), datasets, options);
}
//***************** Memory ********************
function update_mem(data){
$(data).find("memory").each(function() {
mem_data.push( [index, $(this).attr("used")] );
mem_max = $(this).attr("total");
});
$(data).find("swap").each(function() {
swap_data.push( [index, $(this).attr("used")] );
});
if(index>MAX_POINTS){
mem_data.shift();
swap_data.shift();
}
var datasets = [{
//label: "Mem",
data: mem_data,
color: "rgb(200, 20, 30)",
threshold: { below: mem_max*0.9, color: "rgb(30, 180, 20)" },
lines: { show: true, fill: true }
//points: { show: true }
},{
label: "Swap",
data: swap_data,
lines: { show: true, fill: true }
//points: { show: true }
}];
var options = {
legend: { position: "ne" },
xaxis: { ticks: [] },
yaxis: { ticks: 6, max: mem_max, min: 0 }
};
$.plot($("#mem_chart"), datasets, options);
}
//***************** NETWORK *******************
function update_net(data){
}
//***************** HDD ***********************
function update_hdd(data){
var i = 0;
hdd_data = [[],[]];
hdd_names = [];
$(data).find("hdd").each(function() {
$(this).find("disk").each(function() {
hdd_names.push( $(this).attr("name")+"( "+$(this).attr("free")+" GB free)" );
var used = parseFloat($(this).attr("used"));
var total = parseFloat($(this).attr("total"));
hdd_data[0].push( [i, (used/total)*100] );
hdd_data[1].push( [i, 100-((used/total)*100)] );
i += 2;
});
});
var datasets = [{
data: hdd_data[0],
bars: { show: true },
color: "rgb(200, 20, 30)",
stack: true
},{
data: hdd_data[1],
bars: { show: true },
color: "rgb(30, 180, 20)",
stack: true
}];
var options = {
xaxis: { ticks: [] },
yaxis: { ticks: [0,20,40,60,80,100] }
};
var plot = $.plot($("#hdd_chart"), datasets, options);
for(i=0; i<hdd_names.length ;i++){
o = plot.pointOffset({ x: i*2, y: 100});
$("#hdd_chart").append('<div style="position: absolute; left: '+(o.left + 4)+'px; top: '+o.top+'px; color: #666; font-size: 10px; font-weight: bold;">'+hdd_names[i]+'</div>');
}
}
</script>