This commit is contained in:
zhengyingying 2014-03-20 17:42:31 +08:00
commit 657b7a5a5b
33 changed files with 2396 additions and 2 deletions

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>publish</id>
<formats>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<unpack>false</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<files>
<file>
<source>target/bench4q-monitor.jar</source>
<outputDirectory>/</outputDirectory>
</file>
</files>
</assembly>

View File

@ -0,0 +1,111 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.bench4q</groupId>
<artifactId>bench4q-monitor</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Bench4Q Monitor</name>
<description>Bench4Q Monitor</description>
<organization>
<name>TCSE, ISCAS</name>
</organization>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>8.1.11.v20130520</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>8.1.11.v20130520</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>org.bench4q.monitor.MonitorServer</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>make-zip</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<finalName>bench4q-monitor</finalName>
</build>
</project>

View File

@ -0,0 +1,78 @@
package org.bench4q.monitor;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.servlet.DispatcherServlet;
public class MonitorServer {
private Server server;
private int port;
private Server getServer() {
return server;
}
private void setServer(Server server) {
this.server = server;
}
private int getPort() {
return port;
}
private void setPort(int port) {
this.port = port;
}
public MonitorServer(int port) {
this.setPort(port);
}
public boolean start() {
try {
this.setServer(new Server());
Connector connector = new SocketConnector();
connector.setPort(this.getPort());
this.getServer().addConnector(connector);
ServletContextHandler servletContextHandler = new ServletContextHandler();
ServletHolder servletHolder = servletContextHandler.addServlet(
DispatcherServlet.class, "/");
servletHolder
.setInitParameter("contextConfigLocation",
"classpath*:org/bench4q/monitor/config/application-context.xml");
this.getServer().setHandler(servletContextHandler);
this.getServer().start();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean stop() {
try {
if (this.getServer() != null) {
this.getServer().stop();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.setServer(null);
}
}
public static void main(String[] args) throws InterruptedException {
MonitorServer monitorServer = new MonitorServer(5557);
monitorServer.start();
}
}

View File

@ -0,0 +1,34 @@
package org.bench4q.monitor.api;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.bench4q.monitor.model.ListMainModel;
import org.bench4q.monitor.service.ReadSystemInfoFromLocalDisk;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class HistoryDataController {
@RequestMapping("/history")
@ResponseBody ListMainModel getHistory(@RequestParam String starttime, @RequestParam String endtime) throws ParseException
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date startDate = dateFormat.parse(starttime);
Date endDate = dateFormat.parse(endtime);
ReadSystemInfoFromLocalDisk historyservice = new ReadSystemInfoFromLocalDisk();
ListMainModel retModel = new ListMainModel();
//retModel.setHistorylist(historyservice.ReadSystemInfoByDate(startDate, endDate));
retModel.setHistorylist(historyservice.ReadSystemInfoByDate(startDate, endDate));
return retModel;
}
}

View File

@ -0,0 +1,23 @@
package org.bench4q.monitor.api;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import org.bench4q.monitor.model.MonitorMain;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class MainController {
@RequestMapping("/all")
@ResponseBody
MonitorMain getMainModel() throws SigarException, InterruptedException, ExecutionException {
Date date = new Date();
MonitorMain retModel = new MonitorMain(date);
return retModel;
}
}

View File

@ -0,0 +1,19 @@
package org.bench4q.monitor.api;
import org.bench4q.monitor.model.MemoryModel;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class MemoryController {
@RequestMapping("/memory")
@ResponseBody
MemoryModel getMemoryModel() throws SigarException
{
MemoryModel retModel = new MemoryModel();
return retModel;
}
}

View File

@ -0,0 +1,18 @@
package org.bench4q.monitor.api;
import org.bench4q.monitor.model.NetworkInterfaceModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class NetworkController {
@RequestMapping("/network")
@ResponseBody NetworkInterfaceModel getNetworkInterfaceModel(){
NetworkInterfaceModel retModel = new NetworkInterfaceModel();
return retModel;
}
}

View File

@ -0,0 +1,38 @@
package org.bench4q.monitor.api;
import java.util.concurrent.ExecutionException;
import org.bench4q.monitor.model.FileSystemModel;
import org.bench4q.monitor.model.PhysicalDiskModel;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class PhysicalDiskController {
@RequestMapping("/physicalDisk")
@ResponseBody
PhysicalDiskModel getPhysicalDiskModel() throws SigarException,
InterruptedException, ExecutionException {
PhysicalDiskModel retModel = new PhysicalDiskModel();
return retModel;
}
@RequestMapping("/pshysicalDisk/{dir}")
@ResponseBody
public FileSystemModel getFileSystemModel(@PathVariable("dir") String dir)
throws SigarException, InterruptedException, ExecutionException {
PhysicalDiskModel physicalDiskModel = new PhysicalDiskModel();
if (physicalDiskModel.getFieFileSystemModels() != null) {
for (FileSystemModel fileSystemModel : physicalDiskModel
.getFieFileSystemModels()) {
if (fileSystemModel.getFileDir().equals(dir))
return fileSystemModel;
}
}
throw new IllegalArgumentException("dir:" + dir + " not exit!");
}
}

View File

@ -0,0 +1,47 @@
package org.bench4q.monitor.api;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import org.bench4q.monitor.model.ProcessModel;
import org.bench4q.monitor.model.ProcessModelChild;
import org.bench4q.monitor.model.ProcessSigarReleatedModel;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
class ProcessController {
@RequestMapping("/process")
@ResponseBody
public ProcessModel getProcessModel() throws SigarException, InterruptedException, ExecutionException {
ProcessModel processModel = new ProcessModel();
return processModel;
}
@RequestMapping("/process/pid/{pid}")
@ResponseBody
public ProcessModelChild getProcessModelChild(@PathVariable("pid") long pid)
throws SigarException {
ProcessSigarReleatedModel processSigarReleatedModel=new ProcessSigarReleatedModel(pid);
ProcessModelChild processModelChild=new ProcessModelChild(pid, processSigarReleatedModel);
return processModelChild;
}
@RequestMapping("/process/name/{processName}")
@ResponseBody
public ProcessModelChild getProcessModelChild(@PathVariable("processName") String name)
throws SigarException, InterruptedException, ExecutionException {
ProcessModel processModel=new ProcessModel();
ArrayList<ProcessModelChild> proList=(ArrayList<ProcessModelChild>) processModel.getProcessModelList();
if(proList!=null){
for(ProcessModelChild processModelChild:proList){
if(processModelChild.getInstanceString().equals(name))
return processModelChild;
}
}
throw new IllegalArgumentException("process:"+name+" not exit");
}
}

View File

@ -0,0 +1,37 @@
package org.bench4q.monitor.api;
import org.bench4q.monitor.model.ProcessorModel;
import org.bench4q.monitor.model.ProcessorModelChild;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class ProcessorController {
@RequestMapping("/processor")
@ResponseBody
ProcessorModel getResposeModel() throws SigarException {
ProcessorModel retModel = new ProcessorModel();
return retModel;
}
@RequestMapping("/processor/{instanceName}")
@ResponseBody
ProcessorModelChild getProcessorModelChild(
@PathVariable("instanceName") String instanceName) throws SigarException {
ProcessorModel processorModel = new ProcessorModel();
if (processorModel.getProcessorModelList() == null)
throw new IllegalArgumentException(instanceName
+ " not exsist,cpu instance is empty");
for (ProcessorModelChild processorModelChild : processorModel
.getProcessorModelList()) {
if (processorModelChild.getInstance().equals(instanceName))
return processorModelChild;
}
throw new IllegalArgumentException(instanceName + " not exsist");
}
}

View File

@ -0,0 +1,29 @@
package org.bench4q.monitor.api;
import java.util.Timer;
import org.bench4q.monitor.service.TimerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/monitor")
public class StartToRecord {
private Timer timer = new Timer();
@RequestMapping("/start")
@ResponseBody
public String start() {
timer.schedule(new TimerService(), 1000, 2000);
return new String("startted");
}
@RequestMapping("/stop")
@ResponseBody
public String stop() {
timer.cancel();
return new String("stopped");
}
}

View File

@ -0,0 +1,32 @@
package org.bench4q.monitor.exception;
public class MonitorException {
private String errorCode;
private String message;
private String cause;
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCause() {
return cause;
}
public void setCause(String cause) {
this.cause = cause;
}
}

View File

@ -0,0 +1,223 @@
package org.bench4q.monitor.model;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.monitor.service.DataFomat;
import org.bench4q.monitor.service.GetSigar;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement(name = "fileSystem")
public class FileSystemModel {
@Expose
private String fileDir;
@Expose
private Double diskReadKBytesRate;
@Expose
private Double diskWriteKBytesRate;
@Expose
private double curDiskQueLength;
@Expose
private double totalGB;
@Expose
private double usedGB;
@Expose
private double freeGB;
@Expose
private double usedPercent;
@Expose
private double diskTotalKBytesRate;
private FileSystemUsage fileSystemUsage;
public static void main(String args[]) throws SigarException,
InterruptedException, ExecutionException {
FileSystemUsage fileSystemUsage = GetSigar
.getSigar()
.getFileSystemUsage(
GetSigar.getSigar().getFileSystemList()[0].getDirName());
FileSystemModel fileSystemModel = new FileSystemModel(fileSystemUsage,
GetSigar.getSigar().getFileSystemList()[0].getDirName(), 500);
System.out.println(fileSystemModel.getFreeGB());
System.out.println(fileSystemModel.getTotalGB());
System.out.println(fileSystemModel.getDiskReadKBytesRate());
}
public FileSystemModel() {
}
public FileSystemModel(FileSystemUsage fileSystemUsage, String fileDir,
int interval) throws InterruptedException, ExecutionException {
this.fileDir = fileDir;
this.fileSystemUsage = fileSystemUsage;
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Double> caculateReadRateFuture = executorService
.submit(new CalculateDiskReadRate(interval, fileSystemUsage));
Future<Double> caculateWriteRateFuture = executorService
.submit(new CalculateDiskWriteRate(interval, fileSystemUsage));
this.setCurDiskQueLength();
this.setFreeGB();
this.setTotalGB();
this.setUsedGB();
this.setUsedPercent();
this.setDiskReadKBytesRate(caculateReadRateFuture.get());
this.setDiskWriteKBytesRate(caculateWriteRateFuture.get());
this.setDiskTotalKBytesRate();
this.setCurDiskQueLength();
executorService.shutdown();
}
@XmlElement
public String getFileDir() {
return fileDir;
}
@XmlElement
public Double getDiskReadKBytesRate() {
return diskReadKBytesRate;
}
private void setDiskReadKBytesRate(Double diskReadKBytesRate) {
this.diskReadKBytesRate = diskReadKBytesRate;
}
@XmlElement
public Double getDiskWriteKBytesRate() {
return diskWriteKBytesRate;
}
private void setDiskWriteKBytesRate(Double diskWriteKBytesRate) {
this.diskWriteKBytesRate = diskWriteKBytesRate;
}
@XmlElement
public double getCurDiskQueLength() {
return curDiskQueLength;
}
private void setCurDiskQueLength() {
this.curDiskQueLength = this.fileSystemUsage.getDiskQueue();
}
@XmlElement
public double getTotalGB() {
return totalGB;
}
private void setTotalGB() {
this.totalGB = changeBytesToGB(this.fileSystemUsage.getTotal());
}
@XmlElement
public double getUsedGB() {
return usedGB;
}
private void setUsedGB() {
this.usedGB = changeBytesToGB(this.fileSystemUsage.getUsed());
}
@XmlElement
public double getFreeGB() {
return freeGB;
}
private void setFreeGB() {
this.freeGB = changeBytesToGB(this.fileSystemUsage.getFree());
}
@XmlElement
public double getUsedPercent() {
return usedPercent;
}
private void setUsedPercent() {
this.usedPercent = DataFomat.fomatToPercent(fileSystemUsage
.getUsePercent());
}
@XmlElement
public double getDiskTotalKBytesRate() {
return diskTotalKBytesRate;
}
private void setDiskTotalKBytesRate() {
this.diskTotalKBytesRate = this.getDiskReadKBytesRate()
+ this.getDiskWriteKBytesRate();
}
private double changeBytesToGB(long bytes) {
return (double) Math.round(((double) bytes / 1024 / 1024) * 100) / 100;
}
}
abstract class CalculateDiskRate implements Callable<Double> {
private long interval;
private Double KBytesRate;
protected FileSystemUsage fileSystemUsage;
public CalculateDiskRate(long interval, FileSystemUsage fileSystemUsage) {
this.interval = interval;
this.fileSystemUsage = fileSystemUsage;
}
public Double call() throws InterruptedException, SigarException {
long preDiskKBytes = getFileKBytes();
long postDiskKBytes = 0;
long startTime = System.nanoTime();
long endTime = 0;
Thread.sleep(this.interval);
postDiskKBytes = getFileKBytes();
endTime = System.nanoTime();
this.KBytesRate = new Double(
Math.round((postDiskKBytes - preDiskKBytes)
/ DataFomat.caculateTimeInterval(startTime, endTime)
* 10000) / 10000);
return this.KBytesRate;
}
abstract long getFileKBytes() throws SigarException;
}
class CalculateDiskWriteRate extends CalculateDiskRate {
public CalculateDiskWriteRate(long interval, FileSystemUsage fileSystemUsage) {
super(interval, fileSystemUsage);
}
long getFileKBytes() throws SigarException {
return fileSystemUsage.getDiskWriteBytes() / 1024L;
}
}
class CalculateDiskReadRate extends CalculateDiskRate {
public CalculateDiskReadRate(long interval,
FileSystemUsage feFileSystemUsage) {
super(interval, feFileSystemUsage);
}
long getFileKBytes() throws SigarException {
return fileSystemUsage.getDiskReadBytes() / 1024L;
}
}

View File

@ -0,0 +1,22 @@
package org.bench4q.monitor.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="historylist")
public class ListMainModel {
private List<MonitorMain> historylist;
@XmlElementWrapper(name="histories")
@XmlElement(name="history",type=MonitorMain.class)
public List<MonitorMain> getHistorylist() {
return historylist;
}
public void setHistorylist(List<MonitorMain> historylist) {
this.historylist = historylist;
}
}

View File

@ -0,0 +1,172 @@
package org.bench4q.monitor.model;
import java.beans.Transient;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.monitor.service.GetSigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.Mem;
import com.google.gson.annotations.Expose;
@XmlRootElement(name = "Memory")
public class MemoryModel {
@Expose
private long pagesPerSecond;
@Expose
private long pagesInputPerSecond;
@Expose
private long pagesOutputPerSecond;
@Expose
private long availableKiloBytes;
@Expose
private long totalKiloBytes;
@Expose
private double memoryUsedPercent;
@Expose
private double swapKiloBytes;
@Expose
private double swapFreeKiloBytes;
private Sigar sigar = GetSigar.getSigar();
private Swap swap;
private Mem mem;
public static void main(String[] args) throws SigarException {
MemoryModel model = new MemoryModel();
System.out.println("PagesRate: " + model.getPagesPerSecond());
System.out.println("PagesIn: " + model.getPagesInputPerSecond());
System.out.println("PagesIn: " + model.getPagesOutputPerSecond());
System.out.println("UsedPerc: " + model.getMemoryUsedPercent() + "%");
System.out.println("Total: " + model.getTotalKiloBytes() + "kb");
System.out.println("Aval: " + model.getAvailableKiloBytes() + "kb");
System.out.println("swap total:" + model.getSwapKiloBytes() + "kb");
System.out.println("swap free :" + model.getSwapFreeKiloBytes() + "kb");
}
public MemoryModel() throws SigarException {
this.getPagesInputPerSecond();
this.getPagesOutputPerSecond();
this.getPagesPerSecond();
this.getMemoryUsedPercent();
this.getAvailableKiloBytes();
this.getTotalKiloBytes();
this.setSwapKiloBytes();
this.setSwapFreeKiloBytes();
}
@XmlElement
public long getPagesPerSecond() throws SigarException {
setPagesPerSecond(getPagesInputPerSecond() + getPagesOutputPerSecond());
return pagesPerSecond;
}
private void setPagesPerSecond(long pagesPerSecond) {
this.pagesPerSecond = pagesPerSecond;
}
@XmlElement
public long getPagesInputPerSecond() throws SigarException {
swap = sigar.getSwap();
setPagesInputPerSecond(swap.getPageIn());
return pagesInputPerSecond;
}
private void setPagesInputPerSecond(long pagesInputPerSecond) {
this.pagesInputPerSecond = pagesInputPerSecond;
}
@XmlElement
public long getPagesOutputPerSecond() throws SigarException {
swap = sigar.getSwap();
setPagesOutputPerSecond(swap.getPageOut());
return pagesOutputPerSecond;
}
private void setPagesOutputPerSecond(long pagesOutputPerSecond) {
this.pagesOutputPerSecond = pagesOutputPerSecond;
}
@XmlElement
public long getAvailableKiloBytes() throws SigarException {
mem = sigar.getMem();
setAvailableKiloBytes(mem.getActualFree() / 1024L);
return availableKiloBytes;
}
private void setAvailableKiloBytes(long availableKiloBytes) {
this.availableKiloBytes = availableKiloBytes;
}
@XmlElement
public long getTotalKiloBytes() throws SigarException {
mem = sigar.getMem();
setTotalKiloBytes(mem.getTotal() / 1024L);
return totalKiloBytes;
}
private void setTotalKiloBytes(long totalKiloBytes) {
this.totalKiloBytes = totalKiloBytes;
}
@XmlElement
public double getMemoryUsedPercent() throws SigarException {
mem = sigar.getMem();
long temp = Math.round(mem.getUsedPercent() * 100);
setMemoryUsedPercent(temp / 100.0);
return this.memoryUsedPercent;
}
private void setMemoryUsedPercent(double memoryUsedPercent) {
this.memoryUsedPercent = memoryUsedPercent;
}
@XmlElement
public double getSwapKiloBytes() {
return swapKiloBytes;
}
private void setSwapKiloBytes() {
this.swapKiloBytes = this.swap.getTotal() / 1024L;
}
@XmlElement
public double getSwapFreeKiloBytes() {
return swapFreeKiloBytes;
}
private void setSwapFreeKiloBytes() {
this.swapFreeKiloBytes = this.swap.getFree() / 1024L;
}
@Transient
public Sigar getSigar() {
return sigar;
}
public void setSigar(Sigar sigar) {
this.sigar = sigar;
}
@Transient
public Swap getSwap() {
return swap;
}
public void setSwap(Swap swap) {
this.swap = swap;
}
@Transient
public Mem getMem() {
return mem;
}
public void setMem(Mem mem) {
this.mem = mem;
}
}

View File

@ -0,0 +1,82 @@
package org.bench4q.monitor.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import java.text.SimpleDateFormat;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement(name = "history")
@XmlType
public class MonitorMain {
@Expose
@XmlElement
private String date;
@Expose
@XmlElement(name = "processor_info")
private ProcessorModel processorModel;
@Expose
@XmlElement(name = "memory_info")
private MemoryModel memoryModel;
@Expose
@XmlElement(name = "disk_info")
private PhysicalDiskModel physicalDiskModel;
@Expose
@XmlElement(name = "network_info")
private NetworkInterfaceModel networkInterfaceModel;
@Expose
@XmlElement(name = "process_info")
private ProcessModel processModel;
private SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
public MonitorMain(Date date) throws SigarException, InterruptedException,
ExecutionException {
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
this.date = dateFormat.format(date);
long startTime = System.currentTimeMillis();
List<Thread> threadList = new ArrayList<Thread>();
threadList.add(new Thread(new ProcessModel(this)));
threadList.add(new Thread(new PhysicalDiskModel(this)));
threadList.add(new Thread(new ProcessorModel(this)));
threadList.add(new Thread(new NetworkInterfaceModel(this)));
for (Thread thread : threadList)
thread.start();
memoryModel = new MemoryModel();
boolean threadIsAlive = true;
while (threadIsAlive) {
threadIsAlive = false;
for (Thread thread : threadList) {
if (thread.isAlive())
threadIsAlive = true;
}
}
System.out.println(System.currentTimeMillis() - startTime);
}
public void setProcesssModel(ProcessModel processModel) {
this.processModel = processModel;
}
public void setPhysicalDiskModel(PhysicalDiskModel physicalDiskModel) {
this.physicalDiskModel = physicalDiskModel;
}
public void setProcessorModel(ProcessorModel processorModel) {
this.processorModel = processorModel;
}
public void setNetworkInterfaceModel(
NetworkInterfaceModel networkInterfaceModel) {
this.networkInterfaceModel = networkInterfaceModel;
}
}

View File

@ -0,0 +1,191 @@
package org.bench4q.monitor.model;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.log4j.Logger;
import org.bench4q.monitor.service.DataFomat;
import org.bench4q.monitor.service.GetSigar;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement(name = "NetworkInterface")
public class NetworkInterfaceModel implements Runnable {
@Expose
private Double kiloBytesTotalPerSecond;
@Expose
private Double kiloBytesReceivedPerSecond;
@Expose
private Double kiloBytesSentPerSecond;
private long interval = 500;
/* private Logger logger = Logger.getLogger(NetworkInterfaceModel.class); */
public static void main(String[] args) {
while (true) {
long Time = System.currentTimeMillis();
NetworkInterfaceModel test = new NetworkInterfaceModel();
System.out.println("KiloBytesReceivedPerSecond:"
+ test.getKiloBytesReceivedPerSecond() + "kb/s");
System.out.println("KiloBytesSentPerSecond:"
+ test.getKiloBytesSentPerSecond() + "kb/s");
System.out.println("KiloBytesTotalPerSecond:"
+ test.getKiloBytesTotalPerSecond() + "kb/s");
System.out.println(System.currentTimeMillis() - Time);
}
}
private MonitorMain monitorMain;
public NetworkInterfaceModel(MonitorMain monitorMain) {
this.monitorMain = monitorMain;
}
public void run() {
monitorMain.setNetworkInterfaceModel(new NetworkInterfaceModel());
}
@SuppressWarnings("unchecked")
public NetworkInterfaceModel() {
// this can be used for all
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Double> futureBytesReceivedPerSecond = executorService
.submit(new CalculateBytesReceivedPerSecond(interval));
Future<Double> futureBytesSentPerSecond = executorService
.submit(new CalculateBytesSentPerSecond(interval));
try {
this.setKiloBytesReceivedPerSecond(futureBytesReceivedPerSecond
.get());
this.setKiloBytesSentPerSecond(futureBytesSentPerSecond.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
@XmlElement
public Double getKiloBytesReceivedPerSecond() {
return this.kiloBytesReceivedPerSecond;
}
public void setKiloBytesReceivedPerSecond(Double kiloBytesReceivedPerSecond) {
this.kiloBytesReceivedPerSecond = kiloBytesReceivedPerSecond;
}
@XmlElement
public Double getKiloBytesSentPerSecond() {
return this.kiloBytesSentPerSecond;
}
public void setKiloBytesSentPerSecond(Double kiloBytesSentPerSecond) {
this.kiloBytesSentPerSecond = kiloBytesSentPerSecond;
}
@XmlElement
public Double getKiloBytesTotalPerSecond() {
setKiloBytesTotalPerSecond(this.kiloBytesReceivedPerSecond
+ this.kiloBytesSentPerSecond);
return kiloBytesTotalPerSecond;
}
public void setKiloBytesTotalPerSecond(Double kiloBytesTotalPerSecond) {
this.kiloBytesTotalPerSecond = kiloBytesTotalPerSecond;
}
}
@SuppressWarnings("rawtypes")
abstract class CalculateBytesPerSecond implements Callable {
private long interval;
private Logger logger = Logger
.getLogger(CalculateBytesReceivedPerSecond.class);
private Double kiloBytesPerSecond;
public CalculateBytesPerSecond(long interval) {
this.interval = interval;
}
public double getKiloBytesPerSecond() {
return kiloBytesPerSecond;
}
public Double call() {
try {
long startTime = System.nanoTime();
long endTime;
long preBytesSentSoFar = this.getBytesSoFar();
long postBytesSentSoFar = 0;
Thread.sleep(interval);
endTime = System.nanoTime();
postBytesSentSoFar = this.getBytesSoFar();
this.kiloBytesPerSecond = (double) ((postBytesSentSoFar - preBytesSentSoFar)
/ DataFomat.caculateTimeInterval(startTime, endTime) / 1024L);
return new Double(Math.round(this.kiloBytesPerSecond * 100) / 100);
} catch (SigarException e) {
logger.error(e, e.fillInStackTrace());
return new Double(0);
} catch (InterruptedException e) {
// TODO: handle exception
logger.error(e, e.fillInStackTrace());
return new Double(0);
}
}
abstract long getBytesSoFar() throws SigarException;
}
class CalculateBytesSentPerSecond extends CalculateBytesPerSecond {
public CalculateBytesSentPerSecond(long interval) {
super(interval);
}
public double getKiloBytesSentPerSecond() {
return this.getKiloBytesPerSecond();
}
long getBytesSoFar() throws SigarException {
long bytesPostSoFar = 0;
String[] netInterfaceList = GetSigar.getSigar().getNetInterfaceList();
for (int i = 0; i < netInterfaceList.length; ++i)
bytesPostSoFar += GetSigar.getSigar()
.getNetInterfaceStat(netInterfaceList[i]).getTxBytes();
return bytesPostSoFar;
}
}
class CalculateBytesReceivedPerSecond extends CalculateBytesPerSecond {
public CalculateBytesReceivedPerSecond(long interval) {
super(interval);
}
public double getKiloBytesReceivedPerSecond() {
return this.getKiloBytesPerSecond();
}
long getBytesSoFar() throws SigarException {
long bytesReceivedSoFar = 0;
String[] netInterfaceList = GetSigar.getSigar().getNetInterfaceList();
for (int i = 0; i < netInterfaceList.length; ++i)
bytesReceivedSoFar += GetSigar.getSigar()
.getNetInterfaceStat(netInterfaceList[i]).getRxBytes();
return bytesReceivedSoFar;
}
}

View File

@ -0,0 +1,271 @@
package org.bench4q.monitor.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.bench4q.monitor.service.GetSigar;
import org.bench4q.monitor.service.GetThreadPool;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement
public class PhysicalDiskModel implements Runnable{
@Expose
private Double diskReadKBytesRate;
@Expose
private Double diskWriteKBytesRate;
@Expose
private double curDiskQueLength;
@Expose
private double totalGB;
@Expose
private double usedGB;
@Expose
private double freeGB;
@Expose
private double usedPercent;
@Expose
private List<FileSystemModel> fieFileSystemModels;
private Sigar sigar = GetSigar.getSigar();
private FileSystem[] fileSystemList;
private final int interval = 500;
private MonitorMain monitorMain;
private Logger logger = Logger.getLogger(PhysicalDiskModel.class);
public static void main(String[] args) throws SigarException,
InterruptedException, ExecutionException {
PhysicalDiskModel physicalDiskModel = new PhysicalDiskModel();
System.out.println("queue length:"
+ physicalDiskModel.getCurDiskQueLength());
System.out.println("read rate: "
+ physicalDiskModel.getDiskReadKBytesRate());
System.out.println("write rate: "
+ physicalDiskModel.getDiskWriteKBytesRate());
System.out
.println("used percent:" + physicalDiskModel.getUsedPercent());
System.out.println("total:" + physicalDiskModel.getTotalGB());
}
public PhysicalDiskModel(MonitorMain monitorMain) {
this.monitorMain = monitorMain;
}
public void run() {
try {
monitorMain.setPhysicalDiskModel(new PhysicalDiskModel());
} catch (SigarException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
}
}
public PhysicalDiskModel() throws SigarException, InterruptedException,
ExecutionException {
this.setFileSystemList();
this.setFieFileSystemModels();
this.setCurDiskQueLength();
this.setDiskReadKBytesRate();
this.setDiskWriteKBytesRate();
this.setFreeGB();
this.setTotalGB();
this.setUsedGB();
this.setUsedPercent();
}
@XmlElementWrapper
@XmlElement(name = "FileSystem", type = FileSystemModel.class)
public List<FileSystemModel> getFieFileSystemModels() {
return fieFileSystemModels;
}
private void setFieFileSystemModels() throws SigarException,
InterruptedException, ExecutionException {
this.fieFileSystemModels = new ArrayList<FileSystemModel>();
Map<String, FileSystemUsage> fileSysUsageMap = this
.getFileSystemUsages();
if (fileSysUsageMap.keySet() != null) {
List<Future<FileSystemModel>> futures = new ArrayList<Future<FileSystemModel>>();
for (String fileDir : fileSysUsageMap.keySet()) {
futures.add(GetThreadPool.getExecutorService().submit(
new NewFileSystemModel(fileSysUsageMap.get(fileDir),
fileDir, interval)));
}
for (Future<FileSystemModel> future : futures) {
fieFileSystemModels.add(future.get());
}
}
}
@XmlElement
public double getDiskReadKBytesRate() {
return diskReadKBytesRate;
}
private void setDiskReadKBytesRate() {
diskReadKBytesRate = new Double(0);
for (FileSystemModel fileSystemModel : this.fieFileSystemModels) {
diskReadKBytesRate += fileSystemModel.getDiskReadKBytesRate();
}
}
@XmlElement
public double getDiskWriteKBytesRate() {
return this.diskWriteKBytesRate;
}
private void setDiskWriteKBytesRate() {
this.diskWriteKBytesRate = new Double(0);
for (FileSystemModel fileSystemModel : this.fieFileSystemModels) {
this.diskWriteKBytesRate += fileSystemModel
.getDiskWriteKBytesRate();
}
}
@XmlElement
public double getCurDiskQueLength() {
return this.curDiskQueLength;
}
private void setCurDiskQueLength() throws SigarException {
this.curDiskQueLength = new Double(0);
for (FileSystemModel fileSystemModel : this.getFieFileSystemModels()) {
this.curDiskQueLength += fileSystemModel.getCurDiskQueLength();
}
}
@XmlElement
public FileSystem[] getFileSystemList() {
return fileSystemList;
}
private void setFileSystemList() throws SigarException {
this.fileSystemList = this.sigar.getFileSystemList();
}
@XmlElement
public double getTotalGB() {
return this.totalGB;
}
private void setTotalGB() {
this.totalGB = 0;
for (FileSystemModel fileSystemModel : this.fieFileSystemModels) {
this.totalGB += fileSystemModel.getTotalGB();
}
}
@XmlElement
public double getUsedGB() {
return usedGB;
}
private void setUsedGB() {
this.usedGB = 0;
for (FileSystemModel fileSystemModel : this.fieFileSystemModels) {
this.usedGB += fileSystemModel.getUsedGB();
}
this.usedGB=Math.round(this.usedGB*100)/100;
}
@XmlElement
public double getFreeGB() {
return freeGB;
}
private void setFreeGB() {
this.freeGB = 0;
for (FileSystemModel fileSystemModel : this.fieFileSystemModels) {
this.freeGB += fileSystemModel.getFreeGB();
}
}
@XmlElement
public double getUsedPercent() {
return usedPercent;
}
private void setUsedPercent() {
this.usedPercent = 0;
for (FileSystemModel fileSystemModel : this.fieFileSystemModels) {
this.usedPercent += fileSystemModel.getUsedPercent();
}
this.usedPercent=this.usedPercent/this.fieFileSystemModels.size();
}
public Map<String, FileSystemUsage> getFileSystemUsages()
throws SigarException {
Map<String, FileSystemUsage> fileSystemUsages = new HashMap<String, FileSystemUsage>();
if (this.getFileSystemList() == null)
this.setFileSystemList();
for (FileSystem fileSystem : this.getFileSystemList()) {
if (fileSystem.getType() == 2)
fileSystemUsages.put(fileSystem.getDirName(),
sigar.getFileSystemUsage(fileSystem.getDirName()));
}
return fileSystemUsages;
}
}
class NewFileSystemModel implements Callable<FileSystemModel> {
private FileSystemUsage fileSystemUsage;
private String fileDir;
private int interval;
public NewFileSystemModel(FileSystemUsage fileSystemUsage, String fileDir,
int interval) {
this.fileDir = fileDir;
this.fileSystemUsage = fileSystemUsage;
this.interval = interval;
}
public FileSystemModel call() throws InterruptedException,
ExecutionException {
return new FileSystemModel(this.fileSystemUsage, fileDir, interval);
}
public FileSystemUsage getFileSystemUsage() {
return fileSystemUsage;
}
public String getFileDir() {
return fileDir;
}
public long getInterval() {
return interval;
}
}

View File

@ -0,0 +1,180 @@
package org.bench4q.monitor.model;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.log4j.Logger;
import org.bench4q.monitor.service.GetSigar;
import org.bench4q.monitor.service.GetThreadPool;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement
public class ProcessModel implements Runnable {
private Sigar sigar = GetSigar.getSigar();
@Expose
private List<ProcessModelChild> processModelList;
@Expose
private long[] processPids;
@Expose
private List<String> processNameList;
@Expose
private int size;
public static void main(String args[]) throws SigarException,
InterruptedException, ExecutionException {
long time = System.currentTimeMillis();
ProcessModel processModel = new ProcessModel();
System.out.println("total process:"
+ processModel.getProcessPids().length);
for (int i = 0; i < processModel.getProcessPids().length; i++) {
if (processModel.getProcessModelList().get(i) != null) {
System.out.println("pid:"
+ processModel.getProcessModelList().get(i)
.getInstanceString());
System.out.println("name:"
+ processModel.getProcessModelList().get(i)
.getProcessId());
System.out.println("cpu percent:"
+ processModel.getProcessModelList().get(i)
.getProcessorTimePercent());
System.out.println("getResidentKBytes:"
+ processModel.getProcessModelList().get(i)
.getResidentKBytes());
System.out.println("virtural Kbytes:"
+ processModel.getProcessModelList().get(i).getVSize());
System.out.println(" Kbytes:"
+ processModel.getProcessModelList().get(i)
.getMemSize());
break;
}
}
System.out.println(System.currentTimeMillis() - time);
}
private MonitorMain monitorMain;
private Logger logger = Logger.getLogger(ProcessModel.class);
public ProcessModel(MonitorMain monitorMain) {
this.monitorMain = monitorMain;
}
public void run() {
try {
monitorMain.setProcesssModel(new ProcessModel());
} catch (SigarException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
}
}
public ProcessModel() throws SigarException, InterruptedException,
ExecutionException {
this.setProcessPids();
this.setProcesModelList();
this.setProcessNameList();
this.setSize();
}
@XmlElement
public int getSize() {
return this.size;
}
private void setSize() throws SigarException {
this.size = sigar.getProcList().length;
}
@XmlElementWrapper()
@XmlElement(type = ProcessModelChild.class)
public List<ProcessModelChild> getProcessModelList() {
return processModelList;
}
public void setProcesModelList() throws SigarException,
InterruptedException, ExecutionException {
this.processModelList = new ArrayList<ProcessModelChild>();
List<Future<ProcessModelChild>> futures = new ArrayList<Future<ProcessModelChild>>();
for (int i = 0; i < this.processPids.length; ++i) {
try {
futures.add(GetThreadPool.getExecutorService().submit(
new NewProcessChild(processPids[i],
new ProcessSigarReleatedModel(processPids[i]))));
} catch (SigarException e) {
processModelList.add(new ProcessModelChild(processPids[i]));
}
}
for (Future<ProcessModelChild> future : futures) {
processModelList.add(future.get());
}
}
@XmlElement
public long[] getProcessPids() {
return processPids;
}
private void setProcessPids() throws SigarException {
this.processPids = sigar.getProcList();
}
@XmlElementWrapper(name = "processNameList")
@XmlElement(name = "processName", type = String.class)
public List<String> getProcessNameList() {
return processNameList;
}
private void setProcessNameList() throws SigarException {
this.processNameList = new ArrayList<String>();
for (long pid : this.getProcessPids()) {
try {
ProcState procState = sigar.getProcState(pid);
processNameList.add(procState.getName());
} catch (SigarException e) {
}
}
}
}
class NewProcessChild implements Callable<ProcessModelChild> {
private long pid;
private ProcessSigarReleatedModel processSigarReleatedModel;
public NewProcessChild(long pid,
ProcessSigarReleatedModel processSigarReleatedModel) {
this.pid = pid;
this.processSigarReleatedModel = processSigarReleatedModel;
}
public ProcessModelChild call() {
try {
return new ProcessModelChild(pid, processSigarReleatedModel);
} catch (SigarException e) {
return new ProcessModelChild(pid);
}
}
}

View File

@ -0,0 +1,113 @@
package org.bench4q.monitor.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.monitor.service.DataFomat;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement
public class ProcessModelChild {
@Expose
private String instanceString;
@Expose
private long residentKBytes;
@Expose
private double processorTimePercent;
@Expose
private long memSize;
@Expose
private long processId;
@Expose
private long vSize;
private ProcessSigarReleatedModel processSigarReleatedModel;
public ProcessModelChild(){
}
public ProcessModelChild(long pid){
this.processId=pid;
this.instanceString="no power to get info";
}
public ProcessModelChild(long processId,
ProcessSigarReleatedModel processSigarReleatedModel)
throws SigarException {
this.processSigarReleatedModel = processSigarReleatedModel;
this.setProcessId(processId);
this.setInstanceString();
this.setProcessorTimePercent();
this.setMemSize();
this.setResidentKBytes();
this.setVSize();
}
@XmlElement
public double getProcessorTimePercent() throws SigarException {
return processorTimePercent;
}
private void setProcessorTimePercent() {
ProcCpu procCpu = this.processSigarReleatedModel.getProcCpu();
this.processorTimePercent = DataFomat.fomatToPercent(procCpu
.getPercent());
}
@XmlElement
public String getInstanceString() throws SigarException {
return instanceString;
}
private void setInstanceString() {
ProcState procState = this.processSigarReleatedModel.getProcState();
this.instanceString = procState.getName();
}
@XmlElement
public long getProcessId() {
return processId;
}
private void setProcessId(long processId) {
this.processId = processId;
}
@XmlElement
public long getVSize() throws SigarException {
return vSize;
}
private void setVSize() {
ProcMem procMem = this.processSigarReleatedModel.getProcMem();
this.vSize = procMem.getSize() / 1024L;
}
@XmlElement
public long getResidentKBytes() throws SigarException {
return residentKBytes;
}
private void setResidentKBytes() {
ProcMem procMem = this.processSigarReleatedModel.getProcMem();
this.residentKBytes = procMem.getResident() / 1024L;
}
@XmlElement
public long getMemSize() {
return memSize;
}
private void setMemSize() {
ProcMem procMem = this.processSigarReleatedModel.getProcMem();
this.memSize = procMem.getSize();
}
}

View File

@ -0,0 +1,45 @@
package org.bench4q.monitor.model;
import org.bench4q.monitor.service.GetSigar;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.SigarException;
public class ProcessSigarReleatedModel {
private ProcCpu procCpu;
private ProcState procState;
private ProcMem procMem;
public ProcessSigarReleatedModel(long pid) throws SigarException {
this.setProcCpu(GetSigar.getSigar().getProcCpu(pid));
this.setProcMem(GetSigar.getSigar().getProcMem(pid));
this.setProcState(GetSigar.getSigar().getProcState(pid));
}
public ProcCpu getProcCpu() {
return procCpu;
}
private void setProcCpu(ProcCpu procCpu) {
this.procCpu = procCpu;
}
public ProcState getProcState() {
return procState;
}
private void setProcState(ProcState procState) {
this.procState = procState;
}
public ProcMem getProcMem() {
return procMem;
}
private void setProcMem(ProcMem procMem) {
this.procMem = procMem;
}
}

View File

@ -0,0 +1,202 @@
package org.bench4q.monitor.model;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.log4j.Logger;
import org.bench4q.monitor.service.DataFomat;
import org.bench4q.monitor.service.GetSigar;
import org.bench4q.monitor.service.GetThreadPool;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement
public class ProcessorModel implements Runnable {
private List<ProcessorModelChild> processorModelList;
private Sigar sigar = GetSigar.getSigar();
private CpuPerc cpuPerc;
@Expose
private double processorTimePercent;
@Expose
private double privilegedTimePercent;
@Expose
private double userTimePercent;
@Expose
private double speed;
@Expose
private List<String> cpuInstanceList;
@Expose
private int size;
private MonitorMain monitorMain;
private Logger logger = Logger.getLogger(ProcessorModel.class);
public static void main(String args[]) {
try {
long time = System.currentTimeMillis();
ProcessorModel processorModel = new ProcessorModel();
System.out.println(processorModel.getProcessorModelList().size()
+ " instances");
System.out.println("privileged time percent"
+ processorModel.getPrivilegedTimePercent());
System.out.println("user time percent"
+ processorModel.getUserTimePercent());
System.out.println("total time percent:"
+ processorModel.getProcessorTimePercent());
System.out.println("speed:" + processorModel.getSpeed());
System.out.println(System.currentTimeMillis() - time);
} catch (SigarException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public ProcessorModel(MonitorMain monitorMain) {
this.monitorMain = monitorMain;
}
public void run() {
try {
monitorMain.setProcessorModel(new ProcessorModel());
} catch (SigarException e) {
// TODO Auto-generated catch block
logger.info(e, e.fillInStackTrace());
}
}
public ProcessorModel() throws SigarException {
cpuPerc = sigar.getCpuPerc();
this.setPorcessorModelList();
this.setPrivilegedTimePercent();
this.setProcessorTimePercent();
this.setUserTimePercent();
this.setSpeed();
this.setCpuInstanceList();
this.setSize();
}
@XmlElement
public int getSize() {
return size;
}
private void setSize() {
this.size = this.getProcessorModelList().size();
}
@XmlElement
public double getProcessorTimePercent() throws SigarException {
return this.processorTimePercent;
}
private void setProcessorTimePercent() throws SigarException {
this.processorTimePercent = DataFomat.fomatToPercent(1 - cpuPerc
.getIdle());
}
@XmlElement
public double getPrivilegedTimePercent() {
return this.privilegedTimePercent;
}
private void setPrivilegedTimePercent() {
this.privilegedTimePercent = DataFomat.fomatToPercent(cpuPerc.getSys());
}
@XmlElement
public double getUserTimePercent() throws SigarException {
return this.userTimePercent;
}
private void setUserTimePercent() throws SigarException {
this.userTimePercent = DataFomat.fomatToPercent(cpuPerc.getUser());
}
public double getSpeed() {
return this.speed;
}
private void setSpeed() throws SigarException {
this.speed = 0;
CpuInfo[] cpuInfos = GetSigar.getSigar().getCpuInfoList();
if (cpuInfos != null) {
this.speed += cpuInfos[0].getMhz();
}
long temp = Math.round(this.speed * 100);
this.speed = temp / 1024L / 100;
}
@XmlElementWrapper(name = "instanceNameList")
@XmlElement(name = "instanceName", type = String.class)
public List<String> getCpuInstanceList() {
return cpuInstanceList;
}
private void setCpuInstanceList() {
this.cpuInstanceList = new ArrayList<String>();
if (this.getProcessorModelList() != null) {
for (ProcessorModelChild processModelChild : this
.getProcessorModelList()) {
this.cpuInstanceList.add(processModelChild.getInstance());
}
}
}
@XmlElementWrapper(name = "processorlist")
@XmlElement(name = "processor", type = ProcessorModelChild.class)
public List<ProcessorModelChild> getProcessorModelList() {
return processorModelList;
}
private void setPorcessorModelList() throws SigarException {
this.processorModelList = new ArrayList<ProcessorModelChild>();
CpuPerc[] cpuPercList = sigar.getCpuPercList();
List<Future<ProcessorModelChild>> futures = new ArrayList<Future<ProcessorModelChild>>();
for (int i = 0; i < cpuPercList.length; ++i) {
futures.add(GetThreadPool.getExecutorService().submit(
new NewProcessorModelChild(i, cpuPercList[i])));
}
for (Future<ProcessorModelChild> future : futures) {
try {
processorModelList.add(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class NewProcessorModelChild implements Callable<ProcessorModelChild> {
private int id;
private CpuPerc cpuPerc;
public NewProcessorModelChild(int id, CpuPerc cpuPerc) {
this.id = id;
this.cpuPerc = cpuPerc;
}
public ProcessorModelChild call() throws SigarException {
return new ProcessorModelChild(id, cpuPerc);
}
}

View File

@ -0,0 +1,87 @@
package org.bench4q.monitor.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.monitor.service.GetSigar;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.SigarException;
import com.google.gson.annotations.Expose;
@XmlRootElement
public class ProcessorModelChild {
@Expose
private String instance;
@Expose
private double processorTimePercent;
@Expose
private double userTimePercent;
@Expose
private double privilegedTimePercent;
private CpuPerc cpuPerc;
public static void main(String[] agrs) throws SigarException {
long time = System.currentTimeMillis();
ProcessorModelChild testModel = new ProcessorModelChild(0, GetSigar
.getSigar().getCpuPercList()[0]);
System.out.println(testModel.getPrivilegedTimePercent());
System.out.println(testModel.getUserTimePercent());
System.out.println(testModel.getProcessorTimePercent());
System.out.println(System.currentTimeMillis() - time);
}
public ProcessorModelChild(){
}
public ProcessorModelChild(int id) throws SigarException {
this.setInstance("cpu" + id);
this.cpuPerc=GetSigar.getSigar().getCpuPerc();
}
public ProcessorModelChild(int id, CpuPerc cpuPerc) throws SigarException {
this.setInstance("cpu" + id);
this.cpuPerc = cpuPerc;
}
@XmlElement
public String getInstance() {
return this.instance;
}
private void setInstance(String instance) {
this.instance = instance;
}
@XmlElement
public double getProcessorTimePercent() {
long temp = Math.round(cpuPerc.getCombined() * 10000);
this.setProcessorTimePercent(temp / 100.0);
return processorTimePercent;
}
private void setProcessorTimePercent(double processorTimePercent) {
this.processorTimePercent = processorTimePercent;
}
@XmlElement
public double getUserTimePercent() throws SigarException {
long temp = Math.round(cpuPerc.getUser() * 10000);
this.setUserTimePercent(temp / 100.0);
return this.userTimePercent;
}
private void setUserTimePercent(double userTimePercent) {
this.userTimePercent = userTimePercent;
}
@XmlElement
public double getPrivilegedTimePercent() throws SigarException {
long temp = Math.round(cpuPerc.getSys() * 10000);
this.setPrivilegedTimePercent(temp / 100.0);
return this.privilegedTimePercent;
}
private void setPrivilegedTimePercent(double privilegedTimePercent) {
this.privilegedTimePercent = privilegedTimePercent;
}
}

View File

@ -0,0 +1,39 @@
package org.bench4q.monitor.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class SystemModel {
private double fileDataOperationsPerSecond;
public double getFileDataOperationsPerSecond() {
return fileDataOperationsPerSecond;
}
public void setFileDataOperationsPerSecond(
double fileDataOperationsPerSecond) {
this.fileDataOperationsPerSecond = fileDataOperationsPerSecond;
}
public double getProcessorQueueLength() {
return processorQueueLength;
}
public void setProcessorQueueLength(double processorQueueLength) {
this.processorQueueLength = processorQueueLength;
}
private double processorQueueLength;
double totalProceesorTimePercent;
public double getTotalProceesorTimePercent() {
return totalProceesorTimePercent;
}
public void setTotalProceesorTimePercent(double totalProceesorTimePercent2) {
// TODO Auto-generated method stub
this.totalProceesorTimePercent = totalProceesorTimePercent2;
}
}

View File

@ -0,0 +1,12 @@
package org.bench4q.monitor.service;
public class DataFomat {
public static double fomatToPercent(double data) {
long temp = Math.round(data * 10000);
return temp / 100.0;
}
public static double caculateTimeInterval(long startTime, long endTime) {
double temp=(endTime - startTime);
return temp/1000000000L;
}
}

View File

@ -0,0 +1,15 @@
package org.bench4q.monitor.service;
import org.hyperic.sigar.Sigar;
public class GetSigar {
public static Sigar sigar;
public static Sigar getSigar() {
sigar = new Sigar();
return sigar;
}
}

View File

@ -0,0 +1,17 @@
package org.bench4q.monitor.service;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class GetThreadPool {
private static ExecutorService executorService = Executors
.newFixedThreadPool(100);
public static ExecutorService getExecutorService() {
return executorService;
}
public static void shutDownExecutrorService() {
executorService.shutdown();
}
}

View File

@ -0,0 +1,107 @@
package org.bench4q.monitor.service;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.bench4q.monitor.model.MonitorMain;
import java.io.*;
class XmlFileFilter implements FilenameFilter{
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
}
public class ReadSystemInfoFromLocalDisk {
private String savePath;
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
//test code
public static void main(String[] args){
ReadSystemInfoFromLocalDisk test = new ReadSystemInfoFromLocalDisk();
test.setSavePath("sigartmp/");
Calendar lowerCalendal = Calendar.getInstance();
lowerCalendal.clear();
lowerCalendal.set(2014, 0, 8, 20, 10, 0);
Calendar upperCalendar = Calendar.getInstance();
upperCalendar.clear();
upperCalendar.set(2014, 0, 8, 20, 13, 0);
List<MonitorMain> mainModelList = test.ReadSystemInfoByDate(lowerCalendal.getTime(), upperCalendar.getTime());
FileWriter writer = null;
try {
JAXBContext context = JAXBContext.newInstance(MonitorMain.class);
Marshaller marshal = context.createMarshaller();
marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
for(int i = 0; i < mainModelList.size(); ++i){
marshal.marshal(mainModelList.get(i), System.out);
writer = new FileWriter("/Users/apple/Desktop/tmp/" + i + "xml");
marshal.marshal(mainModelList.get(i), writer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setSavePath(String savePath){
this.savePath = savePath;
}
public List<MonitorMain> ReadSystemInfoByDate(Date lowerDate, Date upperDate){
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String lowerDateString = dateFormat.format(lowerDate);
String upperDateString = dateFormat.format(upperDate);
if(lowerDateString.compareTo(upperDateString) > 0){
System.out.println("return");
return null;
}
this.setSavePath("sigartmp/");
File path = new File(savePath);
XmlFileFilter xmlFileFilter = new XmlFileFilter();
String[] xmlFiles = path.list(xmlFileFilter);
Arrays.sort(xmlFiles);
List<MonitorMain> mainModelList = new ArrayList<MonitorMain>();
JAXBContext context;
Unmarshaller unmarshal = null;
try {
context = JAXBContext.newInstance(MonitorMain.class);
unmarshal = context.createUnmarshaller();
} catch (JAXBException e) {
e.printStackTrace();
}
for(int i = 0; i < xmlFiles.length; ++i){
if(xmlFiles[i].compareTo(lowerDateString) >= 0 && xmlFiles[i].compareTo(upperDateString) <= 0){
FileReader reader;
try {
reader = new FileReader(savePath + xmlFiles[i]);
try {
mainModelList.add((MonitorMain)unmarshal.unmarshal(reader));
} catch (JAXBException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
return mainModelList;
}
}

View File

@ -0,0 +1,36 @@
package org.bench4q.monitor.service;
import java.io.File;
import java.io.IOException;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import org.hyperic.sigar.SigarException;
public class TimerService extends TimerTask {
@Override
public void run(){
WriteSystemInfoToLocalDisk testWrite = new WriteSystemInfoToLocalDisk();
String filePath = System.getProperty("user.dir")+"/sigartmp";
new File(filePath).mkdirs();
testWrite.setSavaPath("sigartmp/");
try {
try {
testWrite.writeCurrentSystemInfoToLocalDisk();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SigarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,48 @@
package org.bench4q.monitor.service;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import java.text.SimpleDateFormat;
import java.io.*;
import org.apache.log4j.Logger;
import org.bench4q.monitor.model.*;
import org.hyperic.sigar.SigarException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class WriteSystemInfoToLocalDisk {
private SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
private String savePath;
private Logger logger = Logger.getLogger(WriteSystemInfoToLocalDisk.class);
public static void main(String[] args) throws SigarException,
InterruptedException, ExecutionException, IOException {
WriteSystemInfoToLocalDisk testWrite = new WriteSystemInfoToLocalDisk();
testWrite.setSavaPath("D:/sigartmp/");
testWrite.writeCurrentSystemInfoToLocalDisk();
}
public void setSavaPath(String savePath) {
this.savePath = savePath;
}
public void writeCurrentSystemInfoToLocalDisk() throws SigarException,
InterruptedException, ExecutionException, IOException {
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date date = new Date();
MonitorMain mainModel = new MonitorMain(date);
FileWriter writer = null;
try {
writer = new FileWriter(savePath + dateFormat.format(date)
+ ".json");
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation().create();
gson.toJson(mainModel, writer);
} catch (Exception e) {
logger.error(e, e.fillInStackTrace());
} finally {
writer.close();
}
}
}

View File

@ -0,0 +1,31 @@
log4j.rootLogger = INFO,WARN,ERROR,FALTAL,D
log4j.appender.WARN = org.apache.log4j.DailyRollingFileAppender
log4j.appender.WARN.File = logs/warnlog.log
log4j.appender.WARN.Append = true
log4j.appender.WARN.Threshold = WARN
log4j.appender.WARN.layout = org.apache.log4j.PatternLayout
log4j.appender.WARN.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERROR.File = logs/errorlog.log
log4j.appender.ERROR.Append = true
log4j.appender.ERROR.Threshold = ERROR
log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.FALTAL = org.apache.log4j.DailyRollingFileAppender
log4j.appender.FALTAL.File = logs/faltallog.log
log4j.appender.FALTAL.Append = true
log4j.appender.FALTAL.Threshold = ERROR
log4j.appender.FALTAL.layout = org.apache.log4j.PatternLayout
log4j.appender.FALTAL.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = TRACE
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="org.bench4q" />
<mvc:annotation-driven />
</beans>