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>

View file

@ -0,0 +1,36 @@
package wa.server;
import java.io.File;
import zutil.osal.OSAbstractionLayer;
import zutil.osal.OSAbstractionLayer.OSType;
public class WAConstants {
public static final String DB_TABLE_PREFIX = "wa";
public static String WA_BASE_CONFIG_PATH;
public static final String WA_BASE_CONFIG_PATH_LINUX = "/etc/webadmin";
public static final String WA_BASE_CONFIG_PATH_WINDOWS = ".";
public static final String WA_SSL_CERT = "cert/server.crt";
public static final String WA_SSL_KEY = "cert/server.key";
public static final String WA_CONFIG_BOUNDARY = "---- WebAdmin Configuration ----";
static{
OSAbstractionLayer os = OSAbstractionLayer.getInstance();
if(os.getOSType() == OSType.Linux){
WA_BASE_CONFIG_PATH = WA_BASE_CONFIG_PATH_LINUX;
}
else if(os.getOSType() == OSType.Windows){
WA_BASE_CONFIG_PATH = WA_BASE_CONFIG_PATH_WINDOWS;
}
}
public static File getConfigFile(String name){
return new File(WA_BASE_CONFIG_PATH, name);
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server;
import wa.server.page.struct.WAAlert;
import wa.server.page.struct.WANavigation;
import java.util.ArrayList;
/**
* Created by Ziver on 2015-04-06.
*/
public class WAContext {
private WANavigation[] nav;
private ArrayList<WAAlert> alerts;
public WAContext(){
nav = new WANavigation[]{
new WANavigation("Status"),
new WANavigation("Services", new WANavigation[]{
new WANavigation("Apache"),
new WANavigation("Tomcat"),
new WANavigation("Samba")
}),
new WANavigation("Configure")
};
alerts = new ArrayList<WAAlert>();
}
public WANavigation[] getNavigation(){
return nav;
}
public ArrayList<WAAlert> getAlerts() {
return alerts;
}
}

View file

@ -0,0 +1,40 @@
package wa.server;
import wa.server.page.AbstractPage;
import wa.server.page.StatusPage;
import zutil.io.file.FileUtil;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import zutil.net.http.HttpServer;
import zutil.net.http.pages.HttpFilePage;
import zutil.plugin.PluginManager;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WebAdminServer {
private static Logger log = LogUtil.getLogger();
private PluginManager pluginManager;
public static void main(String[] args){
LogUtil.setGlobalLevel(Level.FINEST);
LogUtil.setGlobalFormatter(new CompactLogFormatter());
new WebAdminServer();
}
public WebAdminServer(){
try {
pluginManager = new PluginManager();
HttpServer http = new HttpServer(80);
http.setPage("/", new StatusPage(pluginManager));
http.setDefaultPage(new HttpFilePage(FileUtil.find("WebContent/")));
http.start();
}catch(Exception e){
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,110 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.page;
import wa.server.WAContext;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;
import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.parser.DataNode;
import zutil.parser.Templator;
import zutil.parser.json.JSONWriter;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Ziver on 2015-04-02.
*/
public abstract class AbstractPage implements HttpPage{
private static final Logger log = LogUtil.getLogger();
private static final String TMPL_FILE = "WebContent/index.tmpl";
private Templator tmpl;
public AbstractPage() {
try {
tmpl = new Templator(FileUtil.find(TMPL_FILE));
} catch(IOException e){
log.log(Level.SEVERE, null, e);
tmpl = new Templator(e.getMessage());
}
}
@Override
public final synchronized void respond(HttpPrintStream out,
HttpHeaderParser client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) {
WAContext context = (WAContext)session.get("context");
if(context == null){
context = new WAContext();
}
if(("application/json").equals(client_info.getHeader("ContentType"))){
DataNode node = jsonResponse(context, client_info, session, cookie, request);
if(node != null) {
out.setHeader("Content-Type", "application/json");
JSONWriter writer = new JSONWriter(out);
writer.write(node);
writer.close();
}
}
else {
tmpl.clear();
tmpl.set("title", "WebAdmin");
tmpl.set("top-nav", context.getNavigation());
tmpl.set("side-nav-show", true);
tmpl.set("side-nav", context.getNavigation()[1].getSubNav());
tmpl.set("alerts", context.getAlerts());
//tmpl.set("footer", null);
Templator content = htmlResponse(context, client_info, session, cookie, request);
if(content != null)
tmpl.set("content", content.compile());
out.print(tmpl.compile());
}
}
public abstract Templator htmlResponse(WAContext context,
HttpHeaderParser client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request);
public DataNode jsonResponse(WAContext context,
HttpHeaderParser client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request){
return null;
}
}

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.page;
import wa.server.WAContext;
import wa.server.plugin.WAStatus;
import zutil.net.http.HttpHeaderParser;
import zutil.parser.DataNode;
import zutil.parser.Templator;
import zutil.plugin.PluginManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Ziver on 2015-04-06.
*/
public class StatusPage extends AbstractPage{
private ArrayList<WAStatus> plugins;
public StatusPage(PluginManager pluginManager){
this.plugins = pluginManager.toArray(WAStatus.class);
}
@Override
public Templator htmlResponse(WAContext context,
HttpHeaderParser client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) {
if(request.containsKey("i")) {
WAStatus obj = getPlugin(Integer.parseInt(request.get("i")));
if(obj != null)
return new Templator(obj.html());
}
return null;
}
public DataNode jsonResponse(WAContext context,
HttpHeaderParser client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request){
if(request.containsKey("i")) {
WAStatus obj = getPlugin(Integer.parseInt(request.get("i")));
DataNode root = new DataNode(DataNode.DataType.Map);
obj.jsonUpdate(root);
return root;
}
return null;
}
private WAStatus getPlugin(int i){
if(0 >= i && i < plugins.size())
return plugins.get(i);
return null;
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.page.struct;
import java.sql.Struct;
/**
* Created by Ziver on 2015-04-03.
*/
public class WAAlert {
public enum AlertType{
DANGER, WARNING, INFO, SUCCESS;
public String toString(){
return super.toString().toLowerCase();
}
}
private String message;
private AlertType type;
public WAAlert(String message, AlertType type) {
this.message = message;
this.type = type;
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.page.struct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Ziver on 2015-04-02.
*/
public class WANavigation {
private String name;
private List<WANavigation> sub_nav;
public WANavigation(String name) {
this.name = name;
}
public WANavigation(String name, WANavigation[] sub_nav) {
this.name = name;
this.sub_nav = Arrays.asList(sub_nav);
}
public Object getSubNav() {
return sub_nav;
}
}

View file

@ -0,0 +1,11 @@
package wa.server.plugin;
import java.io.IOException;
import java.sql.SQLException;
import zutil.db.DBConnection;
public interface WAConfigurator {
public void read(DBConnection db) throws SQLException;
public void save(DBConnection db) throws IOException;
}

View file

@ -0,0 +1,5 @@
package wa.server.plugin;
public interface WAFrontend {
}

View file

@ -0,0 +1,31 @@
/*
* Copyright (c) 2014 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.plugin;
/**
* Created by Ziver on 2014-11-09.
*/
public interface WAInstaller {
public void install();
public void uninstall();
}

View file

@ -0,0 +1,14 @@
package wa.server.plugin;
public interface WAService {
public enum WAServiceStatus{
RUNNING,
NOT_RESPONDING,
UNAVAILABLE,
UNKNOWN
}
public void start();
public void stop();
public WAServiceStatus getStatus();
}

View file

@ -0,0 +1,37 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.plugin;
import zutil.parser.DataNode;
/**
* Created by Ziver on 2015-04-06.
*/
public interface WAStatus {
public String getName();
public String html();
public void jsonUpdate(DataNode root);
}

View file

@ -0,0 +1,40 @@
package wa.server.plugin.apache;
import wa.server.WAConstants;
import zutil.db.bean.DBBean;
import zutil.db.bean.DBBean.DBTable;;
@DBTable(WAConstants.DB_TABLE_PREFIX+"_apache_vhost")
public class ApacheConfigVirtualHost extends DBBean{
protected String domain;
protected String path;
protected boolean ssl;
protected boolean tomcat;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isSSL() {
return ssl;
}
public void setSSL(boolean ssl) {
this.ssl = ssl;
}
public boolean isTomcatApp() {
return tomcat;
}
public void setTomcatApp(boolean tomcat) {
this.tomcat = tomcat;
}
}

View file

@ -0,0 +1,104 @@
package wa.server.plugin.apache;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import wa.server.WAConstants;
import wa.server.plugin.WAConfigurator;
import wa.server.util.ConfigFileUtil;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
public class ApacheConfigurator implements WAConfigurator {
private static final String APACHE_CONF_FILE = "wa_apache_vhost.conf";
private static final String APACHE_MAIN_CONFIG_FILE = "/etc/apache2/apache2.conf";
private static final String STATIC_PRE_CONF = "wa/server/plugin/apache/apache_default.config";
// Configuration data
List<ApacheConfigVirtualHost> vhosts;
public ApacheConfigurator(){
vhosts = new LinkedList<ApacheConfigVirtualHost>();
}
@Override
public void read(DBConnection db) throws SQLException {
vhosts = ApacheConfigVirtualHost.load(db, ApacheConfigVirtualHost.class);
}
@Override
public void save(DBConnection db) throws IOException {
File file = WAConstants.getConfigFile(APACHE_CONF_FILE);
// Update Man configuration file
ConfigFileUtil.writeBetweenBoundary(
new File(APACHE_MAIN_CONFIG_FILE),
"#",
"Include "+file.getAbsolutePath());
// Write Vhost configuration
PrintStream out = new PrintStream(file);
out.println(FileUtil.getContent(new File(STATIC_PRE_CONF)));
out.println("######################################");
out.println("# vhost.php");
for(ApacheConfigVirtualHost vhost : vhosts){
if(vhost.isTomcatApp())
writeTomcatVhost(out, vhost);
else if(vhost.isSSL())
writeSSLVhost(out, vhost);
else
writeVhost(out, vhost);
}
out.close();
}
private void writeVhost(PrintStream out, ApacheConfigVirtualHost conf) throws IOException{
out.println("<VirtualHost *:80>");
out.println(" ServerName "+conf.getDomain()+":80");
out.println(" DocumentRoot "+conf.getPath());
out.println("</VirtualHost>");
out.println("");
}
private void writeSSLVhost(PrintStream out, ApacheConfigVirtualHost conf) throws IOException{
out.println("<VirtualHost *:80>");
out.println(" ServerName "+conf.getDomain()+":80");
out.println(" RewriteEngine On");
out.println(" RewriteCond %{SERVER_PORT} !^443$");
out.println(" RewriteRule ^(.*)$ https://server$1 [L,R]");
out.println("</VirtualHost>");
out.println("<VirtualHost *:443>");
out.println(" ServerName "+conf.getDomain()+":443");
out.println(" DocumentRoot "+conf.getPath());
out.println("");
out.println(" SSLEngine on");
out.println(" SSLCertificateFile "+WAConstants.getConfigFile(WAConstants.WA_SSL_CERT));
out.println(" SSLCertificateKeyFile "+WAConstants.getConfigFile(WAConstants.WA_SSL_KEY));
out.println("</VirtualHost>");
out.println("");
}
private void writeTomcatVhost(PrintStream out, ApacheConfigVirtualHost conf) throws IOException{
out.println("<VirtualHost *:80>");
out.println(" ServerName "+conf.getDomain()+":80");
out.println(" ");
out.println(" RewriteEngine On");
out.println(" RewriteRule ^/$ /"+conf.getPath()+" [R]");
out.println(" ProxyPreserveHost on");
out.println(" <Proxy *>");
out.println(" Order deny,allow");
out.println(" Allow from all");
out.println(" </Proxy>");
out.println(" ProxyPass / ajp://localhost:8009/");
out.println(" ProxyPassReverse / http://localhost:8080/");
out.println("</VirtualHost>");
out.println("");
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2014 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.plugin.apache;
import wa.server.plugin.WAInstaller;
import wa.server.util.AptGet;
import zutil.osal.OSAbstractionLayer;
/**
* Created by Ziver on 2014-11-09.
*/
public class ApacheInstaller implements WAInstaller {
@Override
public void install() {
AptGet.install("apache php5 php5-mcrypt php5-gd imagemagick");
}
@Override
public void uninstall() {
AptGet.purge("apache php5 php5-mcrypt php5-gd imagemagick");
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2014 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.plugin.apache;
import wa.server.plugin.WAService;
import wa.server.util.Ps;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;
import zutil.osal.OSAbstractionLayer;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Ziver on 2014-12-23.
*/
public class ApacheService implements WAService {
private static Logger log = LogUtil.getLogger();
private static OSAbstractionLayer os = OSAbstractionLayer.getInstance();
private static final String PID_FILE = "/var/run/apache2.pid";
@Override
public void start() {
os.runCommand("service apache2 start");
}
@Override
public void stop() {
os.runCommand("service apache2 stop");
}
@Override
public WAServiceStatus getStatus() {
try {
int pid = Integer.parseInt(
FileUtil.getContent(new File(PID_FILE)));
if(Ps.isRunning(pid))
return WAServiceStatus.RUNNING;
return WAServiceStatus.UNAVAILABLE;
}catch(IOException e){
log.log(Level.WARNING, null, e);
}
return WAServiceStatus.UNKNOWN;
}
}

View file

@ -0,0 +1,91 @@
###################################
# default.php
ScriptAlias /cgi-bin/ /home/www/cgi-bin/
#NameVirtualHost *:80
NameVirtualHost *:443
ServerName koc.se
ServerAdmin ziver@koc.se
#<VirtualHost *:80>
# Redirect / http://koc.se
#</VirtualHost>
# WebAdmin {
<VirtualHost *:80>
ServerName admin.koc.se:80
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://admin.koc.se$1 [L,R]
</VirtualHost>
<VirtualHost *:443>
ServerName admin.koc.se:443
DocumentRoot ".$config["apache_www_path"]."/admin
SSLEngine on
SSLCertificateFile ".$config["apache_conf_path"]."/cert/server.crt
SSLCertificateKeyFile ".$config["apache_conf_path"]."/cert/server.key
</VirtualHost>
<VirtualHost *:80>
ServerName server:80
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://server$1 [L,R]
</VirtualHost>
<VirtualHost *:443>
ServerName server:443
DocumentRoot ".$config["apache_www_path"]."/admin
SSLEngine on
SSLCertificateFile ".$config["apache_conf_path"]."/cert/server.crt
SSLCertificateKeyFile ".$config["apache_conf_path"]."/cert/server.key
</VirtualHost>
<VirtualHost *:80>
ServerName localhost:80
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://localhost$1 [L,R]
</VirtualHost>
<VirtualHost *:443>
ServerName localhost:443
DocumentRoot ".$config["apache_www_path"]."/admin
SSLEngine on
SSLCertificateFile ".$config["apache_conf_path"]."/cert/server.crt
SSLCertificateKeyFile ".$config["apache_conf_path"]."/cert/server.key
</VirtualHost>
<VirtualHost *:80>
ServerName 192.168.0.2:80
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://192.168.0.2$1 [L,R]
</VirtualHost>
<VirtualHost *:443>
ServerName 192.168.0.2:443
DocumentRoot ".$config["apache_www_path"]."/admin
SSLEngine on
SSLCertificateFile ".$config["apache_conf_path"]."/cert/server.crt
SSLCertificateKeyFile ".$config["apache_conf_path"]."/cert/server.key
</VirtualHost>
#}
# Mythweb
#<VirtualHost *:80>
# ServerName mythtv.koc.se
# DirectoryIndex mythweb
# DocumentRoot /var/www
#
# # Include /etc/apache2/sites-available/mythweb.conf
#</VirtualHost>
# TvHeadend
<VirtualHost *:80>
ServerName tv.koc.se:80
ProxyPreserveHost on
ProxyPass / http://localhost:9981/
ProxyPassReverse / http://localhost:9981/
</VirtualHost>

View file

@ -0,0 +1,9 @@
{
"version": "1.0",
"name": "Apache Web Server",
"interfaces": {
"wa.server.plugin.WAInstaller": "wa.server.plugin.apache.ApacheInstaller",
"wa.server.plugin.WAConfigurator": "wa.server.plugin.apache.ApacheConfigurator",
"wa.server.plugin.WAService": "wa.server.plugin.apache.ApacheService"
}
}

View file

@ -0,0 +1,71 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.plugin.hwstatus;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.Shell;
import wa.server.plugin.WAStatus;
import zutil.io.file.FileUtil;
import zutil.parser.DataNode;
import java.io.IOException;
/**
* Created by Ziver on 2015-04-07.
*/
public class CpuStatus implements WAStatus {
@Override
public String getName() {
return "Cpu Load";
}
@Override
public String html() {
try {
return FileUtil.getContent(FileUtil.findURL("wa/server/plugin/hwstatus/CpuStatus.tmpl"));
} catch (IOException e) {
return e.getMessage();
}
}
@Override
public void jsonUpdate(DataNode root) {
DataNode cpuNode = new DataNode(DataNode.DataType.List);
try{
Sigar sigar = new Shell().getSigar();
for(CpuInfo cpu_info : sigar.getCpuInfoList()){
for(CpuPerc cpu : sigar.getCpuPercList()){
cpuNode.add(cpu.getCombined());
}
}
} catch (SigarException e) {
e.printStackTrace();
}
root.set("cpu", cpuNode);
}
}

View file

@ -0,0 +1,39 @@
<div class="panel panel-default">
<div class="panel-heading">Cpu Status</div>
<div class="panel-body">
<div id="cpu_chart"></div>
</div>
</div>
<script language="javascript" type="text/javascript">
var cpu_data = [];
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);
}
</script>

View file

@ -0,0 +1,10 @@
{
"version": "1.0",
"name": "HW Status",
"interfaces": [
{"wa.server.plugin.WAStatus": "wa.server.plugin.hwstatus.CpuStatus"},
{"wa.server.plugin.WAStatus": "wa.server.plugin.hwstatus.MemStatus"},
{"wa.server.plugin.WAStatus": "wa.server.plugin.hwstatus.HDDStatus"},
{"wa.server.plugin.WAStatus": "wa.server.plugin.hwstatus.NetStatus"}
]
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2014 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.util;
import zutil.log.LogUtil;
import zutil.osal.OSAbstractionLayer;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Created by Ziver on 2014-11-09.
*/
public class AptGet {
public static final Logger log = LogUtil.getLogger();
private static long updateTimestamp;
public static void install(String pkg) {
update();
OSAbstractionLayer.runCommand("apt-get install " + pkg);
}
public static void update(){
// Only run every 5 min
if(updateTimestamp + 1000*60*5 >System.currentTimeMillis()){
OSAbstractionLayer.runCommand("apt-get update");
}
}
public static void purge(String pkg) {
OSAbstractionLayer.runCommand("apt-get --purge remove " + pkg);
}
}

View file

@ -0,0 +1,23 @@
package wa.server.util;
import java.io.File;
import java.io.IOException;
import wa.server.WAConstants;
import zutil.io.file.FileUtil;
public class ConfigFileUtil {
public static void writeBetweenBoundary(File file, String commentChar, String data) throws IOException{
String boundary = new StringBuilder().
append(commentChar).
append(WAConstants.WA_CONFIG_BOUNDARY).
append(commentChar).toString();
String dataWithComment = new StringBuilder().
append(commentChar).append(" This is auto generated configuration please\n").
append(commentChar).append(" do not edit this as it will be overwritten\n").
append(data).toString();
FileUtil.writeBetweenBoundary(file, boundary, dataWithComment);
}
}

View file

@ -0,0 +1,37 @@
/*
* Copyright (c) 2014 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package wa.server.util;
import zutil.osal.OSAbstractionLayer;
/**
* Created by Ziver on 2014-12-23.
*/
public class Ps {
private static OSAbstractionLayer os = OSAbstractionLayer.getInstance();
public static boolean isRunning(int pid){
String[] output = os.runCommand("ps -p "+pid);
return output.length > 1;
}
}