Moved around OSAL and implemented /proc/net/arp parser

This commit is contained in:
Ziver Koc 2016-09-30 16:57:43 +02:00
parent ab8239a809
commit 1e5e114300
13 changed files with 1160 additions and 941 deletions

5
src/zutil/osal/OSAbstractionLayer.java Normal file → Executable file
View file

@ -24,9 +24,12 @@
package zutil.osal; package zutil.osal;
import zutil.osal.linux.OsalLinuxImpl;
import zutil.osal.macos.OsalMacOSImpl;
import zutil.osal.windows.OsalWindowsImpl;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;

View file

@ -1,33 +1,35 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal; package zutil.osal.linux;
/** import zutil.osal.HardwareAbstractionLayer;
* Created by Ziver on 2015-04-07.
*/ /**
public class HalLinuxImpl implements HardwareAbstractionLayer{ * Created by Ziver on 2015-04-07.
*/
protected HalLinuxImpl(){} public class HalLinuxImpl implements HardwareAbstractionLayer {
}
protected HalLinuxImpl(){}
}

View file

@ -1,82 +1,85 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal; package zutil.osal.linux;
import java.io.File; import zutil.osal.HardwareAbstractionLayer;
import zutil.osal.OSAbstractionLayer;
/**
* Linux platform specific implementation import java.io.File;
*/
public class OsalLinuxImpl extends OSAbstractionLayer { /**
private static HalLinuxImpl hal; * Linux platform specific implementation
*/
@Override public class OsalLinuxImpl extends OSAbstractionLayer {
public OSType getOSType() { private static HalLinuxImpl hal;
return OSType.Linux;
} @Override
public OSType getOSType() {
return OSType.Linux;
@Override }
public String getOSVersion() {
throw new UnsupportedOperationException();
} @Override
public String getOSVersion() {
@Override throw new UnsupportedOperationException();
public String getKernelVersion() { }
try{
return super.getFirstLineFromExec("uname -r"); @Override
} catch(Exception e){ public String getKernelVersion() {
e.printStackTrace(); try{
} return super.getFirstLineFromExec("uname -r");
return null; } catch(Exception e){
} e.printStackTrace();
}
@Override return null;
public String getUsername() { }
try{
return super.getFirstLineFromExec("whoami"); @Override
} catch(Exception e){ public String getUsername() {
e.printStackTrace(); try{
} return super.getFirstLineFromExec("whoami");
return null; } catch(Exception e){
} e.printStackTrace();
}
@Override return null;
public File getUserConfigPath() { }
return new File("/home/"+getUsername());
} @Override
public File getUserConfigPath() {
@Override return new File("/home/"+getUsername());
public File getGlobalConfigPath() { }
return new File("/etc");
} @Override
public File getGlobalConfigPath() {
@Override return new File("/etc");
public HardwareAbstractionLayer getHAL() { }
if(hal == null)
hal = new HalLinuxImpl(); @Override
return hal; public HardwareAbstractionLayer getHAL() {
} if(hal == null)
} hal = new HalLinuxImpl();
return hal;
}
}

View file

@ -1,173 +1,173 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal.app.linux; package zutil.osal.linux.app;
import zutil.Timer; import zutil.Timer;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.osal.OSAbstractionLayer; import zutil.osal.OSAbstractionLayer;
import java.util.HashMap; import java.util.HashMap;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* Created by Ziver on 2014-11-09. * Created by Ziver on 2014-11-09.
*/ */
public class AptGet { public class AptGet {
public static final Logger log = LogUtil.getLogger(); public static final Logger log = LogUtil.getLogger();
private static Timer updateTimer = new Timer(1000*60*5); // 5min timer private static Timer updateTimer = new Timer(1000*60*5); // 5min timer
private static Timer packageTimer = new Timer(1000*60*5); // 5min timer private static Timer packageTimer = new Timer(1000*60*5); // 5min timer
private static HashMap<String, Package> packages = new HashMap<>(); private static HashMap<String, Package> packages = new HashMap<>();
public static void install(String pkg) { public static void install(String pkg) {
update(); update();
OSAbstractionLayer.exec("apt-get -y install " + pkg); OSAbstractionLayer.exec("apt-get -y install " + pkg);
packageTimer.reset(); packageTimer.reset();
} }
public static void upgrade(){ public static void upgrade(){
update(); update();
OSAbstractionLayer.exec("apt-get -y " + OSAbstractionLayer.exec("apt-get -y " +
// Dont display configuration conflicts // Dont display configuration conflicts
"-o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" " + "-o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" " +
"upgrade"); "upgrade");
packageTimer.reset(); packageTimer.reset();
} }
public static void update(){ public static void update(){
// Only run every 5 min // Only run every 5 min
if(updateTimer.hasTimedOut()){ if(updateTimer.hasTimedOut()){
OSAbstractionLayer.exec("apt-get update"); OSAbstractionLayer.exec("apt-get update");
updateTimer.start(); updateTimer.start();
} }
} }
public static void purge(String pkg) { public static void purge(String pkg) {
OSAbstractionLayer.exec("apt-get --purge remove " + pkg); OSAbstractionLayer.exec("apt-get --purge remove " + pkg);
packageTimer.reset(); packageTimer.reset();
} }
public static Package getPackage(String pkg){ public static Package getPackage(String pkg){
updatePackages(); updatePackages();
return packages.get(pkg); return packages.get(pkg);
} }
public static synchronized void updatePackages(){ public static synchronized void updatePackages(){
// Only run every 5 min // Only run every 5 min
if(packageTimer.hasTimedOut()){ if(packageTimer.hasTimedOut()){
String[] output = OSAbstractionLayer.exec("dpkg --list"); String[] output = OSAbstractionLayer.exec("dpkg --list");
for(int i=5; i<output.length; ++i) { for(int i=5; i<output.length; ++i) {
packages.put(output[i], new Package(output[5])); packages.put(output[i], new Package(output[5]));
} }
packageTimer.start(); packageTimer.start();
} }
} }
/** /**
* This class represents a system package and its current status * This class represents a system package and its current status
*/ */
public static class Package{ public static class Package{
public enum PackageState{ public enum PackageState{
// Expected States // Expected States
/* u */ Unknown, /* u */ Unknown,
/* i */ Installed, /* i */ Installed,
/* r */ Removed, /* r */ Removed,
/* p */ Purged, // remove including config files /* p */ Purged, // remove including config files
/* h */ Holding, /* h */ Holding,
// Current States // Current States
/* n */ NotInstalled, /* n */ NotInstalled,
/* i */ //Installed, /* i */ //Installed,
/* c */ ConfigFiles, // only the config files are installed /* c */ ConfigFiles, // only the config files are installed
/* u */ Unpacked, /* u */ Unpacked,
/* f */ HalfConfigured, // configuration failed for some reason /* f */ HalfConfigured, // configuration failed for some reason
/* h */ HalfInstalled, // installation failed for some reason /* h */ HalfInstalled, // installation failed for some reason
/* w */ TriggersAwaited, // package is waiting for a trigger from another package /* w */ TriggersAwaited, // package is waiting for a trigger from another package
/* t */ TriggersPending, //package has been triggered /* t */ TriggersPending, //package has been triggered
// Error States // Error States
/* r */ ReinstallRequired // package broken, reinstallation required /* r */ ReinstallRequired // package broken, reinstallation required
} }
private PackageState expectedState = PackageState.Unknown; private PackageState expectedState = PackageState.Unknown;
private PackageState currentState = PackageState.Unknown;; private PackageState currentState = PackageState.Unknown;;
private PackageState errorState = PackageState.Unknown;; private PackageState errorState = PackageState.Unknown;;
private String name; private String name;
private String version; private String version;
private String description; private String description;
protected Package(String dpkgStr){ protected Package(String dpkgStr){
switch (dpkgStr.charAt(0)){ switch (dpkgStr.charAt(0)){
case 'u': expectedState = PackageState.Unknown; break; case 'u': expectedState = PackageState.Unknown; break;
case 'i': expectedState = PackageState.Installed; break; case 'i': expectedState = PackageState.Installed; break;
case 'r': expectedState = PackageState.Removed; break; case 'r': expectedState = PackageState.Removed; break;
case 'p': expectedState = PackageState.Purged; break; case 'p': expectedState = PackageState.Purged; break;
case 'h': expectedState = PackageState.Holding; break; case 'h': expectedState = PackageState.Holding; break;
} }
switch (dpkgStr.charAt(0)){ switch (dpkgStr.charAt(0)){
case 'n': currentState = PackageState.NotInstalled; break; case 'n': currentState = PackageState.NotInstalled; break;
case 'i': currentState = PackageState.Installed; break; case 'i': currentState = PackageState.Installed; break;
case 'c': currentState = PackageState.ConfigFiles; break; case 'c': currentState = PackageState.ConfigFiles; break;
case 'u': currentState = PackageState.Unpacked; break; case 'u': currentState = PackageState.Unpacked; break;
case 'f': currentState = PackageState.HalfConfigured; break; case 'f': currentState = PackageState.HalfConfigured; break;
case 'h': currentState = PackageState.HalfInstalled; break; case 'h': currentState = PackageState.HalfInstalled; break;
case 'w': currentState = PackageState.TriggersAwaited; break; case 'w': currentState = PackageState.TriggersAwaited; break;
case 't': currentState = PackageState.TriggersPending; break; case 't': currentState = PackageState.TriggersPending; break;
} }
if(dpkgStr.charAt(2) == 'r') if(dpkgStr.charAt(2) == 'r')
errorState = PackageState.ReinstallRequired; errorState = PackageState.ReinstallRequired;
String[] tmp = dpkgStr.split("[ \\t]*", 4); String[] tmp = dpkgStr.split("[ \\t]*", 4);
name = tmp[1]; name = tmp[1];
version = tmp[2]; version = tmp[2];
description = tmp[3]; description = tmp[3];
} }
public PackageState getExpectedState() { public PackageState getExpectedState() {
return expectedState; return expectedState;
} }
public PackageState getCurrentState() { public PackageState getCurrentState() {
return currentState; return currentState;
} }
public PackageState getErrorState() { public PackageState getErrorState() {
return errorState; return errorState;
} }
public String getName() { public String getName() {
return name; return name;
} }
public String getVersion() { public String getVersion() {
return version; return version;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
} }
} }

View file

@ -1,4 +1,4 @@
package zutil.osal.app.linux; package zutil.osal.linux.app;
import zutil.Timer; import zutil.Timer;
import zutil.log.LogUtil; import zutil.log.LogUtil;

View file

@ -1,253 +1,260 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal.app.linux; package zutil.osal.linux.app;
import zutil.StringUtil; import zutil.StringUtil;
import zutil.log.LogUtil; import zutil.Timer;
import zutil.net.ThroughputCalculator; import zutil.log.LogUtil;
import zutil.net.ThroughputCalculator;
import java.io.BufferedReader;
import java.io.FileReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.FileReader;
import java.util.HashMap; import java.io.IOException;
import java.util.logging.Level; import java.util.HashMap;
import java.util.logging.Logger; import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Documentation from https://www.kernel.org/doc/Documentation/block/stat.txt /**
* * Documentation from https://www.kernel.org/doc/Documentation/block/stat.txt
* Created by ezivkoc on 2015-05-19. *
*/ * Created by Ziver on 2015-05-19.
public class ProcDiskstats { */
private static final Logger log = LogUtil.getLogger(); public class ProcDiskstats {
private static final String PROC_PATH = "/proc/diskstats"; private static final Logger log = LogUtil.getLogger();
private static final int TTL = 500; // update stats every 0.5 second private static final String PROC_PATH = "/proc/diskstats";
private static final int TTL = 500; // update stats every 0.5 second
private static HashMap<String, HddStats> hdds = new HashMap<String, HddStats>();
private static long updateTimestamp; private static HashMap<String, HddStats> hdds = new HashMap<String, HddStats>();
private static Timer updateTimer = new Timer(TTL);
private synchronized static void update(){
if(System.currentTimeMillis() - updateTimestamp < TTL) private synchronized static void update(){
return; if(!updateTimer.hasTimedOut())
updateTimestamp = System.currentTimeMillis(); return;
try {
BufferedReader in = new BufferedReader(new FileReader(PROC_PATH)); try {
String line = null; BufferedReader in = new BufferedReader(new FileReader(PROC_PATH));
while((line=in.readLine()) != null){ parse(in);
String[] str = line.trim().split("\\s+", 4); in.close();
if(str.length >= 4) { } catch (IOException e) {
String devName = str[2]; log.log(Level.SEVERE, null, e);
if(!hdds.containsKey(devName)){ }
HddStats hdd = new HddStats(devName); }
hdds.put(hdd.getDevName(), hdd); protected static void parse(BufferedReader in) throws IOException {
} updateTimer.start();
hdds.get(devName).update(str[3]); String line = null;
} while((line=in.readLine()) != null){
} String[] str = line.trim().split("\\s+", 4);
in.close(); if(str.length >= 4) {
} catch (IOException e) { String devName = str[2];
log.log(Level.SEVERE, null, e); if(!hdds.containsKey(devName)){
} HddStats hdd = new HddStats(devName);
} hdds.put(hdd.getDevName(), hdd);
}
public static HddStats getStats(String devName){ hdds.get(devName).update(str[3]);
update(); }
return hdds.get(devName); }
} }
public static class HddStats {
private String devName; public static HddStats getStats(String devName){
//read I/Os requests number of read I/Os processed update();
private long readIO = -1; return hdds.get(devName);
//read merges requests number of read I/Os merged with in-queue I/O }
private long readMerges = -1;
//read sectors sectors number of sectors read
private long readSectors = -1; public static class HddStats {
//read ticks milliseconds total wait time for read requests private String devName;
private long readTicks = -1; //read I/Os requests number of read I/Os processed
//write I/Os requests number of write I/Os processed private long readIO = -1;
private long writeIO = -1; //read merges requests number of read I/Os merged with in-queue I/O
//write merges requests number of write I/Os merged with in-queue I/O private long readMerges = -1;
private long writeMerges = -1; //read sectors sectors number of sectors read
//write sectors sectors number of sectors written private long readSectors = -1;
private long writeSectors = -1; //read ticks milliseconds total wait time for read requests
//write ticks milliseconds total wait time for write requests private long readTicks = -1;
private long writeTicks = -1; //write I/Os requests number of write I/Os processed
//in_flight requests number of I/Os currently in flight private long writeIO = -1;
private long inFlight = -1; //write merges requests number of write I/Os merged with in-queue I/O
//io_ticks milliseconds total time this block device has been active private long writeMerges = -1;
private long ioTicks = -1; //write sectors sectors number of sectors written
//time_in_queue milliseconds total wait time for all requests private long writeSectors = -1;
private long timeInQueue = -1; //write ticks milliseconds total wait time for write requests
private long writeTicks = -1;
private ThroughputCalculator readThroughput; //in_flight requests number of I/Os currently in flight
private ThroughputCalculator writeThroughput; private long inFlight = -1;
//io_ticks milliseconds total time this block device has been active
private long ioTicks = -1;
protected HddStats(String devName) { //time_in_queue milliseconds total wait time for all requests
this.devName = devName; private long timeInQueue = -1;
readThroughput = new ThroughputCalculator();
writeThroughput = new ThroughputCalculator(); private ThroughputCalculator readThroughput;
} private ThroughputCalculator writeThroughput;
protected void update(String line){
String[] stats = line.split("\\s+");
if(stats.length >= 11){ protected HddStats(String devName) {
readIO = Long.parseLong(stats[0]); this.devName = devName;
readMerges = Long.parseLong(stats[1]); readThroughput = new ThroughputCalculator();
readSectors = Long.parseLong(stats[2]); writeThroughput = new ThroughputCalculator();
readTicks = Long.parseLong(stats[3]); }
writeIO = Long.parseLong(stats[4]); protected void update(String line){
writeMerges = Long.parseLong(stats[5]); String[] stats = line.split("\\s+");
writeSectors = Long.parseLong(stats[6]); if(stats.length >= 11){
writeTicks = Long.parseLong(stats[7]); readIO = Long.parseLong(stats[0]);
inFlight = Long.parseLong(stats[8]); readMerges = Long.parseLong(stats[1]);
ioTicks = Long.parseLong(stats[9]); readSectors = Long.parseLong(stats[2]);
timeInQueue = Long.parseLong(stats[10]); readTicks = Long.parseLong(stats[3]);
writeIO = Long.parseLong(stats[4]);
readThroughput.setTotalHandledData(readSectors * 512); writeMerges = Long.parseLong(stats[5]);
writeThroughput.setTotalHandledData(writeSectors * 512); writeSectors = Long.parseLong(stats[6]);
} writeTicks = Long.parseLong(stats[7]);
} inFlight = Long.parseLong(stats[8]);
ioTicks = Long.parseLong(stats[9]);
timeInQueue = Long.parseLong(stats[10]);
public String getDevName() {
return devName; readThroughput.setTotalHandledData(readSectors * 512);
} writeThroughput.setTotalHandledData(writeSectors * 512);
/** }
* This values increment when an I/O request completes. }
*/
public long getReadIO() {
return readIO; public String getDevName() {
} return devName;
/** }
* This value increment when an I/O request is merged with an /**
* already-queued I/O request. * This values increment when an I/O request completes.
*/ */
public long getReadMerges() { public long getReadIO() {
return readMerges; return readIO;
} }
/** /**
* This value count the number of sectors read from to this * This value increment when an I/O request is merged with an
* block device. The "sectors" in question are the standard UNIX 512-byte * already-queued I/O request.
* sectors, not any device- or filesystem-specific block size. The */
* counter is incremented when the I/O completes. public long getReadMerges() {
*/ return readMerges;
public long getReadSectors() { }
return readSectors; /**
} * This value count the number of sectors read from to this
/** * block device. The "sectors" in question are the standard UNIX 512-byte
* This value count the number of milliseconds that I/O requests have * sectors, not any device- or filesystem-specific block size. The
* waited on this block device. If there are multiple I/O requests waiting, * counter is incremented when the I/O completes.
* this value will increase at a rate greater than 1000/second; for */
* example, if 60 read requests wait for an average of 30 ms, the read_ticks public long getReadSectors() {
* field will increase by 60*30 = 1800. return readSectors;
*/ }
public long getReadTicks() { /**
return readTicks; * This value count the number of milliseconds that I/O requests have
} * waited on this block device. If there are multiple I/O requests waiting,
/** * this value will increase at a rate greater than 1000/second; for
* This values increment when an I/O request completes. * example, if 60 read requests wait for an average of 30 ms, the read_ticks
*/ * field will increase by 60*30 = 1800.
public long getWriteIO() { */
return writeIO; public long getReadTicks() {
} return readTicks;
/** }
* This value increment when an I/O request is merged with an /**
* already-queued I/O request. * This values increment when an I/O request completes.
*/ */
public long getWriteMerges() { public long getWriteIO() {
return writeMerges; return writeIO;
} }
/** /**
* This value count the number of sectors written to this * This value increment when an I/O request is merged with an
* block device. The "sectors" in question are the standard UNIX 512-byte * already-queued I/O request.
* sectors, not any device- or filesystem-specific block size. The */
* counter is incremented when the I/O completes. public long getWriteMerges() {
*/ return writeMerges;
public long getWriteSectors() { }
return writeSectors; /**
} * This value count the number of sectors written to this
/** * block device. The "sectors" in question are the standard UNIX 512-byte
* This value count the number of milliseconds that I/O requests have * sectors, not any device- or filesystem-specific block size. The
* waited on this block device. If there are multiple I/O requests waiting, * counter is incremented when the I/O completes.
* this value will increase at a rate greater than 1000/second; for */
* example, if 60 write requests wait for an average of 30 ms, the write_ticks public long getWriteSectors() {
* field will increase by 60*30 = 1800. return writeSectors;
*/ }
public long getWriteTicks() { /**
return writeTicks; * This value count the number of milliseconds that I/O requests have
} * waited on this block device. If there are multiple I/O requests waiting,
/** * this value will increase at a rate greater than 1000/second; for
* This value counts the number of I/O requests that have been issued to * example, if 60 write requests wait for an average of 30 ms, the write_ticks
* the device driver but have not yet completed. It does not include I/O * field will increase by 60*30 = 1800.
* requests that are in the queue but not yet issued to the device driver. */
*/ public long getWriteTicks() {
public long getInFlight() { return writeTicks;
return inFlight; }
} /**
/** * This value counts the number of I/O requests that have been issued to
* This value counts the number of milliseconds during which the device has * the device driver but have not yet completed. It does not include I/O
* had I/O requests queued. * requests that are in the queue but not yet issued to the device driver.
*/ */
public long getIoTicks() { public long getInFlight() {
return ioTicks; return inFlight;
} }
/** /**
* This value counts the number of milliseconds that I/O requests have waited * This value counts the number of milliseconds during which the device has
* on this block device. If there are multiple I/O requests waiting, this * had I/O requests queued.
* value will increase as the product of the number of milliseconds times the */
* number of requests waiting (see "read ticks" above for an example). public long getIoTicks() {
*/ return ioTicks;
public long getTimeInQueue() { }
return timeInQueue; /**
} * This value counts the number of milliseconds that I/O requests have waited
* on this block device. If there are multiple I/O requests waiting, this
/** * value will increase as the product of the number of milliseconds times the
* @return the average byte/second read throughput from the disk * number of requests waiting (see "read ticks" above for an example).
*/ */
public double getReadThroughput(){ public long getTimeInQueue() {
return readThroughput.getByteThroughput(); return timeInQueue;
} }
/**
* @return the average byte/second write throughput to the disk /**
*/ * @return the average byte/second read throughput from the disk
public double getWriteThroughput(){ */
return writeThroughput.getByteThroughput(); public double getReadThroughput(){
} return readThroughput.getByteThroughput();
} }
/**
* @return the average byte/second write throughput to the disk
public static void main(String[] args){ */
while(true){ public double getWriteThroughput(){
HddStats hdd = ProcDiskstats.getStats("sda"); return writeThroughput.getByteThroughput();
System.out.println("sda= " + }
"read: " + StringUtil.formatByteSizeToString((long)hdd.getReadThroughput()) + "/s "+ }
"write: " + StringUtil.formatByteSizeToString((long)hdd.getWriteThroughput()) + "/s");
try{Thread.sleep(1000);}catch (Exception e){}
} public static void main(String[] args){
} while(true){
} HddStats hdd = ProcDiskstats.getStats("sda");
System.out.println("sda= " +
"read: " + StringUtil.formatByteSizeToString((long)hdd.getReadThroughput()) + "/s "+
"write: " + StringUtil.formatByteSizeToString((long)hdd.getWriteThroughput()) + "/s");
try{Thread.sleep(1000);}catch (Exception e){}
}
}
}

View file

@ -0,0 +1,135 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* 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 zutil.osal.linux.app;
import zutil.Timer;
import zutil.converter.Converter;
import zutil.log.LogUtil;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Makes the Linux ARP cache available as Java api
* <p>
* Created by Ziver on 2015-05-19.
*/
public class ProcNetArp {
private static final Logger logger = LogUtil.getLogger();
private static final String PROC_PATH = "/proc/net/arp";
private static final int TTL = 500; // update stats every 0.5 second
private static HashMap<InetAddress, ArpEntry> arpTable = new HashMap<>();
private static Timer updateTimer = new Timer(TTL);
private synchronized static void update() {
if (!updateTimer.hasTimedOut())
return;
try {
BufferedReader in = new BufferedReader(new FileReader(PROC_PATH));
parse(in);
in.close();
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
}
}
protected static void parse(BufferedReader in) throws IOException {
updateTimer.start();
String line = null;
in.readLine(); // Skipp headers
while ((line = in.readLine()) != null) {
String[] str = line.split("\\s+");
if (str.length >= 6) {
InetAddress ip = InetAddress.getByName(str[0]);
if (!arpTable.containsKey(ip))
arpTable.put(ip, new ArpEntry());
ArpEntry entry = arpTable.get(ip);
entry.ip = ip;
entry.hwAddress = Converter.hexToByte(str[3].replaceAll(":", ""));
entry.netIf = str[5];
} else
logger.warning(PROC_PATH + " contains unrecognized format");
}
}
public static Collection<ArpEntry> getAllArpEntries() {
update();
return arpTable.values();
}
public static ArpEntry getArpEntry(InetAddress ip) {
update();
return arpTable.get(ip);
}
public static class ArpEntry {
private InetAddress ip;
private byte[] hwAddress;
private String netIf;
public InetAddress getIp() {
return ip;
}
public byte[] getHwAddress() {
return hwAddress;
}
public String getHwAddressString() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < hwAddress.length; i++) {
if (i != 0)
str.append(':');
str.append(Converter.toHexString(hwAddress[i]));
}
return str.toString();
}
public String getNetworkInterface() {
return netIf;
}
}
public static void main(String[] args) {
for (ArpEntry entry : getAllArpEntries()) {
System.out.println(entry.getIp().getHostAddress() + " => " + entry.getHwAddressString());
}
}
}

View file

@ -1,208 +1,214 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal.app.linux; package zutil.osal.linux.app;
import zutil.Timer; import zutil.Timer;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* Documentation from https://www.kernel.org/doc/Documentation/block/stat.txt * Documentation from https://www.kernel.org/doc/Documentation/block/stat.txt
* *
* Created by ezivkoc on 2015-05-19. * Created by Ziver on 2015-05-19.
*/ */
public class ProcStat { public class ProcStat {
private static final Logger log = LogUtil.getLogger(); private static final Logger log = LogUtil.getLogger();
private static final String PROC_PATH = "/proc/stat"; private static final String PROC_PATH = "/proc/stat";
private static final int TTL = 500; // update stats every 0.5 second private static final int TTL = 500; // update stats every 0.5 second
private static CpuStats cpuTotal = new CpuStats(); private static CpuStats cpuTotal = new CpuStats();
private static ArrayList<CpuStats> cpus = new ArrayList<CpuStats>(); private static ArrayList<CpuStats> cpus = new ArrayList<CpuStats>();
private static long uptime; private static long uptime;
private static long processes; private static long processes;
private static Timer updateTimer = new Timer(TTL); private static Timer updateTimer = new Timer(TTL);
private synchronized static void update(){ private synchronized static void update(){
if(updateTimer.hasTimedOut()) if(!updateTimer.hasTimedOut())
return; return;
updateTimer.start();
try { try {
BufferedReader in = new BufferedReader(new FileReader(PROC_PATH)); BufferedReader in = new BufferedReader(new FileReader(PROC_PATH));
String line = null; parse(in);
while((line=in.readLine()) != null){ in.close();
String[] str = line.split("\\s+"); } catch (IOException e) {
if(str[0].equals("cpu")) { log.log(Level.SEVERE, null, e);
cpuTotal.update(str); }
} }
else if(str[0].startsWith("cpu")){ protected static void parse(BufferedReader in) throws IOException {
int cpuId = Integer.parseInt(str[0].substring(3)); updateTimer.start();
if(cpus.size() <= cpuId) String line = null;
cpus.add(new CpuStats()); while((line=in.readLine()) != null){
cpus.get(cpuId).update(str); String[] str = line.split("\\s+");
} if(str[0].equals("cpu")) {
else if(str[0].startsWith("btime")){ cpuTotal.update(str);
uptime = Long.parseLong(str[1]); }
} else if(str[0].startsWith("cpu")){
else if(str[0].startsWith("processes")){ int cpuId = Integer.parseInt(str[0].substring(3));
processes = Long.parseLong(str[1]); if(cpus.size() <= cpuId)
} cpus.add(new CpuStats());
} cpus.get(cpuId).update(str);
in.close(); }
} catch (IOException e) { else if(str[0].startsWith("btime")){
log.log(Level.SEVERE, null, e); uptime = Long.parseLong(str[1]);
} }
} else if(str[0].startsWith("processes")){
processes = Long.parseLong(str[1]);
public static CpuStats getTotalCpuStats(){ }
update(); }
return cpuTotal; }
}
public static Iterator<CpuStats> getCpuStats(){
update();
return cpus.iterator(); public static CpuStats getTotalCpuStats(){
} update();
/** return cpuTotal;
* @return the time at which the system booted, in seconds since the Unix epoch. }
*/ public static Iterator<CpuStats> getCpuStats(){
public static long getUptime(){ update();
update(); return cpus.iterator();
return uptime; }
} /**
/** * @return the time at which the system booted, in seconds since the Unix epoch.
* @return the number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls. */
*/ public static long getUptime(){
public static long getProcesses(){ update();
update(); return uptime;
return processes; }
} /**
* @return the number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls.
*/
public static long getProcesses(){
public static class CpuStats { update();
// normal processes executing in user mode return processes;
private long user; }
// processes executing in kernel mode
private long system;
// twiddling thumbs
private long idle; public static class CpuStats {
// waiting for I/O to complete // normal processes executing in user mode
private long iowait; private long user;
private long steal; // processes executing in kernel mode
// virtual processes private long system;
private long guest; // twiddling thumbs
private long total; private long idle;
// waiting for I/O to complete
// Percentage private long iowait;
private float load_total; private long steal;
private float load_user; // virtual processes
private float load_system; private long guest;
private float load_iowait; private long total;
private float load_virtual;
// Percentage
protected CpuStats(){} private float load_total;
protected void update(String[] stats){ private float load_user;
long newUser=0, newNice=0, newSystem=0, newIdle=0, newIowait=0, newIrq=0, newSoftirq=0, newSteal=0, newGuest=0, newGuestNice=0; private float load_system;
if(stats.length >= 1+8){ private float load_iowait;
newUser = Long.parseLong(stats[1]); private float load_virtual;
newNice = Long.parseLong(stats[2]);
newSystem = Long.parseLong(stats[3]); protected CpuStats(){}
newIdle = Long.parseLong(stats[4]); protected void update(String[] stats){
newIowait = Long.parseLong(stats[5]); long newUser=0, newNice=0, newSystem=0, newIdle=0, newIowait=0, newIrq=0, newSoftirq=0, newSteal=0, newGuest=0, newGuestNice=0;
newIrq = Long.parseLong(stats[6]); if(stats.length >= 1+8){
newSoftirq = Long.parseLong(stats[7]); newUser = Long.parseLong(stats[1]);
if(stats.length >= 1+8+3){ newNice = Long.parseLong(stats[2]);
newSteal = Long.parseLong(stats[8]); newSystem = Long.parseLong(stats[3]);
newGuest = Long.parseLong(stats[9]); newIdle = Long.parseLong(stats[4]);
newGuestNice = Long.parseLong(stats[10]); newIowait = Long.parseLong(stats[5]);
} newIrq = Long.parseLong(stats[6]);
newSoftirq = Long.parseLong(stats[7]);
// Summarize if(stats.length >= 1+8+3){
newUser = newUser + newNice - newGuest - newGuestNice; newSteal = Long.parseLong(stats[8]);
newSystem = newSystem + newIrq + newSoftirq; newGuest = Long.parseLong(stats[9]);
newGuest = newGuest + newGuestNice; newGuestNice = Long.parseLong(stats[10]);
}
// Calculate the diffs
long userDiff = newUser - user; // Summarize
long idleDiff = (newIdle + newIowait) - (idle + iowait); newUser = newUser + newNice - newGuest - newGuestNice;
long systemDiff = newSystem - system; newSystem = newSystem + newIrq + newSoftirq;
long stealDiff = newSteal - steal; newGuest = newGuest + newGuestNice;
long virtualDiff = newGuest - guest;
long newTotal = userDiff + systemDiff + idleDiff + stealDiff + virtualDiff; // Calculate the diffs
// Calculate load long userDiff = newUser - user;
load_total = (float)(newTotal-idleDiff)/newTotal; long idleDiff = (newIdle + newIowait) - (idle + iowait);
load_user = (float)userDiff/newTotal; long systemDiff = newSystem - system;
load_system = (float)systemDiff/newTotal; long stealDiff = newSteal - steal;
load_iowait = (float)(newIowait - iowait)/newTotal; long virtualDiff = newGuest - guest;
load_virtual = (float)virtualDiff/newTotal; long newTotal = userDiff + systemDiff + idleDiff + stealDiff + virtualDiff;
// Calculate load
// update old values load_total = (float)(newTotal-idleDiff)/newTotal;
user = newUser; load_user = (float)userDiff/newTotal;
system = newSystem; load_system = (float)systemDiff/newTotal;
idle = newIdle; load_iowait = (float)(newIowait - iowait)/newTotal;
iowait = newIowait; load_virtual = (float)virtualDiff/newTotal;
steal = newSteal;
guest = newGuest; // update old values
total = newTotal; user = newUser;
} system = newSystem;
} idle = newIdle;
iowait = newIowait;
public float getTotalLoad() { steal = newSteal;
return load_total; guest = newGuest;
} total = newTotal;
public float getUserLoad() { }
return load_user; }
}
public float getSystemLoad() { public float getTotalLoad() {
return load_system; return load_total;
} }
public float getIOWaitLoad() { public float getUserLoad() {
return load_iowait; return load_user;
} }
public float getVirtualLoad() { public float getSystemLoad() {
return load_virtual; return load_system;
} }
public float getIOWaitLoad() {
} return load_iowait;
}
public static void main(String[] args){ public float getVirtualLoad() {
while(true){ return load_virtual;
Iterator<CpuStats> it = ProcStat.getCpuStats(); }
for(int i=0; it.hasNext(); ++i){
CpuStats cpu = it.next(); }
System.out.print("CPU"+i+": " + cpu.getTotalLoad()+ " ");
} public static void main(String[] args){
System.out.println("Total Load: " + ProcStat.getTotalCpuStats().getTotalLoad()); while(true){
try{Thread.sleep(1000);}catch (Exception e){} Iterator<CpuStats> it = ProcStat.getCpuStats();
} for(int i=0; it.hasNext(); ++i){
} CpuStats cpu = it.next();
} System.out.print("CPU"+i+": " + cpu.getTotalLoad()+ " ");
}
System.out.println("Total Load: " + ProcStat.getTotalCpuStats().getTotalLoad());
try{Thread.sleep(1000);}catch (Exception e){}
}
}
}

View file

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

View file

@ -22,9 +22,11 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal; package zutil.osal.macos;
import com.mysql.jdbc.NotImplemented; import com.mysql.jdbc.NotImplemented;
import zutil.osal.HardwareAbstractionLayer;
import zutil.osal.OSAbstractionLayer;
import java.io.File; import java.io.File;

View file

@ -1,73 +1,76 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.osal; package zutil.osal.windows;
import java.io.File; import zutil.osal.HardwareAbstractionLayer;
import zutil.osal.OSAbstractionLayer;
/**
* Windows platform specific implementation import java.io.File;
*/
public class OsalWindowsImpl extends OSAbstractionLayer { /**
* Windows platform specific implementation
@Override */
public OSType getOSType() { public class OsalWindowsImpl extends OSAbstractionLayer {
return OSType.Windows;
} @Override
public OSType getOSType() {
@Override return OSType.Windows;
public String getOSVersion() { }
throw new UnsupportedOperationException();
} @Override
public String getOSVersion() {
@Override throw new UnsupportedOperationException();
public String getKernelVersion() { }
try {
return getFirstLineFromExec("ver"); @Override
} catch (Exception e) { public String getKernelVersion() {
e.printStackTrace(); try {
} return getFirstLineFromExec("ver");
return null; } catch (Exception e) {
} e.printStackTrace();
}
@Override return null;
public String getUsername() { }
throw new UnsupportedOperationException();
} @Override
public String getUsername() {
@Override throw new UnsupportedOperationException();
public File getUserConfigPath() { }
throw new UnsupportedOperationException();
} @Override
public File getUserConfigPath() {
@Override throw new UnsupportedOperationException();
public File getGlobalConfigPath() { }
throw new UnsupportedOperationException();
} @Override
public File getGlobalConfigPath() {
@Override throw new UnsupportedOperationException();
public HardwareAbstractionLayer getHAL() { }
throw new UnsupportedOperationException();
} @Override
} public HardwareAbstractionLayer getHAL() {
throw new UnsupportedOperationException();
}
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,58 @@
package zutil.osal.linux.app;
import org.junit.Test;
import zutil.io.StringInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import static org.junit.Assert.*;
/**
* Created by ezivkoc on 2016-09-30.
*/
public class ProcNetArpTest {
@Test
public void parse() throws Exception {
StringInputStream buff = new StringInputStream(
"IP address HW type Flags HW address Mask Device\n" +
"192.168.1.140 0x1 0x0 fc:f8:ae:3f:66:64 * eth0\n" +
"169.254.67.249 0x1 0x0 78:ab:bb:c4:05:b3 * eth0\n" +
"192.168.1.127 0x1 0x2 00:05:cd:39:aa:07 * eth0\n" +
"192.168.1.1 0x1 0x2 c0:56:27:c2:5e:82 * eth0\n" +
"192.168.1.190 0x1 0x0 fc:f8:ae:3f:66:64 * eth0\n" +
"192.168.1.253 0x1 0x0 00:00:00:00:00:00 * eth0\n" +
"192.168.1.105 0x1 0x2 24:0a:64:49:c9:7b * eth0\n" +
"192.168.1.110 0x1 0x0 00:00:00:00:00:00 * eth0\n" +
"192.168.1.2 0x1 0x0 00:00:00:00:00:00 * eth0\n" +
"192.168.1.137 0x1 0x2 78:ab:bb:c4:05:b3 * eth0\n" +
"192.168.1.128 0x1 0x2 6c:ad:f8:be:ef:ba * eth0\n" +
"192.168.1.30 0x1 0x0 00:00:00:00:00:00 * eth0\n" +
"192.168.1.12 0x1 0x0 00:00:00:00:00:00 * eth0\n" +
"192.168.1.178 0x1 0x2 6c:ad:f8:be:ef:ba * eth0\n");
ProcNetArp.parse(new BufferedReader(new InputStreamReader(buff)));
ProcNetArp.ArpEntry entry = ProcNetArp.getArpEntry(InetAddress.getByName("192.168.1.140"));
assertEquals("192.168.1.140", entry.getIp().getHostAddress());
assertEquals("fc:f8:ae:3f:66:64", entry.getHwAddressString());
assertEquals("eth0", entry.getNetworkInterface());
entry = ProcNetArp.getArpEntry(InetAddress.getByName("192.168.1.1"));
assertEquals("192.168.1.1", entry.getIp().getHostAddress());
assertEquals("c0:56:27:c2:5e:82", entry.getHwAddressString());
assertEquals("eth0", entry.getNetworkInterface());
entry = ProcNetArp.getArpEntry(InetAddress.getByName("192.168.1.178"));
assertEquals("192.168.1.178", entry.getIp().getHostAddress());
assertEquals("6c:ad:f8:be:ef:ba", entry.getHwAddressString());
assertEquals("eth0", entry.getNetworkInterface());
}
@Test
public void parseTwoTimes() throws Exception {
parse();
parse();
}
}