package com.sbsr.netty.tools;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.sbsr.netty.constants.ServerConstant;
import com.sbsr.netty.model.ClientMachineInfo;
import com.sbsr.netty.tools.shell.OutMessage;
import com.sbsr.netty.tools.shell.ShellExecutor;
public class ToolBusiness {
/**
* 获取客户端节点 硬件信息 及 使用信息
*
* @throws IOException
*
*/
public static ClientMachineInfo getClientMachineInfo() throws IOException {
String cmd = ServerConstant.SHELL_PROP.get("checkclientInfo_shell_url");
OutMessage outMessage = ShellExecutor.exeLocalShell(cmd);
ClientMachineInfo cmi = new ClientMachineInfo();
if (outMessage.getRet() == 0) {
String retStr = outMessage.getOutStr();
BufferedReader in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(retStr.getBytes())));
String str = "";
List<String> list = new ArrayList<String>();
try {
int i = 1;
while ((str = in.readLine()) != null) {
// 操作系统类型
if (i == 1) {
sysInfoHandle(str, cmi);
}
// 磁盘IO读写速率
if (i == 3) {
diskHandle(str, cmi);
}
// CPU 型号
if (i == 5) {
cpuTypeHandle(str, cmi);
}
// 任务信息
if (i == 7) {
taskInfoHandle(str, cmi);
}
// CPU信息
if (i == 8) {
cpuInfoHandle(str, cmi);
}
// 内存信息
if (i == 9) {
memInfoHandle(str, cmi);
}
// 磁盘使用信息
if (i > 11) {
list.add(str);
}
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
// 磁盘使用信息处理
diskUsedHandle(list, cmi);
}
return cmi;
}
// 操作系统类型
private static void sysInfoHandle(String str, ClientMachineInfo cmi) {
String[] arr = str.split("\\s+");
cmi.setOs(arr[0]);
}
// 磁盘IO读写速率
private static void diskHandle(String str, ClientMachineInfo cmi) {
String[] arr = str.split("\\s+");
// cmi.setDiskRead(arr[2] + " kb/s");
// cmi.setDiskWrite(arr[3] + " kb/s");
cmi.setDiskRead(arr[2]);
cmi.setDiskWrite(arr[3]);
}
// CPU型号
private static void cpuTypeHandle(String str, ClientMachineInfo cmi) {
String[] arr = str.split(ServerConstant.SPLIT_COLON);
cmi.setCpuType(arr[1].trim());
}
// 任务信息处理
private static void taskInfoHandle(String str, ClientMachineInfo cmi) {
String[] arr = null;
String[] childArr = null;
arr = str.substring("Tasks:".length(), str.length()).split(ServerConstant.SPLIT_COMMA);
for (String s : arr) {
childArr = s.trim().split(ServerConstant.SPLIT_SPACE);
if ("total".toUpperCase().equals(childArr[1].toUpperCase())) {
cmi.setTaskTotal(Integer.parseInt(childArr[0]));
if (Integer.parseInt(childArr[0]) > cmi.getTaskMax()) {
cmi.setTaskMax(Integer.parseInt(childArr[0]));
}
if (0 == cmi.getTaskMin() || Integer.parseInt(childArr[0]) < cmi.getTaskMin()) {
cmi.setTaskMin(Integer.parseInt(childArr[0]));
}
}
}
}
// Cpu信息处理
private static void cpuInfoHandle(String str, ClientMachineInfo cmi) {
String[] arr = str.substring("%Cpu(s):".length(), str.length()).split(ServerConstant.SPLIT_COMMA);
String[] childArr = null;
for (String s : arr) {
childArr = s.trim().split(ServerConstant.SPLIT_SPACE);
if ("id".toUpperCase().equals(childArr[1].toUpperCase())) {
cmi.setCpuRate((float) (Math.round((100 - Float.parseFloat(childArr[0])) * 100)) / 100 + "%");
}
}
}
// 内存信息处理
private static void memInfoHandle(String str, ClientMachineInfo cmi) {
String[] arr = str.substring("KiB Mem :".length(), str.length()).split(ServerConstant.SPLIT_COMMA);
String[] childArr = null;
float total = 0;
float used = 0;
for (String s : arr) {
childArr = s.trim().split(ServerConstant.SPLIT_SPACE);
if ("total".toUpperCase().equals(childArr[1].toUpperCase())) {
total = Integer.parseInt(childArr[0].trim().substring(0, childArr[0].trim().length() - 1));
float t = total * 10 / (1000 * 1000);
cmi.setRam(String.format("%.0f", t) + " G");
} else if ("used".toUpperCase().equals(childArr[1].toUpperCase())) {
used = Integer.parseInt(childArr[0].trim().substring(0, childArr[0].trim().length() - 1));
float t = 100 * used / total;
cmi.setRamRate(String.format("%.01f", t) + ServerConstant.SPLIT_PERCENT);
}
}
}
// 磁盘使用信息处理
private static void diskUsedHandle(List<String> list, ClientMachineInfo cmi) {
int total = 0;
float usedisk = 0;
String dw = "";
for (int j = 0; j < list.size(); j++) {
String str = list.get(j);
if (!(str.indexOf("tmpfs") > -1 || str.indexOf("devtmpfs") > -1)) {
String[] arr = str.split("\\s+");
total += Float.parseFloat(arr[1].substring(0, arr[1].length() - 1));
dw = arr[2].substring(arr[2].length() - 1, arr[2].length());
if (dw.equals("M") || dw.equals("m")) {
usedisk += Float.parseFloat(arr[2].substring(0, arr[2].length() - 1)) / 1000;
} else {
if (ToolValid.isNotEmpty(arr[2].substring(0, arr[2].length() - 1))) {
usedisk += Float.parseFloat(arr[2].substring(0, arr[2].length() - 1));
}
}
}
}
cmi.setDisk(total + " G");
cmi.setUseDisk(String.format("%.0f", 100 * usedisk / total) + ServerConstant.SPLIT_PERCENT);
}
}
对应脚本:
iostat -d -k | grep 'Linux\|Device\|sda';
echo '';
cat /proc/cpuinfo | grep 'model name' |uniq;
echo '';
top -b -n 1 | grep 'Tasks\|%Cpu(s)\|KiB Mem';
echo '';
df -H
对应实体:
package com.sbsr.netty.model;
import java.io.Serializable;
import lombok.Data;
@Data
public class ClientMachineInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
/**
* 客户端 硬件信息
*/
private String os; // 操作系统
private String cpuType; // cpu型号
private String ram; // 内存容量
private String disk; // 硬盘容量
/**
* 客户端 使用信息
*/
private String cpuRate; // cpu使用率
private String ramRate; // 内存使用率
private String useDisk; // 硬盘使用率
private int taskTotal; // 进程总数
private int taskMin; // 最小进程数
private int taskMax; // 最大进程数
private String inSite; // 入栈速度
private String outSite; // 出栈速度
private String diskRead; // 硬盘读速度
private String diskWrite; // 硬盘写速度
private String flow;// 流量
}
2021-03-03 完善
注:上述JAVA计算的代码中存在些许计算失误及问题,但在此处不做修改。
由于以上JAVA计算方式的繁琐及效率低下,因而优化为由JAVA调用脚本获取。
#!/bin/bash
getHelp(){
echo "
日期: 2020-10-18
作者: shilei
功能: 执行获取操作系统相关硬件信息
系统: Centos 7.5(Docker)
--------------------------------------------
必要属性介绍:
必要属性:参考脚本代码上方注释。
执行脚本传参说明:
(1)操作系统型号
(2)磁盘IO读写速率
(3)CPU型号、CPU使用率
(4)任务进程总数
(5)内存容量、内存使用率
(6)硬盘容量、硬盘使用率
help: 该脚本基本信息、使用说明
示例:
bash check_clientInfo.sh.sh help
bash check_clientInfo.sh.sh 1
bash check_clientInfo.sh.sh 2
"
}
# 宿主机IP
#hostIp=`cat /opt/build/hostIp`;
# 宿主机用户信息
#userInfo=`cat /opt/build/userInfo`;
#OLD_IFS="$IFS"
#IFS=" "
#arr=($userInfo)
#user=${arr[0]}
#freeRef=$user@$hostIp;
os="";
getOS(){
#os=`ssh $freeRef "iostat -d -k" | grep 'Linux' | awk '{print $1" "$2 }'`;
os=`iostat -d -k | grep 'Linux' | awk '{print $1" "$2 }'`;
}
diskRead="";
diskWrite="";
getReadWrite(){
#readWrite=`ssh $freeRef "iostat -d -k" | grep 'sda'`;
readWrite=`iostat -d -k | grep 'sda'`;
diskRead=`echo $readWrite | awk '{print $3 }'`;
diskWrite=`echo $readWrite | awk '{print $4 }'`;
}
cpuType="";
cpuRate="";
getCpuInfo(){
# CPU型号
#cpuType=`ssh $freeRef "cat /proc/cpuinfo" | grep 'model name' | awk "NR==1"`;
cpuType=`cat /proc/cpuinfo | grep 'model name' | awk "NR==1"`;
cpuType=${cpuType#*:};
# CPU使用率
#cpuInfo=`ssh $freeRef "top -b -n 1" | grep '%Cpu(s)'`;
cpuInfo=`top -b -n 1 | grep '%Cpu(s)'`;
cpuInfo=${cpuInfo% id,*}
cpuInfo=${cpuInfo#*ni,}
cpuRate=$cpuInfo'%';
}
taskTotal="";
getTasks(){
#taskTotal=`ssh $freeRef "top -b -n 1" | grep 'Tasks' | awk '{print $2 }'`;
taskTotal=`top -b -n 1 | grep 'Tasks' | awk '{print $2 }'`;
}
ram="";
ramRate="";
getMeminfo(){
#meminfo=`ssh $freeRef "top -b -n 1" | grep 'KiB Mem'`;
meminfo=`top -b -n 1 | grep 'KiB Mem'`;
ram=`echo $meminfo | awk '{print $4 }'`;
use=`echo $meminfo | awk '{print $8 }'`;
ramRate=`awk 'BEGIN{printf "%.2f\n",'$use'/'$ram'*100}'`'%';
ram=$(awk "BEGIN{printf \"%.2f\n\",$ram/1000/1000}")'G';
}
disk="";
useDisk="";
getDisk(){
#diskinfo=`ssh $freeRef "df -B 1g" | grep -v tmpfs | awk "NR>1"`;
diskinfo=`df -B 1g | grep -v tmpfs | awk "NR>1"`;
totalInfo=`echo $diskinfo | awk '{print $2 }' | tr '\n' ' '`;
useInfo=`echo $diskinfo | awk '{print $3 }' | tr '\n' ' '`;
# 总数
total=0;
for i in $totalInfo; do
let total+=$i;
done;
# 已使用
use=0;
for i in $useInfo; do
let use+=$i;
done;
useDisk=`awk 'BEGIN{printf "%.2f\n",'$use'/'$total'*100}'`'%';
disk=$total'G';
}
type=$1
getClientInfo(){
getOS
getReadWrite
getCpuInfo
getTasks
getMeminfo
getDisk
if [[ $type == '' ]]; then
jsonStr='{"os":"'$os'","diskRead":"'$diskRead'","diskWrite":"'$diskWrite'","cpuType":"'$cpuType'","cpuRate":"'$cpuRate'","taskTotal":"'$taskTotal'","ram":"'$ram'","ramRate":"'$ramRate'","disk":"'$disk'","useDisk":"'$useDisk'"}';
echo $jsonStr
elif [[ $type == '1' ]];then
echo $os
elif [[ $type == '2' ]];then
echo $diskRead
echo $diskWrite
elif [[ $type == '3' ]];then
echo $cpuType
echo $cpuRate
elif [[ $type == '4' ]];then
echo $taskTotal
elif [[ $type == '5' ]];then
echo $ram
echo $ramRate
elif [[ $type == '6' ]];then
echo $disk;
echo $useDisk
else
getHelp
fi
}
getClientInfo
#ssh $freeRef "iostat -d -k | grep 'Linux\|Device\|sda'; echo '';cat /proc/cpuinfo | grep 'model name' | uniq; echo '';top -b -n 1 | grep 'Tasks\|%Cpu(s)\|KiB Mem'; echo '';";
#ssh $freeRef "df -B 1g | grep -v tmpfs";