commit 1f6df320923e306d673a0f7525babc030000189e
Author: songtianlun
Date: Tue Dec 20 17:31:11 2022 +0800
clean and init practice repo
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..85f3cc3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+.vscode
+.DS_Store
+*.swp
+.idea
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..aff8fd8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,19 @@
+# Dev Practice
+
+- `compress` : a way to compress
+- cpp: Some demo for c++
+- gcc: Study gcc
+- glog: a example to glog in use
+- go: some demo fo go
+- makefile_1: some demo for c project
+- mult-progress: some demo for mult progress
+- multthread: some demo for mult thread
+- python: some demo fo python
+- socket: some demo for socket connect
+- Switch_DEMO: some demo for Switch
+- system-test: some demo for system in use
+- tcp: some demo for tcp connect
+- tcp_relay-master: a github project for tcp
+- test: some demo
+- zmq: some demo for zmq
+- system_status: get system status use the C
diff --git a/sftp-config.json b/sftp-config.json
new file mode 100644
index 0000000..0a651cc
--- /dev/null
+++ b/sftp-config.json
@@ -0,0 +1,45 @@
+{
+ // The tab key will cycle through the settings when first created
+ // Visit https://codexns.io/products/sftp_for_subime/settings for help
+
+ // sftp, ftp or ftps
+ "type": "sftp",
+
+ "save_before_upload": true,
+ "upload_on_save": false,
+ "sync_down_on_open": false,
+ "sync_skip_deletes": false,
+ "sync_same_age": true,
+ "confirm_downloads": false,
+ "confirm_sync": true,
+ "confirm_overwrite_newer": false,
+
+ "host": "192.168.5.129",
+ "user": "root",
+ "password": "wuzhou@stl",
+ //"port": "22",
+
+ "remote_path": "/root/dev-go/",
+ "ignore_regexes": [
+ "\\.sublime-(project|workspace)", "sftp-config(-alt\\d?)?\\.json",
+ "sftp-settings\\.json", "/venv/", "\\.svn/", "\\.hg/", "\\.git/",
+ "\\.bzr", "_darcs", "CVS", "\\.DS_Store", "Thumbs\\.db", "desktop\\.ini"
+ ],
+ //"file_permissions": "664",
+ //"dir_permissions": "775",
+
+ //"extra_list_connections": 0,
+
+ "connect_timeout": 30,
+ //"keepalive": 120,
+ //"ftp_passive_mode": true,
+ //"ftp_obey_passive_host": false,
+ //"ssh_key_file": "~/.ssh/id_rsa",
+ //"sftp_flags": ["-F", "/path/to/ssh_config"],
+
+ //"preserve_modification_times": false,
+ //"remote_time_offset_in_hours": 0,
+ //"remote_encoding": "utf-8",
+ //"remote_locale": "C",
+ //"allow_config_upload": false,
+}
diff --git a/study_clang/BitArithmetic/README.md b/study_clang/BitArithmetic/README.md
new file mode 100644
index 0000000..f258ec4
--- /dev/null
+++ b/study_clang/BitArithmetic/README.md
@@ -0,0 +1,8 @@
+# 位运算实现四则运算
+
+尝试进行各种情况下位运算实现的四则运算和原生四则运算的速度。
+
+## 结论
+
+- C程序下乘除2,位运算更快。
+- 其他情况下位运算提供的四则运算速度较慢。
diff --git a/study_clang/BitArithmetic/a.out b/study_clang/BitArithmetic/a.out
new file mode 100755
index 0000000..1e6b9b3
Binary files /dev/null and b/study_clang/BitArithmetic/a.out differ
diff --git a/study_clang/BitArithmetic/bitCal b/study_clang/BitArithmetic/bitCal
new file mode 100755
index 0000000..1e6b9b3
Binary files /dev/null and b/study_clang/BitArithmetic/bitCal differ
diff --git a/study_clang/BitArithmetic/bitCal.c b/study_clang/BitArithmetic/bitCal.c
new file mode 100644
index 0000000..1214e16
--- /dev/null
+++ b/study_clang/BitArithmetic/bitCal.c
@@ -0,0 +1,105 @@
+/*************************************************************************
+ > File Name: bitCal.c
+ > Author: TL Song
+ > Mail: songtianlun@frytea.com
+ > Created Time: Fri 28 Aug 2020 12:58:40 AM UTC
+ ************************************************************************/
+
+#include
+
+#include
+
+/*
+ *功能: 两个数相加
+ *@num1, @num2 加法的两个操作数
+ *返回值 : 两个num的相加后的值
+ */
+int Add(int num1, int num2)
+{
+ int exclusive_val = num1; //异或值
+ int carry_val = num2; //进位值
+
+ exclusive_val = num1 ^ num2; //取第一次异或值(没有进位的异或就是相加)
+ carry_val = (num1 & num2) << 1; //取第一次进位值
+
+ //进位值为0是循环终止条件
+ while (carry_val)
+ {
+ int temp = exclusive_val;
+ exclusive_val = exclusive_val ^ carry_val; //异或值与进位值进行异或
+ carry_val = (temp & carry_val) << 1;
+
+ }
+ return exclusive_val;
+}
+
+/*
+ *功能: 减法
+ *算法: A - B = A + B(补码) = A + (B反码 + 1) = A + (~B + 1)
+ *@num1, @num2; 减法的两个操作数
+ *返回值: 两个数的相减值
+ */
+int Sub(int num1, int num2)
+{
+ int temp = Add(~num2, 1); //取反与求补差1
+ return Add(num1, temp);
+}
+
+/*
+ *功能: 除法
+ *算法: A 除 B 的意义就是看A里有多少个B,可以通过A - B实现。
+ * A一直循环减B,直到结果小于0。循环的次数就是结果。
+ *@num1, @num2; 除法的两个操作数
+ *返回值: 两个数的相除值
+ */
+int div(int num1, int num2)
+{
+ int count = 0;
+ while (1)
+ {
+ if ((num1 = Sub(num1, num2)) < 0)
+ {
+ break;
+ }
+ count++;
+ }
+ return count;
+}
+
+/*
+*功能: 乘法
+*算法: A 乘 B 的意义就是A个B累加,定义一个累加器count = 1;
+* 可以通过循环A次累加B相加实现。
+*@num1, @num2; 乘法的两个操作数
+*返回值: 两个数的相乘值
+*/
+int mult(int num1, int num2)
+{
+ int count = 0;
+ int result = 0;
+ int temp = num2;
+ while (1)
+ {
+ if (num1 == count)
+ {
+ break;
+ }
+ result = Add(result, temp);
+ count++;
+ }
+ return result;
+}
+int main(void)
+{
+ int num1, num2;
+ while (1)
+ {
+ printf("请输入两个整数: \n");
+ scanf("%d%d", &num1, &num2);
+ printf("%d + %d = %d\n", num1, num2, Add(num1, num2));
+ printf("%d - %d = %d\n", num1, num2, Sub(num1, num2));
+ printf("%d * %d = %d\n", num1, num2, mult(num1, num2));
+ printf("%d / %d = %d\n", num1, num2, div(num1, num2));
+ }
+ return 0;
+}
diff --git a/study_clang/BitArithmetic/main b/study_clang/BitArithmetic/main
new file mode 100755
index 0000000..53a5b3b
Binary files /dev/null and b/study_clang/BitArithmetic/main differ
diff --git a/study_clang/BitArithmetic/main.cpp b/study_clang/BitArithmetic/main.cpp
new file mode 100644
index 0000000..29fb929
--- /dev/null
+++ b/study_clang/BitArithmetic/main.cpp
@@ -0,0 +1,209 @@
+/*************************************************************************
+ > File Name: main.c
+ > Author: TL Song
+ > Mail: songtianlun@frytea.com
+ > Created Time: Thu 27 Aug 2020 12:08:59 PM UTC
+ ************************************************************************/
+
+#include
+#include
+#include
");
+ return 0;
+ }
+ fscanf(fp,"%s %s %s %s",pcip,task_name,cmanager,manprocess);
+ fclose(fp);
+ while(1)
+ {
+ printf("process num is %s %s %s",task_name,cmanager,manprocess);
+ sleep(1);
+ }
+ pthread_t history_cmd,filecharge,filenumcharge,homenumcharge;
+ Msgreport mesgreport;
+ stProcessState processstate;
+ stFileNum pathreport;
+ stLogMsg syslogreport,commendlog;
+ //syslogreport = (stLogMsg*)malloc(sizeof(stLogMsg)+1);
+ memset(&syslogreport,0, sizeof(stLogMsg));
+ void * ctx = zmq_ctx_new();
+ fb_assert(ctx, "create zmq context faild");
+
+ void *sock = zmq_socket(ctx, ZMQ_REQ);
+ fb_assert(sock, "create zmq socket faild");
+
+ char szaddr[128] = "\0";
+ snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
+
+ {//加密相关代码
+ char szmsg[1024] = {0};
+ //此密钥为服务端产生的公钥
+ strcpy(szmsg, "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE");
+ zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szmsg, strlen(szmsg));
+
+ char szpubkey[64] = {0};
+ char szprikey[64] = {0};
+ zmq_curve_keypair(szpubkey, szprikey);
+ zmq_setsockopt(sock, ZMQ_CURVE_PUBLICKEY, szpubkey, strlen(szpubkey));
+ zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szprikey, strlen(szprikey));
+ }
+
+ zmq_connect(sock, szaddr);
+
+
+ int count = 0;
+
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+
+ // getchar();
+ // sleep(1);
+ err = pthread_create(&history_cmd, NULL, get_historycmd, (void *)&pcip);
+ //printf("have come here");
+ err1 = pthread_create(&filecharge, NULL, monitorfile, (void *)&pcip);
+ err2 = pthread_create(&filenumcharge, NULL, monitorfilenum, (void *)&pcip);
+
+ err3 = pthread_create(&homenumcharge, NULL, monitorhomenum, (void *)&pcip);
+ int memory_have = 0;
+ CPU_OCCUPY cpu_stst1;
+ CPU_OCCUPY cpu_stst2;
+ int cpu;
+
+ while(1)
+ {
+
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+ // snprintf(szmsg, sizeof(szmsg), "I say %d", ++count);
+ // fb_debug("send msg : [%s]", szmsg);
+ // zmq_send(sock, szmsg, strlen(szmsg), 0);
+ // zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ // fb_debug("recv msg : [%s]", szmsg);
+
+ get_cpuoccupy((CPU_OCCUPY *)&cpu_stst1);
+ sleep(1);
+ get_cpuoccupy((CPU_OCCUPY *)&cpu_stst2);
+ cpu = cal_cpuoccupy((CPU_OCCUPY *)&cpu_stst1,(CPU_OCCUPY *)&cpu_stst2);
+ memory_have = 100*get_memoccupy();
+ // printf("1cpu usage:%.2f\%\n mem usage:%.2f\%\n",cpu,memory_have);
+ mesgreport.uiType = 1;
+ mesgreport.uiCpuRate = 100*cpu;
+ mesgreport.uiMemRate = memory_have;
+ stpcpy(mesgreport.szip,pcip);
+
+ //printf("2cpu usage:%.2f\%\n mem usage:%.2f\%\n",mesgreport.uiCpuRate,mesgreport.uiMemRate);
+ //printf("szip is:%s\n",mesgreport.szip);
+ mesgreport.uiCronNum = uiCronNum();
+ tcpnum = processnum_tcp();
+ //tcpnum = 10;
+
+ pronum = processnum();
+
+ mesgreport.uiTcpEstablishNum = tcpnum;
+ mesgreport.uiRunningProcessNum = pronum;
+ //printf("tcp and process is :%d and %d\n",tcpnum,pronum);
+ // judgecommend();
+ // judgelogin();
+ md5passwd = get_md5passwd();
+ printf("test PasswdMd5 is :%s\n",md5passwd);
+ // strcpy(mesgreport.szPasswdMd5,md5passwd);
+
+ memcpy(mesgreport.szPasswdMd5,md5passwd,strlen(md5passwd));
+ md5group = get_md5group();
+ memcpy(mesgreport.szGroupMd5,md5group,strlen(md5group));
+ gettimeofday(&mesgreport.stRcvTime,NULL);
+
+ zmq_send(sock, &mesgreport, sizeof(mesgreport), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ printf("mestype1 recv is %s\n",szmsg);
+ // printf("Type1 send ip is %s\n passmd5 is %s\n groupmd5 is %s\n cpurate is %d\n memrate is %d\n\n\n\n",mesgreport.szip,mesgreport.szPasswdMd5,mesgreport.szGroupMd5,mesgreport.uiCpuRate,mesgreport.uiMemRate);
+ pid = 0 ;
+ getPidByName(&pid, task_name);
+
+ if (pid > 0)
+ cpumemstate1 = 1;
+ else {
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,"cpumem");
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+
+ cmpid = 0;
+ getPidByName(&cmpid, cmanager);
+ printf("pid of top is %d\n\n",cmpid);
+ if (cmpid > 0)
+ cmstate1 = 1;
+ else{
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,"configmanage");
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ // printf("mestype2 recv is %s\n",szmsg);
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+ manpropid = 0;
+ getPidByName(&manpropid, manprocess);
+
+ if (manpropid > 0)
+ manpstate1 = 1;
+ else{
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,"manprocess");
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+
+
+
+ firestate1 = firewallcharge();
+ if (firestate1 == 1)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,"firewall");
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+ newloginnum = judgeiflogin();
+ // printf("newloginnum is %d\n",newloginnum);
+ if (newloginnum != lastloginnum)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ syslogreport = judgelogin(pcip);
+ // printf("log before send struct is %s \n",&commendlog.szMsg[0]);
+ zmq_send(sock, &syslogreport, sizeof(stLogMsg), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ // printf("mestype5 recv is %s\n",szmsg);
+ lastloginnum = newloginnum;
+ // printf("msg login type is %d\nip is %s\nfilename is %s\n ",syslogreport.uiType,syslogreport.szIp,syslogreport.szLogFile);
+ // printf("szMsg0 is %s\n",syslogreport.szMsg[0]);
+ // printf("szMsg1 is %s\n",syslogreport.szMsg[1]);
+ // printf("szMsg2 is %s\n",syslogreport.szMsg[2]);
+ // printf("szMsg3 is %s\n",syslogreport.szMsg[3]);
+ // printf("szMsg4 is %s\n",syslogreport.szMsg[4]);
+ }
+
+ newpathnum = reportpathnum();
+
+ if (newpathnum != lastpathnum)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ pathreport.uiType = 4;
+ stpcpy(pathreport.szIp,pcip);
+ stpcpy(pathreport.szPath,"path");
+ gettimeofday(&pathreport.stRcvTime,NULL);
+ pathreport.uiFileNum = newpathnum;
+ zmq_send(sock, &pathreport, sizeof(pathreport), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ lastpathnum = newpathnum;
+ printf("\n\npath receive is %s\n\n",szmsg);
+ }
+
+
+
+ }
+
+ zmq_close(sock);
+ zmq_ctx_term(ctx);
+ zmq_ctx_destroy(ctx);
+
+ return 0;
+ }
+
diff --git a/study_clang/Mimic/nos_monitor/cron.txt b/study_clang/Mimic/nos_monitor/cron.txt
new file mode 100644
index 0000000..11ae865
--- /dev/null
+++ b/study_clang/Mimic/nos_monitor/cron.txt
@@ -0,0 +1 @@
+no crontab for root
diff --git a/study_clang/Mimic/nos_monitor/crontab b/study_clang/Mimic/nos_monitor/crontab
new file mode 100644
index 0000000..8a75b6b
Binary files /dev/null and b/study_clang/Mimic/nos_monitor/crontab differ
diff --git a/study_clang/Mimic/nos_monitor/crontab.c b/study_clang/Mimic/nos_monitor/crontab.c
new file mode 100644
index 0000000..dddcbad
--- /dev/null
+++ b/study_clang/Mimic/nos_monitor/crontab.c
@@ -0,0 +1,60 @@
+#include "monitsys.h"
+
+void main(void)
+{
+ FILE *fd = NULL,*fp = NULL;
+ unsigned int cronum = 0;
+ char buff[128]="\0";
+ char buff1[]="no";
+
+ system("crontab -l > /root/cheng/cron.txt 2>&1");
+ system("chmod 777 /root/cheng/cron.txt");
+ fd = fopen("/root/cheng/cron.txt","r");
+
+
+ while(NULL != fgets(buff,sizeof(buff),fd))
+ {
+ cronum++;
+ continue;
+ }
+ if(cronum == 1)
+ {
+
+ // if(NULL==(fp = popen("crontab -l","r")))
+
+ // {
+ // fprintf(stdout,"execute crontab failed: ");
+ // return 0;
+ //}
+ fscanf(fd, "%s",buff);
+ buff[2]='\0';
+ if(strcmp(buff,buff1)==0)
+ printf("there is no date");
+ else
+
+ printf("there is date");
+
+ printf("data in buff is %s\n",buff);
+ }
+ // cronum = 0;
+ // printf("There is no date");
+
+ // if(NULL==(fd = popen("crontab -l","r")))
+
+ //{
+ // fprintf(stdout,"execute crontab failed: ");
+ //return 0;
+ //}
+
+
+ //fgets(buff,sizeof(buff),fd);
+// fscanf(fd, "%s",buff);
+ // pronum = atoi(buff);
+// if(buff[0] != 'n')
+
+ //printf("buff is %s \n ",buff);
+
+ fclose(fd);
+ return 0;
+}
+
diff --git a/study_clang/Mimic/nos_monitor/getpidstate b/study_clang/Mimic/nos_monitor/getpidstate
new file mode 100644
index 0000000..d4d70fe
Binary files /dev/null and b/study_clang/Mimic/nos_monitor/getpidstate differ
diff --git a/study_clang/Mimic/nos_monitor/getpidstate.c b/study_clang/Mimic/nos_monitor/getpidstate.c
new file mode 100644
index 0000000..5d963cf
--- /dev/null
+++ b/study_clang/Mimic/nos_monitor/getpidstate.c
@@ -0,0 +1,92 @@
+#include "monitsys.h"
+
+
+ void getPidByName(pid_t *pid, char *task_name)
+ {
+ DIR *dir;
+ struct dirent *ptr;
+ FILE *fp;
+ char filepath[50];
+ char cur_task_name[50];
+ char buf[BUF_SIZE];
+ dir = opendir("/proc");
+ if (NULL != dir)
+ {
+ while ((ptr = readdir(dir)) != NULL) //循环读取/proc下的每一个文件/文件夹
+ {
+ //如果读取到的是"."或者".."则跳过,读取到的不是文件夹名字也跳过
+ if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
+ continue;
+ if (DT_DIR != ptr->d_type)
+ continue;
+ sprintf(filepath, "/proc/%s/status", ptr->d_name);//生成要读取的文件的路径
+ fp = fopen(filepath, "r");
+ if (NULL != fp)
+ {
+ if( fgets(buf, BUF_SIZE-1, fp)== NULL )
+ {
+ fclose(fp);
+ continue;
+ }
+ sscanf(buf, "%*s %s", cur_task_name); //如果文件内容满足要求则打印路径的名字(即进程的PID)
+ if (!strcmp(task_name, cur_task_name))
+ {
+ sscanf(ptr->d_name, "%d", pid);
+ }
+ fclose(fp);
+ }
+ }
+ closedir(dir);
+ }
+ }
+
+ FILE *getshellvalue(char *pcmd)
+{
+ FILE * fstream = NULL;
+
+ if(NULL == (fstream = popen(pcmd,"r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return NULL;
+ }
+
+ //pcmd = "ls -trl | awk '{print $9}'";
+
+ return fstream;
+}
+
+
+int main(void)
+ {
+ pid_t fpid; //fpid表示fork函数返回的值
+ pid_t fpid1;
+
+ char pcip[50]="\0",task_name[50]="\0",cmanager[50]="\0";
+
+ FILE *fp = NULL;
+ fp = fopen ("/root/cheng/initip.ini", "r");
+ if(fp == NULL)
+ {
+ printf("open file:passwd.txt error
");
+ return 0;
+ }
+ // fscanf(fp,"%s %s %s %s",pcip,task_name,cmanager,manprocess);
+ fgets(pcip, sizeof(pcip), fp);
+ fgets(task_name, sizeof(task_name), fp);
+ fgets(cmanager, sizeof(cmanager), fp);
+ // fgets(manprocess, sizeof(manprocess), fp);
+ fclose(fp);
+ printf("name of task is %s\n",cmanager);
+ getPidByName(&pid, cmanager);
+ if (pid > 0)
+ {
+ printf("\nCapture dump function enable..\n");
+ printf("pid1:%d\n", pid);
+ }
+ else
+ {
+ printf("\nCapture dump function disable..\n");
+ printf("pid2:%d\n\n", pid);
+ }
+ return 0;
+ }
\ No newline at end of file
diff --git a/study_clang/Mimic/nos_monitor/login.txt b/study_clang/Mimic/nos_monitor/login.txt
new file mode 100644
index 0000000..e69de29
diff --git a/study_clang/Mimic/nos_monitor/monitsys b/study_clang/Mimic/nos_monitor/monitsys
new file mode 100755
index 0000000..a80e877
Binary files /dev/null and b/study_clang/Mimic/nos_monitor/monitsys differ
diff --git a/study_clang/Mimic/nos_monitor/monitsys.c b/study_clang/Mimic/nos_monitor/monitsys.c
new file mode 100644
index 0000000..2c9eee9
--- /dev/null
+++ b/study_clang/Mimic/nos_monitor/monitsys.c
@@ -0,0 +1,1363 @@
+#include "monitsys.h"
+
+//stLogMsg *syslogreport,commendlog;
+float cal_cpuoccupy(CPU_OCCUPY *o,CPU_OCCUPY *n)
+{
+ unsigned long od,nd;
+ unsigned long id,sd;
+ float cpu_use = 0;
+ od = (unsigned long)(o->user + o->nice + o->system + o->idle);
+ nd = (unsigned long)(n->user + n->nice + n->system + n->idle);
+ id = (unsigned long)(n->nice - o->nice);
+ sd = (unsigned long)(n->idle - o->idle);
+ if((nd-od) != 0)
+ cpu_use = (float)(((nd-od)-sd))*100/(nd-od);
+ else
+ cpu_use = 0;
+
+ return cpu_use;
+}
+
+int judgeiflogin()
+{
+ FILE *fd = NULL;
+ char buff[180],*num=NULL, *cmd=NULL,*cur,bu[180];
+ int i = 0,le = 0,newnum = 0, devalue = 0, t = 0, len = 0;
+ // system("who /var/log/wtmp | wc -l > /home/czl/tengswitch/login.txt");
+ // fd = fopen("/home/czl/tengswitch/login.txt","r");
+ if(NULL==(fd = popen(" who /var/log/wtmp | wc -l ","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return 0;
+ }
+
+ // fd = popen("history | tail -n 6","r");
+ fgets(buff,sizeof(buff),fd);
+ // printf("string in buff is:%s\n", buff);
+ // sscanf(buff,"%s %s",bu,&commendlog->szMsg[0][0]);
+ // printf("newnum in bu is :%s\n", bu);
+
+ newnum = atoi(buff);
+ printf("newnum in bu is :%d\n", newnum);
+ fclose(fd);
+ return newnum;
+}
+
+
+// stLogMsg *judgelogin()
+
+
+/*
+ void judgelogin()
+ {
+ FILE *fd;
+ memset(&commendlog,0,sizeof(stLogMsg));
+ // stLogMsg commendlog ;
+ // commendlog = (stLogMsg*)malloc(sizeof(stLogMsg));
+ // memset(commendlog,0, sizeof(stLogMsg));
+ commendlog.uiType = 5;
+ stpcpy(commendlog.szIp,"172.171.17.213");
+ gettimeofday(&commendlog.stRcvTime,NULL);
+ stpcpy(commendlog.szLogFile,"/log/wtmp");
+ char buff[180],*num=NULL, *cmd=NULL,*cur,bu[180];
+ int i = 0,le = 0,newnum = 0, devalue = 0, t = 0, len = 0;
+ // system("who /var/log/wtmp | wc -l > /home/czl/tengswitch/login.txt");
+ fd = fopen("/home/czl/tengswitch/login.txt","r");
+ // fd = popen("history | tail -n 6","r");
+ // fgets(buff,sizeof(buff),fd);
+ // printf("string in buff is:%s\n", buff);
+ // sscanf(buff,"%s %s",bu,&commendlog->szMsg[0][0]);
+ // printf("newnum in bu is :%s\n", bu);
+
+ // newnum = atoi(buff);
+
+ devalue = newloginnum - lastloginnum;
+
+ if (devalue > 5 || devalue < 0)
+ {
+ printf("devalue in loop1 is :%d\n", devalue);
+ //sprintf(cmd,"who /var/log/wtmp |",);
+ system("who /var/log/wtmp | tail -n 6 > /home/czl/tengswitch/login.txt");
+
+
+ fgets(buff,sizeof(buff),fd);
+ for(le=0;le < 5; le++)
+ {
+ buff[180] = '0';
+ // sscanf(buff,"%s",&commendlog->szMsg[0][le]);
+ fgets(buff,sizeof(buff),fd);
+ memcpy(&commendlog.szMsg[le],buff,strlen(buff));
+ //printf("size of buff is %d \n",sizeof(buff));
+ //printf("strlen of buff is %d \n",strlen(buff));
+ printf("log in 1struct is %s",&commendlog.szMsg[le]);
+
+ }
+ printf("have come here \n");
+ }
+ else if (devalue <= 5 || devalue > 0)
+ {
+
+ sprintf(bu,"who /var/log/wtmp | tail -n %d > /home/czl/tengswitch/login.txt",devalue+1);
+ //printf("bu is :%s\n", bu);
+
+
+ printf("devalue in loop2 is :%d\n", devalue);
+ // cmd =&bu[0];
+ //memcpy(cmd,bu,strlen(bu));
+ //printf("cmd is :%d\n", cmd);
+ system(bu);
+ fgets(buff,sizeof(buff),fd);
+
+ for(le=0; le < devalue; le++)
+ {
+ buff[180] = '0';
+ fgets(buff,sizeof(buff),fd);
+ memcpy(&commendlog.szMsg[le],buff,strlen(buff));
+ printf("log in 2 struct is %s \n",&commendlog.szMsg[le]);
+ }
+
+ }
+
+ // printf("newnum is :%d\n", newnum);
+ // return &commendlog;
+
+ fclose(fd);
+ // printf("end of loop\n");
+ // lastlognum = newnum;
+ }
+
+ */
+
+stLogMsg judgelogin(char *ip)
+{
+ stLogMsg getlogin;
+ // getlogin = (stLogMsg*)malloc(sizeof(stLogMsg));
+ FILE *fd;
+ // memset(&commendlog,0,sizeof(stLogMsg));
+ memset(&getlogin,0,sizeof(stLogMsg));
+ // stLogMsg commendlog ;
+ // commendlog = (stLogMsg*)malloc(sizeof(stLogMsg));
+ // memset(commendlog,0, sizeof(stLogMsg));
+ getlogin.uiType = 5;
+ stpcpy(getlogin.szIp,ip);
+ gettimeofday(&getlogin.stRcvTime,NULL);
+ stpcpy(getlogin.szLogFile,"login");
+ char buff[180],*num=NULL, *cmd=NULL,*cur,bu[180];
+ int i = 0,le = 0,newnum = 0, devalue = 0, t = 0, len = 0;
+ system("who /var/log/wtmp | wc -l > /root/monitor/login.txt");
+ fd = fopen("/root/monitor/login.txt","r");
+ // fd = popen("history | tail -n 6","r");
+ // fgets(buff,sizeof(buff),fd);
+ // printf("string in buff is:%s\n", buff);
+ // sscanf(buff,"%s %s",bu,&commendlog->szMsg[0][0]);
+ // printf("newnum in bu is :%s\n", bu);
+
+ // newnum = atoi(buff);
+ devalue = newloginnum - lastloginnum;
+
+ if (devalue > 5 || devalue < 0)
+ {
+ printf("devalue in loop1 is :%d\n", devalue);
+ //sprintf(cmd,"who /var/log/wtmp |",);
+ system("who /var/log/wtmp | tail -n 6 > /root/monitor/login.txt");
+ fgets(buff,sizeof(buff),fd);
+ for(le=0;le < 5; le++)
+ {
+ buff[180] = '0';
+ // sscanf(buff,"%s",&commendlog->szMsg[0][le]);
+ fgets(buff,sizeof(buff),fd);
+ memset(&getlogin.szMsg[le],0,sizeof(getlogin.szMsg[le]));
+ memcpy(&getlogin.szMsg[le],buff,strlen(buff));
+ //printf("size of buff is %d \n",sizeof(buff));
+ //printf("strlen of buff is %d \n",strlen(buff));
+ //printf("log in 1struct is %s",&getlogin->szMsg[le]);
+ }
+ //printf("have come here \n");
+ }
+ else if (devalue <= 5 || devalue > 0)
+ {
+ memset(&getlogin.szMsg[0],0,5*sizeof(getlogin.szMsg[le]));
+ sprintf(bu,"who /var/log/wtmp | tail -n %d > /root/monitor/login.txt",devalue+1);
+ //printf("bu is :%s\n", bu);
+
+ printf("devalue in loop2 is :%d\n", devalue);
+ // cmd =&bu[0];
+ //memcpy(cmd,bu,strlen(bu));
+ //printf("cmd is :%d\n", cmd);
+ system(bu);
+ fgets(buff,sizeof(buff),fd);
+
+ for(le=0; le < devalue; le++)
+ {
+ buff[180] = '0';
+ fgets(buff,sizeof(buff),fd);
+ memset(&getlogin.szMsg[le],0,sizeof(getlogin.szMsg[le]));
+ memcpy(&getlogin.szMsg[le],buff,strlen(buff));
+ //printf("log in 2 struct is %s \n",&getlogin->szMsg[le]);
+ }
+ }
+
+ // printf("newnum is :%d\n", newnum);
+ // printf("msg login in function type is %d\nip is %s\nfilename is %s\n ",getlogin->uiType,getlogin->szIp,getlogin->szLogFile);
+ // printf("szMsg0 is %s\n",getlogin->szMsg[0]);
+ // printf("szMsg1 is %s\n",getlogin->szMsg[1]);
+ // printf("szMsg2 is %s\n",getlogin->szMsg[2]);
+ // printf("szMsg3 is %s\n",getlogin->szMsg[3]);
+ // printf("szMsg4 is %s\n",getlogin->szMsg[4]);
+
+
+
+
+
+ fclose(fd);
+ return getlogin;
+
+ // lastlognum = newnum;
+ }
+
+ /*
+ void judgecommend()
+ {
+ stLogMsg *commendlog = NULL;//, *pst=NULL;
+ FILE *fd;
+ char buff[180],*num, *cmd,*cur,bu[180];
+ int i = 0,le = 0,newnum = 0, devalue = 0, t = 0, len = 0;
+ const char s[2] = " ";
+ commendlog = (stLogMsg*)malloc(sizeof(stLogMsg));
+ memset(commendlog,0, sizeof(stLogMsg));
+
+ //system("history | tail -n 6 > /home/czl/tengswitch/history.txt");
+ system("who /var/log/wtmp > /home/czl/tengswitch/history.txt");
+ while(1)
+ {
+
+ }
+ fd = fopen("/home/czl/tengswitch/history.txt","r");
+ // fd = popen("history | tail -n 6","r");
+ fgets(buff,sizeof(buff),fd);
+ printf("string in buff is:%s\n", buff);
+ sscanf(buff,"%s %s",bu,&commendlog->szMsg[0][0]);
+ // printf("newnum in bu is :%s\n", bu);
+
+ newnum = atoi(bu);
+ devalue = newnum - lastnum;
+ printf("devalue before loop is %d\n",devalue);
+ printf("begin to loop\n");
+ for(le = 0; le < 5; le++)
+ {
+ memset(commendlog,0, sizeof(stLogMsg));
+ buff[180] = '0';
+ fgets(buff,sizeof(buff),fd);
+ if(le < 5-devalue )
+ continue;
+ printf("%s\n", buff);
+ cur = &buff[0];
+ for(i=0;i<10;i++)
+ {
+ // printf("%d\n", i);
+ if (*cur == ' ')
+ t++;
+ if (t == 2)
+ num = ++cur;
+ if (t == 4)
+ {
+ cmd = ++cur;
+ break;
+ }
+ cur++;
+ }
+
+ // printf("%s\n", num);
+
+ printf("%s\n", cmd);
+ len =strlen(cmd);
+ memcpy(&commendlog->szMsg[0][le],cmd,len);
+
+ printf("string in struct is %s\n", &commendlog->szMsg[0][le]);
+ // printf("4%c\n", buff[3]);
+ // printf("5%c\n", buff[4]);
+ // printf("6%c\n", buff[5]);
+ // printf("7%c\n", buff[6]);
+ // printf("8%c\n", buff[7]);
+ // printf("9%c\n", buff[8]);
+ // num = strtok(buff,s);
+ //printf( "%s\n",num);
+
+ //cmd = strtok(NULL,s);
+ // strcpy(bu, strtok(NULL, " "));
+ // printf("%s\n", num);
+ //sscanf(buff,"%s %s",num, commendlog->szMsg[0][0]);
+ // pis =&commendlog[0];
+ // commendlog->uiType = 1;
+ // printf("%s %s\n", num , commendlog->szMsg[0][0]);
+ // printf("%d \n", commendlog->uiType);
+ }
+ fclose(fd);
+ printf("end of loop\n");
+ lastnum = newnum;
+ }
+*/
+void getPidByName(pid_t *pid, char *task_name)
+{
+ DIR *dir;
+ struct dirent *ptr;
+ FILE *fp;
+ char filepath[50];
+ char cur_task_name[50];
+ char buf[BUF_SIZE];
+ dir = opendir("/proc");
+ if (NULL != dir)
+ {
+ while ((ptr = readdir(dir)) != NULL) //循环读取/proc下的每一个文件/文件夹
+ {
+ //如果读取到的是"."或者".."则跳过,读取到的不是文件夹名字也跳过
+ if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
+ continue;
+ if (DT_DIR != ptr->d_type)
+ continue;
+ sprintf(filepath, "/proc/%s/status", ptr->d_name);//生成要读取的文件的路径
+ fp = fopen(filepath, "r");
+ if (NULL != fp)
+ {
+ if( fgets(buf, BUF_SIZE-1, fp)== NULL )
+ {
+ fclose(fp);
+ continue;
+ }
+ sscanf(buf, "%*s %s", cur_task_name); //如果文件内容满足要求则打印路径的名字(即进程的PID)
+ if (!strcmp(task_name, cur_task_name))
+ {
+ sscanf(ptr->d_name, "%d", pid);
+ }
+ fclose(fp);
+ }
+ }
+ closedir(dir);
+ }
+}
+
+
+void get_cpuoccupy(CPU_OCCUPY *cpust)
+{
+
+ FILE *fd;
+ int n;
+ char buff[256];
+ CPU_OCCUPY *cpu_occupy;
+ cpu_occupy = cpust;
+
+ fd = fopen("/proc/stat","r");
+
+ fgets(buff,sizeof(buff),fd);
+ sscanf(buff,"%s %u %u %u %u",cpu_occupy->name,&cpu_occupy->user,&cpu_occupy->nice,&cpu_occupy->system,&cpu_occupy->idle);
+ // printf("%s %u %u %u %u\n",cpu_occupy->name,cpu_occupy->user,cpu_occupy->nice,cpu_occupy->system,cpu_occupy->idle);
+ fclose(fd);
+}
+
+int firewallcharge()
+{
+ FILE *fd;
+ int n;
+ char buff[16];
+ char buff1[16];
+ // char buff2[16];
+ char buff2[16] = "active";
+ // system("systemctl status firewalld.service | grep Active > /home/czl/tengswitch/firewall.txt");
+ // system("chmod 777 firewall.txt");
+ //fd = fopen("/home/czl/tengswitch/firewall.txt","r");
+ // changed 20200813
+ if(NULL==(fd = popen("systemctl status firewalld.service | grep Active","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return 0;
+ }
+ //fgets(buff,sizeof(buff),fd);
+ fscanf(fd,"%s %s",buff,buff1);
+ // printf("%s %s\n",buff,buff1);
+ n = strcmp(buff1,buff2);
+ fclose(fd);
+ if( n == 0 )
+ {
+ //printf("firewall enable\n");
+ return 0;
+ }
+ else
+ {
+ //printf("firewall disable\n");
+ return 1;
+ }
+
+
+}
+
+
+unsigned int processnum()
+{
+
+ FILE *fd,*fd1;
+ unsigned int pronum;
+ char buff[16];
+ char buff1[16];
+
+ // system("ps -auxw | wc -l >/home/czl/tengswitch/process_num.txt");
+ //system("chmod 777 /home/czl/tengswitch/process_num.txt");
+ //fd = fopen("/home/czl/tengswitch/process_num.txt","r");
+
+ if(NULL==(fd = popen("ps -auxw | wc -l","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return 0;
+ }
+ if(fd == NULL)
+ {
+ printf("open file:process_num.txt error
");
+ exit(0);
+ }
+ ///fgets(buff,sizeof(buff),fd);
+ fscanf(fd,"%s",buff);
+ pronum = atoi(buff);
+ fclose(fd);
+ return pronum;
+}
+
+
+unsigned int uiCronNum()
+{
+ FILE *fd = NULL,*fp = NULL;
+ unsigned int cronum = 0;
+ char buff[128]="\0";
+ char buff1[]="no";
+
+ system("crontab -l > /root/monitor/cron.txt 2>&1");
+ system("chmod 777 /root/monitor/cron.txt");
+ fd = fopen("/root/monitor/cron.txt","r");
+ while(NULL != fgets(buff,sizeof(buff),fd))
+ {
+ cronum++;
+ continue;
+ }
+ if(cronum == 1)
+ {
+ fscanf(fd, "%s",buff);
+ buff[2]='\0';
+ if(strcmp(buff,buff1)==0)
+ {
+ printf("there is no date\n");
+ cronum = 0;
+ }
+ else
+ {
+ cronum = 1;
+ printf("there is date\n");
+ }
+ }
+ fclose(fd);
+ printf("num of crontask is %d\n",cronum);
+ return cronum;
+}
+
+
+unsigned int processnum_tcp()
+{
+
+ FILE *fd,*fd1;
+ unsigned int pronum,tcpnum;
+ char buff[16];
+ char buff1[16];
+ //netstat -an |grep 'ESTABLISHED' |grep 'tcp' |wc -l
+ // system("netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}' > /home/czl/tengswitch/processtcp.txt");
+ // system("chmod 777 /home/czl/tengswitch/processtcp.txt");
+ // fd = fopen("/home/czl/tengswitch/processtcp.txt","r");
+ if(NULL==(fd = popen(" netstat -an |grep 'ESTABLISHED' |grep 'tcp' |wc -l ","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return 0;
+ }
+ fscanf(fd,"%s %s",buff,buff1);
+ tcpnum = atoi(buff1);
+ // printf("%d\n",tcpnum);
+
+ fclose(fd);
+ return tcpnum;
+}
+
+
+
+double get_memoccupy()
+{
+ double memory_have = 0;
+ //system("free -m | grep Mem > memory.txt");
+ //system("chmod 777 memory.txt");
+ FILE * fp = NULL;
+ //fp = fopen ("memory.txt", "r");
+
+ if(NULL==(fp = popen("free -m | grep Mem","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return 0;
+ }
+
+ //if(fp == NULL)
+ //{
+ // printf("open file:memory.txt error
");
+ // return 0;
+ //}
+ char s1[20] = {0};
+ unsigned int total = 0;
+ unsigned int used = 0;
+ fscanf(fp, "%s %d %d", s1, &total, &used);
+ //printf("name: %s\n total:%d\n used:%d\n",s1,total,used);
+ fclose(fp);
+ fp = NULL;
+ memory_have = ((100 * used) / total);
+
+ return memory_have;
+}
+
+int get_md5passwd(char* md5sum)
+{
+ char md5num[128] = {0};
+ char filename[128] = {0};
+ int n;
+ // system("md5sum /etc/passwd > passwd.txt");
+ // system("chmod 777 passwd.txt");
+ FILE * fp = NULL;
+ // fp = fopen ("passwd.txt", "r");
+ // if(fp == NULL)
+ // {
+ // printf("open file:passwd.txt error
");
+ // return 0;
+ // }
+ if(NULL==(fp = popen("md5sum /etc/passwd","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return -1;
+ }
+ //fscanf(fp, "%s %s", md5sum, filename);
+ fread(md5num,1,sizeof(md5num),fp);
+ sscanf(md5num, "%s %s", md5sum, filename);
+ //printf("passwd md5num in function is: %s\n",md5num);
+ fclose(fp);
+ //md5num[32]='\0';
+ //n = strlen(md5num);
+ // printf("len of passwd is %d\n",n);
+ //fp = NULL;
+ return 0;
+}
+
+int get_md5group(char* md5group)
+{
+ char m_md5group[128] = {0};
+ char m_filename[128] = {0};
+ int n;
+ // system("md5sum /etc/passwd > passwd.txt");
+ // system("chmod 777 passwd.txt");
+ FILE * fp = NULL;
+ // fp = fopen ("passwd.txt", "r");
+ // if(fp == NULL)
+ // {
+ // printf("open file:passwd.txt error
");
+ // return 0;
+ // }
+ if(NULL==(fp = popen("md5sum /etc/group","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return -1;
+ }
+ //fscanf(fp, "%s %s", md5group, filename);
+ fread(m_md5group,1,sizeof(m_md5group),fp);
+ sscanf(m_md5group, "%s %s", md5group, m_filename);
+ //printf("passwd md5Group in function is: %s\n",md5group);
+ fclose(fp);
+ //md5num[32]='\0';
+ //n = strlen(md5num);
+ // printf("len of passwd is %d\n",n);
+ //fp = NULL;
+ return 0;
+}
+
+
+FILE *getshellvalue(char *pcmd)
+{
+ FILE * fstream = NULL;
+
+ if(NULL == (fstream = popen(pcmd,"r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return NULL;
+ }
+ //pcmd = "ls -trl | awk '{print $9}'";
+ return fstream;
+}
+
+void *get_historycmd(void *arg)
+{
+ int fd,wd,len,nread,i;
+ char buf[BUFSIZ];
+ struct inotify_event *event;
+ stLogMsg stlogmsg;
+ FILE * fnsteam = NULL;
+ const char *ip = "10.10.10.201";
+ int port = 7002;
+ char *pcip;
+ pcip = (char *)arg;
+
+ void * ctx = zmq_ctx_new();
+ fb_assert(ctx, "create zmq context faild");
+
+ void *sock = zmq_socket(ctx, ZMQ_REQ);
+ fb_assert(sock, "create zmq socket faild");
+
+ char szaddr[128] = {0};
+ char cmdbuff[128] = {0};
+ char cmd[128] = {0};
+ snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
+
+ {//加密相关代码
+ char szmsg[1024] = {0};
+ //此密钥为服务端产生的公钥
+ strcpy(szmsg, "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE");
+ zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szmsg, strlen(szmsg));
+
+ char szpubkey[64] = {0};
+ char szprikey[64] = {0};
+ zmq_curve_keypair(szpubkey, szprikey);
+ zmq_setsockopt(sock, ZMQ_CURVE_PUBLICKEY, szpubkey, strlen(szpubkey));
+ zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szprikey, strlen(szprikey));
+ }
+
+ zmq_connect(sock, szaddr);
+
+
+ int count = 0;
+
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+
+ fd = inotify_init();
+ if (fd < 0)
+ {
+ fprintf(stderr, "inotify_init failed\n");
+ return NULL;
+ }
+
+ //wd = inotify_add_watch(fd, "/home/czl/test", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //inotify_add_watch(fd, "/home/czl/tengswitch", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ wd = inotify_add_watch(fd, "/tmp/dbasky/root", IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO);
+ if (wd < 0)
+ {
+ fprintf(stderr, "inotify_add_watch %s failed\n", "/tmp/dbasky/root");
+ return NULL;
+ }
+
+ buf[sizeof(buf) - 1] = 0;
+ while ((len = read(fd, buf, sizeof(buf) - 1)) > 0)
+ {
+ nread = 0;
+ while (len > 0)
+ {
+ event = (struct inotify_event *)&buf[nread];
+ for (i = 0; imask >> i) & 1)
+ {
+ if (event->len > 0)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ bzero(cmdbuff, sizeof(cmdbuff));
+ //fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
+ stlogmsg.uiType = 5;
+
+ stpcpy(stlogmsg.szIp,pcip);
+ // stpcpy(stfilestate.szPath,"/home/czl/test");
+ gettimeofday(&stlogmsg.stRcvTime,NULL);
+ //stpcpy(stlogmsg.szLogFile,event->name);
+ stpcpy(stlogmsg.szLogFile,"history");
+ char text[128];
+ stpcpy(text,event->name);
+ if (text[0] != '.')
+ {
+ // zmq_send(sock, &stfilestate, sizeof(stFileState), 0);
+ // zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ printf("type is %d\n ip is %s\n filename is %s\n ",stlogmsg.uiType,stlogmsg.szIp,stlogmsg.szLogFile);
+ sprintf(cmd,"tac /tmp/dbasky/root/%s",event->name);
+ // printf("cmd in fprintf is %s",cmd);
+ fnsteam = getshellvalue(cmd);
+ count = 0;
+ while(NULL != fgets(cmdbuff,sizeof(cmdbuff),fnsteam))
+ {
+ // fgets(cmdbuff,sizeof(cmdbuff),fnsteam);
+
+ if (count< 5 )
+ {
+ stpcpy(stlogmsg.szMsg[count],cmdbuff);
+ printf("cmd in struct is %s\n",stlogmsg.szMsg[count]);
+ }
+ else
+ break;
+ count++;
+ }
+ zmq_send(sock, &stlogmsg, sizeof(stLogMsg), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, ZMQ_DONTWAIT);
+ printf("return of history cmd is %s\n",szmsg);
+ }
+ fclose(fnsteam);
+ // printf("mestype5 recv is %s\n",szmsg);
+ }
+ }
+ }
+ nread = nread + sizeof(struct inotify_event) + event->len;
+ len = len - sizeof(struct inotify_event) - event->len;
+ }
+ }
+
+ return 0;
+}
+void *monitorfile(void *arg)
+{
+ int fd,wd,len,nread,i;
+ char buf[BUFSIZ];
+ struct inotify_event *event;
+ stFileState stfilestate;
+ const char *ip = "10.10.10.201";
+ char *pcip;
+ pcip = (char *)arg;
+
+ int port = 7002;
+ void * ctx = zmq_ctx_new();
+ fb_assert(ctx, "create zmq context faild");
+
+ void *sock = zmq_socket(ctx, ZMQ_REQ);
+ fb_assert(sock, "create zmq socket faild");
+
+ char szaddr[128] = {0};
+ snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
+
+ {//加密相关代码
+ char szmsg[1024] = {0};
+ //此密钥为服务端产生的公钥
+ strcpy(szmsg, "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE");
+ zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szmsg, strlen(szmsg));
+
+ char szpubkey[64] = {0};
+ char szprikey[64] = {0};
+ zmq_curve_keypair(szpubkey, szprikey);
+ zmq_setsockopt(sock, ZMQ_CURVE_PUBLICKEY, szpubkey, strlen(szpubkey));
+ zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szprikey, strlen(szprikey));
+ }
+ zmq_connect(sock, szaddr);
+ int count = 0;
+
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+
+
+
+ fd = inotify_init();
+ if (fd < 0)
+ {
+ fprintf(stderr, "inotify_init failed\n");
+ return NULL;
+ }
+
+ //wd = inotify_add_watch(fd, "/home/czl/test", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //inotify_add_watch(fd, "/home/czl/tengswitch", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //wd = inotify_add_watch(fd, "/home/czl/test", IN_MODIFY);
+
+ wd = inotify_add_watch(fd, "/etc", IN_MODIFY);
+ inotify_add_watch(fd, "/etc/profile.d", IN_MODIFY);
+ inotify_add_watch(fd, "/etc/rc.d/init.d", IN_MODIFY);
+ //inotify_add_watch(fd, "/etc/rc.local", IN_MODIFY);
+ if (wd < 0)
+ {
+ fprintf(stderr, "inotify_add_watch %s failed\n", "/etc");
+ return NULL;
+ }
+
+ buf[sizeof(buf) - 1] = 0;
+ while ((len = read(fd, buf, sizeof(buf) - 1)) > 0)
+ {
+ nread = 0;
+ while (len > 0)
+ {
+ event = (struct inotify_event *)&buf[nread];
+ for (i = 0; imask >> i) & 1)
+ {
+ if (event->len > 0)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ //fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
+ stfilestate.uiType = 3;
+
+ stpcpy(stfilestate.szIp,pcip);
+ // stpcpy(stfilestate.szPath,"/home/czl/test");
+ gettimeofday(&stfilestate.stRcvTime,NULL);
+ stpcpy(stfilestate.szFileName,event->name);
+ if (stfilestate.szFileName[0] != '.')
+ {
+ zmq_send(sock, &stfilestate, sizeof(stFileState), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, ZMQ_DONTWAIT);
+ printf("modify event happend\n");
+ printf("file changed \n type is %d\n ip is %s\n filename is %s\n ",stfilestate.uiType,stfilestate.szIp,stfilestate.szFileName);
+ }
+
+ // printf("mestype5 recv is %s\n",szmsg);
+
+ }
+ }
+ }
+ nread = nread + sizeof(struct inotify_event) + event->len;
+ len = len - sizeof(struct inotify_event) - event->len;
+ }
+ }
+ return 0;
+}
+
+void *monitorfilenum(void *arg)
+{
+ int fd,wd,len,nread,i;
+ char buf[BUFSIZ],num[10];
+ struct inotify_event *event;
+ stFileNum stfilenum;
+ FILE* fp = NULL;
+ // if (argc < 2)
+ // {
+ // fprintf(stderr, "%s path\n", argv[0]);
+ // return -1;
+ //}
+ char *pcip;
+ pcip = (char *)arg;
+
+ const char *ip = "10.10.10.201";
+ int port = 7002;
+ void * ctx = zmq_ctx_new();
+ fb_assert(ctx, "create zmq context faild");
+
+ void *sock = zmq_socket(ctx, ZMQ_REQ);
+ fb_assert(sock, "create zmq socket faild");
+
+ char szaddr[128] = {0};
+ snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
+
+ {//加密相关代码
+ char szmsg[1024] = {0};
+ //此密钥为服务端产生的公钥
+ strcpy(szmsg, "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE");
+ zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szmsg, strlen(szmsg));
+
+ char szpubkey[64] = {0};
+ char szprikey[64] = {0};
+ zmq_curve_keypair(szpubkey, szprikey);
+ zmq_setsockopt(sock, ZMQ_CURVE_PUBLICKEY, szpubkey, strlen(szpubkey));
+ zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szprikey, strlen(szprikey));
+ }
+ zmq_connect(sock, szaddr);
+ int count = 0;
+
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+
+ fd = inotify_init();
+ if (fd < 0)
+ {
+ fprintf(stderr, "inotify_init failed\n");
+ return NULL;
+ }
+
+ wd = inotify_add_watch(fd, "/usr/local/sbin", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //inotify_add_watch(fd, "/home/czl/tengswitch", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //wd = inotify_add_watch(fd, "/home/czl/test", IN_MODIFY);
+ if (wd < 0)
+ {
+ fprintf(stderr, "inotify_add_watch %s failed\n", "/usr/local/sbin");
+ return NULL;
+ }
+
+ buf[sizeof(buf) - 1] = 0;
+ while ((len = read(fd, buf, sizeof(buf) - 1)) > 0)
+ {
+ nread = 0;
+ while (len > 0)
+ {
+ event = (struct inotify_event *)&buf[nread];
+ for (i = 0; imask >> i) & 1)
+ {
+ if (event->len > 0)
+ //fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
+ {
+
+ stpcpy(stfilenum.szFileName,event->name);
+ if (stfilenum.szFileName[0] != '.')
+ {
+ printf("num in test event happened \n");
+ bzero(szmsg, sizeof(szmsg));
+ stfilenum.uiType = 4;
+ stpcpy(stfilenum.szIp,pcip);
+ stpcpy(stfilenum.szPath,"/usr/local/sbin");
+ gettimeofday(&stfilenum.stRcvTime,NULL);
+ // system("ls -l /home/czl/test |grep '^-' |wc -l > /home/czl/tengswitch/filenum.txt");
+ // a = fopen("/home/czl/tengswitch/filenum.txt","r");
+ // if(a == NULL)
+ // {
+ // printf("open file:filenum.txt error
");
+ // exit(0);
+ // }
+
+ if(NULL==( fp = popen("ls -l /usr/local/sbin |grep '^-' |wc -l ","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return NULL;
+ }
+
+ fscanf(fp,"%s",num);
+ //printf("filenum charged is %s\n",num);
+ stfilenum.uiFileNum = atoi(num);
+ fclose(fp);
+
+ printf("type 4 root file num changed\n type is %d\n ip is %s\n path is %s\n filename is %s\n file num is %d\n\n\n\n",stfilenum.uiType,stfilenum.szIp,stfilenum.szPath,stfilenum.szFileName,stfilenum.uiFileNum);
+ zmq_send(sock, &stfilenum, sizeof(stFileNum), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ printf("tpye num recv is %s\n",szmsg);
+
+ }
+ }
+ //else
+ //fprintf(stdout, "%s --- %s\n", " ", event_str[i]);
+ }
+ }
+ nread = nread + sizeof(struct inotify_event) + event->len;
+ len = len - sizeof(struct inotify_event) - event->len;
+ }
+ }
+ return 0;
+}
+
+void *monitorhomenum(void *arg)
+{
+ int fd,wd,len,nread,i;
+ char buf[BUFSIZ],num[10];
+ struct inotify_event *event;
+ stFileNum stfilenum;
+ FILE* fp = NULL;
+ // if (argc < 2)
+ // {
+ // fprintf(stderr, "%s path\n", argv[0]);
+ // return -1;
+ //}
+
+ char *pcip;
+ pcip = (char *)arg;
+
+ const char *ip = "10.10.10.201";
+ int port = 7002;
+ void * ctx = zmq_ctx_new();
+ fb_assert(ctx, "create zmq context faild");
+
+ void *sock = zmq_socket(ctx, ZMQ_REQ);
+ fb_assert(sock, "create zmq socket faild");
+
+ char szaddr[128] = {0};
+ snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
+
+ {//加密相关代码
+ char szmsg[1024] = {0};
+ //此密钥为服务端产生的公钥
+ strcpy(szmsg, "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE");
+ zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szmsg, strlen(szmsg));
+
+ char szpubkey[64] = {0};
+ char szprikey[64] = {0};
+ zmq_curve_keypair(szpubkey, szprikey);
+ zmq_setsockopt(sock, ZMQ_CURVE_PUBLICKEY, szpubkey, strlen(szpubkey));
+ zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szprikey, strlen(szprikey));
+ }
+ zmq_connect(sock, szaddr);
+ int count = 0;
+
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+
+ fd = inotify_init();
+ if (fd < 0)
+ {
+ fprintf(stderr, "inotify_init failed\n");
+ return NULL;
+ }
+
+ wd = inotify_add_watch(fd, "/home", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //inotify_add_watch(fd, "/home/czl/tengswitch", IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO );
+ //wd = inotify_add_watch(fd, "/home/czl/test", IN_MODIFY);
+ if (wd < 0)
+ {
+ fprintf(stderr, "inotify_add_watch %s failed\n", "/home");
+ return NULL;
+ }
+
+ buf[sizeof(buf) - 1] = 0;
+ while ((len = read(fd, buf, sizeof(buf) - 1)) > 0)
+ {
+ nread = 0;
+ while (len > 0)
+ {
+ event = (struct inotify_event *)&buf[nread];
+ for (i = 0; imask >> i) & 1)
+ {
+ if (event->len > 0)
+ //fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
+ {
+ stpcpy(stfilenum.szFileName,event->name);
+ // system("ls -l /home/czl/test |grep '^-' |wc -l > /home/czl/tengswitch/filenum.txt");
+ // a = fopen("/home/czl/tengswitch/filenum.txt","r");
+ // if(a == NULL)
+ // {
+ // printf("open file:filenum.txt error
");
+ // exit(0);
+ // }
+ if (stfilenum.szFileName[0] != '.')
+ {
+ printf("num in home event happened \n");
+ bzero(szmsg, sizeof(szmsg));
+ stfilenum.uiType = 4;
+ stpcpy(stfilenum.szIp,pcip);
+ stpcpy(stfilenum.szPath,"/home");
+ gettimeofday(&stfilenum.stRcvTime,NULL);
+
+ if(NULL==( fp = popen("ls -l /home |grep '^-' |wc -l ","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return NULL;
+ }
+
+ fscanf(fp,"%s",num);
+ //printf("filenum charged is %s\n",num);
+ stfilenum.uiFileNum = atoi(num);
+ fclose(fp);
+ printf("type 4 home file num changed\n type is %d\n ip is %s\n path is %s\n filename is %s\n file num is %d\n\n\n\n",stfilenum.uiType,stfilenum.szIp,stfilenum.szPath,stfilenum.szFileName,stfilenum.uiFileNum);
+ zmq_send(sock, &stfilenum, sizeof(stFileNum), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ printf("tpye num recv is %s\n",szmsg);
+ }
+
+ }
+ //else
+ //fprintf(stdout, "%s --- %s\n", " ", event_str[i]);
+ }
+ }
+ nread = nread + sizeof(struct inotify_event) + event->len;
+ len = len - sizeof(struct inotify_event) - event->len;
+ }
+ }
+ return 0;
+}
+
+int reportpathnum()
+{
+ FILE *fd = NULL,*fp = NULL;
+ char path[1024]="\0",b[10][128],i=0,j,num[128],cmd[128] = "\0";
+ unsigned int filenum = 0,allnum = 0,pathnum = 0;
+ if(NULL==(fd = popen("echo $PATH","r")))
+ {
+ fprintf(stdout,"execute command failed: ");
+ return 0;
+ }
+ if (NULL == fgets(path,sizeof(path),fd))
+ return 0;
+ fclose(fd);
+
+ printf("date in path is %s\n",path);
+ pathnum = strlen(path);
+ path[pathnum-1] = '\0';
+ char* token = strtok(path,":");
+ while(token != NULL)
+ {
+ strcpy(b[i++],token);
+ token = strtok(NULL,":");
+ if( i == 9 )
+ break;
+ }
+
+ for(j=0;jopen file: /etc/nos_monitor_conf.ini error");
+ return 0;
+ }
+ // fscanf(fp,"%s %s %s %s",pcip,task_name,cmanager,manprocess);
+ fgets(pcip, sizeof(pcip), fp);
+ // while(1)
+ // {
+ // printf("\n length of pcip is %d \n",strlen(pcip));
+ iplen = strlen(pcip);
+ pcip[iplen-1]='\0';
+ // printf("\n ip get is %s \n",pcip);
+ // sleep(1);
+ // }
+
+ fgets(task_name, sizeof(task_name), fp);
+ tasklen = strlen(task_name);
+ //printf("\n tasklen get is %d \n",tasklen);
+ task_name[tasklen-1]='\0';
+ // printf("\n task_name get is %s \n",task_name);
+
+ fgets(cmanager, sizeof(cmanager), fp);
+ cmlen = strlen(cmanager);
+ // printf("\n cmlen get is %d \n",cmlen);
+ cmanager[cmlen-1]='\0';
+ //printf("\n cmanager get is %s \n",cmanager);
+ fgets(manprocess, sizeof(manprocess), fp);
+ manlen = strlen(manprocess);
+ // printf("\n manlen get is %d \n",manlen);
+ manprocess[manlen-1] = '\0';
+ // printf("\n manprocess get is %s \n",manprocess);
+ fclose(fp);
+ pthread_t history_cmd,filecharge,filenumcharge,homenumcharge;
+ Msgreport mesgreport;
+ stProcessState processstate;
+ stFileNum pathreport;
+ stLogMsg syslogreport,commendlog;
+ //syslogreport = (stLogMsg*)malloc(sizeof(stLogMsg)+1);
+ memset(&syslogreport,0, sizeof(stLogMsg));
+ void * ctx = zmq_ctx_new();
+ fb_assert(ctx, "create zmq context faild");
+
+ void *sock = zmq_socket(ctx, ZMQ_REQ);
+ fb_assert(sock, "create zmq socket faild");
+
+ char szaddr[128] = "\0";
+ snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
+
+ {//加密相关代码
+ char szmsg[1024] = {0};
+ //此密钥为服务端产生的公钥
+ strcpy(szmsg, "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE");
+ zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szmsg, strlen(szmsg));
+
+ char szpubkey[64] = {0};
+ char szprikey[64] = {0};
+ zmq_curve_keypair(szpubkey, szprikey);
+ zmq_setsockopt(sock, ZMQ_CURVE_PUBLICKEY, szpubkey, strlen(szpubkey));
+ zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szprikey, strlen(szprikey));
+ }
+
+ zmq_connect(sock, szaddr);
+
+
+ int count = 0;
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+ // getchar();
+ // sleep(1);
+ err = pthread_create(&history_cmd, NULL, get_historycmd, (void *)&pcip);
+ //printf("have come here");
+ err1 = pthread_create(&filecharge, NULL, monitorfile, (void *)&pcip);
+ err2 = pthread_create(&filenumcharge, NULL, monitorfilenum, (void *)&pcip);
+
+ err3 = pthread_create(&homenumcharge, NULL, monitorhomenum, (void *)&pcip);
+ int memory_have = 0;
+ CPU_OCCUPY cpu_stst1;
+ CPU_OCCUPY cpu_stst2;
+ int cpu;
+
+ while(1)
+ {
+ char szmsg[1024] = {0};
+ bzero(szmsg, sizeof(szmsg));
+ // snprintf(szmsg, sizeof(szmsg), "I say %d", ++count);
+ // fb_debug("send msg : [%s]", szmsg);
+ // zmq_send(sock, szmsg, strlen(szmsg), 0);
+ // zmq_recv(sock, szmsg, sizeof(szmsg) - 1, 0);
+ // fb_debug("recv msg : [%s]", szmsg);
+
+ get_cpuoccupy((CPU_OCCUPY *)&cpu_stst1);
+ sleep(1);
+ get_cpuoccupy((CPU_OCCUPY *)&cpu_stst2);
+ cpu = cal_cpuoccupy((CPU_OCCUPY *)&cpu_stst1,(CPU_OCCUPY *)&cpu_stst2);
+ memory_have = 100*get_memoccupy();
+ // printf("1cpu usage:%.2f\%\n mem usage:%.2f\%\n",cpu,memory_have);
+ mesgreport.uiType = 1;
+ mesgreport.uiCpuRate = 100*cpu;
+ mesgreport.uiMemRate = memory_have;
+ stpcpy(mesgreport.szip,pcip);
+ //printf("2cpu usage:%.2f\%\n mem usage:%.2f\%\n",mesgreport.uiCpuRate,mesgreport.uiMemRate);
+ //printf("szip is:%s\n",mesgreport.szip);
+ mesgreport.uiCronNum = uiCronNum();
+ tcpnum = processnum_tcp();
+ //tcpnum = 10;
+
+ pronum = processnum();
+
+ mesgreport.uiTcpEstablishNum = tcpnum;
+ mesgreport.uiRunningProcessNum = pronum;
+ //printf("tcp and process is :%d and %d\n",tcpnum,pronum);
+ // judgecommend();
+ // judgelogin();
+ get_md5passwd(md5passwd);
+ //printf("test PasswdMd5 is :%s\n",md5passwd);
+ // strcpy(mesgreport.szPasswdMd5,md5passwd);
+
+ memcpy(mesgreport.szPasswdMd5,md5passwd,strlen(md5passwd));
+ //md5group = get_md5group();
+ get_md5group(md5group);
+ memcpy(mesgreport.szGroupMd5,md5group,strlen(md5group));
+ gettimeofday(&mesgreport.stRcvTime,NULL);
+
+ zmq_send(sock, &mesgreport, sizeof(mesgreport), 0);
+ // printf("have send success \n");
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, ZMQ_DONTWAIT);
+ // printf("have recv success \n");
+ // printf("mestype1 recv is %s\n",szmsg);
+ // printf("Type1 send ip is %s\n passmd5 is %s\n groupmd5 is %s\n cpurate is %d\n memrate is %d\n\n\n\n",mesgreport.szip,mesgreport.szPasswdMd5,mesgreport.szGroupMd5,mesgreport.uiCpuRate,mesgreport.uiMemRate);
+ pid = 0 ;
+ getPidByName(&pid, task_name);
+ //printf("pid of monitsys is %d",pid);
+ if (pid > 0)
+ cpumemstate1 = 1;
+ else
+ {
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,task_name);
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+
+ cmpid = 0;
+ getPidByName(&cmpid, cmanager);
+ printf("pid of top is %d\n\n",cmpid);
+ if (cmpid > 0)
+ cmstate1 = 1;
+ else{
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,cmanager);
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ // printf("mestype2 recv is %s\n",szmsg);
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+ manpropid = 0;
+ getPidByName(&manpropid, manprocess);
+
+ if (manpropid > 0)
+ manpstate1 = 1;
+ else
+ {
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,manprocess);
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate),0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1, ZMQ_DONTWAIT);
+
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+
+ firestate1 = firewallcharge();
+ if (firestate1 == 1)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ processstate.uiType = 2;
+ stpcpy(processstate.szIp,pcip);
+ gettimeofday(&processstate.stRcvTime,NULL);
+ stpcpy(processstate.uiProcessname,"firewall");
+ processstate.uiProcessState = 0;
+ zmq_send(sock, &processstate, sizeof(processstate), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ printf("type 2 send ip is %s\n Type is %d\n processname is %s\n processstate is %d\n\n\n",processstate.szIp,processstate.uiType,processstate.uiProcessname,processstate.uiProcessState);
+ sleep(1);
+ }
+ newloginnum = judgeiflogin();
+ // printf("newloginnum is %d\n",newloginnum);
+ if (newloginnum != lastloginnum)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ syslogreport = judgelogin(pcip);
+ // printf("log before send struct is %s \n",&commendlog.szMsg[0]);
+ zmq_send(sock, &syslogreport, sizeof(stLogMsg), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ // printf("mestype5 recv is %s\n",szmsg);
+ lastloginnum = newloginnum;
+ // printf("msg login type is %d\nip is %s\nfilename is %s\n ",syslogreport.uiType,syslogreport.szIp,syslogreport.szLogFile);
+ // printf("szMsg0 is %s\n",syslogreport.szMsg[0]);
+ // printf("szMsg1 is %s\n",syslogreport.szMsg[1]);
+ // printf("szMsg2 is %s\n",syslogreport.szMsg[2]);
+ // printf("szMsg3 is %s\n",syslogreport.szMsg[3]);
+ // printf("szMsg4 is %s\n",syslogreport.szMsg[4]);
+ }
+
+ newpathnum = reportpathnum();
+
+ if (newpathnum != lastpathnum)
+ {
+ bzero(szmsg, sizeof(szmsg));
+ pathreport.uiType = 4;
+ stpcpy(pathreport.szIp,pcip);
+ stpcpy(pathreport.szPath,"path");
+ gettimeofday(&pathreport.stRcvTime,NULL);
+ pathreport.uiFileNum = newpathnum;
+ zmq_send(sock, &pathreport, sizeof(pathreport), 0);
+ zmq_recv(sock, szmsg, sizeof(szmsg) - 1,ZMQ_DONTWAIT);
+ lastpathnum = newpathnum;
+ printf("\n\npath receive is %s\n\n",szmsg);
+ }
+ }
+
+ zmq_close(sock);
+ zmq_ctx_term(ctx);
+ zmq_ctx_destroy(ctx);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/study_clang/Mimic/nos_monitor/monitsys.h b/study_clang/Mimic/nos_monitor/monitsys.h
new file mode 100644
index 0000000..278ebbe
--- /dev/null
+++ b/study_clang/Mimic/nos_monitor/monitsys.h
@@ -0,0 +1,111 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define EVENT_NUM 12
+#define BUF_SIZE 1024
+//gcc monitsys.c -lzmq -lpthread -L/usr/local/lib -I/usr/local/include -Wl,-rpath=/usr/local/lib/ -o monitsys
+#define fb_debug(fmt, arg...) \
+ do{ \
+ printf("%s %d : ", __FILE__, __LINE__); \
+ printf(fmt, ##arg); \
+ printf("\n"); \
+ }while(0)
+
+#define fb_assert(var, info) \
+ do{ \
+ if(!(var)) { \
+ fb_debug(info); \
+ } \
+ }while(0)
+
+typedef unsigned int uint;
+
+char *event_str[EVENT_NUM] =
+{
+ "IN_ACCESS",
+ "IN_MODIFY",
+ "IN_ATTRIB",
+ "IN_CLOSE_WRITE",
+ "IN_CLOSE_NOWRITE",
+ "IN_OPEN",
+ "IN_MOVED_FROM",
+ "IN_MOVED_TO",
+ "IN_CREATE",
+ "IN_DELETE",
+ "IN_DELETE_SELF",
+ "IN_MOVE_SELF"
+};
+
+int lastnum = 0,lastlognum = 0,newloginnum = 0,lastloginnum = 0;
+
+typedef struct CPU_PACKED
+{
+ char name[20]; //
+ unsigned int user;
+ unsigned int nice;
+ unsigned int system;
+ unsigned int idle;
+}CPU_OCCUPY;
+
+typedef struct
+{
+ uint uiType; // 1
+ char szip[32];
+ struct timeval stRcvTime;
+ uint uiCpuRate;
+ uint uiMemRate;
+ uint uiTcpEstablishNum;
+ uint uiRunningProcessNum;
+ uint uiCronNum;
+ char szPasswdMd5[64];
+ char szGroupMd5[64];
+}Msgreport;
+
+typedef struct
+{
+ uint uiType;//2
+ char szIp[32];
+ struct timeval stRcvTime;
+ char uiProcessname[32];
+ uint uiProcessState;// 0 mains enable,1 disable
+}stProcessState;
+
+typedef struct
+{
+ uint uiType; //3
+ char szIp[32];
+ struct timeval stRcvTime;
+ char szFileName[32]; //filename modified
+ //char eventType[16]; //eventType of filename
+ char szFileMd5[64]; //md5num of file name
+}stFileState;
+
+typedef struct
+{
+ uint uiType; //4
+ char szIp[32];
+ struct timeval stRcvTime;
+ char szPath[32]; //监控路径
+ char szFileName[32]; //增加或删除的文件名称
+ uint uiFileNum; //当前文件夹下文件数量
+}stFileNum;
+
+
+typedef struct
+{
+ uint uiType;//5
+ char szIp[32];
+ struct timeval stRcvTime;
+ char szLogFile[32];
+ char szMsg[5][128];
+}stLogMsg;
\ No newline at end of file
diff --git a/study_clang/Mimic/nos_monitor/nos_monitor.tar.gz b/study_clang/Mimic/nos_monitor/nos_monitor.tar.gz
new file mode 100644
index 0000000..ee88cd8
Binary files /dev/null and b/study_clang/Mimic/nos_monitor/nos_monitor.tar.gz differ
diff --git a/study_clang/Mimic/nos_monitor/nos_monitor_conf.ini b/study_clang/Mimic/nos_monitor/nos_monitor_conf.ini
new file mode 100644
index 0000000..e1c8e60
--- /dev/null
+++ b/study_clang/Mimic/nos_monitor/nos_monitor_conf.ini
@@ -0,0 +1,4 @@
+10.10.10.242
+monitsys
+top
+systemd
diff --git a/study_clang/Mimic/piggie/piggie b/study_clang/Mimic/piggie/piggie
new file mode 100755
index 0000000..c264081
Binary files /dev/null and b/study_clang/Mimic/piggie/piggie differ
diff --git a/study_clang/Mimic/piggie/piggie.c b/study_clang/Mimic/piggie/piggie.c
new file mode 100644
index 0000000..22a270d
--- /dev/null
+++ b/study_clang/Mimic/piggie/piggie.c
@@ -0,0 +1,55 @@
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define STKS (4*4096)
+
+#ifndef CLONE_NEWPID
+#define CLONE_NEWPID 0x20000000
+#endif
+
+int main(int argc, char **argv)
+{
+ //int pid;
+ //void *stk;
+ int fd, i = 0;
+ char log_file[] = "/var/log/piggie.log";
+
+ time_t t;
+ struct tm *timeinfo;
+
+ //stk = mmap(NULL, STKS, PROT_READ | PROT_WRITE,
+ //MAP_PRIVATE | MAP_ANON | MAP_GROWSDOWN, 0, 0);
+ //pid = clone(do_test, stk + STKS, SIGCHLD | CLONE_NEWPID, argv[1]);
+ //printf("Child forked, pid %d\n", pid);
+ fd = open("/dev/null", O_RDONLY);
+ if (fd != 0) {
+ dup2(fd, 0);
+ close(fd);
+ }
+ if(NULL != argv[1])
+ fd = open(argv[1], O_WRONLY | O_TRUNC | O_CREAT, 0600);
+ else
+ fd = open(log_file, O_WRONLY | O_TRUNC | O_CREAT, 0600);
+
+ dup2(fd, 1);
+ dup2(fd, 2);
+ if (fd != 1 && fd != 2)
+ close(fd);
+
+ while (1) {
+ sleep(1);
+ time(&t);
+ timeinfo = localtime(&t);
+ printf("%d %s\n", i++, asctime(timeinfo));
+ fflush(stdout);
+ }
+
+
+ return 0;
+}
\ No newline at end of file
diff --git a/study_clang/Mimic/piggie/piggie_thread.c b/study_clang/Mimic/piggie/piggie_thread.c
new file mode 100644
index 0000000..b8fd2a4
--- /dev/null
+++ b/study_clang/Mimic/piggie/piggie_thread.c
@@ -0,0 +1,61 @@
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define STKS (4*4096)
+
+#ifndef CLONE_NEWPID
+#define CLONE_NEWPID 0x20000000
+#endif
+
+static int do_test(void *logf)
+{
+ int fd, i = 0;
+ time_t t;
+ struct tm *timeinfo;
+ setsid();
+
+ close(0);
+ close(1);
+ close(2);
+
+ fd = open("/dev/null", O_RDONLY);
+ if (fd != 0) {
+ dup2(fd, 0);
+ close(fd);
+ }
+
+ fd = open(logf, O_WRONLY | O_TRUNC | O_CREAT, 0600);
+ dup2(fd, 1);
+ dup2(fd, 2);
+ if (fd != 1 && fd != 2)
+ close(fd);
+
+ while (1) {
+ sleep(1);
+ time(&t);
+ timeinfo = localtime(&t);
+ printf("%d %s\n", i++, asctime(timeinfo));
+ fflush(stdout);
+ }
+
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ int pid;
+ void *stk;
+
+ stk = mmap(NULL, STKS, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANON | MAP_GROWSDOWN, 0, 0);
+ pid = clone(do_test, stk + STKS, SIGCHLD | CLONE_NEWPID, argv[1]);
+ printf("Child forked, pid %d\n", pid);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/study_clang/Mimic/ssh_proxy/frame_incrypt b/study_clang/Mimic/ssh_proxy/frame_incrypt
new file mode 100755
index 0000000..ec7f450
Binary files /dev/null and b/study_clang/Mimic/ssh_proxy/frame_incrypt differ
diff --git a/study_clang/Mimic/ssh_proxy/frame_incrypt.cpp b/study_clang/Mimic/ssh_proxy/frame_incrypt.cpp
new file mode 100644
index 0000000..9cadf3e
--- /dev/null
+++ b/study_clang/Mimic/ssh_proxy/frame_incrypt.cpp
@@ -0,0 +1,344 @@
+/*****************************************************************************
+ * @Author : Songsk
+ * @Date : 2020-07-17 00:02:36
+ * @LastEditors : songshuaikang@comleader.com.cn
+ * @LastEditTime : 2020-07-20 23:17:04
+ * @Description : file content
+ *******************************************************************************/
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define ACTIVE_NUM_NUM 3
+#define UNSIGNED_INT_LEN 32
+#define MAX_PADDING_SIZE 128
+#define uint unsigned int
+#define uchar unsigned char
+
+#define _ENCRYPT(a,b,c) (a=(b^c))
+#define _DECRYPT _ENCRYPT
+#define _CHECKSUM(_checksum, _cipher, _key, _len)\
+ {\
+ uint _m_i = 0;\
+ uint sum = 0;\
+ for(_m_i=0; _m_i< _len; _m_i++)\
+ sum = sum + (0xffffffff & _cipher[_m_i]) + (0xffffffff & _key[_m_i]);\
+ _checksum = 0xff - (0xff & (sum)) - ((sum) >> 8);\
+ }
+#define ENCRYPT_FUNC(_cipher, _plain, _key, _len)\
+{\
+ int _m_i = 0;\
+ for(_m_i=0; _m_i< _len; _m_i++)\
+ _ENCRYPT(_cipher[_m_i], _plain[_m_i], _key[_m_i]);\
+}
+
+#define DECRYPT_FUNC(_plain, _cipher, _key, _len)\
+{\
+ int _m_i = 0;\
+ for(_m_i=0; _m_i< _len; _m_i++)\
+ _DECRYPT( _plain[_m_i],_cipher[_m_i], _key[_m_i]);\
+}
+
+static unsigned int seed = 0;
+#define SNAP_LEN 65536
+#define INTERFACE_STR "eth0"
+
+#define SHD_PRIVATE_PROTOCOL_H 0x09
+
+#define HexPrint(_buf, _len) \
+{\
+ int _m_i = 0;\
+ char *_m_buf = (char *)(_buf);\
+ int _m_len = (int)(_len);\
+ printf("[%s:%d] \r\n", __FUNCTION__, __LINE__);\
+ printf("***************************************************\n");\
+ for(_m_i = 0; _m_i < _m_len; _m_i++)\
+ {\
+ if(_m_i == 0) printf("\033[31m%02x \033[0m",_m_i);\
+ printf("\033[32m%02x \033[0m", _m_buf[_m_i] & 0xff);\
+ if(!((_m_i+1) % 16)) printf("\n\033[31m%02x \033[0m",_m_i);\
+ }\
+ printf("\nsize = %d\n***************************************************\n", _m_len);\
+}
+
+typedef struct frame_head_t
+{
+ uchar dmac[6];
+ uchar smac[6];
+ uchar dot1q[4];
+ uchar protocol[2];
+ uchar padding;
+ uchar len;
+}FRAME_HEAD_T;
+
+typedef struct msg_to_proxy_t
+{
+ uchar master_nos = 1;
+ uchar active_nos[3];
+}MSG_TO_PROXY_T;
+
+typedef struct timeval TS_TO_PROXY_T;
+
+typedef enum shd_action_type_e
+{
+ ACTION_TELL_ACTIVE_NOS =1,
+ ACTION_SEND_TIMESTAMP,
+ ACTINON_MAX
+}SHD_ACTION;
+
+typedef enum shd_private_protocol_code_low_e
+{
+ PROTOCOL_TELL_ACTIVE_NOS = 0x88,
+ PROTOCOL_SEND_TIMESTAMP,
+ PROTOCOL_MAX
+}SHD_PROTOCOL;
+
+/**
+ * @description: 发送数据包,发送的网卡在宏定义中指定
+ * @param {pkt:数据包内容,包含包头与payload; len:数据包长度}
+ * @return: 0:success
+ */
+int send_packet_with_pcap(const uchar *pkt, uint len)
+{
+ static pcap_t *handle = NULL;
+ char dev_str[64];
+ char err_buf[PCAP_ERRBUF_SIZE];
+
+ strcpy(dev_str, INTERFACE_STR);
+ if(NULL == handle)
+ {
+ handle = pcap_open_live(dev_str, SNAP_LEN, 1, 1000, err_buf);
+ if (handle == NULL)
+ {
+ fprintf(stderr, "Couldn't open device %s: %s\n", dev_str, err_buf);
+ return 0;
+ }
+ }
+
+ return pcap_sendpacket(handle, pkt, len);
+}
+
+/**
+ * @description: 随机函数,原子操作,提供一个字节的随机值
+ * @param void
+ * @return: unsigned char
+ */
+uchar _random(void)
+{
+ seed += (unsigned int)time(0) + 781;
+ srand(seed);
+ uchar temp = (uchar)(rand()%256);
+ return temp;
+}
+
+uint fill_with_random(uchar* buf , uint len)
+{
+ for(int i = 0; i< len; i++)
+ *(buf+i) =(_random());
+ return len;
+}
+
+void print_buffer_hex(const char * text, uchar * buf, uint len)
+{
+ printf("%s\n", text);
+ // for(int i = 0; i < len; i++)
+ // {
+ // printf("%2X ",buf[i]);
+ // if(i != 0 && i % 16 == 0)
+ // printf("\n");
+ // }
+ HexPrint(buf, len);
+ printf("\n");
+}
+
+int is_unicast_macaddr(uchar * mac)
+{
+ if(mac[0] & 1)
+ return 1;
+ return 0;
+}
+
+int make_frame_up(const int type, uchar *frame, uchar * ciphertext, uchar * key, uint len, uint frame_len)
+{
+ //int p = 0;
+
+ /*fill buffer with random value*/
+ fill_with_random(frame, frame_len);
+
+ /*create a frame header, include Ehthernet header | vlan header | protocol code */
+ FRAME_HEAD_T frame_head;
+ do
+ {
+ printf(".");
+ fill_with_random(frame_head.smac, sizeof(frame_head.smac));
+ }
+ while (is_unicast_macaddr(frame_head.smac));
+ printf("\nfill smac\n");
+ do
+ {
+ printf(".");
+ fill_with_random(frame_head.dmac, sizeof(frame_head.dmac));
+ }
+ while (is_unicast_macaddr(frame_head.dmac));
+ printf("\nfill dmac\n");
+ frame_head.dot1q[0] = 0x81;
+ frame_head.dot1q[1] = 0x00;
+ frame_head.dot1q[2] = 0x07;
+ frame_head.dot1q[3] = 0xd0;
+ frame_head.protocol[0] = 0x08;
+ //frame_head.protocol[1] = 0x06;
+ (ACTION_TELL_ACTIVE_NOS == type) ? frame_head.protocol[1] = PROTOCOL_TELL_ACTIVE_NOS : frame_head.protocol[1] = PROTOCOL_SEND_TIMESTAMP;
+
+ /*get a padding*/
+ uchar padding = 0;
+ while(1)
+ {
+ srand(time(NULL));
+ int a = sizeof(FRAME_HEAD_T) + len * 2 + 1;
+ printf("a is %d, frame_len is %d\n", a, frame_len);
+ padding = (uchar)rand()%(frame_len
+ - sizeof(FRAME_HEAD_T)
+ - len * 2 - 1)
+ + sizeof(FRAME_HEAD_T);
+ if(padding + len * 2 > frame_len)
+ continue;
+ frame_head.padding = padding;
+ printf("padding is 0x%x\n", padding);
+ frame_head.len = len;
+ break;
+ }
+
+ /*copy frame header and payload into buffer*/
+ memcpy(frame, &frame_head, sizeof(frame_head));
+ memcpy(frame + padding, ciphertext, len);
+ memcpy(frame + padding + len, key, len);
+ char checksum=0;
+ _CHECKSUM(checksum, ciphertext, key, len);
+ print_buffer_hex("计算校验和:", (unsigned char *)&checksum,sizeof(checksum));
+ memcpy(frame + padding + len + len, &checksum, 1);
+ /*send packet finally*/
+ print_buffer_hex("产生报文:", frame,frame_len);
+ return send_packet_with_pcap(frame, frame_len);
+}
+
+int shd_send_cmd_to_proxy(MSG_TO_PROXY_T * msg)
+{
+ int ret = 0;
+ uchar key[sizeof(MSG_TO_PROXY_T)];
+ uchar ciphertext[sizeof(MSG_TO_PROXY_T)];
+
+ /*get plaintext*/
+ uchar plaintext[sizeof(MSG_TO_PROXY_T)];
+ memcpy(plaintext, msg, sizeof(MSG_TO_PROXY_T));
+ print_buffer_hex("产生明文:", plaintext, sizeof(plaintext));
+
+ /*create a key with random num*/
+ ret = fill_with_random(key, sizeof(key));
+ print_buffer_hex("产生掩码:", key, sizeof(key));
+
+ /*incrypt*/
+ ENCRYPT_FUNC(ciphertext, plaintext, key,sizeof(MSG_TO_PROXY_T));
+ print_buffer_hex("计算密文:", ciphertext, sizeof(ciphertext));
+ /*create and send frame*/
+ srand(seed);
+ uint frame_len = sizeof(FRAME_HEAD_T) //以太网帧头
+ + sizeof(MSG_TO_PROXY_T) * 2 //信息量长度
+ + 1
+ + 10
+ + rand()%MAX_PADDING_SIZE; //padding长度
+ uchar * frame = (uchar*)malloc(frame_len);
+ ret = make_frame_up(ACTION_TELL_ACTIVE_NOS ,frame, ciphertext, key, sizeof(key), frame_len);
+ if(ret)
+ {
+ printf("send packet error\n");
+ free(frame);
+ return -1;
+ }
+ free(frame);
+
+ return 0;
+}
+
+int shd_send_timestamp_to_nos()
+{
+ int ret = 0;
+ uchar key[sizeof(TS_TO_PROXY_T)];
+ uchar ciphertext[sizeof(TS_TO_PROXY_T)];
+ uchar plaintext[sizeof(TS_TO_PROXY_T)];
+
+ TS_TO_PROXY_T time;
+ gettimeofday(&time,NULL);
+
+ memcpy(plaintext, &time, sizeof(TS_TO_PROXY_T));
+ print_buffer_hex("产生明文:", plaintext, sizeof(plaintext));
+ ret = fill_with_random(key, sizeof(key));
+ print_buffer_hex("产生掩码:", key, sizeof(key));
+ ENCRYPT_FUNC(ciphertext, plaintext, key,sizeof(TS_TO_PROXY_T));
+ print_buffer_hex("计算密文:", ciphertext, sizeof(ciphertext));
+ srand(seed);
+ int a = rand();
+ printf("seed is %x, rand is %d, MAX_PADDING_SIZE is %d\n", seed, a, MAX_PADDING_SIZE);
+ uint frame_len = sizeof(FRAME_HEAD_T) //以太网帧头
+ + sizeof(TS_TO_PROXY_T) * 2 //信息量长度
+ + 1
+ + 10
+ + a % MAX_PADDING_SIZE; //padding长度
+ printf("frame_len is %u\n", frame_len);
+ uchar * frame = (uchar*)malloc(frame_len);
+ if(NULL == frame)
+ {
+ printf("malloc error!!\n");
+ }else
+ {
+ printf("frame addr is %x\n", frame);
+ }
+
+ ret = make_frame_up(ACTION_SEND_TIMESTAMP,frame, ciphertext, key, sizeof(key), frame_len);
+ if(ret)
+ {
+ printf("send packet error\n");
+ free(frame);
+ return -1;
+ }
+ free(frame);
+ return 0;
+}
+
+int main()
+{
+ int ret = 0;
+ while(1)
+ {
+ #if 0
+ #else
+ MSG_TO_PROXY_T msg;
+ msg.master_nos = 1;
+ msg.active_nos[0] = 1;
+ msg.active_nos[1] = 2;
+ msg.active_nos[2] = 3;
+
+ ret = shd_send_cmd_to_proxy(&msg);
+ if(ret)
+ {
+ printf("cmd send error\n");
+ return -1;
+ }
+ ret = shd_send_timestamp_to_nos();
+ if(ret)
+ {
+ printf("cmd send error\n");
+ return -1;
+ }
+ #endif
+ // usleep(5000);
+ getchar();
+ }
+
+ return 0;
+}
diff --git a/study_clang/Mimic/ssh_proxy/scapy_test.py b/study_clang/Mimic/ssh_proxy/scapy_test.py
new file mode 100755
index 0000000..bc13fa7
--- /dev/null
+++ b/study_clang/Mimic/ssh_proxy/scapy_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+# -*- coding: UTF-8 -*-
+from scapy.all import *
+
+def pack_callback(packet):
+ print ("---------------- packet -----------------")
+ print ( packet.show() )
+ print ("-----------------------------------------")
+ '''
+ if packet['Ether'].payload:
+ print (packet['Ether'].src)
+ print (packet['Ether'].dst)
+ print (packet['Ether'].type)
+
+ if packet['ARP'].payload:
+ print (packet['ARP'].psrc)
+ print (packet['ARP'].pdst)
+ print (packet['ARP'].hwsrc)
+ print (packet['ARP'].hwdst)
+ '''
+ time.sleep(2)
+
+filterstr="vlan"
+
+sniff(filter=filterstr,prn=pack_callback, iface='eth0', count=0)
diff --git a/study_clang/Mimic/telnet_proxy/Makefile b/study_clang/Mimic/telnet_proxy/Makefile
new file mode 100644
index 0000000..7926777
--- /dev/null
+++ b/study_clang/Mimic/telnet_proxy/Makefile
@@ -0,0 +1,22 @@
+# Batch Single C file MakeFile
+
+# 指定CPU架构 Architecture -> ARCH
+ARCH ?=
+CC = $(ARCH)gcc
+SUFFIX = .c
+CFLAGS += -Wall -g
+LD = -lpcap -pthread
+
+CUR_SOURCE = $(wildcard *$(SUFFIX))
+CUR_TARGETS = $(patsubst %$(SUFFIX), %, $(CUR_SOURCE))
+
+all:$(CUR_TARGETS)
+
+# %:%.c 是一个表示与目标相同 文件的模式变量
+$(CUR_TARGETS):%:%$(SUFFIX)
+ $(CC) $< $(CFLAGS) -o $@ $(LD)
+
+# 指定伪目标
+.PHONY:clean all
+ clean:
+ -rm -rf $(TARGETS)
diff --git a/study_clang/Mimic/telnet_proxy/telnet_proxy_single b/study_clang/Mimic/telnet_proxy/telnet_proxy_single
new file mode 100755
index 0000000..5b6925e
Binary files /dev/null and b/study_clang/Mimic/telnet_proxy/telnet_proxy_single differ
diff --git a/study_clang/Mimic/telnet_proxy/telnet_proxy_single.c b/study_clang/Mimic/telnet_proxy/telnet_proxy_single.c
new file mode 100644
index 0000000..31f0120
--- /dev/null
+++ b/study_clang/Mimic/telnet_proxy/telnet_proxy_single.c
@@ -0,0 +1,194 @@
+/*************************************************************************
+ > File Name : telnet_proxy.c
+ > Author : TL Song
+ > EMail : songtianlun@frytea.com
+ > Created Time : Thu Feb 18 18:57:20 2021
+ ************************************************************************/
+#include
+#include
+// #include
+#include
+
+#define RECV_SEND_DEVICE "eth1"
+#define RETU_DEVICE "linux_dal"
+#define RETU_SEND_DEVICE RECV_DEVICE
+#define RECV_FILTER "src host 192.168.8.123 and arp or icmp or dst port 23"
+#define RETU_FILTER ""
+// switch, 1、定义后以多进程模式运行;2、定义后为抓到的包追加vlan标签。
+// #define RUNNING_WITH_MULT_PROGRESS 0
+// #define GREP_WITH_MAKE_VLAN 0
+
+#define SNAP_LEN 65536
+#ifndef GREP_WITH_MAKE_VLAN
+#define RECV_DEVICE "eth0"
+#else
+#define RECV_DEVICE "eth0.3000"
+#endif
+
+static char g_vlan_tag[4] = {0x81, 0x00, 0x0B, 0xB8};
+#define dPrint(fmt, ...) do{fprintf(stderr, "[%s:%d] " fmt "\r\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}while(0)
+#define HexPrint(_buf, _len) \
+{\
+ int _m_i = 0;\
+ char *_m_buf = (char *)(_buf);\
+ int _m_len = (int)(_len);\
+ printf("[%s:%d] \r\n", __FUNCTION__, __LINE__);\
+ printf("*****************************\n");\
+ for(_m_i = 0; _m_i < _m_len; _m_i++)\
+ {\
+ printf("\033[32m%02x \033[0m", _m_buf[_m_i] & 0xff);\
+ if(!((_m_i+1) % 10)) printf("\n");\
+ }\
+ printf("\nsize = %d\n*****************************\n", _m_len);\
+}
+
+ char err_buf[PCAP_ERRBUF_SIZE];
+ struct bpf_program fp_recv; /* The compiled filter expression */
+ struct bpf_program fp_retu; /* The compiled filter expression */
+ char filter_recv[] = RECV_FILTER; /* The filter expression (filter 53 port)*/
+ char filter_retu[] = RETU_FILTER; /* The filter expression (filter 53 port)*/
+ pcap_t *handle_recv;
+ pcap_t *handle_retu;
+ pcap_t *handle_recv_send;
+ bpf_u_int32 mask_recv; /* The netmask of our sniffing device */
+ bpf_u_int32 mask_retu; /* The netmask of our sniffing device */
+ bpf_u_int32 net_recv; /* The IP of our sniffing device */
+ bpf_u_int32 net_retu; /* The IP of our sniffing device */
+
+void recv_dispatcher_handler(u_char *temp1, const struct pcap_pkthdr *header, const u_char *pkt_data)
+{
+ // HexPrint((const char *)pkt_data, header->caplen);
+#ifndef GREP_WITH_MAKE_VLAN
+ u_char pkt_send[header->caplen];
+ memset(pkt_send, 0x00, sizeof(pkt_send));
+ memcpy(pkt_send, pkt_data, header->caplen);
+#else
+ u_char pkt_send[header->caplen + sizeof(g_vlan_tag)];
+ memset(pkt_send, 0x00, sizeof(pkt_send));
+ memcpy(pkt_send, pkt_data, header->caplen);
+ memcpy(pkt_send+16, pkt_send+12, header->caplen-12);
+ memcpy(pkt_send+12, g_vlan_tag, sizeof(g_vlan_tag));
+#endif
+
+ // HexPrint((const char *)pkt_send, sizeof(pkt_send));
+ dPrint("Send to %s ret : %d", RECV_SEND_DEVICE, pcap_sendpacket(handle_recv_send, pkt_send, sizeof(pkt_send)) );
+}
+
+void retu_dispatcher_handler(u_char *temp1, const struct pcap_pkthdr *header, const u_char *pkt_data)
+{
+ // HexPrint((const char *)pkt_data, header->caplen);
+ u_char pkt_send[header->caplen];
+ memset(pkt_send, 0x00, sizeof(pkt_send));
+ memcpy(pkt_send, pkt_data, header->caplen);
+ // HexPrint((const char *)pkt_send, sizeof(pkt_send));
+
+ dPrint("Send to %s ret : %d", RECV_DEVICE, pcap_sendpacket(handle_recv, pkt_send, sizeof(pkt_send)) );
+}
+
+// 接收前面板 eth0 发来的消息,转发到 eth1
+void *recv_handl(void *args)
+{
+ struct pcap_pkthdr *header;
+ const u_char *pkt_data;
+ // pcap_loop(handle_recv, -1, recv_dispatcher_handler, NULL);
+ while(1)
+ {
+ if(0 <= pcap_next_ex(handle_recv, &header, &pkt_data))
+ dPrint("Send to %s ret : %d", RECV_SEND_DEVICE, pcap_sendpacket(handle_recv_send, pkt_data, header->caplen) );
+ }
+
+ dPrint("Capture complete.");
+}
+
+// 接收 linux_dal 发来的流量,转发到 eth0
+void *retu_handl(void *args)
+{
+ pcap_loop(handle_retu, -1, retu_dispatcher_handler, NULL);
+ dPrint("Capture complete.");
+}
+
+int main()
+{
+ pthread_t tid_retu;
+
+ printf("Recv Device: %s\n", RECV_DEVICE);
+ printf("Retu Device: %s\n", RETU_DEVICE);
+ printf("Recv Send Device: %s\n", RECV_SEND_DEVICE);
+ printf("Retu Send Device: %s\n", RETU_SEND_DEVICE);
+
+ /*get network mask*/
+ if (pcap_lookupnet(RECV_DEVICE, &net_recv, &mask_recv, err_buf) == -1) {
+ fprintf(stderr, "Can't get netmask for device %s\n", RECV_DEVICE);
+ net_recv = 0;
+ mask_recv = 0;
+ }
+ if (pcap_lookupnet(RETU_DEVICE, &net_retu, &mask_retu, err_buf) == -1) {
+ fprintf(stderr, "Can't get netmask for device %s\n", RETU_DEVICE);
+ net_retu = 0;
+ mask_retu = 0;
+ }
+ /*Open the session in promiscuous mode*/
+ handle_recv = pcap_open_live(RECV_DEVICE, BUFSIZ, 1, 1000, err_buf);
+ if (handle_recv == NULL) {
+ fprintf(stderr, "Couldn't open device %s: %s\n", RECV_DEVICE, err_buf);
+ return;
+ }
+ handle_recv_send = pcap_open_live(RECV_SEND_DEVICE, SNAP_LEN, 1, 1000, err_buf);
+ if (handle_recv_send == NULL)
+ {
+ fprintf(stderr, "Couldn't open device %s: %s\n", RECV_SEND_DEVICE, err_buf);
+ return 0;
+ }
+ handle_retu = pcap_open_live(RETU_DEVICE, BUFSIZ, 1, 1000, err_buf);
+ if (handle_retu == NULL) {
+ fprintf(stderr, "Couldn't open device %s: %s\n", RETU_DEVICE, err_buf);
+ return;
+ }
+ /* Compile and apply the filter */
+ if (pcap_compile(handle_recv, &fp_recv, filter_recv, 0, net_recv) == -1) {
+ fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_recv, pcap_geterr(handle_recv));
+ return;
+ }
+ if (pcap_compile(handle_retu, &fp_retu, filter_retu, 0, net_retu) == -1) {
+ fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_retu, pcap_geterr(handle_retu));
+ return;
+ }
+ if (pcap_setfilter(handle_recv, &fp_recv) == -1) {
+ fprintf(stderr, "Couldn't install filter %s: %s\n", filter_recv, pcap_geterr(handle_recv));
+ return;
+ }
+ if (pcap_setfilter(handle_retu, &fp_retu) == -1) {
+ fprintf(stderr, "Couldn't install filter %s: %s\n", filter_retu, pcap_geterr(handle_retu));
+ return;
+ }
+
+#ifndef RUNNING_WITH_MULT_PROGRESS
+ int ret = pthread_create(&tid_retu, NULL, retu_handl, NULL);
+ if (ret != 0) {
+ printf("pthread_create error: error_code = %d\n", ret);
+ }
+ recv_handl(NULL);
+ pthread_exit(NULL);
+#else
+ pid_t fpid=fork();
+ if(fpid==0)
+ {
+ retu_handl(NULL);
+ printf("son/n");
+ }
+ else
+ {
+ recv_handl(NULL);
+ printf("father/n");
+ }
+#endif
+
+ /* cleanup */
+ pcap_freecode(&fp_recv);
+ pcap_close(handle_recv);
+ pcap_freecode(&fp_retu);
+ pcap_close(handle_retu);
+
+ dPrint("Capture complete.");
+ return 0;
+}
diff --git a/study_clang/Mimic/test_judge/Makefile b/study_clang/Mimic/test_judge/Makefile
new file mode 100644
index 0000000..5be74f5
--- /dev/null
+++ b/study_clang/Mimic/test_judge/Makefile
@@ -0,0 +1,44 @@
+
+ARCH ?=
+CC = $(ARCH)g++
+STRIP = $(ARCH)strip
+
+#以下同根目录下的makefile的相同代码的解释
+INC_DIR=./include ../common
+DIR_SRC=./src
+OBJS_DIR=./obj
+LD_DIR=
+
+
+TARGETS=./judge_test
+
+CUR_SOURCE=$(wildcard ${DIR_SRC}/*.cpp)
+CFLAGS += $(foreach dir,$(INC_DIR),-I$(dir))
+CUR_OBJS = $(patsubst $(DIR_SRC)/%.cpp, $(OBJS_DIR)/%.o, $(CUR_SOURCE))
+
+CFLAGS += -Wall -std=c++11 -g
+LD=-lpthread $$(mysql_config --cflags --libs) -lzmq
+
+all:$(TARGETS)
+$(OBJS_DIR)/%.o : $(DIR_SRC)/%.cpp
+ @mkdir -p $(OBJS_DIR)
+ @$(CC) $(CFLAGS) -c $< -o $@
+ @echo $(CC) $(CFLAGS) "-c" $(notdir $<) "-o" $(notdir $@)
+
+$(TARGETS): $(CUR_OBJS)
+ @$(CC) $(CUR_OBJS) -o $(TARGETS) -L$(LD_DIR) $(LD)
+#@$(STRIP) $(TARGETS)
+
+clean:
+ @rm -rf $(CUR_OBJS)
+ @rm -rf $(TARGETS)
+ @rm -rf $(OBJS_DIR)
+
+install:
+ $(INSTALL) $(TARGETS) $(BIN_DIR)
+
+print:
+ @echo $(CC) $(CFLAGS)
+ @echo $(CUR_OBJS)
+ @echo $(CUR_SOURCE)
+
diff --git a/study_clang/Mimic/test_judge/include/CConfig.h b/study_clang/Mimic/test_judge/include/CConfig.h
new file mode 100644
index 0000000..3d0a19f
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CConfig.h
@@ -0,0 +1,132 @@
+/*************************************************************************
+ > File Name : CConfig.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:31:50 AM CST
+ ************************************************************************/
+
+#include
+#include
+#include
+#include
+#include "CJudgeUtils.h"
+#include "CTypedef.h"
+
+class Config : public CSingleton
+{
+public:
+ Config() {}
+ virtual ~Config() {}
+public:
+
+ void Init(const std::string& file_name)
+ {
+ INIReader reader;
+ reader.Parse(file_name);
+
+ std::string strNosIdx;
+ for(int i = 0; i < NOS_MAX_NUM; i++)
+ {
+ strNosIdx.clear();
+ strNosIdx = "nos" + std::to_string((i + 1)) + "_ip";
+ nos_ip[i] = reader.Get("judge", strNosIdx, strNosIdx);
+ }
+
+ #define _GET_JUDGE_CFG(value) value = reader.GetInt32("judge", #value, value)
+ _GET_JUDGE_CFG(schedule_port);
+ _GET_JUDGE_CFG(pluginsctrl_port);
+ _GET_JUDGE_CFG(sub_nos_state_port);
+ _GET_JUDGE_CFG(nos_num);
+ _GET_JUDGE_CFG(running_num);
+
+ #undef _GET_JUDGE_CFG
+
+ #define _GET_JUDGE_CFG(value) value = reader.Get("judge", #value, value)
+ _GET_JUDGE_CFG(config_manager_ip);
+ _GET_JUDGE_CFG(schedule_ip);
+ _GET_JUDGE_CFG(pluginsctrl_ip);
+
+ #undef _GET_JUDGE_CFG
+
+ // Judge_sys_info
+ #define _GET_JUDGE_SYS_INFO_CFG(value) value = reader.GetInt32("judge_sys_info", #value, value)
+ _GET_JUDGE_SYS_INFO_CFG(nos_report_port);
+ _GET_JUDGE_SYS_INFO_CFG(msg_time_out);
+ _GET_JUDGE_SYS_INFO_CFG(cpu_occupy_max);
+ _GET_JUDGE_SYS_INFO_CFG(mem_occupy_max);
+ _GET_JUDGE_SYS_INFO_CFG(tcp_socket_max);
+ _GET_JUDGE_SYS_INFO_CFG(process_max);
+ _GET_JUDGE_SYS_INFO_CFG(cron_max);
+ _GET_JUDGE_SYS_INFO_CFG(path_file_max);
+ _GET_JUDGE_SYS_INFO_CFG(home_file_max);
+ _GET_JUDGE_SYS_INFO_CFG(process_running_code);
+
+ #undef _GET_JUDGE_SYS_INFO_CFG
+
+ #define _GET_JUDGE_SYS_INFO_CFG(value) value = reader.Get("judge_sys_info", #value, value)
+ _GET_JUDGE_SYS_INFO_CFG(sys_shell_log_name);
+ _GET_JUDGE_SYS_INFO_CFG(sys_login_log_name);
+ _GET_JUDGE_SYS_INFO_CFG(user_md5);
+ _GET_JUDGE_SYS_INFO_CFG(group_md5);
+ _GET_JUDGE_SYS_INFO_CFG(config_manager_md5);
+ _GET_JUDGE_SYS_INFO_CFG(auto_start_md5);
+ _GET_JUDGE_SYS_INFO_CFG(process_manager_name);
+ _GET_JUDGE_SYS_INFO_CFG(process_protocol_name);
+ _GET_JUDGE_SYS_INFO_CFG(process_local_cfgm_name);
+ _GET_JUDGE_SYS_INFO_CFG(process_firewall_name);
+
+ #undef _GET_JUDGE_SYS_INFO_CFG
+
+ #define _GET_JUDGE_CFG(value) value = reader.GetInt32("trans", #value, value)
+ _GET_JUDGE_CFG(trans_send_port);
+ _GET_JUDGE_CFG(trans_recv_port);
+
+ #undef _GET_JUDGE_CFG
+
+ #define _GET_JUDGE_CFG(value) value = reader.Get("trans", #value, value)
+ _GET_JUDGE_CFG(trans_send_ip);
+
+ #undef _GET_JUDGE_CFG
+ }
+
+ std::string nos_ip[NOS_MAX_NUM];
+ std::string config_manager_ip;
+ std::string schedule_ip;
+ std::string pluginsctrl_ip;
+
+ std::string trans_send_ip;
+
+ int sub_nos_state_port;
+ int schedule_port;
+ int pluginsctrl_port;
+ int nos_num;
+ int running_num;
+
+ // Judge_sys_info
+ std::string sys_shell_log_name;
+ std::string sys_login_log_name;
+ std::string process_manager_name;
+ std::string process_protocol_name;
+ std::string process_local_cfgm_name;
+ std::string process_firewall_name;
+
+ std::string user_md5;
+ std::string group_md5;
+ std::string config_manager_md5;
+ std::string auto_start_md5;
+
+ int nos_report_port;
+ int msg_time_out;
+ int cpu_occupy_max;
+ int mem_occupy_max;
+ int tcp_socket_max;
+ int process_max;
+ int cron_max;
+ int path_file_max;
+ int home_file_max;
+
+ int process_running_code;
+
+ int trans_send_port;
+ int trans_recv_port;
+};
diff --git a/study_clang/Mimic/test_judge/include/CJudgeConf.h b/study_clang/Mimic/test_judge/include/CJudgeConf.h
new file mode 100644
index 0000000..1e90788
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CJudgeConf.h
@@ -0,0 +1,49 @@
+/*************************************************************************
+ > File Name : ../include/CJudge.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:33:38 AM CST
+ ************************************************************************/
+
+#ifndef CJUDGE_H
+#define CJUDGE_H
+
+#include
+#include "CTypedef.h"
+#include "CJudgeUtils.h"
+
+typedef std::map > CACHE_MAP;
+typedef std::vector MSG_VEC;
+
+struct MsgGroup
+{
+ CACHE_MAP cache_map; // 一组执行体消息的对比缓存
+ MSG_VEC msg_vec; // 一组执行体消息源
+ time_t start_ms; // 一组新消息进入起始时间
+ unsigned int uiPort; // 一组消息的端口
+};
+
+class JudgeConf : public CSingleton
+{
+public:
+ JudgeConf() { }
+ virtual ~JudgeConf() { }
+
+public:
+ void Init(int _nos_num, int _running_num);
+ void Judge();
+
+private:
+ std::map group_map; // 按iCmd划分消息组,nos端口相同
+
+ int nos_num;
+ int running_num;
+
+ int nos_status; // 各个nos是否running TODO
+
+private:
+ int GetCacheNosNum(CACHE_MAP& map);
+
+};
+
+#endif
diff --git a/study_clang/Mimic/test_judge/include/CJudgeSysInfo.h b/study_clang/Mimic/test_judge/include/CJudgeSysInfo.h
new file mode 100644
index 0000000..79a05c1
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CJudgeSysInfo.h
@@ -0,0 +1,130 @@
+/*************************************************************************
+ > File Name : CJudgeSysInfo.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:47:20 AM CST
+ ************************************************************************/
+
+#ifndef CJUDGE_SYS_INFO_H
+#define CJUDGE_SYS_INFO_H
+
+
+#include "CTypedef.h"
+#include "CJudgeUtils.h"
+#include
+#include "CZeroMQ.h"
+
+#define MAX_MSG_BUFFER 1024 // 通信消息缓存区
+#define getbit(x,y) ((x) >> (y)&1)
+#define setbit(x,y) x|=(1< SysState_MV;
+typedef std::vector SysLog_MV;
+
+typedef struct
+{
+ SysState_MV sys_state_mv;
+ time_t start_ms;
+}SysState_Group;
+
+typedef struct
+{
+ SysLog_MV sys_log_mv;
+ time_t start_ms;
+}SysLog_Group;
+*/
+class CJudgeSysInfo : public CSingleton
+{
+public:
+ CJudgeSysInfo();
+ virtual ~CJudgeSysInfo();
+public:
+ void Init();
+ void RcvNosStateMessage();
+ void Judge();
+ int GetNosRunning(int nos_id);
+private:
+ void JudgeSysState(std::vector& sys_state_v, uint& nos_time_out_bit);
+ void JudgeProcessState();
+ void JudgeFileState();
+ void JudgeFileNum();
+ void JudgeSysLog(std::vector& SysShellLog_MV, std::vector& SysLoginLog_MV);
+
+ int JudgeCpuOccupy(uint cpu_occupy, uint nos_id);
+ int JudgeMemOccupy(uint mem_occupy, uint nos_id);
+ int JudgeTcpSocket(uint tcp_establish_num, uint nos_id);
+ int JudgeProcessNum(uint running_process, uint nos_id);
+ void JudgeLoginLog(std::vector& SysLoginLog_CMV);
+ void JudgeShellLog(std::vector& SysShellLog_CMV);
+ int JudgeUserInfo(char passwd_md5[64], uint nos_id);
+ int JudgeGroupInfo(char group_md5[64], uint nos_id);
+ int JudgeCronNum(uint cron_num, uint nos_id);
+ void JudgePathFileNum();
+ void JudgeHomeFileNum();
+ void JudgeAppMd5();
+ void JudgeAutoStartMd5();
+ void JudgeManagerProgress();
+ void JudgeProtocolProgress();
+ void JudgeLocalConfigManager();
+ void JudgeFirewell();
+
+ int SendDataToShd(const void *pvData, unsigned int uiDataLen);
+ int RecvDataFromShd(void *pvBuff, unsigned int uiBuffLen);
+
+ // 消息解析函数
+ SysState_T SplitMsgToSysState(char *buffer, int len_Buffer);
+ ProcessState_T SplitMsgToProcessState(char *buffer, int len_Buffer);
+ FileState_T SplitMsgToFileState(char *buffer, int len_Buffer);
+ FileNum_T SplitMsgToFileNum(char *buffer, int len_Buffer);
+ SysLog_T SplitMsgToSysLog(char *buffer, int len_Buffer);
+
+ uint GetNosId(char ip[32]);
+
+private:
+ // 全局标志位
+ uint nos_running_bit;
+ // 配置
+ int nos_report_port;
+ int schedule_port;
+ int msg_time_out;
+ int nos_num;
+ uint running_num;
+ std::string schedule_ip;
+
+ SysState_T m_SysState; // 系统运行状态消息
+ ProcessState_T m_ProcessState; // 关键进程状态消息
+ FileState_T m_FileState; // 关键文件状态消息
+ FileNum_T m_FileNum; // 关键文件数量消息
+ SysLog_T m_SysLog; // 关键日志增量消息
+
+ // Judge_sys_info
+ std::string sys_shell_log_name;
+ std::string sys_login_log_name;
+ std::string process_manager_name;
+ std::string process_protocol_name;
+ std::string process_local_cfgm_name;
+ std::string process_firewall_name;
+
+ std::string user_md5;
+ std::string group_md5;
+ std::string config_manager_md5;
+ std::string auto_start_md5;
+
+ uint cpu_occupy_max;
+ uint mem_occupy_max;
+ uint tcp_socket_max;
+ uint process_max;
+ uint cron_max;
+ uint path_file_max;
+ uint home_file_max;
+
+ uint process_running_code;
+
+ // ZeroMQ Connect
+ CZMQReqRep *m_pShdClient;
+ CZMQReqRep *m_pNosServer;
+};
+
+
+#endif
diff --git a/study_clang/Mimic/test_judge/include/CJudgeUtils.h b/study_clang/Mimic/test_judge/include/CJudgeUtils.h
new file mode 100644
index 0000000..e254f2d
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CJudgeUtils.h
@@ -0,0 +1,140 @@
+/*************************************************************************
+ > File Name : CJudgeUtils.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:34:47 AM CST
+ ************************************************************************/
+
+#ifndef _JUDGE_COMMON_H_
+#define _JUDGE_COMMON_H_
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "CLog.h"
+
+class CNonCopyable
+{
+protected:
+ CNonCopyable() {}
+ ~CNonCopyable() {}
+private:
+ CNonCopyable(const CNonCopyable &);
+ const CNonCopyable& operator=(const CNonCopyable &);
+};
+
+class CMutexLockGuard:CNonCopyable
+{
+ public:
+ explicit CMutexLockGuard(pthread_mutex_t& mutex)
+ : m_mutex(mutex)
+ {
+ pthread_mutex_lock(&m_mutex);
+ }
+
+ ~CMutexLockGuard()
+ {
+ pthread_mutex_unlock(&m_mutex);
+ }
+
+private:
+ pthread_mutex_t& m_mutex;
+};
+
+template
+class CSingleton
+{
+private:
+ static std::once_flag SingletonFlag;
+ static std::unique_ptr Instance;
+
+protected:
+ CSingleton() = default;
+ CSingleton(const T&) = delete;
+ CSingleton& operator=(const T&) = delete;
+
+public:
+ static T& GetInstance()
+ {
+ std::call_once(SingletonFlag, [=]() {
+ Instance.reset(new T);
+ });
+
+ return *(Instance.get());
+ }
+};
+
+template std::unique_ptr CSingleton ::Instance = nullptr;
+template std::once_flag CSingleton ::SingletonFlag;
+
+class INIReader
+{
+public:
+ explicit INIReader() {}
+ ~INIReader() {}
+
+ /// @brief 解析文件
+ /// @return 0 成功
+ /// @return <0 失败
+ /// @note 每次调用会清除上一次的解析结果
+ int32_t Parse(const std::string& filename);
+
+ void Clear();
+
+ /// @brief 获取string类型字段的值,字段未配置时使用默认值
+ std::string Get(const std::string& section, const std::string& name,
+ const std::string& default_value);
+
+ // Get an integer (long) value from INI file, returning default_value
+ // if not found or not a valid integer (decimal "1234", "-1234",
+ // or hex "0x4d2").
+ int32_t GetInt32(const std::string& section, const std::string& name,
+ int32_t default_value);
+
+ uint32_t GetUInt32(const std::string& section, const std::string& name,
+ uint32_t default_value);
+
+ int64_t GetInt64(const std::string& section, const std::string& name,
+ int64_t default_value);
+
+ uint64_t GetUInt64(const std::string& section, const std::string& name,
+ uint64_t default_value);
+
+ // Get a real (floating point double) value from INI file, returning
+ // default_value if not found or not a valid floating point value
+ // according to strtod().
+ double GetReal(const std::string& section, const std::string& name, double default_value);
+
+ // Get a boolean value from INI file, returning default_value
+ // if not found or if not a valid true/false value. Valid true
+ // values are "true", "yes", "on", "1", and valid false values are
+ // "false", "no", "off", "0" (not case sensitive).
+ bool GetBoolean(const std::string& section, const std::string& name, bool default_value);
+
+ // Returns all the section names from the INI file, in alphabetical order,
+ // but in the original casing
+ const std::set& GetSections() const;
+
+ // Returns all the field names from a section in the INI file, in
+ // alphabetical order, but in the original casing. Returns an
+ // empty set if the field name is unknown
+ std::set GetFields(const std::string& section);
+
+ /// @brief 返回最后错误字符串描述
+ /// @return 最后一次错误的信息
+ const char* GetLastError() const { return m_last_error; }
+private:
+ int32_t ParseFile(FILE* file);
+private:
+ char m_last_error[256];
+ std::set m_sections;
+ std::map > m_fields;
+};
+
+#endif
diff --git a/study_clang/Mimic/test_judge/include/CLog.h b/study_clang/Mimic/test_judge/include/CLog.h
new file mode 100644
index 0000000..e8c6c20
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CLog.h
@@ -0,0 +1,93 @@
+/*************************************************************************
+ > File Name : CLog.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:33:22 AM CST
+ ************************************************************************/
+ #ifndef CLOG_H
+ #define CLOG_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+
+//颜色宏定义
+#define NONE "\033[m"
+#define RED "\033[0;32;31m"
+#define LIGHT_RED "\033[1;31m"
+#define GREEN "\033[0;32;32m"
+#define LIGHT_GREEN "\033[1;32m"
+#define BLUE "\033[0;32;34m"
+#define LIGHT_BLUE "\033[1;34m"
+#define DARY_GRAY "\033[1;30m"
+#define CYAN "\033[0;36m"
+#define LIGHT_CYAN "\033[1;36m"
+#define PURPLE "\033[0;35m"
+#define LIGHT_PURPLE "\033[1;35m"
+#define BROWN "\033[0;33m"
+#define YELLOW "\033[1;33m"
+#define LIGHT_GRAY "\033[0;37m"
+#define WHITE "\033[1;37m"
+
+#define PRO_NAME "JUDGE"
+#define _FUN_ __FUNCTION__
+
+typedef enum tagLogLevel
+{
+ FATAL = 0,
+ ALERT,
+ ERROR,
+ WARN,
+ NOTICE,
+ INFO,
+ DEBUG
+} CYBERER_LOG_LEVEL_E;
+
+
+/*
+ * priorities/facilities are encoded into a single 32-bit quantity, where the
+ * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
+ * (0-big number). Both the priorities and the facilities map roughly
+ * one-to-one to strings in the syslogd(8) source code. This mapping is
+ * included in this file.
+ *
+ * priorities (these are ordered)
+ *
+ * #define LOG_EMERG 0 // system is unusable /
+ * #define LOG_ALERT 1 // action must be taken immediately /
+ * #define LOG_CRIT 2 // critical conditions /
+ * #define LOG_ERR 3 // error conditions /
+ * #define LOG_WARNING 4 // warning conditions /
+ * #define LOG_NOTICE 5 // normal but significant condition /
+ * #define LOG_INFO 6 // informational /
+ * #define LOG_DEBUG 7 // debug-level messages /
+*/
+#define SLOG_EMERG LOG_EMERG /* system is unusable */
+#define SLOG_ALERT LOG_ALERT /* action must be taken immediately */
+#define SLOG_CRIT LOG_CRIT /* critical conditions */
+#define SLOG_ERR LOG_ERR /* error conditions */
+#define SLOG_WARNING LOG_WARNING /* warning conditions */
+#define SLOG_NOTICE LOG_NOTICE /* normal but significant condition */
+#define SLOG_INFO LOG_INFO /* informational */
+#define SLOG_DEBUG LOG_DEBUG /* debug-level messages */
+#define SysLog(_level, fmt, ...) \
+ do{openlog("[JUDGE]", LOG_NDELAY | LOG_CONS | LOG_PID | LOG_PERROR , LOG_LOCAL5); \
+ syslog(_level, "[%s:%d] " fmt "", __FILE__, __LINE__, ##__VA_ARGS__); \
+ closelog();}while(0)
+
+extern void LogPrint(const int level,const char *proName,const char *func,const int line,const char *format, ...);
+extern void BufPrint(const char *func,const int line, const char *pData, int iDataLen);
+
+#define cPrint(fmt, ...) do{fprintf(stderr, PRO_NAME "[%s:%d] " fmt "\r\n", __FILE__, __LINE__, ##__VA_ARGS__);}while(0)
+#define dPrint(fmt, ...) do{fprintf(stderr, YELLOW PRO_NAME "[%s:%d] " fmt "\r\n" NONE, __FILE__, __LINE__, ##__VA_ARGS__);}while(0)
+#define lPrint(DLevel, format, ...) LogPrint(DLevel, PRO_NAME, __FILE__, __LINE__,format, ##__VA_ARGS__)
+#define bufPrint(pData, iDataLen) BufPrint(__FILE__, __LINE__, (const char *)pData, (int)iDataLen)
+
+#endif
+
diff --git a/study_clang/Mimic/test_judge/include/CMain.h b/study_clang/Mimic/test_judge/include/CMain.h
new file mode 100644
index 0000000..a1b3d19
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CMain.h
@@ -0,0 +1,42 @@
+/*************************************************************************
+ > File Name : ../include/CMain.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:32:23 AM CST
+ ************************************************************************/
+
+#ifndef CMAIN_H
+#define CMAIN_H
+
+ #include "CJudgeUtils.h"
+
+class CMain : public CSingleton
+{
+public:
+ CMain();
+ virtual ~CMain();
+public:
+
+ void Init();
+ int MainProcess();
+ int ReleaseSource();
+
+private:
+ int StartThreadTasks();
+
+ static void *NosHostConfMsgRcvThread(void *args);
+ static void *NosKernelConfMsgRcvThread(void *args);
+ static void *NosStateRcvThread(void *args);
+ static void *NosSysInfoRcvThread(void *args);
+ static void *NosSysInfoJudgeThread(void *args);
+ static void *SendPluginsCtrlThread(void *args);
+ static void *TransNosHostDataThread(void *args);
+ static void *TransNosKernelDataThread(void *args);
+ static void *TransDataToOtherThread(void *args);
+
+};
+
+
+#endif
+
+
diff --git a/study_clang/Mimic/test_judge/include/CMessageQueue.h b/study_clang/Mimic/test_judge/include/CMessageQueue.h
new file mode 100644
index 0000000..bed5e49
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CMessageQueue.h
@@ -0,0 +1,245 @@
+/*************************************************************************
+ > File Name : ../include/CMessageQueue.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:35:11 AM CST
+ ************************************************************************/
+
+#ifndef CMESSAGEQUEUE_H
+#define CMESSAGEQUEUE_H
+#include "CTypedef.h"
+#include "CJudgeUtils.h"
+
+template
+class CMessageQueue : public CSingleton >
+{
+public:
+ CMessageQueue();
+ virtual ~CMessageQueue();
+public:
+
+ void push(T stData,Message_QueueType_E MessageType = m_MessageTypeE);
+ void pop(Message_QueueType_E MessageType = m_MessageTypeE);
+ T& front(Message_QueueType_E MessageType = m_MessageTypeE);
+ T& back(Message_QueueType_E MessageType = m_MessageTypeE);
+ int empty(Message_QueueType_E MessageType = m_MessageTypeE);
+ uint size(Message_QueueType_E MessageType = m_MessageTypeE);
+ void remove(T stData, Message_QueueType_E MessageType = m_MessageTypeE);
+
+private:
+
+
+private:
+ static const Message_QueueType_E m_MessageTypeE = MQT_CONFIG_E;
+
+ pthread_mutex_t m_QueueMutex;
+ std::list m_queue;
+
+ pthread_mutex_t ss_QueueMutex;
+ std::list q_SysState;
+
+ pthread_mutex_t ps_QueueMutex;
+ std::list q_ProcessState;
+
+ pthread_mutex_t fs_QueueMutex;
+ std::list q_FileState;
+
+ pthread_mutex_t fn_QueueMutex;
+ std::list q_FileNum;
+
+ pthread_mutex_t sl_QueueMutex;
+ std::list q_SysLog;
+};
+
+
+template
+CMessageQueue::CMessageQueue()
+{
+ pthread_mutex_init(&m_QueueMutex, NULL);
+
+ pthread_mutex_init(&ss_QueueMutex, NULL);
+ pthread_mutex_init(&ps_QueueMutex, NULL);
+ pthread_mutex_init(&fs_QueueMutex, NULL);
+ pthread_mutex_init(&fn_QueueMutex, NULL);
+ pthread_mutex_init(&sl_QueueMutex, NULL);
+}
+
+template
+CMessageQueue::~CMessageQueue()
+{
+ pthread_mutex_destroy(&m_QueueMutex);
+
+ pthread_mutex_destroy(&ss_QueueMutex);
+ pthread_mutex_destroy(&ps_QueueMutex);
+ pthread_mutex_destroy(&fs_QueueMutex);
+ pthread_mutex_destroy(&fn_QueueMutex);
+ pthread_mutex_destroy(&sl_QueueMutex);
+}
+
+template
+void CMessageQueue::push(T stData,Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_PUSH(type, q, lock) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ q.push_back(stData); \
+ break;\
+ }
+ _MQT_PUSH(CONFIG, m_queue, m);
+ _MQT_PUSH(SYS_STATE, q_SysState, ss);
+ _MQT_PUSH(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_PUSH(FILE_STATE, q_FileState, fs);
+ _MQT_PUSH(FILE_NUM, q_FileNum, fn);
+ _MQT_PUSH(SYS_LOG, q_SysLog, sl);
+#undef _MQT_PUSH
+ default:
+ break;
+ }
+}
+
+template
+void CMessageQueue::pop(Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_POP(type, q, lock ) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ q.pop_front(); \
+ break; \
+ }
+ _MQT_POP(CONFIG, m_queue, m);
+ _MQT_POP(SYS_STATE, q_SysState, ss);
+ _MQT_POP(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_POP(FILE_STATE, q_FileState, fs);
+ _MQT_POP(FILE_NUM, q_FileNum, fn);
+ _MQT_POP(SYS_LOG, q_SysLog, sl);
+#undef _MQT_POP
+ default:
+ break;
+ }
+
+}
+
+template
+T& CMessageQueue::front(Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_FRONT(type, q, lock) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ return q.front(); \
+ }
+ _MQT_FRONT(CONFIG, m_queue, m);
+ _MQT_FRONT(SYS_STATE, q_SysState, ss);
+ _MQT_FRONT(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_FRONT(FILE_STATE, q_FileState, fs);
+ _MQT_FRONT(FILE_NUM, q_FileNum, fn);
+ _MQT_FRONT(SYS_LOG, q_SysLog, sl);
+#undef _MQT_FRONT
+ default:
+ return m_queue.front();
+ }
+
+}
+
+template
+T& CMessageQueue::back(Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_BACK(type, q, lock) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ return q.back(); \
+ }
+ _MQT_BACK(CONFIG, m_queue, m);
+ _MQT_BACK(SYS_STATE, q_SysState, ss);
+ _MQT_BACK(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_BACK(FILE_STATE, q_FileState, fs);
+ _MQT_BACK(FILE_NUM, q_FileNum, fn);
+ _MQT_BACK(SYS_LOG, q_SysLog, sl);
+#undef _MQT_BACK
+ default:
+ return m_queue.back();
+ }
+}
+
+template
+int CMessageQueue::empty(Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_EMPTY(type, q, lock) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ return q.empty(); \
+ }
+ _MQT_EMPTY(CONFIG, m_queue, m);
+ _MQT_EMPTY(SYS_STATE, q_SysState, ss);
+ _MQT_EMPTY(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_EMPTY(FILE_STATE, q_FileState, fs);
+ _MQT_EMPTY(FILE_NUM, q_FileNum, fn);
+ _MQT_EMPTY(SYS_LOG, q_SysLog, sl);
+#undef _MQT_EMPTY
+ default:
+ return 0;
+ }
+ return 0;
+}
+
+template
+uint CMessageQueue::size(Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_SIZE(type, q, lock) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ return q.size(); \
+ }
+ _MQT_SIZE(CONFIG, m_queue, m);
+ _MQT_SIZE(SYS_STATE, q_SysState, ss);
+ _MQT_SIZE(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_SIZE(FILE_STATE, q_FileState, fs);
+ _MQT_SIZE(FILE_NUM, q_FileNum, fn);
+ _MQT_SIZE(SYS_LOG, q_SysLog, sl);
+#undef _MQT_SIZE
+ default:
+ return 0;
+ }
+}
+
+template
+void CMessageQueue::remove(T stData, Message_QueueType_E MessageType)
+{
+ switch(MessageType)
+ {
+#define _MQT_REMOVE(type, q, lock) \
+ case MQT_##type##_E: \
+ { \
+ CMutexLockGuard MutexLock(lock##_QueueMutex); \
+ return q.remove(stData); \
+ }
+ _MQT_REMOVE(CONFIG, m_queue, m);
+ _MQT_REMOVE(SYS_STATE, q_SysState, ss);
+ _MQT_REMOVE(PROCESS_STATE, q_ProcessState, ps);
+ _MQT_REMOVE(FILE_STATE, q_FileState, fs);
+ _MQT_REMOVE(FILE_NUM, q_FileNum, fn);
+ _MQT_REMOVE(SYS_LOG, q_SysLog, sl);
+#undef _MQT_REMOVE
+ default:
+ break;
+ }
+}
+#endif
+
diff --git a/study_clang/Mimic/test_judge/include/CMysqlPool.h b/study_clang/Mimic/test_judge/include/CMysqlPool.h
new file mode 100644
index 0000000..18075a2
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CMysqlPool.h
@@ -0,0 +1,98 @@
+/*************************************************************************
+ > File Name : CMysqlPool.h
+ > Author : liuzhao
+ > EMail : liuzhao@comleader.com.cn
+ > Created Time : Fri 17 Jul 2020 09:40:09 AM CST
+ ************************************************************************/
+
+#ifndef MYSQLPOOL_H
+#define MYSQLPOOL_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "CJudgeUtils.h"
+
+struct MysqlResults
+{
+ int field_count;
+ int record_count;
+ std::vector> value;
+ std::vector field_name;
+
+ MysqlResults() : field_count(0), record_count(0) {}
+ void Print()
+ {
+ std::cout << "[field_count:" << field_count << "]" << std::endl;
+ std::cout << "[record_count:" << record_count << "]" << std::endl;
+ int i = 0;
+ std::cout << "[field]" << "\t";
+ for (auto v : field_name)
+ {
+ std::cout << v << "\t";
+ }
+ std::cout << std::endl;
+
+ for (auto v : value)
+ {
+ int j = 0;
+ std::cout << "[row:" << i << "]" << "\t";
+ for (auto x : v)
+ {
+ std::cout << x << "\t";
+ j++;
+ }
+ std::cout << std::endl;
+ i ++;
+ }
+ }
+};
+
+class MysqlPool : public CSingleton
+{
+public:
+ MysqlPool();
+ virtual ~MysqlPool();
+
+public:
+ void executeSql(MysqlResults& results, const char* sql);//sql语句的执行函数
+ void setParameter( const char* _mysqlhost,
+ const char* _mysqluser,
+ const char* _mysqlpwd,
+ const char* _databasename,
+ unsigned int _port = 0,
+ const char* _socket = NULL,
+ unsigned long _client_flag = 0,
+ unsigned int MAX_CONNECT = 50 ); //设置数据库参数
+ private:
+ MYSQL* createOneConnect(); //创建一个新的连接对象
+ MYSQL* getOneConnect(); //获取一个连接对象
+ void close(MYSQL* conn); //关闭连接对象
+ bool isEmpty(); //连接池队列池是否为空
+ MYSQL* poolFront(); //连接池队列的队头
+ unsigned int poolSize(); //获取连接池的大小
+ void poolPop(); //弹出连接池队列的队头
+ private:
+ std::queue mysqlpool; //连接池队列
+ const char* _mysqlhost; //mysql主机地址
+ const char* _mysqluser; //mysql用户名
+ const char* _mysqlpwd; //mysql密码
+ const char* _databasename; //要使用的mysql数据库名字
+ unsigned int _port; //mysql端口
+ const char* _socket; //可以设置成Socket or Pipeline,通常设置为NULL
+ unsigned long _client_flag; //设置为0
+ unsigned int MAX_CONNECT; //同时允许最大连接对象数量
+ unsigned int connect_count; //目前连接池的连接对象数量
+ static std::mutex objectlock; //对象锁
+ static std::mutex poollock; //连接池锁
+ static MysqlPool* mysqlpool_object; //类的对象
+};
+
+#endif
diff --git a/study_clang/Mimic/test_judge/include/CNetManager.h b/study_clang/Mimic/test_judge/include/CNetManager.h
new file mode 100644
index 0000000..b7aa233
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CNetManager.h
@@ -0,0 +1,101 @@
+/*************************************************************************
+ > File Name : CNetManager.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:31:31 AM CST
+ ************************************************************************/
+
+#ifndef CNETMANAGER_H
+#define CNETMANAGER_H
+
+#include
+#include "CTypedef.h"
+#include "CUdpServer.h"
+#include "CUdpClient.h"
+#include "CZeroMQ.h"
+#include "CJudgeUtils.h"
+
+#define PORT_BIND_SET_HOST 10014
+#define PORT_BIND_GET_HOST 10013
+#define PORT_BIND_SET_KERNEL 10012
+#define PORT_BIND_GET_KERNEL 10011
+
+#define PORT_SET_HOST 10004
+#define PORT_GET_HOST 10003
+#define PORT_SET_KERNEL 10002
+#define PORT_GET_KERNEL 10001
+
+class CNetManager : public CSingleton
+{
+public:
+ CNetManager();
+ virtual ~CNetManager();
+public:
+ int RecvDataToConfManagerHost(void *pvBuff, unsigned int uiBuffLen);
+ int SendDataToConfManagerHost(const void *pvData, unsigned int uiDataLen);
+
+ int RecvDataToConfManagerKernel(void *pvBuff, unsigned int uiBuffLen);
+ int SendDataToConfManagerKernel(const void *pvData, unsigned int uiDataLen);
+
+ int SendHostDataToAllNos(const void *pvData, unsigned int uiDataLen);
+ int SendHostDataToNos(int iNosIdx, const void *pvData, unsigned int uiDataLen);
+
+ int SendKernelDataToAllNos(const void *pvData, unsigned int uiDataLen);
+ int SendKernelDataToNos(int iNosIdx, const void *pvData, unsigned int uiDataLen);
+
+ int SendDataToShd(const void *pvData, unsigned int uiDataLen);
+ int RecvDataFromShd(void *pvBuff, unsigned int uiBuffLen);
+
+ int SendDataToPCtl(const void *pvData, unsigned int uiDataLen);
+ int RecvDataFromPCtl(void *pvBuff, unsigned int uiBuffLen);
+
+ void RecvNosDataHost();
+ void RecvNosDataKernel();
+
+ void RecvNosStateFromShd();
+ int GetNosStateById(int iIdx);
+
+ int SetNosNetInfoHost(unsigned int uiIdx, const SOCKADDR_IN_T *pstInfo);
+ int GetNosNetInfoHost(unsigned int uiIdx, SOCKADDR_IN_T *pstInfo);
+
+ int SetNosNetInfoKernel(unsigned int uiIdx, const SOCKADDR_IN_T *pstInfo);
+ int GetNosNetInfoKernel(unsigned int uiIdx, SOCKADDR_IN_T *pstInfo);
+
+ void TransNosHostData();
+ void TransNosKernelData();
+ void TransBroadcastDataToOther();
+
+ void SendPluginsCtrl();
+
+private:
+ int GetNosIdxBySock(SOCKADDR_IN_T *pstSockAddrIn);
+
+private:
+ pthread_mutex_t m_NosNetInfoHostMutex;
+ pthread_mutex_t m_NosNetInfoKernelMutex;
+
+ SOCKADDR_IN_T m_stNosNetInfoHost[NOS_MAX_NUM];
+ SOCKADDR_IN_T m_stNosNetInfoKernel[NOS_MAX_NUM];
+
+ CUdpClient m_ConfigManagerHost;
+ CUdpClient m_ConfigManagerKernel;
+
+ CUdpServer m_NosDataHost;
+ CUdpServer m_NosDataKernel;
+
+ CZMQReqRep *m_pShdClient;
+ CZMQReqRep *m_pPCtlClient;
+ CZMQSubscriber *m_pNosStateSub;
+
+ NosState_T m_stNosState[NOS_MAX_NUM];
+
+ CUdpServer m_NosHostTrans;
+ CUdpServer m_NosKernelTrans;
+
+ CUdpServer m_BroadcastDataTrans;
+};
+
+
+#endif /*CNETMANAGER_H*/
+
+
diff --git a/study_clang/Mimic/test_judge/include/CSwitchCommon.h b/study_clang/Mimic/test_judge/include/CSwitchCommon.h
new file mode 100644
index 0000000..a42e772
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CSwitchCommon.h
@@ -0,0 +1,192 @@
+/*************************************************************************
+ > File Name : CSwitchCommon.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 23 Jul 2020 09:13:37 AM CST
+ ************************************************************************/
+
+#ifndef CSWITCHCOMMON_H
+#define CSWITCHCOMMON_H
+
+#define MAX_NOS_NUM 8
+
+typedef enum Judge_Error_Code_E
+{
+ JUDGE_ALL_SUCCESS=0, /*接收到所有执行体消息,全部一致*/
+ /*
+ ----+----+-----
+ | A | B | C | 1、线上执行体为A/B/C
+ ----+----+-----
+ | 1 | 1 | 1 | 2、收到A/B/C全部一致的消息
+ ----+----+-----
+
+ uiNosIdx = 0;
+ */
+ JUDGE_SUCC_WITH_TWO_STAGE, /*接收到所有执行体消息,有多数一致,但少数也一致*/
+ /*
+ ----+----+----
+ | A | B | C 1、线上执行体为A/B/C
+ ----+----+----
+ | 1 | 1 | 2 2、收到的消息中,A/B全部一致
+ ----+----+----
+
+ uiNosIdx = C;
+ */
+ JUDGE_SUCC_WITH_MANY_STAGE, /*接收到所有执行体消息,有多数一致,但有多个少数群体*/
+ /*
+ ----+----+----+----+-----
+ | A | B | C | D | E 1、线上执行体为A/B/C/D/E
+ ----+----+----+----+-----
+ | 1 | 1 | 1 | 2 | 3 2、收到的消息中,A/B/C全部一致,D/E不一致
+ ----+----+----+----+-----
+
+ uiNosIdx = D | E;
+ */
+ JUDGE_SUCC_WITH_TIMEOUT, /*未收到所有执行体消息,全部一致*/
+ /*
+ ----+----+-----
+ | A | B | C | 1、线上执行体为A/B/C
+ ----+----+-----
+ | 1 | 1 | | 2、收到A/B全部一致的消息,未收到C的消息
+ ----+----+-----
+
+ uiNosIdx = 1 << C;
+ */
+ JUDGE_SUCC_WITH_TIMEOUT_TWO_STAGE, /*未收到所有执行体消息,有多数一致,但少数也一致*/
+ /*
+ ----+----+----+----+-----
+ | A | B | C | D | E 1、线上执行体为A/B/C/D/E
+ ----+----+----+----+-----
+ | 1 | 1 | 1 | 2 | 2、收到的消息中,A/B/C全部一致,收到D的消息,E超时
+ ----+----+----+----+-----
+
+ uiNosIdx = D | E;
+ */
+ JUDGE_SUCC_WITH_TIMEOUT_MANY_STAGE, /*未收到所有执行体消息,有多数一致,但有多个少数群体*/
+ /*
+ ----+----+----+----+----+----+-----
+ | A | B | C | D | E | F | G 1、线上执行体为A/B/C/D/E/F/G
+ ----+----+----+----+----+----+-----
+ | 1 | 1 | 1 | 1 | 2 | 3 | 2、收到的消息中,A/B/C全部一致,D/E不一致,G超时
+ ----+----+----+----+----+----+-----
+
+ uiNosIdx = E | F | G;
+ */
+ JUDGE_ALL_FAIL_WITH_DIFF, /*收到所有执行体消息,全部不一致*/
+ /*
+ ----+----+-----
+ | A | B | C | 1、线上执行体为A/B/C
+ ----+----+-----
+ | 1 | 2 | 3 | 2、收到A/B/C的消息,但完全不同
+ ----+----+-----
+
+ uiNosIdx = A | B | C;
+ */
+ JUDGE_FAIL_WITH_TWO_STAGE, /*收到所有执行体消息,分为数目相同的两个群体*/
+ /*
+ ----+----+----+----
+ | A | B | C | D 1、线上执行体为A/B/C/D
+ ----+----+----+----
+ | 1 | 1 | 2 | 2 2、收到A/B/C/D的消息,A/B一致,C/D一致
+ ----+----+----+----
+
+ uiNosIdx = A | B | C | D;
+ */
+ JUDGE_FAIL_WITH_MANY_STAGE, /*收到所有执行体信息,分为多个少数群体*/
+ /*
+ ----+----+----+----+-----
+ | A | B | C | D | E 1、线上执行体为A/B/C/D/E
+ ----+----+----+----+-----
+ | 1 | 1 | 2 | 2 | 3 2、收到的消息中,A/B全部一致,C/D全部一致
+ ----+----+----+----+-----
+
+ uiNosIdx = A | B | C | D | E;
+ */
+ JUDGE_FAIL_WITH_TIMEOUT, /*未收到所有执行体消息,达不到裁决条件*/
+ /*
+ ----+----+-----
+ | A | B | C | 1、线上执行体为A/B/C
+ ----+----+-----
+ | 1 | | | 2、收到A/B/C的消息,但完全不同
+ ----+----+-----
+
+ uiNosIdx = A;
+ */
+ JUDGE_FAIL_WITH_TIMEOUT_TWO_STAGE, /*未收到所有执行体消息,分为两个少数群体*/
+ /*
+ ----+----+-----
+ | A | B | C | 1、线上执行体为A/B/C
+ ----+----+-----
+ | 1 | 2 | | 2、收到A/B的消息,A/B不同, C超时
+ ----+----+-----
+
+ uiNosIdx = A | B | C;
+ */
+ JUDGE_FAIL_WITH_TIMEOUT_MANY_STAGE, /*未收到所有执行体消息,分为多个少数群体*/
+ /*
+ ----+----+----+----+-----
+ | A | B | C | D | E 1、线上执行体为A/B/C/D/E
+ ----+----+----+----+-----
+ | 1 | 1 | 2 | 2 | 2、收到的消息中,A/B全部一致,C/D全部一致,E超时
+ ----+----+----+----+-----
+
+ uiNosIdx = A | B | C | D | E;
+ */
+ JUDGE_RET_MAX,
+
+ JUDGE_SYS_RUNNING, /* Nos正常运行 */
+ JUDGE_EXCESSIVE_CPU_OCCUPY, /*CPU占用率偏高*/
+ JUDGE_EXCESSIVE_MEM_OCCUPY, /*内存占用率偏高*/
+ JUDGE_EXCESSIVE_TCP_SOCKET, /*TCP SOCKET连接数过多*/
+ JUDGE_EXCESSIVE_PROGRESS, /*进程总数过多*/
+ JUDGE_SOMEONE_BROKEN_INTO, /*执行体被登入*/
+ JUDGE_EXCEPTION_SHELL, /*执行体运行了异常的shell命令*/
+ JUDGE_EXCEPTION_USER, /*执行体系统用户账户信息发生变化*/
+ JUDGE_EXCEPTION_GROUP, /*执行体系统用户组信息发生变化*/
+ JUDGE_CHANGE_CRON, /*计划任务个数产生变动*/
+ JUDGE_CHANGE_FILE_IN_PATH, /*PATH目录下文件个数产生变动*/
+ JUDGE_CHANGE_FILE_IN_HOME, /*用户目录下文件个数产生变动*/
+ JUDGE_EXCEPTION_APP, /*关键可执行文件被篡改*/
+ JUDGE_EXCEPTION_AUTOSTART, /*开机自启文件被篡改*/
+ JUDGE_EXCEPTION_MANAGER, /*管理进程被异常停止*/
+ JUDGE_EXCEPTION_PROTOCOL, /*协议进程被异常停止*/
+ JUDGE_EXCEPTION_LOCAL_CONFIG_MANAGER, /*本地配置管理器被异常停止*/
+ JUDGE_EXCEPTION_FIREWALL, /*防火墙被异常关闭*/
+ JUDGE_TIME_OUT, /*某执行体状态信息上报超时*/
+
+ ERROR_CODE_MAX
+}Judge_Error_Code_T;
+
+typedef struct Judge_Error_Msg_S
+{
+ Judge_Error_Code_T uiErrorCode; //错误代码
+#define NOS1_FLAG 1<<0
+#define NOS2_FLAG 1<<1
+#define NOS3_FLAG 1<<2
+#define NOS4_FLAG 1<<3
+#define NOS5_FLAG 1<<4
+#define NOS6_FLAG 1<<5
+#define NOS7_FLAG 1<<6
+#define NOS8_FLAG 1<<7
+#define NOS9_FLAG 1<<8
+#define NOS10_FLAG 1<<9
+ uint uiNosIdx;
+ char szReserve[32];
+}Judge_Error_Msg_T;
+
+typedef enum {
+ HB_JUDGE_E = 1,
+ HB_SHD_E,
+ HB_MYSQL_E,
+ HB_WEB_E,
+ HB_CFG_MANAGER_E,
+ HB_MAX_E
+}HEARBEAT_E;
+
+typedef enum {
+ NOS_STATE_INVALID_E,
+ NOS_STATE_STOP_E,
+ NOS_STATE_START_E
+}NOS_STATE_E;
+
+#endif /*CSWITCHCOMMON_H*/
diff --git a/study_clang/Mimic/test_judge/include/CTypedef.h b/study_clang/Mimic/test_judge/include/CTypedef.h
new file mode 100644
index 0000000..4744e3b
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CTypedef.h
@@ -0,0 +1,124 @@
+/*************************************************************************
+ > File Name : CTypedef.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:32:54 AM CST
+ ************************************************************************/
+#ifndef CTYPEDEF_H
+#define CTYPEDEF_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "CLog.h"
+#include "CSwitchCommon.h"
+
+#ifndef MAX_NOS_NUM
+#define NOS_MAX_NUM 8
+#else
+#define NOS_MAX_NUM MAX_NOS_NUM
+#endif
+
+#define CONF_FILE_PATH "./judge_conf.ini"
+
+#define JUDGE_PUBLIC_KEY (const char *)"p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE"
+#define JUDGE_PRIVATE_KEY (const char *)"q0]#)iuwR*H5hz.} File Name : CUdpClient.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:29:08 AM CST
+ ************************************************************************/
+
+#ifndef CUDPCLIENT_H
+#define CUDPCLIENT_H
+#include "CTypedef.h"
+
+
+class CUdpClient
+{
+public:
+ CUdpClient();
+ CUdpClient(const char *pcHost, unsigned int uiPort);
+ ~CUdpClient();
+
+ int CUdpRecvData(void *pcBuff, unsigned int uiBuffLen);
+ int CUdpSendData(const void *pcData, unsigned int uiDataLen);
+ int CUdpRecvData(void *pcBuff, unsigned int uiBuffLen, const char *pcHost, unsigned int uiPort);
+ int CUdpSendData(const void *pcData, unsigned int uiDataLen, const char *pcHost, unsigned int uiPort);
+
+ int CUdpSetSendTimeout(unsigned int uiSeconds = 3);
+ int CUdpSetRecvTimeout(unsigned int uiSeconds = 3);
+ int CUdpSetBroadcastOpt();
+
+private:
+ int CUdpSocket();
+ int CUdpGetSockaddr(const char * pcHost, unsigned int uiPort, SOCKADDR_IN_T *pstSockaddr);
+
+private:
+ int m_iClientSock;
+ unsigned int m_uiPort;
+ unsigned char m_ucHost[16];
+ SOCKADDR_IN_T m_stServerInfo;
+};
+
+
+
+
+
+#endif /*CUDPCLIENT_H*/
+
diff --git a/study_clang/Mimic/test_judge/include/CUdpServer.h b/study_clang/Mimic/test_judge/include/CUdpServer.h
new file mode 100644
index 0000000..4e2ddfe
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CUdpServer.h
@@ -0,0 +1,32 @@
+/*************************************************************************
+ > File Name : CUdpServer.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:29:21 AM CST
+ ************************************************************************/
+#ifndef CUDPSERVER_H
+#define CUDPSERVER_H
+
+#include "CTypedef.h"
+
+
+class CUdpServer
+{
+public:
+ CUdpServer();
+ CUdpServer(unsigned int uiPort);
+ ~CUdpServer();
+
+ int CUdpSocket();
+ int CUdpSocket(unsigned int uiPort);
+ int CUdpRecvData(void *pvBuff, unsigned int uiBuffLen, SOCKADDR_IN_T *pstClientInfo);
+ int CUdpSendData(const void *pvData, unsigned int uiDataLen, SOCKADDR_IN_T stClientInfo);
+
+
+private:
+ int m_iSerSock;
+ unsigned int m_uiPort;
+};
+
+#endif /*CUDPSERVER_H*/
+
diff --git a/study_clang/Mimic/test_judge/include/CZeroMQ.h b/study_clang/Mimic/test_judge/include/CZeroMQ.h
new file mode 100644
index 0000000..d4cf2cc
--- /dev/null
+++ b/study_clang/Mimic/test_judge/include/CZeroMQ.h
@@ -0,0 +1,64 @@
+/*****************************************************************************
+ * @Descripttion:
+ * @Author: FengChao
+ * @Date: 2020-08-07 16:56:44
+ * @LastEditors: LastEditors
+ * @LastEditTime: 2020-08-07 17:29:41
+ *****************************************************************************/
+/*************************************************************************
+ > File Name : CZeroMQ.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:30:51 AM CST
+ ************************************************************************/
+
+#ifndef CZEROMQ_H
+#define CZEROMQ_H
+#include
+
+class CZMQSubscriber
+{
+public:
+ explicit CZMQSubscriber(const char *pcAddrPort, const char *pcPriKey = NULL, const char *pcPubKey = NULL);
+ ~CZMQSubscriber();
+
+ int SetRecvTimeout(unsigned int uiSeconds = 3);
+ int RecvData(void *pvBuff, unsigned int uiBuffLen);
+
+private:
+ int SocketInit();
+
+private:
+ void *m_pvSubCtx;
+ void *m_pvSubSock;
+ std::string m_strAddrPort;
+ std::string m_StrPriKey;
+ std::string m_StrPubKey;
+};
+
+
+class CZMQReqRep
+{
+public:
+ explicit CZMQReqRep(int iType, const char *pcAddrPort, const char *pcPriKey = NULL, const char *pcPubKey = NULL);
+ ~CZMQReqRep();
+
+ int RecvData(void *pvBuff, unsigned int uiBuffLen);
+ int SendData(const void *pvData, unsigned int uiDataLen);
+ int SetRecvTimeout(unsigned int uiSeconds = 3);
+ int SetSendTimeout(unsigned int uiSeconds = 3);
+
+private:
+ int SocketInit();
+
+private:
+ int m_iType;
+ void *m_pvCtx;
+ void *m_pvSock;
+ std::string m_strAddrPort;
+ std::string m_StrPriKey;
+ std::string m_StrPubKey;
+};
+
+#endif /*CZEROMQ_H*/
+
diff --git a/study_clang/Mimic/test_judge/judge b/study_clang/Mimic/test_judge/judge
new file mode 100644
index 0000000..427a227
Binary files /dev/null and b/study_clang/Mimic/test_judge/judge differ
diff --git a/study_clang/Mimic/test_judge/judge_conf.ini b/study_clang/Mimic/test_judge/judge_conf.ini
new file mode 100644
index 0000000..8bf2a80
--- /dev/null
+++ b/study_clang/Mimic/test_judge/judge_conf.ini
@@ -0,0 +1,44 @@
+[judge]
+schedule_ip=30.30.30.2
+schedule_port=8100
+sub_nos_state_port=8200
+
+pluginsctrl_ip=172.18.0.1
+pluginsctrl_port=8301
+
+nos1_ip=10.10.10.241
+nos2_ip=10.10.10.242
+nos3_ip=10.10.10.243
+nos4_ip=10.10.10.244
+
+config_manager_ip=192.168.0.250
+
+running_num=3
+nos_num=3
+
+[judge_sys_info]
+nos_report_port=7002
+msg_time_out=3000
+sys_shell_log_name=history
+sys_login_log_name=wtmp
+process_manager_name=manager
+process_protocol_name=protocol
+process_local_cfgm_name=localcfgmanager
+process_firewall=firewall
+
+cpu_occupy_max=900
+mem_occupy_max=900
+tcp_socket_max=30
+process_max=500
+cron_max=20
+path_file_max=500
+home_file_max=100
+user_md5=155c0f8a0aca2bfa5f2e85a32be41803
+group_md5=62bc68396162fda049d1ba7c7d04eb54
+config_manager_md5=62bc68396162fda049d1ba7c7d04eb54
+auto_start_md5=62bc68396162fda049d1ba7c7d04eb54
+
+[trans]
+trans_send_ip=192.168.0.250
+trans_send_port=6677
+trans_recv_port=8899
diff --git a/study_clang/Mimic/test_judge/judge_test b/study_clang/Mimic/test_judge/judge_test
new file mode 100755
index 0000000..cb9f992
Binary files /dev/null and b/study_clang/Mimic/test_judge/judge_test differ
diff --git a/study_clang/Mimic/test_judge/obj/CJudgeConf.o b/study_clang/Mimic/test_judge/obj/CJudgeConf.o
new file mode 100644
index 0000000..82333f3
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CJudgeConf.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CJudgeSysInfo.o b/study_clang/Mimic/test_judge/obj/CJudgeSysInfo.o
new file mode 100644
index 0000000..bcc1c9c
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CJudgeSysInfo.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CJudgeUtils.o b/study_clang/Mimic/test_judge/obj/CJudgeUtils.o
new file mode 100644
index 0000000..64b23a7
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CJudgeUtils.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CLog.o b/study_clang/Mimic/test_judge/obj/CLog.o
new file mode 100644
index 0000000..2c754c9
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CLog.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CMain.o b/study_clang/Mimic/test_judge/obj/CMain.o
new file mode 100644
index 0000000..0e28643
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CMain.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CMessageQueue.o b/study_clang/Mimic/test_judge/obj/CMessageQueue.o
new file mode 100644
index 0000000..797e0ed
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CMessageQueue.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CMysqlPool.o b/study_clang/Mimic/test_judge/obj/CMysqlPool.o
new file mode 100644
index 0000000..02d583b
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CMysqlPool.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CNetManager.o b/study_clang/Mimic/test_judge/obj/CNetManager.o
new file mode 100644
index 0000000..ec673c3
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CNetManager.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CUdpClient.o b/study_clang/Mimic/test_judge/obj/CUdpClient.o
new file mode 100644
index 0000000..499ed7f
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CUdpClient.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CUdpServer.o b/study_clang/Mimic/test_judge/obj/CUdpServer.o
new file mode 100644
index 0000000..0006b32
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CUdpServer.o differ
diff --git a/study_clang/Mimic/test_judge/obj/CZeroMQ.o b/study_clang/Mimic/test_judge/obj/CZeroMQ.o
new file mode 100644
index 0000000..53d3761
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/CZeroMQ.o differ
diff --git a/study_clang/Mimic/test_judge/obj/main.o b/study_clang/Mimic/test_judge/obj/main.o
new file mode 100644
index 0000000..800e2fd
Binary files /dev/null and b/study_clang/Mimic/test_judge/obj/main.o differ
diff --git a/study_clang/Mimic/test_judge/src/CJudgeConf.cpp b/study_clang/Mimic/test_judge/src/CJudgeConf.cpp
new file mode 100644
index 0000000..2afd148
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CJudgeConf.cpp
@@ -0,0 +1,334 @@
+/*************************************************************************
+ > File Name : CJudge.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:33:21 AM CST
+ ************************************************************************/
+
+#include "CJudgeConf.h"
+#include "CMessageQueue.h"
+#include "CNetManager.h"
+#include "CMysqlPool.h"
+
+#define MSG_TIMEOUT 3000
+
+time_t GetTimeStampMS()
+{
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+ return tv.tv_sec*1000 + tv.tv_usec/1000;
+}
+
+void JudgeConf::Init(int _nos_num, int _running_num)
+{
+ nos_num = _nos_num;
+ running_num = _running_num;
+
+ nos_status = 0;
+ for (auto i = 0; i < running_num; i++)
+ {
+ nos_status |= 1 << i;
+ }
+
+ group_map.clear();
+}
+
+int JudgeConf::GetCacheNosNum(CACHE_MAP& map)
+{
+ int num = 0;
+ for (auto &v : map)
+ {
+ num += v.second.size();
+ }
+ return num;
+}
+
+/*
+* 其他线程 nos_status TODO
+*/
+void JudgeConf::Judge()
+{
+ while(true)
+ {
+ time_t now_ms = GetTimeStampMS();
+ if (CMessageQueue::GetInstance().empty())
+ {
+ for (std::map::iterator it = group_map.begin(); it != group_map.end();)
+ {
+ MsgGroup& mg = it->second;
+ if (now_ms - mg.start_ms >= MSG_TIMEOUT)
+ {
+ // TODO 超时逻辑
+ Judge_Error_Msg_T ret;
+ std::string succ_str;
+ bool succ = false;
+
+ for (auto &v : mg.cache_map)
+ {
+ if ((int)v.second.size() >= running_num / 2 + 1)
+ {
+ succ = true;
+ succ_str = v.first;
+ break;
+ }
+ }
+
+ // 裁决成功 str达到半数以上相同; 给ConfManager发消息
+ ConfJudgeMsg_ST j2n_msg;
+ memset(&j2n_msg, 0, sizeof(j2n_msg));
+ if (succ)
+ {
+ j2n_msg.iCmd = 1; // TODO
+
+ /*
+ ConfJudgeMsg_ST j2c_msg;
+ memset(&j2c_msg, 0, sizeof(j2c_msg));
+
+ j2c_msg.iCmd = it->first;
+ memcpy(j2c_msg.ucData, succ_str.c_str(), succ_str.size());
+
+ if (mg.uiPort == PORT_BIND_SET_KERNEL)
+ {
+ CNetManager::GetInstance().SendDataToConfManagerKernel(&j2c_msg, sizeof(int) + succ_str.size());
+ ConfJudgeMsg_ST c2j_msg;
+ if (CNetManager::GetInstance().RecvDataToConfManagerKernel(&c2j_msg, sizeof(c2j_msg)) < 0)
+ {
+ SysLog(LOG_ERR, "recv confManagerKernel error");
+ }
+ }
+ else if (mg.uiPort == PORT_BIND_SET_HOST)
+ {
+ CNetManager::GetInstance().SendDataToConfManagerHost(&j2c_msg, sizeof(int) + succ_str.size());
+ if (CNetManager::GetInstance().RecvDataToConfManagerHost(&j2n_msg, sizeof(j2n_msg)) < 0)
+ {
+ SysLog(LOG_ERR, "recv confManagerHost error");
+ }
+ }
+ else
+ {
+ SysLog(LOG_ERR, "[uiPort:%d] error", mg.uiPort);
+ }*/
+ }
+
+ // 给NOS回消息
+ CNetManager::GetInstance().SendHostDataToAllNos(&j2n_msg, sizeof(j2n_msg));
+
+ // 裁决结果给调度
+ if (succ)
+ {
+ if (mg.cache_map.size() == 1)
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_SUCC_WITH_TIMEOUT;
+ }
+ else if (mg.cache_map.size() == 2)
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_SUCC_WITH_TIMEOUT_TWO_STAGE;
+ }
+ else
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_SUCC_WITH_TIMEOUT_MANY_STAGE;
+ }
+ }
+ else
+ {
+ if (mg.cache_map.size() == 1)
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_FAIL_WITH_TIMEOUT;
+ }
+ else if (mg.cache_map.size() == 2)
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_FAIL_WITH_TIMEOUT_TWO_STAGE;
+ }
+ else
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_FAIL_WITH_TIMEOUT_MANY_STAGE;
+ }
+ }
+
+ ret.uiNosIdx = 0;
+ for (auto &v : mg.cache_map)
+ {
+ if ((int)v.second.size() < running_num / 2 + 1)
+ {
+ for (auto x : v.second)
+ {
+ ret.uiNosIdx |= 1 << x;
+ }
+ }
+ }
+
+ int send_num = CNetManager::GetInstance().SendDataToShd(&ret, sizeof(ret));
+ int recv_num = CNetManager::GetInstance().RecvDataFromShd(&ret, sizeof(ret));
+ if (recv_num <= 0)
+ {
+ SysLog(LOG_ERR, "recv Shd error send_num:%d recv_num%d", send_num, recv_num);
+ }
+
+ // 清理消息组缓存
+ mg.cache_map.clear();
+ mg.msg_vec.clear();
+ SysLog(LOG_INFO, "judge [result:%d] [mask:%d] [type:%d] [succ:%d] [succ_str:%s]",
+ ret.uiErrorCode, ret.uiNosIdx, it->first, succ, succ_str.c_str());
+
+ char sql[128];
+ memset(sql, 0, sizeof(sql));
+ sprintf(sql, "insert into judge_info(msg, ret, mask, date) values(\"%s\", %d, %d, now())",
+ "TimeOut", ret.uiErrorCode, ret.uiNosIdx);
+ MysqlResults m;
+ MysqlPool::GetInstance().executeSql(m , sql);
+
+ group_map.erase(it++);
+ continue;
+ }
+ it++;
+ }
+ usleep(1000);
+ continue;
+ }
+ else
+ {
+ NosConfMsg_ST& msg = CMessageQueue::GetInstance().front();
+ msg.uiNosIdx = msg.iCmd; // TODO del
+ msg.iCmd = 1; // TODO del
+ /*if (!(nos_status & (1 << (msg.uiNosIdx - 1))))
+ {
+ SysLog(LOG_ERR, "judge get [nosid:%d] [type:%d] [msg:%s] not running", msg.uiNosIdx, msg.iCmd, msg.ucData);
+ CMessageQueue::GetInstance().pop();
+ continue;
+ }*/
+
+ std::string str((const char *)msg.ucData, msg.uiDataLen);
+
+ auto it = group_map.find(msg.iCmd);
+ if (it == group_map.end())
+ {
+ MsgGroup mg;
+ mg.start_ms = now_ms;
+ mg.uiPort = msg.uiPort;
+ mg.cache_map[str].insert(msg.uiNosIdx);
+ mg.msg_vec.push_back(msg);
+ group_map.insert(std::make_pair(msg.iCmd, mg));
+ }
+ else
+ {
+ MsgGroup& mg = it->second;
+ mg.cache_map[str].insert(msg.uiNosIdx);
+ mg.msg_vec.push_back(msg);
+
+ // 一组消息接收完毕, 开始裁决
+ if (GetCacheNosNum(mg.cache_map) >= running_num)
+ {
+ Judge_Error_Msg_T ret;
+ bool succ = false;
+ std::string succ_str;
+
+ for (auto &v : mg.cache_map)
+ {
+ if ((int)v.second.size() >= running_num / 2 + 1)
+ {
+ succ = true;
+ succ_str = v.first;
+ break;
+ }
+ }
+
+ // 裁决成功 str达到半数以上相同; 给ConfManager发消息
+ ConfJudgeMsg_ST j2n_msg;
+ memset(&j2n_msg, 0, sizeof(j2n_msg));
+ if (succ)
+ {
+ j2n_msg.iCmd = 1; // TODO
+
+ /*ConfJudgeMsg_ST j2c_msg;
+ memset(&j2c_msg, 0, sizeof(j2c_msg));
+
+ j2c_msg.iCmd = msg.iCmd;
+ memcpy(j2c_msg.ucData, succ_str.c_str(), succ_str.size());
+
+ if (mg.uiPort == PORT_BIND_SET_KERNEL)
+ {
+ CNetManager::GetInstance().SendDataToConfManagerKernel(&j2c_msg, sizeof(int) + succ_str.size());
+ ConfJudgeMsg_ST j2n_msg;
+ if (CNetManager::GetInstance().RecvDataToConfManagerKernel(&j2n_msg, sizeof(j2n_msg)) < 0)
+ {
+ SysLog(LOG_ERR, "recv confManagerKernel error");
+ }
+ }
+ else if (mg.uiPort == PORT_BIND_SET_HOST)
+ {
+ CNetManager::GetInstance().SendDataToConfManagerHost(&j2c_msg, sizeof(int) + succ_str.size());
+ if (CNetManager::GetInstance().RecvDataToConfManagerHost(&j2n_msg, sizeof(j2n_msg)) < 0)
+ {
+ SysLog(LOG_ERR, "recv confManagerHost error");
+ }
+ }
+ else
+ {
+ SysLog(LOG_ERR, "[uiPort:%d] error", mg.uiPort);
+ }*/
+ }
+
+ // 给NOS回消息
+ CNetManager::GetInstance().SendHostDataToAllNos(&j2n_msg, sizeof(j2n_msg));
+
+ // 裁决结果给调度
+ if (succ)
+ {
+ if (mg.cache_map.size() == 1)
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_ALL_SUCCESS;
+ }
+ else if (mg.cache_map.size() == 2)
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_SUCC_WITH_TWO_STAGE;
+ }
+ else
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_SUCC_WITH_MANY_STAGE;
+ }
+ }
+ else
+ {
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_ALL_FAIL_WITH_DIFF;
+ }
+
+ ret.uiNosIdx = 0;
+ for (auto &v : mg.cache_map)
+ {
+ if ((int)v.second.size() < running_num / 2 + 1)
+ {
+ for (auto x : v.second)
+ {
+ ret.uiNosIdx |= 1 << x;
+ }
+ }
+ }
+
+ CNetManager::GetInstance().SendDataToShd(&ret, sizeof(ret));
+ if (CNetManager::GetInstance().RecvDataFromShd(&ret, sizeof(ret)) < 0)
+ {
+ SysLog(LOG_ERR, "recv Shd error");
+ }
+
+ // 清理消息组缓存
+ mg.cache_map.clear();
+ mg.msg_vec.clear();
+ SysLog(LOG_INFO, "judge [result:%d] [mask:%d] [type:%d] [succ:%d] [succ_str:%s]",
+ ret.uiErrorCode, ret.uiNosIdx, it->first, succ, succ_str.c_str());
+
+ char sql[128];
+ memset(sql, 0, sizeof(sql));
+ sprintf(sql, "insert into judge_info(msg, ret, mask, date) values(\"%s\", %d, %d, now())",
+ "ok", ret.uiErrorCode, ret.uiNosIdx);
+ MysqlResults m;
+ MysqlPool::GetInstance().executeSql(m , sql);
+
+ group_map.erase(it);
+ }
+ }
+
+ SysLog(LOG_INFO, "judge get [nosid:%d] [type:%d] [msg:%s] ", msg.uiNosIdx, msg.iCmd, msg.ucData);
+ CMessageQueue::GetInstance().pop();
+ }
+ }
+}
diff --git a/study_clang/Mimic/test_judge/src/CJudgeSysInfo.cpp b/study_clang/Mimic/test_judge/src/CJudgeSysInfo.cpp
new file mode 100644
index 0000000..8ee3e66
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CJudgeSysInfo.cpp
@@ -0,0 +1,623 @@
+/*************************************************************************
+ > File Name: CJudgeSysInfo.cpp
+ > Author: SongTL
+ > Mail: songtianlun@comleader.com.cn
+ > Created Time: 2020年07月22日 星期三 15时37分13秒
+ ************************************************************************/
+
+#include "CJudgeSysInfo.h"
+#include "CConfig.h"
+#include "CMessageQueue.h"
+#include
+
+//#include "CZeroMQ.cpp"
+
+CJudgeSysInfo::CJudgeSysInfo()
+{}
+
+CJudgeSysInfo::~CJudgeSysInfo()
+{}
+
+void CJudgeSysInfo::Init()
+{
+ nos_report_port = Config::GetInstance().nos_report_port;
+ msg_time_out = Config::GetInstance().msg_time_out;
+ nos_num = Config::GetInstance().nos_num;
+ running_num = Config::GetInstance().running_num;
+ schedule_ip = Config::GetInstance().schedule_ip;
+ schedule_port = Config::GetInstance().schedule_port;
+ process_running_code = Config::GetInstance().process_running_code;
+
+ sys_shell_log_name = Config::GetInstance().sys_shell_log_name;
+ sys_login_log_name = Config::GetInstance().sys_login_log_name;
+ process_manager_name = Config::GetInstance().process_manager_name;
+ process_protocol_name = Config::GetInstance().process_protocol_name;
+ process_local_cfgm_name = Config::GetInstance().process_local_cfgm_name;
+ process_firewall_name = Config::GetInstance().process_firewall_name;
+
+ user_md5 = Config::GetInstance().user_md5;
+ group_md5 = Config::GetInstance().group_md5;
+ config_manager_md5 = Config::GetInstance().config_manager_md5;
+ auto_start_md5 = Config::GetInstance().auto_start_md5;
+
+ cpu_occupy_max = Config::GetInstance().cpu_occupy_max;
+ mem_occupy_max = Config::GetInstance().mem_occupy_max;
+ tcp_socket_max = Config::GetInstance().tcp_socket_max;
+ process_max = Config::GetInstance().process_max;
+ cron_max = Config::GetInstance().cron_max;
+ path_file_max = Config::GetInstance().path_file_max;
+ home_file_max = Config::GetInstance().home_file_max;
+
+ nos_running_bit = 0;
+
+#define _LOG_INT_CONFIG(type) \
+ SysLog(LOG_DEBUG,"Load Config %s: %d", #type, type);
+ _LOG_INT_CONFIG(nos_report_port);
+ _LOG_INT_CONFIG(schedule_port);
+ _LOG_INT_CONFIG(msg_time_out);
+ _LOG_INT_CONFIG(nos_num);
+#undef __LOG_INT_CONFIG
+
+#define _LOG_UINT_CONFIG(type) \
+ SysLog(LOG_DEBUG, "Load Config %s: %d", #type, type);
+ _LOG_UINT_CONFIG(running_num);
+ _LOG_UINT_CONFIG(cpu_occupy_max);
+ _LOG_UINT_CONFIG(mem_occupy_max);
+ _LOG_UINT_CONFIG(tcp_socket_max);
+ _LOG_UINT_CONFIG(process_max);
+ _LOG_UINT_CONFIG(cron_max);
+ _LOG_UINT_CONFIG(path_file_max);
+ _LOG_UINT_CONFIG(home_file_max);
+#undef __LOG_UINT_CONFIG
+
+#define _LOG_STRING_CONFIG(type) \
+ SysLog(LOG_DEBUG, "Load Config %s: %s",#type ,type.c_str());
+ _LOG_STRING_CONFIG(schedule_ip);
+ _LOG_STRING_CONFIG(sys_shell_log_name);
+ _LOG_STRING_CONFIG(sys_login_log_name);
+ _LOG_STRING_CONFIG(user_md5);
+ _LOG_STRING_CONFIG(group_md5);
+ _LOG_STRING_CONFIG(config_manager_md5);
+ _LOG_STRING_CONFIG(auto_start_md5);
+#undef __LOG_STRING_CONFIG
+
+ char ZMQAddrPort[16];
+ sprintf(ZMQAddrPort, "tcp://*:%d", nos_report_port);
+ m_pNosServer = new CZMQReqRep(ZMQ_REP, ZMQAddrPort);
+ SysLog(LOG_DEBUG, "creative zmq communication with nos, port: %d", nos_report_port);
+
+ std::string strShdSvrAddr;
+ strShdSvrAddr.clear();
+ strShdSvrAddr = "tcp://" + schedule_ip + ":" + std::to_string(schedule_port);
+ m_pShdClient = new CZMQReqRep(ZMQ_REQ, strShdSvrAddr.c_str(), JUDGE_PRIVATE_KEY, JUDGE_PUBLIC_KEY);
+ SysLog(LOG_DEBUG, "creative zmq communication with schedule, ip %s, port: %d", schedule_ip.c_str(), nos_report_port);
+ }
+
+
+void CJudgeSysInfo::RcvNosStateMessage()
+{
+ while(true){
+ char buffer[MAX_MSG_BUFFER];
+ memset(buffer, 0x00, sizeof(buffer));
+ int recvNum = m_pNosServer->RecvData(buffer, MAX_MSG_BUFFER);
+ if(recvNum <= 0)
+ {
+ int err = errno;
+ SysLog(LOG_ERR, "revc nos error, recvNum%d err:%d", recvNum, err);
+ //sleep(1);
+ continue;
+ }
+ int sendNum = m_pNosServer->SendData(buffer, sizeof(buffer));
+ if (recvNum <= 0)
+ {
+ int err = errno;
+ SysLog(LOG_ERR, "send nos error, sendNum:%d recvNum%d errno=%d", sendNum, recvNum, err);
+ continue;
+ }
+ if(buffer!=NULL)
+ {
+ SysLog(LOG_DEBUG, "recv msg from nos, msg type: %d", *(uint *)buffer);
+ switch(*(uint *)buffer)
+ {
+ case 1:
+ m_SysState = CJudgeSysInfo::SplitMsgToSysState(buffer, sizeof(buffer));
+ CMessageQueue::GetInstance().push(m_SysState, MQT_SYS_STATE_E);
+ SysLog(LOG_DEBUG, "--------------------------------------------------------");
+ SysLog(LOG_DEBUG, "szIP : %s", m_SysState.szIp);
+ SysLog(LOG_DEBUG, "stRcvTime : %ld.%ld", m_SysState.stRcvTime.tv_sec,m_SysState.stRcvTime.tv_usec);
+ SysLog(LOG_DEBUG, "uiCpuRate : %d", m_SysState.uiCpuRate);
+ SysLog(LOG_DEBUG, "uiMemRate : %d", m_SysState.uiMemRate);
+ SysLog(LOG_DEBUG, "uiTcpEstablishNum : %d", m_SysState.uiTcpEstablishNum);
+ SysLog(LOG_DEBUG, "uiRunningProcessNum : %d", m_SysState.uiRunningProcessNum);
+ SysLog(LOG_DEBUG, "uiCronNum : %d", m_SysState.uiCronNum);
+ SysLog(LOG_DEBUG, "szPasswdMd5 : %s", m_SysState.szPasswdMd5);
+ SysLog(LOG_DEBUG, "szGroupMd5 : %s", m_SysState.szGroupMd5);
+ SysLog(LOG_DEBUG, "--------------------------------------------------------");
+ break;
+ case 2:
+ m_ProcessState = CJudgeSysInfo::SplitMsgToProcessState(buffer, sizeof(buffer));
+ CMessageQueue::GetInstance().push(m_ProcessState, MQT_PROCESS_STATE_E);
+ SysLog(LOG_DEBUG, "--------------------------------------------------------");
+ SysLog(LOG_DEBUG, "szIP : %s", m_ProcessState.szIp);
+ SysLog(LOG_DEBUG, "stRcvTime : %ld.%ld", m_ProcessState.stRcvTime.tv_sec,m_ProcessState.stRcvTime.tv_usec);
+ SysLog(LOG_DEBUG, "szProcessName : %s", m_ProcessState.szProcessName);
+ SysLog(LOG_DEBUG, "uiProcessState : %d", m_ProcessState.uiProcessState);
+ SysLog(LOG_DEBUG, "--------------------------------------------------------");
+ break;
+ case 3:
+ m_FileState = CJudgeSysInfo::SplitMsgToFileState(buffer, sizeof(buffer));
+ CMessageQueue::GetInstance().push(m_FileState, MQT_FILE_STATE_E);
+ break;
+ case 4:
+ m_FileNum = CJudgeSysInfo::SplitMsgToFileNum(buffer, sizeof(buffer));
+ CMessageQueue::GetInstance().push(m_FileNum, MQT_FILE_NUM_E);
+ break;
+ case 5:
+ m_SysLog = CJudgeSysInfo::SplitMsgToSysLog(buffer, sizeof(buffer));
+ CMessageQueue::GetInstance().push(m_SysLog, MQT_SYS_LOG_E);
+ break;
+ default:
+ break;
+ }
+ }
+ else
+ {
+ SysLog(LOG_ERR, "recv nos msg error");
+ }
+ }
+}
+
+void CJudgeSysInfo::Judge()
+{
+ std::vector sys_state_v;
+ //uint nos_running_bit = 0;
+ uint nos_not_time_out_bit = 0;
+
+ std::vector sys_shell_log_v;
+ std::vector sys_login_log_v;
+
+ // Check Message Queue
+ while(true)
+ {
+ // 系统状态裁决在收到所有执行体消息后开始
+ if(CMessageQueue::GetInstance().size(MQT_SYS_STATE_E)>=running_num / 2 + 1 )
+ {
+ JudgeSysState(sys_state_v, nos_not_time_out_bit);
+ }
+ // 系统日志分情况进行,系统命令日志在收到所有执行体信息后开始,用户登录信息立即开始裁决。
+ if(!CMessageQueue::GetInstance().empty(MQT_SYS_LOG_E))
+ {
+ JudgeSysLog(sys_shell_log_v, sys_login_log_v);
+ }
+ if(!CMessageQueue::GetInstance().empty(MQT_PROCESS_STATE_E))
+ {
+ JudgeProcessState();
+ }
+ if(!CMessageQueue::GetInstance().empty(MQT_FILE_STATE_E))
+ {
+ JudgeFileState();
+ }
+ if(!CMessageQueue::GetInstance().empty(MQT_FILE_NUM_E))
+ {
+ JudgeFileNum();
+ }
+ //sleep(1);
+ }
+}
+
+void CJudgeSysInfo::JudgeSysState(std::vector& sys_state_v, uint& nos_not_time_out_bit)
+{
+ bool second_timeout = false;
+ uint nos_time_out_bit = 0;
+
+ if(nos_not_time_out_bit!=0)
+ second_timeout = true;
+ while(!CMessageQueue::GetInstance().empty(MQT_SYS_STATE_E))
+ {
+ SysState_T sys_state_t = CMessageQueue::GetInstance().front(MQT_SYS_STATE_E);
+ CMessageQueue::GetInstance().pop(MQT_SYS_STATE_E);
+ sys_state_v.push_back(sys_state_t);
+
+ nos_not_time_out_bit |= 1<= (running_num / 2 + 1))
+ {
+ for(auto sys_state_it=sys_state_v.begin(); sys_state_it!=sys_state_v.end(); sys_state_it++)
+ {
+ int nos_id = GetNosId(sys_state_it->szIp);
+ if(JudgeCpuOccupy(sys_state_it->uiCpuRate, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ if(JudgeMemOccupy(sys_state_it->uiMemRate, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ if(JudgeTcpSocket(sys_state_it->uiTcpEstablishNum, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ if(JudgeProcessNum(sys_state_it->uiRunningProcessNum, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ if(JudgeCronNum(sys_state_it->uiCronNum, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ if(JudgeUserInfo(sys_state_it->szPasswdMd5, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ if(JudgeGroupInfo(sys_state_it->szGroupMd5, nos_id)==0)
+ clrbit(nos_running_bit, nos_id);
+ }
+ sys_state_v.clear();
+ }
+ // TODO normal report
+ if(nos_running_bit)
+ {
+ for(int i=0;i::GetInstance().empty(MQT_PROCESS_STATE_E))
+ {
+ ProcessState_T tProcessState = CMessageQueue::GetInstance().front(MQT_PROCESS_STATE_E);
+ CMessageQueue::GetInstance().pop(MQT_PROCESS_STATE_E);
+ uint nosID = GetNosId(tProcessState.szIp);
+ if(tProcessState.uiProcessState != process_running_code)
+ {
+ Judge_Error_Msg_T eMsg;
+ if(strcmp(tProcessState.szProcessName,process_manager_name.c_str())==0)
+ {
+ eMsg.uiErrorCode = JUDGE_EXCEPTION_MANAGER;
+ SysLog(LOG_ERR, "Nos %d manager process exception.", nosID);
+ }
+ else if(strcmp(tProcessState.szProcessName,process_protocol_name.c_str())==0)
+ {
+ eMsg.uiErrorCode = JUDGE_EXCEPTION_PROTOCOL;
+ SysLog(LOG_ERR, "Nos %d protocol process exception.", nosID);
+ }
+ else if(strcmp(tProcessState.szProcessName,process_local_cfgm_name.c_str())==0)
+ {
+ eMsg.uiErrorCode = JUDGE_EXCEPTION_LOCAL_CONFIG_MANAGER;
+ SysLog(LOG_ERR, "Nos %d local-config-manager process exception.", nosID);
+ }
+ else if(strcmp(tProcessState.szProcessName,process_firewall_name.c_str())==0)
+ {
+ eMsg.uiErrorCode = JUDGE_EXCEPTION_FIREWALL;
+ SysLog(LOG_ERR, "Nos %d firewall exception.", nosID);
+ }
+ else
+ {
+ SysLog(LOG_ERR, "Recv a error process report from Nos %d.", nosID);
+ return;
+ }
+ eMsg.uiNosIdx = 1>>nosID;
+ int sendNum = SendDataToShd(&eMsg, sizeof(eMsg));
+ int recvNum = RecvDataFromShd(&eMsg, sizeof(eMsg));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ }
+ }
+ //sleep(1);
+}
+
+void CJudgeSysInfo::JudgeFileState()
+{
+ //sleep(1);
+}
+
+void CJudgeSysInfo::JudgeFileNum()
+{
+ //sleep(1);
+}
+
+void CJudgeSysInfo::JudgeSysLog(std::vector& SysShellLog_MV, std::vector& SysLoginLog_MV)
+{
+ while(!CMessageQueue::GetInstance().empty(MQT_SYS_LOG_E))
+ {
+ SysLog_T SysLog_CT = CMessageQueue::GetInstance().front(MQT_SYS_LOG_E);
+ CMessageQueue::GetInstance().pop(MQT_SYS_LOG_E);
+ if(strcmp(SysLog_CT.szLogFile,sys_shell_log_name.c_str())==0)
+ {
+ SysShellLog_MV.push_back(SysLog_CT);
+ //SysLog(LOG_DEBUG, "Recv a set of sys shell log from %s",SysLog_CT.szIp);
+ //SysLog(LOG_DEBUG, "Size of shell log message queue: %d",SysShellLog_MV.size());
+ }
+ else if(strcmp(SysLog_CT.szLogFile,sys_login_log_name.c_str())==0)
+ {
+ SysLoginLog_MV.push_back(SysLog_CT);
+ //SysLog(LOG_DEBUG, "Recv a set of sys login log from %s",SysLog_CT.szIp);
+ }
+ else
+ {
+ SysLog(LOG_ERR, "recv nos error sys_log: %s", SysLog_CT.szLogFile);
+ }
+ }
+ if(SysShellLog_MV.size()>=running_num)
+ {
+ JudgeShellLog(SysShellLog_MV);
+ SysShellLog_MV.clear();
+ }
+ if(SysLoginLog_MV.size()>0)
+ {
+ JudgeLoginLog(SysLoginLog_MV);
+ SysLoginLog_MV.clear();
+ }
+ //sleep(1);
+}
+
+int CJudgeSysInfo::JudgeCpuOccupy(uint cpu_occupy, uint nos_id)
+{
+ if(cpu_occupy>cpu_occupy_max)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_EXCESSIVE_CPU_OCCUPY;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "Nos %d Cpu occupy is too hight! Used:%d", nos_id, cpu_occupy);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+int CJudgeSysInfo::JudgeMemOccupy(uint mem_occupy, uint nos_id)
+{
+ if(mem_occupy>mem_occupy_max)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_EXCESSIVE_MEM_OCCUPY;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "Nos %d Mem occupy is too hight! Used:%d", nos_id, mem_occupy);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+int CJudgeSysInfo::JudgeTcpSocket(uint tcp_establish_num, uint nos_id)
+{
+ if(tcp_establish_num > tcp_socket_max)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_EXCESSIVE_TCP_SOCKET;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "Nos %d build too many Tcp socket! Establish num:%d", nos_id, tcp_establish_num);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+int CJudgeSysInfo::JudgeProcessNum(uint running_process_num, uint nos_id)
+{
+ if(running_process_num > process_max)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_EXCESSIVE_PROGRESS;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "Nos %d is starting too many Process! Process num:%d",nos_id, running_process_num);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+int CJudgeSysInfo::JudgeCronNum(uint cron_num, uint nos_id)
+{
+ if(cron_num != cron_max)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_CHANGE_CRON;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "The number of Nos %d booting tasks bas been changed to %d, plan num is %d", nos_id, cron_num, cron_max);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+int CJudgeSysInfo::JudgeUserInfo(char passwd_md5[64], uint nos_id)
+{
+ if(strcmp(passwd_md5, user_md5.c_str())!=0)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_EXCEPTION_USER;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "There has been a change in the nos %d user account, passwd md5 changs to: %s", nos_id, passwd_md5);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+int CJudgeSysInfo::JudgeGroupInfo(char cgroup_md5[64], uint nos_id)
+{
+ if(strcmp(cgroup_md5, group_md5.c_str())!=0)
+ {
+ Judge_Error_Msg_T ret;
+ ret.uiErrorCode = Judge_Error_Code_E::JUDGE_EXCEPTION_GROUP;
+ ret.uiNosIdx = nos_id;
+ SysLog(LOG_ERR, "There has been a change in the nos %d user group, group md5 changs to: %s", nos_id, cgroup_md5);
+ int sendNum = SendDataToShd(&ret, sizeof(ret));
+ int recvNum = RecvDataFromShd(&ret, sizeof(ret));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+ return 0;
+ }
+ return 1;
+}
+
+void CJudgeSysInfo::JudgeLoginLog(std::vector& SysLoginLog_CMV)
+{
+ // 遍历容器,若消息非空则向调度发送错误警报
+ Judge_Error_Msg_T Msg_e;
+ for(auto SysLoginLog_it=SysLoginLog_CMV.begin(); SysLoginLog_it!=SysLoginLog_CMV.end(); SysLoginLog_it++)
+ {
+ Msg_e.uiErrorCode = JUDGE_SOMEONE_BROKEN_INTO;
+ //Msg_e.uiNosIdx = GetNosId(SysLoginLog_it->szIp);
+ Msg_e.uiNosIdx = 1 << GetNosId(SysLoginLog_it->szIp);
+ int sendNum = SendDataToShd(&Msg_e, sizeof(Msg_e));
+ int recvNum = RecvDataFromShd(&Msg_e, sizeof(Msg_e));
+ if (recvNum <= 0)
+ {
+ SysLog(LOG_ERR, "recv shd error sendNum:%d recvNum%d", sendNum, recvNum);
+ }
+
+ for(auto &it : SysLoginLog_it->szMsg)
+ SysLog(LOG_ERR, "Warning, someone broke into the nos body, nos ip: %s, log: %s", SysLoginLog_it->szIp, it);
+ }
+}
+void CJudgeSysInfo::JudgeShellLog(std::vector& SysShellLog_CMV)
+{
+ std::map > log_map;
+ for(auto &SysShellLog_it : SysShellLog_CMV)
+ {
+ for(auto &p_count : SysShellLog_it.szMsg)
+ {
+ uint nos_id = GetNosId(SysShellLog_it.szIp);
+ log_map[(std::string)p_count].insert(nos_id);
+ }
+ }
+ for(auto &p_check : log_map)
+ {
+ for(auto iter=p_check.second.begin();iter!=p_check.second.end();iter++)
+ {
+
+ if(p_check.second.size() < running_num / 2 + 1)
+ SysLog(LOG_ERR, "nos %d run an abnormal command: %s",*iter , p_check.first.c_str());
+ else
+ SysLog(LOG_ERR, "nos %d run an command: %s",*iter , p_check.first.c_str());
+ }
+ }
+ log_map.clear();
+}
+
+void CJudgeSysInfo::JudgePathFileNum()
+{}
+void CJudgeSysInfo::JudgeHomeFileNum()
+{}
+void CJudgeSysInfo::JudgeAppMd5()
+{}
+void CJudgeSysInfo::JudgeAutoStartMd5()
+{}
+void CJudgeSysInfo::JudgeManagerProgress()
+{}
+void CJudgeSysInfo::JudgeProtocolProgress()
+{}
+void CJudgeSysInfo::JudgeLocalConfigManager()
+{}
+void CJudgeSysInfo::JudgeFirewell()
+{}
+
+SysState_T CJudgeSysInfo::SplitMsgToSysState(char *buffer, int lenBuffer)
+{
+ memcpy(&(m_SysState),buffer,sizeof(m_SysState));
+ return m_SysState;
+}
+ProcessState_T CJudgeSysInfo::SplitMsgToProcessState(char *buffer, int lenBuffer)
+{
+ memcpy(&(m_ProcessState),buffer,sizeof(m_ProcessState));
+ return m_ProcessState;
+}
+FileState_T CJudgeSysInfo::SplitMsgToFileState(char *buffer, int lenBuffer)
+{
+ memcpy(&(m_FileState),buffer,sizeof(m_FileState));
+ return m_FileState;
+}
+FileNum_T CJudgeSysInfo::SplitMsgToFileNum(char *buffer, int lenBuffer)
+{
+ memcpy(&(m_FileNum),buffer,sizeof(m_FileNum));
+ return m_FileNum;
+}
+SysLog_T CJudgeSysInfo::SplitMsgToSysLog(char *buffer, int lenBuffer)
+{
+ memcpy(&m_SysLog,buffer,sizeof(m_SysLog));
+ return m_SysLog;
+}
+
+uint CJudgeSysInfo::GetNosId(char ip[32])
+{
+ for(int i=0; iSendData(pvData, uiDataLen);
+}
+
+int CJudgeSysInfo::RecvDataFromShd(void *pvBuff, unsigned int uiBuffLen)
+{
+ return 1;
+ //return m_pShdClient->RecvData(pvBuff, uiBuffLen);
+}
+
diff --git a/study_clang/Mimic/test_judge/src/CJudgeUtils.cpp b/study_clang/Mimic/test_judge/src/CJudgeUtils.cpp
new file mode 100644
index 0000000..cee7bde
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CJudgeUtils.cpp
@@ -0,0 +1,273 @@
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "CJudgeUtils.h"
+
+std::string& Ltrim(std::string& str)
+{
+ // NOLINT
+ std::string::iterator it = find_if(str.begin(), str.end(), std::not1(std::ptr_fun(::isspace)));
+ str.erase(str.begin(), it);
+ return str;
+}
+
+std::string& Rtrim(std::string& str)
+{
+ // NOLINT
+ std::string::reverse_iterator it = find_if(str.rbegin(),
+ str.rend(), std::not1(std::ptr_fun(::isspace)));
+
+ str.erase(it.base(), str.end());
+ return str;
+}
+
+std::string& Trim(std::string& str)
+{
+ // NOLINT
+ return Rtrim(Ltrim(str));
+}
+
+int INIReader::Parse(const std::string& filename)
+{
+ FILE* file = fopen(filename.c_str(), "r");
+ if (NULL == file)
+ {
+ //_LOG_LAST_ERROR("open %s failed(%d:%s)", filename.c_str(), errno, strerror(errno));
+ return -1;
+ }
+
+ Clear();
+
+ int32_t ret = ParseFile(file);
+
+ fclose(file);
+
+ return ret;
+}
+
+void INIReader::Clear()
+{
+ m_sections.clear();
+ m_fields.clear();
+}
+
+int32_t INIReader::ParseFile(FILE* file)
+{
+ static const int32_t MAX_BUFF_LEN = 2048;
+ char buff[MAX_BUFF_LEN] = {0};
+
+ int32_t line_no = 0;
+ std::string key, value, line;
+ std::string utf8bom;
+ utf8bom.push_back(0xEF);
+ utf8bom.push_back(0xBB);
+ utf8bom.push_back(0xBF);
+ std::map* fields_map = NULL;
+ while (fgets(buff, MAX_BUFF_LEN, file) != NULL)
+ {
+ line_no++;
+ line = buff;
+
+ // 0. 支持UTF-8 BOM
+ if (1 == line_no && line.find_first_of(utf8bom) == 0)
+ {
+ line.erase(0, 3);
+ }
+
+ // 1. 去掉注释
+ for (size_t i = 0; i < line.length(); ++i)
+ {
+ if (';' == line[i] || '#' == line[i])
+ {
+ line.erase(i);
+ break;
+ }
+ }
+
+ // 2. 去掉首尾空格
+ Trim(line);
+ // 3. 去掉空行
+ if (line.empty())
+ {
+ continue;
+ }
+
+ // section
+ if (line[0] == '[' && line[line.length() - 1] == ']')
+ {
+ std::string section(line.substr(1, line.length() - 2));
+ Trim(section);
+ if (section.empty())
+ {
+ return line_no;
+ }
+ m_sections.insert(section);
+ fields_map = &(m_fields[section]);
+ key.clear();
+ continue;
+ }
+
+ if (NULL == fields_map)
+ {
+ key.clear();
+ continue;
+ }
+
+ // fileds
+ size_t pos = line.find('=');
+ if (std::string::npos == pos)
+ {
+ if (!key.empty())
+ {
+ if ((*fields_map).find(key) == fields_map->end())
+ {
+ (*fields_map)[key] = line;
+ }
+ else
+ {
+ (*fields_map)[key] += line;
+ }
+ }
+ continue;
+ }
+
+ key = line.substr(0, pos);
+ value = line.substr(pos + 1);
+ Trim(key);
+ Trim(value);
+ if (key.empty() || value.empty())
+ {
+ continue;
+ }
+
+ (*fields_map)[key] = value;
+ }
+
+ return 0;
+}
+
+std::string INIReader::Get(const std::string& section, const std::string& name,
+ const std::string& default_value)
+{
+
+ std::map >::iterator it = m_fields.find(section);
+ if (m_fields.end() == it)
+ {
+ return default_value;
+ }
+
+ std::map& fields_map = it->second;
+ std::map::iterator cit = fields_map.find(name);
+ if (fields_map.end() == cit)
+ {
+ return default_value;
+ }
+
+ return cit->second;
+}
+
+int32_t INIReader::GetInt32(const std::string& section, const std::string& name, int32_t default_value)
+{
+ std::string value = Get(section, name, "");
+
+ const char* begin = value.c_str();
+ char* end = NULL;
+
+ int32_t n = strtol(begin, &end, 0);
+ return end > begin ? n : default_value;
+}
+
+uint32_t INIReader::GetUInt32(const std::string& section, const std::string& name, uint32_t default_value)
+{
+ std::string value = Get(section, name, "");
+ const char* begin = value.c_str();
+ char* end = NULL;
+
+ int32_t n = strtol(begin, &end, 0);
+ if (end > begin && n >= 0)
+ {
+ return n;
+ }
+ return default_value;
+}
+
+int64_t INIReader::GetInt64(const std::string& section, const std::string& name, int64_t default_value)
+{
+ std::string value = Get(section, name, "");
+ const char* begin = value.c_str();
+ char* end = NULL;
+
+ int64_t n = strtoll(begin, &end, 0);
+ return end > begin ? n : default_value;
+}
+
+uint64_t INIReader::GetUInt64(const std::string& section, const std::string& name, uint64_t default_value)
+{
+ std::string value = Get(section, name, "");
+ const char* begin = value.c_str();
+ char* end = NULL;
+
+ int64_t n = strtoll(begin, &end, 0);
+ if (end > begin && n >= 0)
+ {
+ return n;
+ }
+ return default_value;
+}
+
+double INIReader::GetReal(const std::string& section, const std::string& name, double default_value)
+{
+ std::string value = Get(section, name, "");
+ const char* begin = value.c_str();
+ char* end = NULL;
+ double n = strtod(begin, &end);
+ return end > begin ? n : default_value;
+}
+
+bool INIReader::GetBoolean(const std::string& section, const std::string& name, bool default_value)
+{
+ std::string value = Get(section, name, "");
+
+ std::transform(value.begin(), value.end(), value.begin(), ::tolower);
+ if (value == "true" || value == "yes" || value == "on" || value == "1")
+ {
+ return true;
+ }
+ else if (value == "false" || value == "no" || value == "off" || value == "0")
+ {
+ return false;
+ }
+ else
+ {
+ return default_value;
+ }
+}
+
+const std::set& INIReader::GetSections() const
+{
+ return m_sections;
+}
+
+std::set INIReader::GetFields(const std::string& section)
+{
+ std::set fields;
+
+ std::map >::iterator it = m_fields.find(section);
+ if (m_fields.end() == it)
+ {
+ return fields;
+ }
+
+ std::map& fields_map = it->second;
+ std::map::iterator cit = fields_map.begin();
+ for (; cit != fields_map.end(); ++cit)
+ {
+ fields.insert(cit->first);
+ }
+
+ return fields;
+}
diff --git a/study_clang/Mimic/test_judge/src/CLog.cpp b/study_clang/Mimic/test_judge/src/CLog.cpp
new file mode 100644
index 0000000..8f3e79d
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CLog.cpp
@@ -0,0 +1,135 @@
+/*************************************************************************
+ > File Name : CLog.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 05:36:24 PM CST
+ ************************************************************************/
+
+#include "CLog.h"
+
+#define DEBUG_LOG //lPrint()打印开关
+
+// 打印信息级别
+char *PutOutLevel[] =
+{
+ (char *)"[FATEL ]",
+ (char *)"[ALERT ]",
+ (char *)"[ERROR ]",
+ (char *)"[ WARN ]",
+ (char *)"[NOTICE]",
+ (char *)"[ INFO ]",
+ (char *)"[DEBUG ]"
+};
+
+// 打印信息颜色
+char *PutOutColor[] =
+{
+ (char *)LIGHT_RED, //FATEL
+ (char *)PURPLE, // ALERT
+ (char *)RED, // ERROR
+ (char *)YELLOW, // WARM
+ (char *)BLUE, // NOTICE
+ (char *)CYAN, // INFO
+ (char *)GREEN // DEBUG
+};
+/*****************************************************************************
+ Prototype : GetTimeString
+ Description : 获取格式化收后的时间字符串
+ Input : char *pTimeBuf
+ int s32Len
+ Output : None
+ Return Value : char
+
+ History :
+ 1.Date : 20181011
+ Author : FengChao
+ Modification : Created function
+
+*****************************************************************************/
+char *GetTimeString(char *pTimeBuf, int s32Len)
+{
+ char timeBuf[32] = {0};
+ time_t nowTime = 0;
+ struct tm *pTm = NULL;
+
+ if (s32Len < (int)sizeof(timeBuf))
+ {
+ return NULL;
+ }
+
+ nowTime = time((time_t *)NULL);
+ pTm = localtime(&nowTime);
+ if (strftime(timeBuf, sizeof(timeBuf), "%D %H:%M:%S", pTm) == 0)
+ {
+ return NULL;
+ }
+
+ if(pTimeBuf != NULL)
+ {
+ memcpy(pTimeBuf, timeBuf, sizeof(timeBuf));
+ }
+ else
+ {
+ return NULL;
+ }
+
+ return pTimeBuf;
+}
+
+
+/*****************************************************************************
+ Prototype :
+ Description :
+ Input : None
+ Output : None
+ Return Value : int
+
+ History :
+ 1.Date : 20181011
+ Author : FengChao
+ Modification : Created function
+
+*****************************************************************************/
+void LogPrint(const int level,const char *proName,const char *func,const int line,const char *format, ...)
+{
+ #ifdef DEBUG_LOG
+ va_list args;
+
+ if ((level > DEBUG) || (level < FATAL))
+ {
+ printf("Gole Printf Input Err Level %d\n", level);
+ return;
+ }
+
+ char timeBuf[32] = {0};
+
+ va_start(args, format);
+ printf("%s%s:%-8s: %s %s [%d]: ",PutOutColor[level],\
+ GetTimeString(timeBuf,sizeof(timeBuf)),\
+ PutOutLevel[level],\
+ proName,func,line);
+
+ vprintf(format, args);
+ printf("\r\n" NONE);
+
+ va_end(args);
+ #endif
+}
+
+void BufPrint(const char *func,const int line, const char *pData, int iDataLen)
+{
+ int i = 0;
+
+ printf("[%s:%d] :\n", func, line);
+ printf("*****************************\n" GREEN);
+ for(i = 0; i < iDataLen; i++)
+ {
+ printf("%02x ", pData[i] & 0xFF);
+ if(!((i+1) % 10)) printf("\n");
+ }
+
+ printf("\nsize = %d\n", iDataLen);
+ printf(NONE "*****************************\r\n");
+}
+
+
diff --git a/study_clang/Mimic/test_judge/src/CMain.cpp b/study_clang/Mimic/test_judge/src/CMain.cpp
new file mode 100644
index 0000000..1eab886
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CMain.cpp
@@ -0,0 +1,154 @@
+/*************************************************************************
+ > File Name : CMain.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:31:56 AM CST
+ ************************************************************************/
+
+#include
+#include "CMain.h"
+#include "CConfig.h"
+#include "CJudgeConf.h"
+#include "CNetManager.h"
+#include "CJudgeSysInfo.h"
+#include "CMysqlPool.h"
+
+using namespace std;
+
+CMain::CMain()
+{
+
+
+}
+
+CMain::~CMain()
+{
+
+}
+
+void CMain::Init()
+{
+ Config::GetInstance().Init(CONF_FILE_PATH);
+ JudgeConf::GetInstance().Init(Config::GetInstance().nos_num, Config::GetInstance().running_num);
+ CJudgeSysInfo::GetInstance().Init();
+
+ MysqlPool::GetInstance().setParameter("172.18.0.4","root","root","mimicswdb",3306,NULL,0,2);
+ MysqlResults m;
+ MysqlPool::GetInstance().executeSql(m ,"CREATE TABLE IF NOT EXISTS `judge_info`( \
+ `id` INT UNSIGNED AUTO_INCREMENT, \
+ `msg` VARCHAR(100) NOT NULL, \
+ `ret` INT UNSIGNED, \
+ `mask` INT UNSIGNED, \
+ `date` DATETIME, \
+ PRIMARY KEY (id) \
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
+
+ StartThreadTasks();
+}
+
+int CMain::MainProcess()
+{
+ //Judge process
+ while(1)
+ {
+ JudgeConf::GetInstance().Judge();
+ }
+
+ return 0;
+}
+
+int CMain::ReleaseSource()
+{
+ //release source
+ return 0;
+}
+
+int CMain::StartThreadTasks()
+{
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+ pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); //设置线程可分离
+
+ pthread_t tNosHostConfMsgRcvThread;
+ pthread_create(&tNosHostConfMsgRcvThread, &attr, NosHostConfMsgRcvThread, NULL);
+
+ pthread_t tNosKernelConfMsgRcvThread;
+ pthread_create(&tNosKernelConfMsgRcvThread, &attr, NosKernelConfMsgRcvThread, NULL);
+
+ pthread_t tNosStateRcvThread;
+ pthread_create(&tNosStateRcvThread, &attr, NosStateRcvThread, NULL);
+
+ pthread_t tSysInfoRcvThread;
+ pthread_create(&tSysInfoRcvThread, &attr, NosSysInfoRcvThread, NULL);
+
+ pthread_t tSysInfoJudgeThread;
+ pthread_create(&tSysInfoJudgeThread, &attr, NosSysInfoJudgeThread, NULL);
+
+ pthread_t tSendPluginsCtrlThread;
+ pthread_create(&tSendPluginsCtrlThread, &attr, SendPluginsCtrlThread, NULL);
+
+ pthread_t tTransNosHostDataThread;
+ pthread_create(&tTransNosHostDataThread, &attr, TransNosHostDataThread, NULL);
+
+ pthread_t tTransNosKernelDataThread;
+ pthread_create(&tTransNosKernelDataThread, &attr, TransNosKernelDataThread, NULL);
+
+ pthread_t tTransDataToOtherThread;
+ pthread_create(&tTransDataToOtherThread, &attr, TransDataToOtherThread, NULL);
+
+ return 0;
+}
+
+void *CMain::NosHostConfMsgRcvThread(void *args)
+{
+ CNetManager::GetInstance().RecvNosDataHost();
+ return NULL;
+}
+
+void *CMain::NosKernelConfMsgRcvThread(void *args)
+{
+ CNetManager::GetInstance().RecvNosDataKernel();
+ return NULL;
+}
+
+void *CMain::NosStateRcvThread(void *args)
+{
+ CNetManager::GetInstance().RecvNosStateFromShd();
+ return NULL;
+}
+
+void *CMain::NosSysInfoRcvThread(void *args)
+{
+ CJudgeSysInfo::GetInstance().RcvNosStateMessage();
+ return NULL;
+}
+
+void *CMain::NosSysInfoJudgeThread(void *args)
+{
+ CJudgeSysInfo::GetInstance().Judge();
+ return NULL;
+}
+
+void *CMain::SendPluginsCtrlThread(void *args)
+{
+ CNetManager::GetInstance().SendPluginsCtrl();
+ return NULL;
+}
+
+void *CMain::TransNosHostDataThread(void *args)
+{
+ CNetManager::GetInstance().TransNosHostData();
+ return NULL;
+}
+
+void *CMain::TransNosKernelDataThread(void *args)
+{
+ CNetManager::GetInstance().TransNosKernelData();
+ return NULL;
+}
+
+void *CMain::TransDataToOtherThread(void *args)
+{
+ CNetManager::GetInstance().TransBroadcastDataToOther();
+ return NULL;
+}
diff --git a/study_clang/Mimic/test_judge/src/CMessageQueue.cpp b/study_clang/Mimic/test_judge/src/CMessageQueue.cpp
new file mode 100644
index 0000000..c9a2522
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CMessageQueue.cpp
@@ -0,0 +1,14 @@
+/*************************************************************************
+ > File Name : CMessageQueue.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:34:46 AM CST
+ ************************************************************************/
+
+#include
+#include "CMessageQueue.h"
+
+using namespace std;
+
+
+
diff --git a/study_clang/Mimic/test_judge/src/CMysqlPool.cpp b/study_clang/Mimic/test_judge/src/CMysqlPool.cpp
new file mode 100644
index 0000000..4c2485e
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CMysqlPool.cpp
@@ -0,0 +1,230 @@
+/*************************************************************************
+ > File Name : CMysqlPool.cpp
+ > Author : liuzhao
+ > EMail : liuzhao@comleader.com.cn
+ > Created Time : Thu 16 Jul 2020 11:33:21 AM CST
+ ************************************************************************/
+
+#include "CMysqlPool.h"
+#include "CLog.h"
+
+std::mutex MysqlPool::poollock;
+
+MysqlPool::MysqlPool() {}
+
+/*
+ *配置数据库参数
+ */
+void MysqlPool::setParameter( const char* mysqlhost,
+ const char* mysqluser,
+ const char* mysqlpwd,
+ const char* databasename,
+ unsigned int port,
+ const char* socket,
+ unsigned long client_flag,
+ unsigned int max_connect )
+{
+ _mysqlhost = mysqlhost;
+ _mysqluser = mysqluser;
+ _mysqlpwd = mysqlpwd;
+ _databasename = databasename;
+ _port = port;
+ _socket = socket;
+ _client_flag = client_flag;
+ MAX_CONNECT = max_connect;
+ connect_count = 0;
+}
+
+/*
+ *创建一个连接对象
+ */
+MYSQL* MysqlPool::createOneConnect()
+{
+ MYSQL* conn = NULL;
+ conn = mysql_init(conn);
+ if (conn != NULL)
+ {
+ if (mysql_real_connect(conn,
+ _mysqlhost,
+ _mysqluser,
+ _mysqlpwd,
+ _databasename,
+ _port,
+ _socket,
+ _client_flag))
+ {
+ connect_count++;
+ return conn;
+ }
+ else
+ {
+ SysLog(LOG_ERR, "mysql:%s", mysql_error(conn));
+ return NULL;
+ }
+ }
+ else
+ {
+ SysLog(LOG_ERR, "mysql:init failed");
+ return NULL;
+ }
+}
+
+/*
+ *判断当前MySQL连接池的是否空
+ */
+bool MysqlPool::isEmpty()
+{
+ return mysqlpool.empty();
+}
+/*
+ *获取当前连接池队列的队头
+ */
+MYSQL* MysqlPool::poolFront()
+{
+ return mysqlpool.front();
+}
+/*
+ *
+ */
+unsigned int MysqlPool::poolSize()
+{
+ return mysqlpool.size();
+}
+/*
+ *弹出当前连接池队列的队头
+ */
+void MysqlPool::poolPop()
+{
+ mysqlpool.pop();
+}
+/*
+ *获取连接对象,如果连接池中有连接,就取用;没有,就重新创建一个连接对象。
+ *同时注意到MySQL的连接的时效性,即在连接队列中,连接对象在超过一定的时间后没有进行操作,
+ *MySQL会自动关闭连接,当然还有其他原因,比如:网络不稳定,带来的连接中断。
+ *所以在获取连接对象前,需要先判断连接池中连接对象是否有效。
+ *考虑到数据库同时建立的连接数量有限制,在创建新连接需提前判断当前开启的连接数不超过设定值。
+ */
+MYSQL* MysqlPool::getOneConnect()
+{
+ poollock.lock();
+ MYSQL *conn = NULL;
+ if (!isEmpty())
+ {
+ while (!isEmpty() && mysql_ping(poolFront()))
+ {
+ mysql_close(poolFront());
+ poolPop();
+ connect_count--;
+ }
+ if (!isEmpty())
+ {
+ conn = poolFront();
+ poolPop();
+ }
+ else
+ {
+ if (connect_count < MAX_CONNECT)
+ conn = createOneConnect();
+ else
+ SysLog(LOG_ERR, "mysql:the number of mysql connections is too much!");
+ }
+ }
+ else
+ {
+ if (connect_count < MAX_CONNECT)
+ conn = createOneConnect();
+ else
+ SysLog(LOG_ERR, "mysql:the number of mysql connections is too much!");
+ }
+ poollock.unlock();
+ return conn;
+}
+/*
+ *将有效的链接对象放回链接池队列中,以待下次的取用。
+ */
+void MysqlPool::close(MYSQL* conn)
+{
+ if (conn != NULL)
+ {
+ poollock.lock();
+ mysqlpool.push(conn);
+ poollock.unlock();
+ }
+}
+/*
+ * sql语句执行函数,并返回结果,没有结果的SQL语句返回空结果,
+ * 每次执行SQL语句都会先去连接队列中去一个连接对象,
+ * 执行完SQL语句,就把连接对象放回连接池队列中。
+ * 返回对象用map主要考虑,用户可以通过数据库字段,直接获得查询的字。
+ * 例如:m["字段"][index]。
+ */
+void MysqlPool::executeSql(MysqlResults& results, const char* sql)
+{
+ MYSQL* conn = getOneConnect();
+ if (conn)
+ {
+ mysql_query(conn, "SET NAMES UTF8"); // TODO
+ if (mysql_query(conn,sql) == 0)
+ {
+ MYSQL_RES *res = mysql_store_result(conn);
+ if (res)
+ {
+ results.field_count = (int32_t)mysql_num_fields(res);
+ results.record_count = (int32_t)mysql_num_rows(res);
+
+ MYSQL_ROW row = NULL;
+ unsigned long *row_len = NULL;
+
+ while ((row = mysql_fetch_row(res)) != NULL)
+ {
+ if ((row_len = mysql_fetch_lengths(res)) != NULL )
+ {
+ std::vector f_vec;
+ for (auto i = 0; i < results.field_count; i++)
+ {
+ if (row[i] != NULL && row_len[i] > 0)
+ {
+ f_vec.push_back(row[i]);
+ }
+ }
+ results.value.push_back(f_vec);
+ }
+ }
+
+ MYSQL_FIELD* field = NULL;
+ for (auto i = 0; (field = mysql_fetch_field(res)) != NULL; i++)
+ {
+ results.field_name.push_back(field->name);//field->type;
+ }
+
+ mysql_free_result(res);
+ }
+ else
+ {
+ if (mysql_field_count(conn) != 0)
+ SysLog(LOG_ERR, "mysql:%s", mysql_error(conn));
+ }
+ }
+ else
+ {
+ SysLog(LOG_ERR, "mysql:%s", mysql_error(conn));
+ }
+ close(conn);
+ }
+ else
+ {
+ SysLog(LOG_ERR, "mysql:%s", mysql_error(conn));
+ }
+}
+/*
+ * 析构函数,将连接池队列中的连接全部关闭
+ */
+MysqlPool::~MysqlPool()
+{
+ while (poolSize() != 0)
+ {
+ mysql_close(poolFront());
+ poolPop();
+ connect_count--;
+ }
+}
diff --git a/study_clang/Mimic/test_judge/src/CNetManager.cpp b/study_clang/Mimic/test_judge/src/CNetManager.cpp
new file mode 100644
index 0000000..cdd7982
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CNetManager.cpp
@@ -0,0 +1,483 @@
+/*************************************************************************
+ > File Name : CNetManager.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Wed 22 Jul 2020 07:04:38 PM CST
+ ************************************************************************/
+
+#include
+#include
+#include
+#include
+#include
+#include "CNetManager.h"
+#include "CLog.h"
+#include "CConfig.h"
+#include "CMessageQueue.h"
+#include "CJudgeUtils.h"
+
+CNetManager::CNetManager()
+{
+ pthread_mutex_init(&m_NosNetInfoHostMutex, NULL);
+ pthread_mutex_init(&m_NosNetInfoKernelMutex, NULL);
+
+ memset(m_stNosState, 0x00, sizeof(m_stNosState));
+ memset(m_stNosNetInfoHost, 0x00, sizeof(m_stNosNetInfoHost));
+ memset(m_stNosNetInfoKernel, 0x00, sizeof(m_stNosNetInfoKernel));
+
+ std::string strShdSvrAddr;
+ strShdSvrAddr.clear();
+ strShdSvrAddr = "tcp://" + Config::GetInstance().schedule_ip + ":" + std::to_string(Config::GetInstance().schedule_port);
+ m_pShdClient = new CZMQReqRep(ZMQ_REQ, strShdSvrAddr.c_str());
+
+ strShdSvrAddr.clear();
+ strShdSvrAddr = "tcp://" + Config::GetInstance().pluginsctrl_ip + ":" + std::to_string(Config::GetInstance().pluginsctrl_port);
+ m_pPCtlClient = new CZMQReqRep(ZMQ_REQ, strShdSvrAddr.c_str());
+
+ strShdSvrAddr.clear();
+ strShdSvrAddr = "tcp://" + Config::GetInstance().schedule_ip + ":" + std::to_string(Config::GetInstance().sub_nos_state_port);
+ m_pNosStateSub = new CZMQSubscriber(strShdSvrAddr.c_str());
+}
+
+CNetManager::~CNetManager()
+{
+ pthread_mutex_destroy(&m_NosNetInfoHostMutex);
+ pthread_mutex_destroy(&m_NosNetInfoKernelMutex);
+ delete m_pShdClient;
+ delete m_pPCtlClient;
+}
+
+int CNetManager::RecvDataToConfManagerHost(void *pvBuff, unsigned int uiBuffLen)
+{
+ return m_ConfigManagerHost.CUdpRecvData(pvBuff, uiBuffLen, \
+ Config::GetInstance().config_manager_ip.c_str(), \
+ PORT_SET_HOST);
+}
+
+int CNetManager::SendDataToConfManagerHost(const void *pvData, unsigned int uiDataLen)
+{
+ return m_ConfigManagerHost.CUdpSendData(pvData, uiDataLen, \
+ Config::GetInstance().config_manager_ip.c_str(), \
+ PORT_SET_HOST);
+}
+
+int CNetManager::RecvDataToConfManagerKernel(void *pvBuff, unsigned int uiBuffLen)
+{
+ return m_ConfigManagerHost.CUdpRecvData(pvBuff, uiBuffLen, \
+ Config::GetInstance().config_manager_ip.c_str(), \
+ PORT_SET_KERNEL);
+}
+
+int CNetManager::SendDataToConfManagerKernel(const void *pvData, unsigned int uiDataLen)
+{
+ return m_ConfigManagerHost.CUdpSendData(pvData, uiDataLen, \
+ Config::GetInstance().config_manager_ip.c_str(), \
+ PORT_SET_KERNEL);
+}
+
+int CNetManager::SendHostDataToAllNos(const void *pvData, unsigned int uiDataLen)
+{
+ SOCKADDR_IN_T stSockAddr;
+
+ for(int i = 0; i < NOS_MAX_NUM; i++)
+ {
+ memset(&stSockAddr, 0x00, sizeof(stSockAddr));
+ if(0 == GetNosNetInfoHost((unsigned int)(i + 1), &stSockAddr))
+ {
+ if(stSockAddr.sin_addr.s_addr != INADDR_NONE)
+ {
+ m_NosDataHost.CUdpSendData(pvData, uiDataLen, stSockAddr);
+ }
+ }
+ }
+
+ return 0;
+}
+
+int CNetManager::SendHostDataToNos(int iNosIdx, const void *pvData, unsigned int uiDataLen)
+{
+ SOCKADDR_IN_T stSockAddr;
+
+ memset(&stSockAddr, 0x00, sizeof(stSockAddr));
+ if(0 != GetNosNetInfoHost((unsigned int)iNosIdx, &stSockAddr))
+ {
+ SysLog(SLOG_ERR, "Get net info error!");
+ return -1;
+ }
+
+ return m_NosDataHost.CUdpSendData(pvData, uiDataLen, stSockAddr);
+}
+
+
+int CNetManager::SendKernelDataToAllNos(const void *pvData, unsigned int uiDataLen)
+{
+ SOCKADDR_IN_T stSockAddr;
+
+ for(int i = 0; i < NOS_MAX_NUM; i++)
+ {
+ memset(&stSockAddr, 0x00, sizeof(stSockAddr));
+ if(0 == GetNosNetInfoKernel((unsigned int)(i + 1), &stSockAddr))
+ {
+ if(stSockAddr.sin_addr.s_addr != INADDR_NONE)
+ {
+ m_NosDataKernel.CUdpSendData(pvData, uiDataLen, stSockAddr);
+ }
+ }
+ }
+
+ return 0;
+}
+
+int CNetManager::SendKernelDataToNos(int iNosIdx, const void *pvData, unsigned int uiDataLen)
+{
+ SOCKADDR_IN_T stSockAddr;
+
+ memset(&stSockAddr, 0x00, sizeof(stSockAddr));
+ if(0 != GetNosNetInfoKernel((unsigned int)iNosIdx, &stSockAddr))
+ {
+ SysLog(SLOG_ERR, "Get net info error!");
+ return -1;
+ }
+
+ return m_NosDataKernel.CUdpSendData(pvData, uiDataLen, stSockAddr);
+}
+
+
+int CNetManager::SendDataToShd(const void *pvData, unsigned int uiDataLen)
+{
+ return m_pShdClient->SendData(pvData, uiDataLen);
+}
+
+int CNetManager::RecvDataFromShd(void *pvBuff, unsigned int uiBuffLen)
+{
+ return m_pShdClient->RecvData(pvBuff, uiBuffLen);
+}
+
+int CNetManager::SendDataToPCtl(const void *pvData, unsigned int uiDataLen)
+{
+ return m_pPCtlClient->SendData(pvData, uiDataLen);
+}
+
+int CNetManager::RecvDataFromPCtl(void *pvBuff, unsigned int uiBuffLen)
+{
+ return m_pPCtlClient->RecvData(pvBuff, uiBuffLen);
+}
+
+int CNetManager::GetNosIdxBySock(SOCKADDR_IN_T *pstSockAddrIn)
+{
+ for(int i = 0; i < NOS_MAX_NUM; i++)
+ {
+ if(pstSockAddrIn->sin_addr.s_addr == inet_addr(Config::GetInstance().nos_ip[i].c_str()))
+ {
+ return (i + 1);
+ }
+ }
+
+ return -1;
+}
+
+void CNetManager::RecvNosDataHost()
+{
+ int iNosId = 0;
+ int inRead = 0;
+ NosConfMsg_ST stNosConfData;
+ SOCKADDR_IN_T stSockAddrIn;
+
+ m_NosDataHost.CUdpSocket(PORT_BIND_SET_HOST);
+ while(1)
+ {
+ memset(&stSockAddrIn, 0x00, sizeof(stSockAddrIn));
+ memset(&stNosConfData, 0x00, sizeof(stNosConfData));
+ inRead = m_NosDataHost.CUdpRecvData(&stNosConfData.iCmd, sizeof(stNosConfData.ucData) + sizeof(int), &stSockAddrIn);
+ if (inRead <= 0)
+ {
+ int err = errno;
+ if (err != EAGAIN && err != EWOULDBLOCK)
+ {
+ SysLog(LOG_ERR, "[uiPort:%d] error", err);
+ dPrint("[RECV ERROR] inRead = %d, %d", inRead, err);
+ }
+ usleep(100);
+ continue;
+ }
+ else
+ {
+ //bufPrint(&stNosConfData.iCmd, inRead);
+ //continue;
+ }
+ iNosId = GetNosIdxBySock(&stSockAddrIn);
+ if((-1 != iNosId) && (NOS_MAX_NUM >= iNosId))
+ {
+ SetNosNetInfoHost((unsigned int)iNosId, (const SOCKADDR_IN_T *)&stSockAddrIn);
+ }
+
+ stNosConfData.uiNosIdx = iNosId;
+ gettimeofday(&stNosConfData.stRcvTime, NULL);
+ stNosConfData.uiPort = PORT_SET_HOST;
+ stNosConfData.uiDataLen = inRead - sizeof(int);
+ CMessageQueue::GetInstance().push(stNosConfData);
+ }
+}
+
+void CNetManager::RecvNosDataKernel()
+{
+ int iNosId = 0;
+ int inRead = 0;
+ NosConfMsg_ST stNosConfData;
+ SOCKADDR_IN_T stSockAddrIn;
+
+ m_NosDataKernel.CUdpSocket(PORT_BIND_SET_KERNEL);
+ while(1)
+ {
+ memset(&stSockAddrIn, 0x00, sizeof(stSockAddrIn));
+ memset(&stNosConfData, 0x00, sizeof(stNosConfData));
+ inRead = m_NosDataKernel.CUdpRecvData(&stNosConfData.iCmd, sizeof(stNosConfData.ucData) + sizeof(int), &stSockAddrIn);
+ if (inRead <= 0)
+ {
+ int err = errno;
+ if (err != EAGAIN && err != EWOULDBLOCK)
+ {
+ SysLog(LOG_ERR, "[uiPort:%d] error", err);
+ dPrint("[RECV ERROR] inRead = %d, %d", inRead, err);
+ }
+ usleep(100);
+ continue;
+ }
+ else
+ {
+ bufPrint(&stNosConfData.iCmd, inRead);
+ }
+ iNosId = GetNosIdxBySock(&stSockAddrIn);
+ if((-1 != iNosId) && (NOS_MAX_NUM >= iNosId))
+ {
+ memcpy(&m_stNosNetInfoKernel[iNosId - 1], &stSockAddrIn, sizeof(SOCKADDR_IN_T));
+ }
+
+ stNosConfData.uiNosIdx = iNosId;
+ gettimeofday(&stNosConfData.stRcvTime, NULL);
+ stNosConfData.uiPort = PORT_SET_KERNEL;
+ stNosConfData.uiDataLen = inRead - sizeof(int);
+ CMessageQueue::GetInstance().push(stNosConfData);
+ }
+}
+
+
+void CNetManager::RecvNosStateFromShd()
+{
+ int inRead = 0;
+ NosState_T stNosState;
+
+ while(1)
+ {
+ memset(&stNosState, 0x00, sizeof(stNosState));
+ inRead = m_pNosStateSub->RecvData(&stNosState, sizeof(stNosState));
+ if(0 < inRead)
+ {
+ if((0 < stNosState.uiNosIdx) && (NOS_MAX_NUM > stNosState.uiNosIdx))
+ {
+ memcpy(&m_stNosState[stNosState.uiNosIdx - 1], &stNosState, sizeof(NosState_T));
+ }
+ }
+ }
+}
+
+int CNetManager::GetNosStateById(int iIdx)
+{
+ return m_stNosState[iIdx - 1].iState;
+}
+
+int CNetManager::SetNosNetInfoHost(unsigned int uiIdx, const SOCKADDR_IN_T *pstInfo)
+{
+ if((0 > uiIdx) || (uiIdx > NOS_MAX_NUM) || (NULL == pstInfo))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ CMutexLockGuard MutexInfo(m_NosNetInfoHostMutex);
+ memcpy(&m_stNosNetInfoHost[uiIdx - 1], pstInfo, sizeof(SOCKADDR_IN_T));
+ char IPdotdec[20];
+ inet_pton(AF_INET, IPdotdec, (void *)&(m_stNosNetInfoHost[uiIdx - 1].sin_addr));
+ inet_ntop(AF_INET, (void *)&(m_stNosNetInfoHost[uiIdx - 1].sin_addr), IPdotdec, 16);// 反转换
+ SysLog(SLOG_ERR, "SetNosNetInfoHost %d %s", uiIdx - 1, IPdotdec);
+ SysLog(LOG_ERR, "SetNosNetInfoHost [tid:%ld] [addr:%p] [lock_p:%p]", syscall(SYS_gettid), this, &m_NosNetInfoHostMutex);
+
+ return 0;
+}
+
+int CNetManager::GetNosNetInfoHost(unsigned int uiIdx, SOCKADDR_IN_T *pstInfo)
+{
+ if((0 > uiIdx) || (uiIdx > NOS_MAX_NUM) || (NULL == pstInfo))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ CMutexLockGuard MutexInfo(m_NosNetInfoHostMutex);
+ char IPdotdec[20];
+ inet_pton(AF_INET, IPdotdec, (void *)&(m_stNosNetInfoHost[uiIdx - 1].sin_addr));
+ inet_ntop(AF_INET, (void *)&(m_stNosNetInfoHost[uiIdx - 1].sin_addr), IPdotdec, 16);// 反转换
+ SysLog(SLOG_ERR, "GetNosNetInfoHost %d %s", uiIdx - 1, IPdotdec);
+ SysLog(LOG_ERR, "GetNosNetInfoHost tid:%ld [addr:%p] [lock_p:%p]", syscall(SYS_gettid), this, &m_NosNetInfoHostMutex);
+ memcpy(pstInfo, &m_stNosNetInfoHost[uiIdx - 1], sizeof(SOCKADDR_IN_T));
+
+ return 0;
+}
+
+int CNetManager::SetNosNetInfoKernel(unsigned int uiIdx, const SOCKADDR_IN_T *pstInfo)
+{
+ if((0 > uiIdx) || (uiIdx > NOS_MAX_NUM) || (NULL == pstInfo))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ CMutexLockGuard MutexInfo(m_NosNetInfoKernelMutex);
+ memcpy(&m_stNosNetInfoKernel[uiIdx - 1], pstInfo, sizeof(SOCKADDR_IN_T));
+
+ return 0;
+}
+
+int CNetManager::GetNosNetInfoKernel(unsigned int uiIdx, SOCKADDR_IN_T *pstInfo)
+{
+ if((0 > uiIdx) || (uiIdx > NOS_MAX_NUM) || (NULL == pstInfo))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ CMutexLockGuard MutexInfo(m_NosNetInfoKernelMutex);
+ memcpy(pstInfo, &m_stNosNetInfoKernel[uiIdx - 1], sizeof(SOCKADDR_IN_T));
+
+ return 0;
+}
+
+void CNetManager::TransNosHostData()
+{
+ int inRead = 0;
+ unsigned char ucBuff[2048];
+ SOCKADDR_IN_T stSockAddr;
+ CUdpClient TransClient(Config::GetInstance().config_manager_ip.c_str(), PORT_GET_HOST);
+
+ TransClient.CUdpSetSendTimeout(0);
+ m_NosHostTrans.CUdpSocket(PORT_BIND_GET_HOST);
+
+ while(1)
+ {
+ memset(ucBuff, 0x00, sizeof(ucBuff));
+ inRead = m_NosHostTrans.CUdpRecvData(ucBuff, sizeof(ucBuff), &stSockAddr);
+ if(0 >= inRead)
+ {
+ continue;
+ }
+
+ if(0 >= TransClient.CUdpSendData(ucBuff, inRead))
+ {
+ SysLog(SLOG_ERR, "Trans host data failed!");
+ continue;
+ }
+
+ memset(ucBuff, 0x00, sizeof(ucBuff));
+ inRead = TransClient.CUdpRecvData(ucBuff, sizeof(ucBuff));
+ if(0 >= inRead)
+ {
+ SysLog(SLOG_ERR, "Trans host data failed!");
+ continue;
+ }
+
+ if(0 >= m_NosHostTrans.CUdpSendData(ucBuff, inRead, stSockAddr))
+ {
+ SysLog(SLOG_ERR, "Trans host data failed!");
+ continue;
+ }
+ usleep(1000);
+ }
+}
+
+
+void CNetManager::TransNosKernelData()
+{
+ int inRead = 0;
+ unsigned char ucBuff[2048];
+ SOCKADDR_IN_T stSockAddr;
+ CUdpClient TransClient(Config::GetInstance().config_manager_ip.c_str(), PORT_GET_KERNEL);
+
+ TransClient.CUdpSetSendTimeout(0);
+ m_NosKernelTrans.CUdpSocket(PORT_BIND_GET_KERNEL);
+
+ while(1)
+ {
+ memset(ucBuff, 0x00, sizeof(ucBuff));
+ inRead = m_NosKernelTrans.CUdpRecvData(ucBuff, sizeof(ucBuff), &stSockAddr);
+ if(0 >= inRead)
+ {
+ continue;
+ }
+
+ if(0 >= TransClient.CUdpSendData(ucBuff, inRead))
+ {
+ SysLog(SLOG_ERR, "Trans host data failed!");
+ continue;
+ }
+
+ memset(ucBuff, 0x00, sizeof(ucBuff));
+ inRead = TransClient.CUdpRecvData(ucBuff, sizeof(ucBuff));
+ if(0 >= inRead)
+ {
+ SysLog(SLOG_ERR, "Trans host data failed!");
+ continue;
+ }
+
+ if(0 >= m_NosKernelTrans.CUdpSendData(ucBuff, inRead, stSockAddr))
+ {
+ SysLog(SLOG_ERR, "Trans host data failed!");
+ continue;
+ }
+ usleep(1000);
+ }
+}
+
+void CNetManager::SendPluginsCtrl()
+{
+ m_pPCtlClient->SetRecvTimeout(1);
+ m_pPCtlClient->SetSendTimeout(1);
+ while(1)
+ {
+ int index = HEARBEAT_E::HB_JUDGE_E;
+ SendDataToPCtl(&index, sizeof(index));
+ if (RecvDataFromPCtl(&index, sizeof(index)) < 0)
+ {
+ SysLog(SLOG_ERR, "recv plugins ctrl error");
+ }
+ sleep(1);
+ }
+}
+
+void CNetManager::TransBroadcastDataToOther()
+{
+ int inRead = 0;
+ unsigned char ucBuff[2048];
+ SOCKADDR_IN_T stSockAddr;
+ CUdpClient TransClient(Config::GetInstance().trans_send_ip.c_str(), Config::GetInstance().trans_send_port);
+
+ TransClient.CUdpSetBroadcastOpt();
+ TransClient.CUdpSetSendTimeout(0);
+ m_BroadcastDataTrans.CUdpSocket(Config::GetInstance().trans_recv_port);
+
+ while(1)
+ {
+ memset(ucBuff, 0x00, sizeof(ucBuff));
+ inRead = m_BroadcastDataTrans.CUdpRecvData(ucBuff, sizeof(ucBuff), &stSockAddr);
+ if(0 >= inRead)
+ {
+ continue;
+ }
+
+ if(0 >= TransClient.CUdpSendData(ucBuff, inRead))
+ {
+ SysLog(SLOG_ERR, "Trans data to other failed!");
+ continue;
+ }
+ usleep(1000);
+ }
+}
diff --git a/study_clang/Mimic/test_judge/src/CUdpClient.cpp b/study_clang/Mimic/test_judge/src/CUdpClient.cpp
new file mode 100644
index 0000000..9fca04e
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CUdpClient.cpp
@@ -0,0 +1,170 @@
+/*************************************************************************
+ > File Name : CUdpClient.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Tue 21 Jul 2020 02:02:08 PM CST
+ ************************************************************************/
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "CUdpClient.h"
+#include "CLog.h"
+
+CUdpClient::CUdpClient()
+{
+ m_iClientSock = -1;
+ m_uiPort = 0;
+ memset(m_ucHost, 0x00, sizeof(m_ucHost));
+ memset(&m_stServerInfo, 0x00, sizeof(m_stServerInfo));
+ CUdpSocket();
+}
+
+CUdpClient::CUdpClient(const char *pcHost, unsigned int uiPort)
+{
+ m_iClientSock = -1;
+ m_uiPort = uiPort;
+ memset(m_ucHost, 0x00, sizeof(m_ucHost));
+ strcpy((char*)m_ucHost, pcHost);
+ memset(&m_stServerInfo, 0x00, sizeof(m_stServerInfo));
+ CUdpSocket();
+}
+
+CUdpClient::~CUdpClient()
+{
+ if(0 < m_iClientSock) close(m_iClientSock);
+}
+
+int CUdpClient::CUdpGetSockaddr(const char * pcHost, unsigned int uiPort, SOCKADDR_IN_T *pstSockaddr)
+{
+ SOCKADDR_IN_T stSockaddr;
+
+ if((NULL == pcHost) || (0 == uiPort) || (NULL == pstSockaddr))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ memset(&stSockaddr, 0x00, sizeof(stSockaddr));
+ stSockaddr.sin_family = AF_INET;
+ stSockaddr.sin_port = htons(uiPort);
+ stSockaddr.sin_addr.s_addr = inet_addr(pcHost);
+ if(stSockaddr.sin_addr.s_addr == INADDR_NONE)
+ {
+ SysLog(SLOG_ERR, "Incorrect ip address!");
+ return -1;
+ }
+
+ memcpy(pstSockaddr, &stSockaddr, sizeof(SOCKADDR_IN_T));
+
+ return 0;
+}
+
+
+int CUdpClient::CUdpSocket()
+{
+ m_iClientSock = socket(AF_INET, SOCK_DGRAM, 0);
+ if(0 > m_iClientSock)
+ {
+ SysLog(SLOG_ERR, "Udp client socket failed!");
+ return 0;
+ }
+
+ CUdpSetRecvTimeout(3);
+ CUdpSetSendTimeout(0);
+
+ return 0;
+}
+
+int CUdpClient::CUdpSetSendTimeout(unsigned int uiSeconds)
+{
+ TIMEVAL_T stTimeout;
+
+ stTimeout.tv_sec = uiSeconds;
+ stTimeout.tv_usec = 0;
+
+ return setsockopt(m_iClientSock, SOL_SOCKET, SO_SNDTIMEO, &stTimeout, sizeof(stTimeout));
+}
+
+int CUdpClient::CUdpSetRecvTimeout(unsigned int uiSeconds)
+{
+ TIMEVAL_T stTimeout;
+
+ stTimeout.tv_sec = uiSeconds;
+ stTimeout.tv_usec = 0;
+
+ return setsockopt(m_iClientSock, SOL_SOCKET, SO_RCVTIMEO, &stTimeout, sizeof(stTimeout));
+}
+
+int CUdpClient::CUdpSetBroadcastOpt()
+{
+ int iOptval = 1;
+ return setsockopt(m_iClientSock, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &iOptval, sizeof(int));
+}
+
+int CUdpClient::CUdpRecvData(void *pcBuff, unsigned int uiBuffLen)
+{
+ return CUdpRecvData(pcBuff, uiBuffLen, (const char *)m_ucHost, m_uiPort);
+}
+
+int CUdpClient::CUdpRecvData(void *pcBuff, unsigned int uiBuffLen, const char *pcHost, unsigned int uiPort)
+{
+ SOCKLEN_T stSockLen = 0;
+ SOCKADDR_IN_T stSockaddr;
+
+ if((NULL == pcBuff) || (NULL == pcHost) || (0 == uiPort))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ memset(&stSockaddr, 0x00, sizeof(stSockaddr));
+ if(0 != CUdpGetSockaddr(pcHost, uiPort, &stSockaddr))
+ {
+ SysLog(SLOG_ERR, "Get sockaddr failed!");
+ return -1;
+ }
+
+ stSockLen = sizeof(SOCKADDR_IN_T);
+ return recvfrom(m_iClientSock, pcBuff, uiBuffLen, 0, (SOCKADDR_T *)&stSockaddr, (SOCKLEN_T *)&stSockLen);
+}
+
+int CUdpClient::CUdpSendData(const void *pcData, unsigned int uiDataLen)
+{
+ return CUdpSendData(pcData, uiDataLen, (const char*)m_ucHost, m_uiPort);
+}
+
+int CUdpClient::CUdpSendData(const void *pcData, unsigned int uiDataLen, const char *pcHost, unsigned int uiPort)
+{
+ SOCKADDR_IN_T stSockaddr;
+
+ if((NULL == pcData) || (NULL == pcHost) || (0 == uiPort))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ memset(&stSockaddr, 0x00, sizeof(stSockaddr));
+ if(0 != CUdpGetSockaddr(pcHost, uiPort, &stSockaddr))
+ {
+ SysLog(SLOG_ERR, "Get sockaddr failed!");
+ return -1;
+ }
+
+ return sendto(m_iClientSock, pcData, uiDataLen, 0, (SOCKADDR_T *)&stSockaddr, (SOCKLEN_T)sizeof(stSockaddr));
+}
+
+
+
+
diff --git a/study_clang/Mimic/test_judge/src/CUdpServer.cpp b/study_clang/Mimic/test_judge/src/CUdpServer.cpp
new file mode 100644
index 0000000..b9e9c14
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CUdpServer.cpp
@@ -0,0 +1,141 @@
+/*************************************************************************
+ > File Name : CUdpServer.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Tue 21 Jul 2020 10:31:10 AM CST
+ ************************************************************************/
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "CUdpServer.h"
+#include "CLog.h"
+
+CUdpServer::CUdpServer()
+{
+ m_uiPort = 0;
+ m_iSerSock = -1;
+}
+
+CUdpServer::CUdpServer(unsigned int uiPort)
+{
+ m_uiPort = uiPort;
+ CUdpSocket();
+}
+
+CUdpServer::~CUdpServer()
+{
+ m_uiPort = 0;
+ if(0 < m_iSerSock) close(m_iSerSock);
+}
+
+int CUdpServer::CUdpSocket()
+{
+ if(0 == m_uiPort)
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ return CUdpSocket(m_uiPort);
+}
+
+int CUdpServer::CUdpSocket(unsigned int uiPort)
+{
+ int iRet = 0;
+
+ m_uiPort = uiPort;
+ if(0 == m_uiPort)
+ {
+ assert(true);
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ m_iSerSock = socket(AF_INET, SOCK_DGRAM, 0);
+ if(0 > m_iSerSock)
+ {
+ SysLog(SLOG_ERR, "Udp server socket failed!");
+ return -1;
+ }
+
+ int flag = fcntl(m_iSerSock, F_GETFL, 0);
+ if (flag < 0) {
+ SysLog(SLOG_ERR, "fcntl F_GETFL fail!");
+ return -1;
+ }
+ if (fcntl(m_iSerSock, F_SETFL, flag | O_NONBLOCK) < 0) {
+ SysLog(SLOG_ERR, "fcntl F_SETFL fail");
+ return -1;
+ }
+
+ TIMEVAL_T stTimeout;
+ stTimeout.tv_sec = 3;
+ stTimeout.tv_usec = 0;
+ setsockopt(m_iSerSock, SOL_SOCKET, SO_RCVTIMEO, &stTimeout, sizeof(stTimeout));
+
+ int iOptval = 1;
+ setsockopt(m_iSerSock, SOL_SOCKET, SO_REUSEADDR, &iOptval, sizeof(int));
+
+ struct sockaddr_in stAddr;
+ stAddr.sin_family = AF_INET;
+ stAddr.sin_port = htons(m_uiPort);
+ stAddr.sin_addr.s_addr = htonl(INADDR_ANY);
+ iRet = bind(m_iSerSock, (struct sockaddr *)&stAddr, (socklen_t)sizeof(stAddr));
+ if(0 > iRet)
+ {
+ SysLog(SLOG_ERR, "Udp server bind failed!");
+ return -1;
+ }
+
+ return m_iSerSock;
+}
+
+int CUdpServer::CUdpRecvData(void *pvBuff, unsigned int uiBuffLen, SOCKADDR_IN_T *pstClientInfo)
+{
+ int inRead = 0;
+ SOCKLEN_T stAddrLen;
+
+ if((NULL == pvBuff) || (NULL == pstClientInfo))
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ stAddrLen = sizeof(SOCKADDR_IN_T);
+ inRead = recvfrom(m_iSerSock, pvBuff, uiBuffLen, 0, (SOCKADDR_T *)pstClientInfo,(SOCKLEN_T *)&stAddrLen);
+
+ return inRead;
+}
+
+int CUdpServer::CUdpSendData(const void *pvData, unsigned int uiDataLen, SOCKADDR_IN_T stClientInfo)
+{
+ int inSend = 0;
+
+ if(NULL == pvData)
+ {
+ SysLog(SLOG_ERR, "Para is error!");
+ return -1;
+ }
+
+ inSend = sendto(m_iSerSock, pvData, uiDataLen, 0, (SOCKADDR_T *)&stClientInfo, sizeof(SOCKADDR_T));
+
+ return inSend;
+}
+
+
+
diff --git a/study_clang/Mimic/test_judge/src/CZeroMQ.cpp b/study_clang/Mimic/test_judge/src/CZeroMQ.cpp
new file mode 100644
index 0000000..8b452ca
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/CZeroMQ.cpp
@@ -0,0 +1,222 @@
+/*************************************************************************
+ > File Name : CZeroMQ.cpp
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 10:00:33 AM CST
+ ************************************************************************/
+
+#include
+#include
+#include "CZeroMQ.h"
+#include "CLog.h"
+#include "CTypedef.h"
+
+CZMQSubscriber::CZMQSubscriber(const char *pcAddrPort, const char *pcPriKey, const char *pcPubKey)
+{
+ m_strAddrPort = pcAddrPort;
+ m_StrPriKey.clear();
+ m_StrPubKey.clear();
+ if(NULL != pcPriKey) m_StrPriKey = pcPriKey;
+ if(NULL != pcPubKey) m_StrPubKey = pcPubKey;
+ m_pvSubCtx = NULL;
+ m_pvSubSock = NULL;
+ SocketInit();
+}
+
+CZMQSubscriber::~CZMQSubscriber()
+{
+ if(NULL != m_pvSubSock) zmq_close(m_pvSubSock);
+ if(NULL != m_pvSubCtx) zmq_ctx_destroy(m_pvSubCtx);
+}
+
+int CZMQSubscriber::SocketInit()
+{
+ int iRet = 0;
+
+ m_pvSubCtx = zmq_ctx_new();
+ if(NULL == m_pvSubCtx)
+ {
+ SysLog(SLOG_ERR, "ZMQ ctx new failed!");
+ return -1;
+ }
+
+ m_pvSubSock = zmq_socket(m_pvSubCtx, ZMQ_SUB);
+ if(NULL == m_pvSubSock)
+ {
+ SysLog(SLOG_ERR, "ZMQ socket failed!");
+ zmq_ctx_destroy(m_pvSubCtx);
+ m_pvSubCtx = NULL;
+ return -1;
+ }
+
+ if(!m_StrPubKey.empty())
+ {
+ zmq_setsockopt(m_pvSubSock, ZMQ_CURVE_SERVERKEY, m_StrPubKey.c_str(), m_StrPubKey.length());
+
+ char szPubKey[64] = {0};
+ char szPriKey[64] = {0};
+ zmq_curve_keypair(szPubKey, szPriKey);
+ zmq_setsockopt(m_pvSubSock, ZMQ_CURVE_PUBLICKEY, szPubKey, strlen(szPubKey));
+ zmq_setsockopt(m_pvSubSock, ZMQ_CURVE_SECRETKEY, szPriKey, strlen(szPriKey));
+ }
+
+ iRet = zmq_connect(m_pvSubSock, m_strAddrPort.c_str());
+ if(0 > iRet)
+ {
+ SysLog(SLOG_ERR, "ZMQ connect failed!");
+ zmq_close(m_pvSubSock);
+ zmq_ctx_destroy(m_pvSubCtx);
+ m_pvSubCtx = NULL;
+ m_pvSubSock = NULL;
+ return -1;
+ }
+
+ iRet = zmq_setsockopt(m_pvSubSock, ZMQ_SUBSCRIBE, "", 0);
+ if(0 != iRet)
+ {
+ SysLog(SLOG_ERR, "ZMQ set ZMQ_SUBSCRIBE failed");
+ zmq_close(m_pvSubSock);
+ zmq_ctx_destroy(m_pvSubCtx);
+ m_pvSubCtx = NULL;
+ m_pvSubSock = NULL;
+ return -1;
+ }
+
+ SetRecvTimeout();
+
+ return 0;
+}
+
+int CZMQSubscriber::SetRecvTimeout(unsigned int uiSeconds)
+{
+ unsigned int uiTimeout = uiSeconds * 1000;
+
+ return zmq_setsockopt(m_pvSubSock, ZMQ_RCVTIMEO, &uiTimeout, sizeof(uiTimeout));
+}
+
+int CZMQSubscriber::RecvData(void *pvBuff, unsigned int uiBuffLen)
+{
+ if(NULL == m_pvSubSock) SocketInit();
+
+ return zmq_recv(m_pvSubSock, pvBuff, uiBuffLen, 0);
+}
+
+CZMQReqRep::CZMQReqRep(int iType, const char *pcAddrPort, const char *pcPriKey, const char *pcPubKey)
+{
+ m_iType = iType;
+ m_strAddrPort = pcAddrPort;
+ m_StrPriKey.clear();
+ m_StrPubKey.clear();
+ if(NULL != pcPriKey) m_StrPriKey = pcPriKey;
+ if(NULL != pcPubKey) m_StrPubKey = pcPubKey;
+ m_pvCtx = NULL;
+ m_pvSock = NULL;
+ SocketInit();
+}
+
+CZMQReqRep::~CZMQReqRep()
+{
+ if(NULL != m_pvSock) zmq_close(m_pvSock);
+ if(NULL != m_pvCtx) zmq_ctx_destroy(m_pvCtx);
+}
+
+int CZMQReqRep::RecvData(void *pvBuff, unsigned int uiBuffLen)
+{
+ return zmq_recv(m_pvSock, pvBuff, uiBuffLen, 0);
+}
+
+int CZMQReqRep::SendData(const void *pvData, unsigned int uiDataLen)
+{
+ return zmq_send(m_pvSock, pvData, uiDataLen, 0);
+}
+
+int CZMQReqRep::SetRecvTimeout(unsigned int uiSeconds)
+{
+ unsigned int uiTimeout = uiSeconds * 1000;
+
+ return zmq_setsockopt(m_pvSock, ZMQ_RCVTIMEO, &uiTimeout, sizeof(uiTimeout));
+}
+
+int CZMQReqRep::SetSendTimeout(unsigned int uiSeconds)
+{
+ unsigned int uiTimeout = uiSeconds * 1000;
+
+ return zmq_setsockopt(m_pvSock, ZMQ_SNDTIMEO, &uiTimeout, sizeof(uiTimeout));
+}
+
+int CZMQReqRep::SocketInit()
+{
+ unsigned int uiTimeout = 0;
+
+ m_pvCtx = zmq_ctx_new();
+ if(NULL == m_pvCtx)
+ {
+ SysLog(SLOG_ERR, "ZMQ ctx new failed!");
+ return -1;
+ }
+
+ m_pvSock = zmq_socket(m_pvCtx, m_iType);
+ if(NULL == m_pvSock)
+ {
+ SysLog(SLOG_ERR, "ZMQ socket failed!");
+ zmq_ctx_destroy(m_pvCtx);
+ m_pvCtx = NULL;
+ return -1;
+ }
+
+ uiTimeout = 3*1000;
+ zmq_setsockopt(m_pvSock, ZMQ_LINGER, &uiTimeout, sizeof(uiTimeout));
+
+ SetRecvTimeout();
+ SetSendTimeout();
+
+ int iCurveRet = 0;
+ if(ZMQ_REQ == m_iType)
+ {
+ if(!m_StrPubKey.empty())
+ {
+ dPrint("ZMQ with curve.");
+ dPrint("Pubkey <%s> <%d>", m_StrPubKey.c_str(), m_StrPubKey.length());
+ iCurveRet = zmq_setsockopt(m_pvSock, ZMQ_CURVE_SERVERKEY, m_StrPubKey.c_str(), m_StrPubKey.length());
+ dPrint("iCurveRet = %d", iCurveRet);
+
+ char szPubKey[64] = {0};
+ char szPriKey[64] = {0};
+ iCurveRet = zmq_curve_keypair(szPubKey, szPriKey);
+ zmq_setsockopt(m_pvSock, ZMQ_CURVE_PUBLICKEY, szPubKey, strlen(szPubKey));
+ dPrint("iCurveRet = %d", iCurveRet);
+ iCurveRet = zmq_setsockopt(m_pvSock, ZMQ_CURVE_SECRETKEY, szPriKey, strlen(szPriKey));
+ dPrint("iCurveRet = %d", iCurveRet);
+ }
+ if(0 > zmq_connect(m_pvSock, m_strAddrPort.c_str()))
+ {
+ zmq_close(m_pvSock);
+ zmq_ctx_destroy(m_pvCtx);
+ m_pvCtx = NULL;
+ m_pvSock = NULL;
+ return -1;
+ }
+ }
+ else if(ZMQ_REP == m_iType)
+ {
+ if(!m_StrPriKey.empty())
+ {
+ int option = 1;
+ zmq_setsockopt(m_pvSock, ZMQ_CURVE_SERVER, &option, sizeof(option));
+ zmq_setsockopt(m_pvSock, ZMQ_CURVE_SECRETKEY, m_StrPriKey.c_str(), m_StrPriKey.length());
+ }
+ if(0 > zmq_bind(m_pvSock, m_strAddrPort.c_str()))
+ {
+ zmq_close(m_pvSock);
+ zmq_ctx_destroy(m_pvCtx);
+ m_pvCtx = NULL;
+ m_pvSock = NULL;
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+
+
diff --git a/study_clang/Mimic/test_judge/src/main.cpp b/study_clang/Mimic/test_judge/src/main.cpp
new file mode 100644
index 0000000..3fc70bc
--- /dev/null
+++ b/study_clang/Mimic/test_judge/src/main.cpp
@@ -0,0 +1,335 @@
+#include
+#include
+
+#include "CTypedef.h"
+#include "CZeroMQ.h"
+
+using std::cout;
+using std::endl;
+
+CZMQReqRep *client;
+
+void init_file_num_msg(FileNum_T& msg)
+{
+ msg.uiType = 4;
+ strcpy(msg.szIp, "10.10.10.241");
+ gettimeofday(&msg.stRcvTime,NULL);
+ strcpy(msg.szDirPath, "/home");
+ strcpy(msg.szFileName, "add breakup");
+ msg.uiFileNum = 120;
+}
+
+void init_file_state_msg(FileState_T& msg)
+{
+ msg.uiType = 3;
+ strcpy(msg.szIp, "10.10.10.241");
+ gettimeofday(&msg.stRcvTime,NULL);
+ strcpy(msg.szFileName, "Config Manager");
+ strcpy(msg.eventType, "Modify");
+ strcpy(msg.szFileMd5, "23333333333333333333333333333333");
+}
+
+void init_process_state_msg(ProcessState_T& msg, int id = 1)
+{
+ switch(id)
+ {
+ case 1:
+ msg.uiType = 2;
+ strcpy(msg.szIp, "10.10.10.241");
+ gettimeofday(&msg.stRcvTime,NULL);
+ strcpy(msg.szProcessName, "manager");
+ msg.uiProcessState=-1;
+ break;
+ case 2:
+ msg.uiType = 2;
+ strcpy(msg.szIp, "10.10.10.242");
+ gettimeofday(&msg.stRcvTime,NULL);
+ strcpy(msg.szProcessName, "manager");
+ msg.uiProcessState=-1;
+ break;
+ case 3:
+ msg.uiType = 2;
+ strcpy(msg.szIp, "10.10.10.243");
+ gettimeofday(&msg.stRcvTime,NULL);
+ strcpy(msg.szProcessName, "manager");
+ msg.uiProcessState=-1;
+ break;
+ case 4:
+ case 5:
+ default:
+ break;
+ };
+}
+
+void init_sys_state_msg(SysState_T& msg, int id = 1)
+{
+ switch(id)
+ {
+ case 1:
+ msg.uiType = 1;
+ strcpy(msg.szIp, "10.10.10.241");
+ gettimeofday(&msg.stRcvTime,NULL);
+ msg.uiCpuRate = 600;
+ msg.uiMemRate = 500;
+ msg.uiTcpEstablishNum = 10;
+ msg.uiRunningProcessNum = 100;
+ msg.uiCronNum = 20;
+ strcpy(msg.szPasswdMd5, "155c0f8a0aca2bfa5f2e85a32be41803");
+ strcpy(msg.szGroupMd5, "62bc68396162fda049d1ba7c7d04eb54");
+ break;
+ case 2:
+ msg.uiType = 1;
+ strcpy(msg.szIp, "10.10.10.242");
+ gettimeofday(&msg.stRcvTime,NULL);
+ msg.uiCpuRate = 600;
+ msg.uiMemRate = 500;
+ msg.uiTcpEstablishNum = 10;
+ msg.uiRunningProcessNum = 100;
+ msg.uiCronNum = 20;
+ strcpy(msg.szPasswdMd5, "155c0f8a0aca2bfa5f2e85a32be41803");
+ strcpy(msg.szGroupMd5, "62bc68396162fda049d1ba7c7d04eb54");
+ break;
+ case 3:
+ msg.uiType = 1;
+ strcpy(msg.szIp, "10.10.10.243");
+ gettimeofday(&msg.stRcvTime,NULL);
+ msg.uiCpuRate = 600;
+ msg.uiMemRate = 500;
+ msg.uiTcpEstablishNum = 10;
+ msg.uiRunningProcessNum = 100;
+ msg.uiCronNum = 20;
+ strcpy(msg.szPasswdMd5, "155c0f8a0aca2bfa5f2e85a32be41803");
+ strcpy(msg.szGroupMd5, "62bc68396162fda049d1ba7c7d04eb54");
+ break;
+ case 4:
+ msg.uiType = 1;
+ strcpy(msg.szIp, "10.10.10.244");
+ gettimeofday(&msg.stRcvTime,NULL);
+ msg.uiCpuRate = 600;
+ msg.uiMemRate = 500;
+ msg.uiTcpEstablishNum = 10;
+ msg.uiRunningProcessNum = 100;
+ msg.uiCronNum = 20;
+ strcpy(msg.szPasswdMd5, "155c0f8a0aca2bfa5f2e85a32be41803");
+ strcpy(msg.szGroupMd5, "62bc68396162fda049d1ba7c7d04eb54");
+ break;
+ case 5:
+ default:
+ break;
+ };
+}
+
+void init_sys_shell_log_msg(SysLog_T& log, int id = 1)
+{
+ switch(id)
+ {
+ case 1:
+ log.uiType = 5;
+ strcpy(log.szIp, "10.10.10.241");
+ strcpy(log.szLogFile, "history");
+ strcpy(log.szMsg[0], "ls");
+ strcpy(log.szMsg[1], "rm -rf *");
+ strcpy(log.szMsg[2], "shutdown -h now");
+ strcpy(log.szMsg[3], "reboot");
+ strcpy(log.szMsg[4], "free");
+ break;
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ default:
+ break;
+ };
+ cout << "send " << " ip: " << log.szIp << ", logfile: " << log.szLogFile;
+ for(int i=1;i<6;i++)
+ cout << ", shell" << i << ": " << log.szMsg[i];
+ cout << endl;
+
+}
+
+void init_sys_login_log_msg(SysLog_T& log, int id = 1)
+{
+ switch(id)
+ {
+ case 1:
+ log.uiType = 5;
+ strcpy(log.szIp, "10.10.10.241");
+ strcpy(log.szLogFile, "wtmp");
+ strcpy(log.szMsg[0], "mswitch pts/0 192.168.6.129 Tue Jul 28 01:54 - 02:27 (00:33)");
+ strcpy(log.szMsg[1], "fengchao pts/2 10.10.11.177 Tue Jul 28 23:15 - 23:44 (00:28)");
+ strcpy(log.szMsg[2], "liuzhao pts/1 10.10.11.173 Tue Jul 28 22:49 - 03:58 (05:09)");
+ strcpy(log.szMsg[3], "songtian pts/4 10.10.11.170 Wed Jul 29 04:41 - 08:05 (03:24)");
+ strcpy(log.szMsg[4], "hongqian pts/4 10.10.11.156 Thu Jul 30 08:24 - 10:38 (02:14)");
+ break;
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ default:
+ break;
+ };
+ cout << "send " << " ip: " << log.szIp << ", logfile: " << log.szLogFile;
+ for(int i=1;i<6;i++)
+ cout << ", shell" << i << ": " << log.szMsg[i];
+ cout << endl;
+
+}
+void send_msg(CZMQReqRep* client, const void *pvData, uint uiDataLen)
+{
+ char buffer[1024];
+
+ memset(buffer, 0X00, sizeof(buffer));
+ int send_num = client->SendData(pvData, uiDataLen);
+ int recv_num = client->RecvData(buffer, sizeof(buffer));
+
+ cout << "send code: " << send_num << endl;
+ cout << "recv code: " << recv_num << " ,msg: " << buffer << endl;
+ //sleep(1);
+}
+
+// 1、消息解析测试
+
+void test_msg_analysis()
+{
+ SysState_T mSysState;
+ ProcessState_T mProcessState;
+ FileState_T mFileState;
+ FileNum_T mFileNum;
+ SysLog_T mSysLog;
+
+ init_sys_state_msg(mSysState);
+ init_process_state_msg(mProcessState);
+ init_file_state_msg(mFileState);
+ init_file_num_msg(mFileNum);
+ init_sys_shell_log_msg(mSysLog);
+
+ cout << "开始测试消息解析,1-5号消息各一条,检查裁决消息解析。" << endl;
+
+ send_msg(client, &mSysState, sizeof(mSysState) );
+ send_msg(client, &mProcessState, sizeof(mProcessState));
+ send_msg(client, &mFileState, sizeof(mFileState) );
+ send_msg(client, &mFileNum, sizeof(mFileNum) );
+ send_msg(client, &mSysLog, sizeof(mSysLog) );
+}
+
+// 2、系统运行状态裁决,正常时向上反馈运行正常,异常时反馈错误代码(包括超时)
+void test_sys_state()
+{
+
+ SysState_T mSysState;
+
+ cout << "开始测试系统运行状态裁决,所有项正常,裁决应报告nos1,2,3运行正常。" << endl;
+ for(int i=1;i<5;i++)
+ {
+ init_sys_state_msg(mSysState, i);
+ send_msg(client, &mSysState, sizeof(mSysState));
+ }
+
+ sleep(1);
+
+ cout << "开始测试系统运行状态裁决,模拟仅Nos1正常,,裁决应报告nos1运行正常,其他离线。" << endl;
+ for(int i=1;i<5;i++)
+ {
+ init_sys_state_msg(mSysState, 1);
+ send_msg(client, &mSysState, sizeof(mSysState));
+ sleep(1);
+ }
+
+}
+
+// 3、进程状态裁决,进程挂掉时裁决失败,向SHD反馈错误代码
+void test_process_state()
+{
+ cout << "开始测试进程状态裁决,应报告nos1进程运行异常。" << endl;
+ ProcessState_T mProcessState;
+ init_process_state_msg(mProcessState,2);
+ send_msg(client, &mProcessState, sizeof(mProcessState));
+}
+
+// 4、文件状态裁决,文件被修改时裁决失败,向SHD反馈错误代码
+void test_file_state()
+{
+ cout << "开始测试文件状态裁决,应报告nos1文件异常。" << endl;
+ FileState_T mFileState;
+ init_file_state_msg(mFileState);
+ send_msg(client, &mFileState, sizeof(mFileState));
+}
+
+// 5、目录状态裁决,当文件个数过多时裁决失败,向SHD反馈错误代码
+void test_file_num()
+{
+ cout << "开始测试目录状态裁决,应报告nos1目录异常。" << endl;
+ FileNum_T mFileNum;
+ init_file_num_msg(mFileNum);
+ send_msg(client, &mFileNum, sizeof(mFileNum));
+}
+
+// 6、系统日志裁决,出现登录或是shell被运行时裁决失败,向SHD反馈错误代码
+void test_sys_log()
+{
+ cout << "开始系统日志裁决,应报告nos1目录异常。" << endl;
+ SysLog_T mSysLog;
+
+ init_sys_login_log_msg(mSysLog);
+ send_msg(client, &mSysLog, sizeof(mSysLog));
+
+ sleep(1);
+
+ init_sys_shell_log_msg(mSysLog);
+ //send_msg(client, &mSysLog, sizeof(mSysLog));
+}
+
+int main()
+{
+ /*MysqlPool::GetInstance().setParameter("localhost","root","123456","test",0,NULL,0,2);
+ std::map > m = MysqlPool::GetInstance().executeSql("INSERT INTO test(id, title, author, date)VALUES(7, \"学习\", \"日志\", NOW());");
+
+ Config::GetInstance().Init("./judge.ini");
+ std::cout << Config::GetInstance().judge_ip << " " << Config::GetInstance().judge_port << std::endl;*/
+
+ //CMain::GetInstance().Init();
+ //CMain::GetInstance().MainProcess();
+
+
+ //SysState_T mSysState;
+ //ProcessState_T mProcessState;
+ //FileState_T mFileState;
+ //FileNum_T mFileNum;
+ //SysLog_T mSysLog;
+
+ SysLog_T m_sys_login_log;
+ SysLog_T m_sys_shell_log;
+
+ client = new CZMQReqRep(ZMQ_REQ, "tcp://127.0.0.1:7002", JUDGE_PRIVATE_KEY, JUDGE_PUBLIC_KEY);
+
+
+ while(true)
+ {
+ test_msg_analysis();
+ test_sys_state();
+ test_process_state();
+ test_file_state();
+ test_file_num();
+ test_sys_log();
+ sleep(1);
+ }
+
+
+ //for(int i=0;i<1000;i++)
+ {
+ //init_sys_state_log_msg(m_sys_state_log,0);
+ //send_msg(client, &m_sys_state_log, sizeof(m_sys_state_log));
+
+ //init_process_state_msg(m_process_state,0);
+ //send_msg(client, &m_process_state, sizeof(m_process_state));
+
+ //init_sys_shell_log_msg(m_sys_shell_log,0);
+ //send_msg(client, &m_sys_shell_log, sizeof(m_sys_shell_log));
+
+ //init_sys_login_log_msg(m_sys_login_log,0);
+ //send_msg(client, &m_sys_login_log, sizeof(m_sys_login_log));
+ //if(i%5==0)
+ //sleep(3);
+ }
+ return 0;
+}
diff --git a/study_clang/Mimic/test_messagequeue/core.19948 b/study_clang/Mimic/test_messagequeue/core.19948
new file mode 100644
index 0000000..e77fc2a
Binary files /dev/null and b/study_clang/Mimic/test_messagequeue/core.19948 differ
diff --git a/study_clang/Mimic/test_messagequeue/include/CConfig.h b/study_clang/Mimic/test_messagequeue/include/CConfig.h
new file mode 100644
index 0000000..164e1c2
--- /dev/null
+++ b/study_clang/Mimic/test_messagequeue/include/CConfig.h
@@ -0,0 +1,97 @@
+/*************************************************************************
+ > File Name : CConfig.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:31:50 AM CST
+ ************************************************************************/
+
+#include
+#include
+#include
+#include
+#include "CJudgeUtils.h"
+#include "CTypedef.h"
+
+class Config : public CSingleton
+{
+public:
+ Config() {}
+ virtual ~Config() {}
+
+ void Init(const std::string& file_name)
+ {
+ INIReader reader;
+ reader.Parse(file_name);
+
+ std::string strNosIdx;
+ for(int i = 0; i < NOS_MAX_NUM; i++)
+ {
+ strNosIdx.clear();
+ strNosIdx = "nos" + std::to_string((i + 1)) + "_ip";
+ nos_ip[i] = reader.Get("judge", strNosIdx, strNosIdx);
+ }
+
+ #define _GET_JUDGE_CFG(value) value = reader.GetInt32("judge", #value, value)
+ _GET_JUDGE_CFG(schedule_port);
+ _GET_JUDGE_CFG(pluginsctrl_port);
+ _GET_JUDGE_CFG(sub_nos_state_port);
+ _GET_JUDGE_CFG(nos_num);
+ _GET_JUDGE_CFG(running_num);
+
+ #undef _GET_JUDGE_CFG
+
+ #define _GET_JUDGE_CFG(value) value = reader.Get("judge", #value, value)
+ _GET_JUDGE_CFG(config_manager_ip);
+ _GET_JUDGE_CFG(schedule_ip);
+ _GET_JUDGE_CFG(pluginsctrl_ip);
+
+ #undef _GET_JUDGE_CFG
+
+ // Judge_sys_info
+ #define _GET_JUDGE_SYS_INFO_CFG(value) value = reader.GetInt32("judge_sys_info", #value, value)
+ _GET_JUDGE_SYS_INFO_CFG(nos_monitor_port);
+ _GET_JUDGE_SYS_INFO_CFG(cpu_occupy_max);
+ _GET_JUDGE_SYS_INFO_CFG(mem_occupy_max);
+ _GET_JUDGE_SYS_INFO_CFG(tcp_socket_max);
+ _GET_JUDGE_SYS_INFO_CFG(progress_max);
+ _GET_JUDGE_SYS_INFO_CFG(cron_max);
+ _GET_JUDGE_SYS_INFO_CFG(path_file_max);
+ _GET_JUDGE_SYS_INFO_CFG(home_file_max);
+
+ #undef _GET_JUDGE_SYS_INFO_CFG
+
+ #define _GET_JUDGE_SYS_INFO_CFG(value) value = reader.Get("judge_sys_info", #value, value)
+ _GET_JUDGE_SYS_INFO_CFG(user_md5);
+ _GET_JUDGE_SYS_INFO_CFG(group_md5);
+ _GET_JUDGE_SYS_INFO_CFG(config_manager_md5);
+ _GET_JUDGE_SYS_INFO_CFG(auto_start_md5);
+
+ #undef _GET_JUDGE_SYS_INFO_CFG
+ }
+
+ std::string nos_ip[NOS_MAX_NUM];
+ std::string config_manager_ip;
+ std::string schedule_ip;
+ std::string pluginsctrl_ip;
+
+ int sub_nos_state_port;
+ int schedule_port;
+ int pluginsctrl_port;
+ int nos_num;
+ int running_num;
+
+ // Judge_sys_info
+ std::string user_md5;
+ std::string group_md5;
+ std::string config_manager_md5;
+ std::string auto_start_md5;
+
+ int nos_monitor_port;
+ int cpu_occupy_max;
+ int mem_occupy_max;
+ int tcp_socket_max;
+ int progress_max;
+ int cron_max;
+ int path_file_max;
+ int home_file_max;
+};
diff --git a/study_clang/Mimic/test_messagequeue/include/CJudgeConf.h b/study_clang/Mimic/test_messagequeue/include/CJudgeConf.h
new file mode 100644
index 0000000..597ef64
--- /dev/null
+++ b/study_clang/Mimic/test_messagequeue/include/CJudgeConf.h
@@ -0,0 +1,48 @@
+/*************************************************************************
+ > File Name : ../include/CJudge.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Thu 16 Jul 2020 11:33:38 AM CST
+ ************************************************************************/
+
+#ifndef CJUDGE_H
+#define CJUDGE_H
+
+#include
+#include "CTypedef.h"
+#include "CJudgeUtils.h"
+
+typedef std::map > CACHE_MAP;
+typedef std::vector MSG_VEC;
+
+struct MsgGroup
+{
+ CACHE_MAP cache_map; // 一组执行体消息的对比缓存
+ MSG_VEC msg_vec; // 一组执行体消息源
+ time_t start_ms; // 一组新消息进入起始时间
+ unsigned int uiPort; // 一组消息的端口
+};
+
+class JudgeConf : public CSingleton
+{
+public:
+ JudgeConf() { }
+ ~JudgeConf() { }
+
+ void Init(int _nos_num, int _running_num);
+ void Judge();
+
+private:
+ std::map group_map; // 按iCmd划分消息组,nos端口相同
+
+ int nos_num;
+ int running_num;
+
+ int nos_status; // 各个nos是否running TODO
+
+private:
+ int GetCacheNosNum(CACHE_MAP& map);
+
+};
+
+#endif
diff --git a/study_clang/Mimic/test_messagequeue/include/CJudgeSysInfo.h b/study_clang/Mimic/test_messagequeue/include/CJudgeSysInfo.h
new file mode 100644
index 0000000..76224b3
--- /dev/null
+++ b/study_clang/Mimic/test_messagequeue/include/CJudgeSysInfo.h
@@ -0,0 +1,103 @@
+/*************************************************************************
+ > File Name : CJudgeSysInfo.h
+ > Author : FengChao
+ > EMail : smile.fengchao@gmail.com
+ > Created Time : Fri 17 Jul 2020 09:47:20 AM CST
+ ************************************************************************/
+
+#ifndef CJUDGE_SYS_INFO_H
+#define CJUDGE_SYS_INFO_H
+
+
+#include "CTypedef.h"
+#include "CJudgeUtils.h"
+
+#define MAX_MSG_BUFFER 1024 // 通信消息缓存区
+#define TIME_OUT_JUDGE 30 // 超时裁决时间
+
+
+
+class CJudgeSysInfo : public CSingleton
+{
+public:
+ CJudgeSysInfo();
+ ~CJudgeSysInfo();
+ void Init();
+ void RcvNosStateMessage();
+private:
+ int StartMultiThreadJudge();
+ void JudgeSysState(); // 裁决系统运行状态
+ void JudgeProcessState(); // 裁决系统进程状态
+ void JudgeFileState(); // 裁决关键文件状态
+ void JudgeFileNum(); // 裁决关键文件数量
+ void JudgeSysLog(); // 裁决系统关键日志
+
+ static void AlarmJudgeSysState(int sig); // 系统状态超时裁决
+
+ void StartJudgeSysState(); // 开始裁决系统运行状态
+ void StartJudgeProcessState(); // 开始裁决系统进程状态
+ void StartJudgeFileState(); // 开始裁决关键文件状态
+ void StartJudgeFileNum(); // 开始裁决关键文件数量
+ void StartJudgeSysLog(); // 开始裁决系统关键日志
+
+ void JudgeCpuOccupy(uint current_cpu_occupy, uint nos_id);
+ void JudgeMemOccupy();
+ void JudgeTcpSocket();
+ void JudgeProcessNum();
+ void JudgeLoginLog();
+ void JudgeCmdLog();
+ void JudgeUserInfo();
+ void JudgeGroupInfo();
+ void JudgeCronNum();
+ void JudgePathFileNum();
+ void JudgeHomeFileNum();
+ void JudgeAppMd5();
+ void JudgeAutoStartMd5();
+ void JudgeManagerProgress();
+ void JudgeProtocolProgress();
+ void JudgeLocalConfigManager();
+ void JudgeFirewell();
+
+
+ // 消息解析函数
+ SystemState_T SplitMsgToSysState(char *buffer, int len_Buffer);
+ ProcessState_T SplitMsgToProcessState(char *buffer, int len_Buffer);
+ FileState_T SplitMsgToFileState(char *buffer, int len_Buffer);
+ FileNum_T SplitMsgToFileNum(char *buffer, int len_Buffer);
+ SysLog_T SplitMsgToSysLog(char *buffer, int len_Buffer);
+
+ uint GetNosId(char ip[32]);
+
+private:
+ int nos_num;
+ uint running_num;
+
+ SystemState_T m_SysState; // 系统运行状态消息
+ ProcessState_T m_ProcessState; // 关键进程状态消息
+ FileState_T m_FileState; // 关键文件状态消息
+ FileNum_T m_FileNum; // 关键文件数量消息
+ SysLog_T m_SysLog; // 关键日志增量消息
+ std::list ml_SysState; // 系统运行状态消息组
+ std::list