clean and init practice repo

This commit is contained in:
songtianlun 2022-12-20 17:31:11 +08:00
commit 1f6df32092
No known key found for this signature in database
GPG Key ID: A1B4E1B94AF5F6AF
1071 changed files with 152358 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.vscode
.DS_Store
*.swp
.idea

19
README.md Normal file
View File

@ -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

45
sftp-config.json Normal file
View File

@ -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,
}

View File

@ -0,0 +1,8 @@
# 位运算实现四则运算
尝试进行各种情况下位运算实现的四则运算和原生四则运算的速度。
## 结论
- C程序下乘除2位运算更快。
- 其他情况下位运算提供的四则运算速度较慢。

BIN
study_clang/BitArithmetic/a.out Executable file

Binary file not shown.

BIN
study_clang/BitArithmetic/bitCal Executable file

Binary file not shown.

View File

@ -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<stdio.h>
#include <stdio.h>
/*
*:
*@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里有多少个BA - B实现
* A一直循环减B0
*@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;
}

BIN
study_clang/BitArithmetic/main Executable file

Binary file not shown.

View File

@ -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<stdio.h>
#include<time.h>
#include<map>
#include<iostream>
using namespace std;
int bitAdd(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;
}
int add(int a, int b)
{
return a+b;
}
int bitSubtraction(int num1, int num2)
{
int temp = bitAdd(~num2, 1); //取反与求补差1
return bitAdd(num1, temp);
}
int subtraction(int a, int b)
{
return a - b;
}
int bitDivide(int x, int y) {
int ans=0;
for(int i=31;i>=0;i--)
{
// //比较x是否大于y的(1<<i)次方避免将x与(y<<i)比较因为不确定y的(1<<i)次方是否溢出
if( (x>>i) >=y )
{
ans+=(1<<i);
x-= (y<<i);
}
}
return ans;
}
int divide(int a, int b)
{
return a/b;
}
int multiply(int a, int b)
{
return a * b;
}
int bitMultiply(int a, int b)
{
int ans = 0;
while(b)
{
if(b&1) //b最后一位是否为1
ans = bitAdd(ans, a);
a = (a<<1);
b = (b>>1);
}
return ans;
}
int mulTwo(int n)
{
return n << 1;
}
int divTwo(int n)
{
return n >> 1;
}
int getAverage(int x, int y)
{
return ( x + y ) >> 1;
}
int main()
{
int i;
int a,b;
int result;
int num = 10000000;
clock_t start, finish;
double duration;
//printf("Test Add:\n");
printf("Please Enter the num1: ");
scanf("%d",&a);
printf("Please Enter the num2: ");
scanf("%d",&b);
printf("---------------------------------------------------------------------------------------------\n");
start = clock();
for(i=0;i<num;i++)
result = bitAdd(a,b);
// printf("Bit add calculation result: %d, ", bitAdd(a,b));
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Bit add calculation %d times total time: %f, Last result: %d\n", num,duration,result);
start = clock();
for(i=0;i<num;i++)
result = add(a,b);
// printf("Direct add calculation result: %d, ", (a+b));
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Direct add calculation %d times total time: %f, Last result: %d\n", num,duration,result);
printf("---------------------------------------------------------------------------------------------\n");
start = clock();
for(i=0;i<num;i++)
result =bitMultiply(a,b);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Bit multiply calculation %d times total time: %f, Last result: %d\n", num,duration,result);
start = clock();
for(i=0;i<num;i++)
result = multiply(a,b);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Direct multiply calculation %d times total time: %f, Last result: %d\n", num,duration,result);
printf("---------------------------------------------------------------------------------------------\n");
start = clock();
for(i=0;i<num;i++)
result =bitDivide(a,b);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Bit divide calculation %d times total time: %f, Last result: %d\n", num,duration,result);
start = clock();
for(i=0;i<num;i++)
result = divide(a,b);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Direct divide calculation %d times total time: %f, Last result: %d\n", num,duration,result);
printf("---------------------------------------------------------------------------------------------\n");
start = clock();
for(i=0;i<num;i++)
result = mulTwo(a);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Bit multiply 2 calculation %d times total time: %f, Last result: %d\n", num,duration,result);
start = clock();
for(i=0;i<num;i++)
result = multiply(a,2);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Direct multiply 2 calculation %d times total time: %f, Last result: %d\n", num,duration,result);
printf("---------------------------------------------------------------------------------------------\n");
start = clock();
for(i=0;i<num;i++)
result = divTwo(a);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Bit divide 2 calculation %d times total time: %f, Last result: %d\n", num,duration,result);
start = clock();
for(i=0;i<num;i++)
result = divide(a,2);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Direct divide 2 calculation %d times total time: %f, Last result: %d\n", num,duration,result);
printf("---------------------------------------------------------------------------------------------\n");
start = clock();
for(i=0;i<num;i++)
result = getAverage(a,b);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Bit average calculation %d times total time: %f, Last result: %d\n", num,duration,result);
start = clock();
for(i=0;i<num;i++)
result = divide(a+b,2);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("> Direct average calculation %d times total time: %f, Last result: %d\n", num,duration,result);
printf("---------------------------------------------------------------------------------------------\n");
}

22
study_clang/Makefile Normal file
View File

@ -0,0 +1,22 @@
# Batch Single C file MakeFile
# 指定CPU架构 Architecture -> ARCH
ARCH ?=
CC = $(ARCH)gcc
SUFFIX = .c
CFLAGS += -Wall -g
LD =
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)

View File

@ -0,0 +1,93 @@
/*************************************************************************
> File Name : OperateNos.cpp
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Thu 03 Dec 2020 09:13:38 AM CST
************************************************************************/
#include "FOperateNos.h"
int FOperateNos::StartNos(int iNosIdx)
{
// char szmsg[1024] = {0};
// strcpy(szmsg,"Start Nos");
Web_Msg_T webMsg;
memset(&webMsg, 0x00, sizeof(webMsg));
webMsg.nos_id = iNosIdx;
webMsg.nos_op = NOS_POWER_ON;
SendCmdToShd(&webMsg, sizeof(webMsg));
std::cout << "Nos" << webMsg.nos_id << " will be power on, result " << webMsg.result << std::endl;
}
int FOperateNos::StopNos(int iNosIdx)
{
Web_Msg_T webMsg;
memset(&webMsg, 0x00, sizeof(webMsg));
webMsg.nos_id = iNosIdx;
webMsg.nos_op = NOS_POWER_OFF;
SendCmdToShd(&webMsg, sizeof(webMsg));
std::cout << "Nos" << webMsg.nos_id << " will be power off, result " << webMsg.result << std::endl;
}
int FOperateNos::RestartNos(int iNosIdx)
{
Web_Msg_T webMsg;
memset(&webMsg, 0x00, sizeof(webMsg));
webMsg.nos_id = iNosIdx;
webMsg.nos_op = NOS_RESTART;
SendCmdToShd(&webMsg, sizeof(webMsg));
std::cout << "Nos" << webMsg.nos_id << " will be restart, result " << webMsg.result << std::endl;
}
void FOperateNos::Init()
{
reader = INIReader("operate_nos_conf.ini");
if (reader.ParseError() < 0)
std::cout << "Can't load 'test.ini'\n";
std::cout << "Init F Operate Nos" << std::endl;
InitSocket();
}
void FOperateNos::InitSocket()
{
char szPubKey[64] = {0};
char szPriKey[64] = {0};
char szSerKey[64] = {0};
char szaddr[128] = {0};
ctx = zmq_ctx_new();
sock = zmq_socket(ctx, ZMQ_REQ);
strcpy(szSerKey, ZMQ_PUBLIC_KEY_1);
snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", \
reader.Get("general", "shd_ip", "UNKNOWN").c_str(), \
reader.GetInteger("general", "shd_port", -1)
);
std::cout << "Connect to zmq server : " << szaddr << std::endl;
// 加密
// zmq_setsockopt(sock, ZMQ_CURVE_SERVERKEY, szSerKey, strlen(szSerKey));
// 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);
// 超时
unsigned int uiTimeout = 30 * 1000;
zmq_setsockopt(sock, ZMQ_RCVTIMEO, &uiTimeout, sizeof(uiTimeout));
}
void FOperateNos::DestroySocket()
{
zmq_close(sock);
zmq_ctx_term(ctx);
zmq_ctx_destroy(ctx);
}
int FOperateNos::SendCmdToShd(void * sMsg, int iMsgLen)
{
int iResult;
iResult = zmq_send(sock, sMsg, iMsgLen, 0);
if(0 > iResult)
std::cout << "Send Msg To Shd Error, Code " << iResult << std::endl;
iResult = zmq_recv(sock, sMsg, iMsgLen, 0);
if(0 > iResult)
std::cout << "Recv Msg From Shd Error, Code " << iResult << std::endl;
}

View File

@ -0,0 +1,486 @@
/*************************************************************************
> File Name : OperateNos.h
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Thu 03 Dec 2020 09:13:48 AM CST
************************************************************************/
#include <stdio.h>
#include <iostream>
#include <ctype.h>
#include <string.h>
#include <zmq.h>
#include <unistd.h>
#define ZMQ_PUBLIC_KEY_1 "@M[-VQ%R2MKguD/h/0w7.fNq%GGjV!1Q:bVeu*u>"
#define ZMQ_PRIVATE_KEY_1 "S*{[[V$7f<(jA<XWT?&baG>p^]M>I!n?dN]SXgB]"
#define WEB_EXEC_FAILED 201
#define WEB_EXEC_SUCCES 202
typedef enum Web_Op_E
{
NOS_POWER_ON=1,
NOS_POWER_OFF,
NOS_RESTART
}Web_Op_T;
typedef struct Web_Msg_S
{
unsigned int nos_id;
Web_Op_T nos_op;
unsigned int result; //0:defaule 201:failed 202:succeed
}Web_Msg_T;
// INIReader.h https://github.com/jtilly/inih
#ifndef __INI_H__
#define __INI_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef int (*ini_handler)(void* user, const char* section,
const char* name, const char* value);
typedef char* (*ini_reader)(char* str, int num, void* stream);
int ini_parse(const char* filename, ini_handler handler, void* user);
int ini_parse_file(FILE* file, ini_handler handler, void* user);
int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,
void* user);
#ifndef INI_ALLOW_MULTILINE
#define INI_ALLOW_MULTILINE 1
#endif
#ifndef INI_ALLOW_BOM
#define INI_ALLOW_BOM 1
#endif
#ifndef INI_ALLOW_INLINE_COMMENTS
#define INI_ALLOW_INLINE_COMMENTS 1
#endif
#ifndef INI_INLINE_COMMENT_PREFIXES
#define INI_INLINE_COMMENT_PREFIXES ";"
#endif
/* Nonzero to use stack, zero to use heap (malloc/free). */
#ifndef INI_USE_STACK
#define INI_USE_STACK 1
#endif
/* Stop parsing on first error (default is to keep parsing). */
#ifndef INI_STOP_ON_FIRST_ERROR
#define INI_STOP_ON_FIRST_ERROR 0
#endif
/* Maximum line length for any line in INI file. */
#ifndef INI_MAX_LINE
#define INI_MAX_LINE 200
#endif
#ifdef __cplusplus
}
#endif
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#if !INI_USE_STACK
#include <stdlib.h>
#endif
#define MAX_SECTION 50
#define MAX_NAME 50
/* Strip whitespace chars off end of given string, in place. Return s. */
inline static char* rstrip(char* s)
{
char* p = s + strlen(s);
while (p > s && isspace((unsigned char)(*--p)))
*p = '\0';
return s;
}
/* Return pointer to first non-whitespace char in given string. */
inline static char* lskip(const char* s)
{
while (*s && isspace((unsigned char)(*s)))
s++;
return (char*)s;
}
/* Return pointer to first char (of chars) or inline comment in given string,
or pointer to null at end of string if neither found. Inline comment must
be prefixed by a whitespace character to register as a comment. */
inline static char* find_chars_or_comment(const char* s, const char* chars)
{
#if INI_ALLOW_INLINE_COMMENTS
int was_space = 0;
while (*s && (!chars || !strchr(chars, *s)) &&
!(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) {
was_space = isspace((unsigned char)(*s));
s++;
}
#else
while (*s && (!chars || !strchr(chars, *s))) {
s++;
}
#endif
return (char*)s;
}
/* Version of strncpy that ensures dest (size bytes) is null-terminated. */
inline static char* strncpy0(char* dest, const char* src, size_t size)
{
strncpy(dest, src, size);
dest[size - 1] = '\0';
return dest;
}
/* See documentation in header file. */
inline int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,
void* user)
{
/* Uses a fair bit of stack (use heap instead if you need to) */
#if INI_USE_STACK
char line[INI_MAX_LINE];
#else
char* line;
#endif
char section[MAX_SECTION] = "";
char prev_name[MAX_NAME] = "";
char* start;
char* end;
char* name;
char* value;
int lineno = 0;
int error = 0;
#if !INI_USE_STACK
line = (char*)malloc(INI_MAX_LINE);
if (!line) {
return -2;
}
#endif
/* Scan through stream line by line */
while (reader(line, INI_MAX_LINE, stream) != NULL) {
lineno++;
start = line;
#if INI_ALLOW_BOM
if (lineno == 1 && (unsigned char)start[0] == 0xEF &&
(unsigned char)start[1] == 0xBB &&
(unsigned char)start[2] == 0xBF) {
start += 3;
}
#endif
start = lskip(rstrip(start));
if (*start == ';' || *start == '#') {
/* Per Python configparser, allow both ; and # comments at the
start of a line */
}
#if INI_ALLOW_MULTILINE
else if (*prev_name && *start && start > line) {
#if INI_ALLOW_INLINE_COMMENTS
end = find_chars_or_comment(start, NULL);
if (*end)
*end = '\0';
rstrip(start);
#endif
/* Non-blank line with leading whitespace, treat as continuation
of previous name's value (as per Python configparser). */
if (!handler(user, section, prev_name, start) && !error)
error = lineno;
}
#endif
else if (*start == '[') {
/* A "[section]" line */
end = find_chars_or_comment(start + 1, "]");
if (*end == ']') {
*end = '\0';
strncpy0(section, start + 1, sizeof(section));
*prev_name = '\0';
}
else if (!error) {
/* No ']' found on section line */
error = lineno;
}
}
else if (*start) {
/* Not a comment, must be a name[=:]value pair */
end = find_chars_or_comment(start, "=:");
if (*end == '=' || *end == ':') {
*end = '\0';
name = rstrip(start);
value = lskip(end + 1);
#if INI_ALLOW_INLINE_COMMENTS
end = find_chars_or_comment(value, NULL);
if (*end)
*end = '\0';
#endif
rstrip(value);
/* Valid name[=:]value pair found, call handler */
strncpy0(prev_name, name, sizeof(prev_name));
if (!handler(user, section, name, value) && !error)
error = lineno;
}
else if (!error) {
/* No '=' or ':' found on name[=:]value line */
error = lineno;
}
}
#if INI_STOP_ON_FIRST_ERROR
if (error)
break;
#endif
}
#if !INI_USE_STACK
free(line);
#endif
return error;
}
/* See documentation in header file. */
inline int ini_parse_file(FILE* file, ini_handler handler, void* user)
{
return ini_parse_stream((ini_reader)fgets, file, handler, user);
}
/* See documentation in header file. */
inline int ini_parse(const char* filename, ini_handler handler, void* user)
{
FILE* file;
int error;
file = fopen(filename, "r");
if (!file)
return -1;
error = ini_parse_file(file, handler, user);
fclose(file);
return error;
}
#endif /* __INI_H__ */
#ifndef __INIREADER_H__
#define __INIREADER_H__
#include <map>
#include <set>
#include <string>
// Read an INI file into easy-to-access name/value pairs. (Note that I've gone
// for simplicity here rather than speed, but it should be pretty decent.)
class INIReader
{
public:
// Empty Constructor
INIReader() {};
// Construct INIReader and parse given filename. See ini.h for more info
// about the parsing.
INIReader(std::string filename);
// Construct INIReader and parse given file. See ini.h for more info
// about the parsing.
INIReader(FILE *file);
// Return the result of ini_parse(), i.e., 0 on success, line number of
// first error on parse error, or -1 on file open error.
int ParseError() const;
// Return the list of sections found in ini file
const std::set<std::string>& Sections() const;
// Get a string value from INI file, returning default_value if not found.
std::string Get(std::string section, std::string name,
std::string default_value) const;
// 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").
long GetInteger(std::string section, std::string name, long default_value) const;
// 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(std::string section, std::string name, double default_value) const;
// Get a single precision floating point number value from INI file, returning
// default_value if not found or not a valid floating point value
// according to strtof().
float GetFloat(std::string section, std::string name, float default_value) const;
// 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(std::string section, std::string name, bool default_value) const;
protected:
int _error;
std::map<std::string, std::string> _values;
std::set<std::string> _sections;
static std::string MakeKey(std::string section, std::string name);
static int ValueHandler(void* user, const char* section, const char* name,
const char* value);
};
#endif // __INIREADER_H__
#ifndef __INIREADER__
#define __INIREADER__
#include <algorithm>
#include <cctype>
#include <cstdlib>
inline INIReader::INIReader(std::string filename)
{
_error = ini_parse(filename.c_str(), ValueHandler, this);
}
inline INIReader::INIReader(FILE *file)
{
_error = ini_parse_file(file, ValueHandler, this);
}
inline int INIReader::ParseError() const
{
return _error;
}
inline const std::set<std::string>& INIReader::Sections() const
{
return _sections;
}
inline std::string INIReader::Get(std::string section, std::string name, std::string default_value) const
{
std::string key = MakeKey(section, name);
return _values.count(key) ? _values.at(key) : default_value;
}
inline long INIReader::GetInteger(std::string section, std::string name, long default_value) const
{
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
// This parses "1234" (decimal) and also "0x4D2" (hex)
long n = strtol(value, &end, 0);
return end > value ? n : default_value;
}
inline double INIReader::GetReal(std::string section, std::string name, double default_value) const
{
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
double n = strtod(value, &end);
return end > value ? n : default_value;
}
inline float INIReader::GetFloat(std::string section, std::string name, float default_value) const
{
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
float n = strtof(value, &end);
return end > value ? n : default_value;
}
inline bool INIReader::GetBoolean(std::string section, std::string name, bool default_value) const
{
std::string valstr = Get(section, name, "");
// Convert to lower case to make string comparisons case-insensitive
std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
return true;
else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
return false;
else
return default_value;
}
inline std::string INIReader::MakeKey(std::string section, std::string name)
{
std::string key = section + "=" + name;
// Convert to lower case to make section/name lookups case-insensitive
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
return key;
}
inline int INIReader::ValueHandler(void* user, const char* section, const char* name,
const char* value)
{
INIReader* reader = (INIReader*)user;
std::string key = MakeKey(section, name);
if (reader->_values[key].size() > 0)
reader->_values[key] += "\n";
reader->_values[key] += value;
reader->_sections.insert(section);
return 1;
}
#endif // __INIREADER__
// 单实例模板类 饿汉模式
#ifndef __SINGLETON_CLASS_H__
#define __SINGLETON_CLASS_H__
template <typename T>
class singleton
{
private:
static T* p; //标志指针
public:
static T* instance(); //得到类型为T对象的方法
};
template <typename T>
T* singleton<T>::p = new T(); //不管外部是否要使用对象进入main函数前就生成T对象p指向该对象的地址
template <typename T>
T* singleton<T>::instance()
{
return p;
}
#endif /* __SINGLETON_CLASS_H__ */
#ifndef FOPERATENOS_H
#define FOPERATENOS_H
class FOperateNos
{
public:
FOperateNos(){};
virtual ~FOperateNos(){
DestroySocket();
};
public:
void Init();
int StartNos(int iNosIdx);
int StopNos(int iNosIdx);
int RestartNos(int iNosIdx);
private:
void InitSocket();
void DestroySocket();
int SendCmdToShd(void * sMsg, int iMsgLen);
friend class singleton<FOperateNos>;
private:
void * ctx;
void *sock;
INIReader reader;
};
#endif /* FOPERATENOS_H */

View File

@ -0,0 +1,20 @@
# Author: Tianlun Song, songtianlun@frytea.com, In Nov 22, 2020.
ARCH ?=
CC = $(ARCH)g++
SUFFIX = .cpp
CFLAGS += -g -L ./
LD = -lzmq
CUR_SOURCE = $(wildcard *.cpp)
# CUR_SOURCE = main.cpp FOperateNos.cpp
CUR_TARGETS = ./operate_nos
all:$(CUR_TARGETS)
$(CUR_TARGETS):$(CUR_SOURCE)
$(CC) $^ $(CFLAGS) -o $@ $(LD)
# 指定伪目标
.PHONY:clean all
clean:
-rm -rf $(TARGETS)

View File

@ -0,0 +1,40 @@
/*************************************************************************
> File Name : main.cpp
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Thu 03 Dec 2020 09:43:19 AM CST
************************************************************************/
#include "FOperateNos.h"
/*
s_web_to_shd_addr=30.30.30.202:8201
#define WEB_EXEC_FAILED 201
#define WEB_EXEC_SUCCES 202
typedef enum Web_Op_E
{
NOS_POWER_ON=1,
NOS_POWER_OFF,
NOS_RESTART
}Web_Op_T;
typedef struct Web_Msg_S
{
unsigned int nos_id;
Web_Op_T nos_op;
unsigned int result; //0:defaule 201:failed 202:succeed
}Web_Msg_T;
*/
int main(int argc, char* argv[])
{
singleton<FOperateNos>::instance()->Init();
sleep(1);
singleton<FOperateNos>::instance()->StartNos(1);
sleep(1);
singleton<FOperateNos>::instance()->StopNos(2);
sleep(1);
singleton<FOperateNos>::instance()->RestartNos(3);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,6 @@
; Config file for OperateNos
; Author: Tianlun Song. songtianlun@frytea.com.
[general] ; General configuration
shd_ip=30.30.30.202 ; SHD IP
shd_port=8201 ; SHD Port

View File

@ -0,0 +1,22 @@
# Batch Single C file MakeFile
# 指定CPU架构 Architecture -> ARCH
ARCH ?=
CC = $(ARCH)gcc
SUFFIX = .c
CFLAGS += -Wall -g -lzmq -lpthread
LD =
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)

Binary file not shown.

View File

@ -0,0 +1,76 @@
/*************************************************************************
> File Name : server.c
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Wed 02 Dec 2020 04:50:40 PM CST
************************************************************************/
#include <stdio.h>
#include <zmq.h>
#include <string.h>
#define ZMQ_PUBLIC_KEY_1 "@M[-VQ%R2MKguD/h/0w7.fNq%GGjV!1Q:bVeu*u>"
#define ZMQ_PRIVATE_KEY_1 "S*{[[V$7f<(jA<XWT?&baG>p^]M>I!n?dN]SXgB]"
#define ZMQ_PUBLIC_KEY_2 "p=lDOa9WKUKz!I9{G)uPX4@&CrV-(>tDg:kaSGzE"
#define ZMQ_PRIVATE_KEY_2 "q0]#)<fZP>iuwR*H5hz.}<AR^RSWunZ8H+oc8l1k"
#define WEB_EXEC_FAILED 201
#define WEB_EXEC_SUCCES 202
typedef enum Web_Op_E
{
NOS_POWER_ON=1,
NOS_POWER_OFF,
NOS_RESTART
}Web_Op_T;
typedef struct Web_Msg_S
{
unsigned int nos_id;
Web_Op_T nos_op;
unsigned int result; //0:defaule 201:failed 202:succeed
}Web_Msg_T;
int main()
{
const char *ip = "*";
int port = 8201;
char szPubKey[64] = {0};
char szPriKey[64] = {0};
void * ctx = zmq_ctx_new();
void *sock = zmq_socket(ctx, ZMQ_REP);
strcpy(szPubKey, ZMQ_PUBLIC_KEY_1);
strcpy(szPriKey, ZMQ_PRIVATE_KEY_1);
int option = 1;
zmq_setsockopt(sock, ZMQ_CURVE_SERVER, &option, sizeof(option));
zmq_setsockopt(sock, ZMQ_CURVE_SECRETKEY, szPriKey, strlen(szPriKey));
char szaddr[128] = {0};
snprintf(szaddr, sizeof(szaddr), "tcp://%s:%d", ip, port);
zmq_bind(sock, szaddr);
//char szmsg[1024] = {0};
Web_Msg_T msg;
while(1) {
memset(&msg, 0x00, sizeof(msg));
zmq_recv(sock, &msg, sizeof(msg) - 1, 0);
printf("recv msg from nos %d, option %d, result %d\n", msg.nos_id, msg.nos_op, msg.result);
msg.result = WEB_EXEC_SUCCES;
zmq_send(sock, &msg, sizeof(msg), 0);
printf("send msg from nos %d, option %d, result %d\n", msg.nos_id, msg.nos_op, msg.result);
zmq_send(sock, &msg, sizeof(msg), 0);
}
zmq_unbind(sock, szaddr);
zmq_close(sock);
zmq_ctx_term(ctx);
zmq_ctx_destroy(ctx);
return 0;
}

View File

@ -0,0 +1,12 @@
<!--
* @Author: songtl
* @Date: 2020-07-20 09:03:59
* @LastEditors: songtl
* @LastEditTime: 2020-07-20 09:10:06
* @Description: 描述文件
-->
# DM-SW6620-32X2Q-Mimic-Switch
> 一些关于 `DM-SW6620-32X2Q` 拟态交换机的代码。
- monitor_system_status: 监控系统状况,并向裁决模块发送系统状态报文。
- judge_status: 裁决模块中的系统状态裁决。

View File

@ -0,0 +1,53 @@
class GlobalVar:
proxy_interface = "ens8"
nos1_interface = "ens8f5"
nos2_interface = "ens8f5"
nos3_interface = "ens8f5"
nos4_interface = "ens8f5"
master_nos_interface = "ens8f5"
master_nos_vlan = "200"
nos_ip = "192.168.11.1"
#def set_db_handle(db):
# GlobalVar.db_handle = db
def get_proxy_interface():
return GlobalVar.proxy_interface
def get_nos1_interface():
return GlobalVar.nos1_interface
def get_nos2_interface():
return GlobalVar.nos2_interface
def get_nos3_interface():
return GlobalVar.nos3_interface
def get_nos4_interface():
return GlobalVar.nos4_interface
def get_master_nos_interface():
fileHandle = open ('nos.conf','r')
nos = fileHandle.read (1)
fileHandle.close()
if nos == "1":
GlobalVar.master_nos_interface = GlobalVar.nos1_interface
elif nos == "2":
GlobalVar.master_nos_interface = GlobalVar.nos2_interface
elif nos == "3":
GlobalVar.master_nos_interface = GlobalVar.nos3_interface
elif nos == "4":
GlobalVar.master_nos_interface = GlobalVar.nos4_interface
else:
GlobalVar.master_nos_interface = GlobalVar.nos1_interface
return GlobalVar.master_nos_interface
def get_master_nos_vlan():
fileHandle = open ('nos_vlan.conf','r')
nosvlan = fileHandle.read (3)
fileHandle.close()
GlobalVar.master_nos_vlan = nosvlan
return GlobalVar.master_nos_vlan
def get_nos_ip():
return GlobalVar.nos_ip

View File

@ -0,0 +1,166 @@
#!/bin/bash
#----------------------------------------------------------------------------------------------------------------------------------------------
#
# 1、 judgeMasterNos.py 先启动,以后台方式启动;
# 2、 judgeMasterNos.py启动以后sleep 2秒后再启动arpProxy.py同时通过ps命令查看arpProxy.py进程是否存在如果不存在将启动失败信息写入到当前目录下的log中
# 3、 arpProxy.py启动以后sleep 2秒后再启动icmpProxy.py同时通过ps命令查看icmpProxy.py进程是否存在如果不存在将启动失败信息写入到当前目录下的log中
# 4、 icmpProxy.py启动以后sleep 2秒后再启动udpProxy.py同时通过ps命令查看udpProxy.py进程是否存在如果不存在将启动失败信息写入到当前目录下的log中
# 5、 udpProxy.py启动以后sleep 2秒后再启动tcpProxy.py同时通过ps命令查看tcpProxy.py进程是否存在如果不存在将启动失败信息写入到当前目录下的log中
# 6、 判断arpProxy.py、icmpProxy.py、udpProxy.py、tcpProxy.py四个进程是否存在如果不存在将错误信息写入到log中。
#
#----------------------------------------------------------------------------------------------------------------------------------------------
#cmdpre="awk '/"
#cmdsuf="/' awk.temp"
log_mod="init_err" #用于分支不同的log格式
#在启动时的log记录
function log()
{
ERR_LOGFILE="error.log"
echo "[$pro] failed."
CUR_TIME=`date +'%Y-%m-%d %H-%M-%S'`
if [ -f $ERR_LOGFILE ];then
echo "[$pro] started failed at time $CUR_TIME" >> error.log;
fi
}
#在最后检查时的log记录
function log_check()
{
ERR_LOGFILE="error.log"
echo "[$pro] don't exist."
CUR_TIME=`date +'%Y-%m-%d %H-%M-%S'`
if [ -f $ERR_LOGFILE ];then
echo "[$pro] don't exist at time $CUR_TIME" >> error.log;
fi
}
#判断是否从ps中抓取到进程没有则调用log
function isNull()
{
if [ "$a" = "" ];then
if [ $log_mod = "init_err" ];then
log
else
log_check
fi
fi
}
#启动一个进程然后启动后抓取ps
function start()
{
sleep 2
echo "[$pro] init..."
if [ -f "${pro}.pyc" ];then
$s python ${pro}.pyc >/dev/null 2>&1 &
ps a > ps.temp
awk '{print $6}' 'ps.temp' > awk.temp
#cmd=${cmdpre}${pro}${cmdsuf} #尝试用连接的方法将awk组合命令但是会报错
fi
}
#'sudo' 命令前缀
s=''
# 1、
if [ -f "judgeMasterNos.pyc" ];then
$s nohup python judgeMasterNos.pyc >/dev/null 2>&1 &
fi
# 2、
pro="arpProxy"
start
a=`awk '/arpProxy/' 'awk.temp'` #因为命令中不能引用变量所以在这里分别写。
isNull
# 3、
pro="icmpProxy"
start
a=`awk '/icmpProxy/' 'awk.temp'`
isNull
# 4、
pro="udpProxy"
start
a=`awk '/udpProxy/' 'awk.temp'`
isNull
# 5、
pro="tcpProxy"
start
a=`awk '/tcpProxy/' 'awk.temp'`
isNull
pro="sshRelay"
start
a=`awk '/sshRelay/' 'awk.temp'`
isNull
pro="pro_mimic"
start
a=`awk '/pro_mimic/' 'awk.temp'`
isNull
pro="rip_mimic"
start
a=`awk '/rip_mimic/' 'awk.temp'`
isNull
# 6、
#改变log格式
log_mod="check"
ps a > ps.temp
awk '{print $6}' 'ps.temp' > awk.temp
pro="arpProxy"
a=`awk '/arpProxy/' 'awk.temp'`
isNull
# 6、
#改变log格式
log_mod="check"
ps a > ps.temp
awk '{print $6}' 'ps.temp' > awk.temp
pro="arpProxy"
a=`awk '/arpProxy/' 'awk.temp'`
isNull
pro="icmpProxy"
a=`awk '/icmpProxy/' 'awk.temp'`
isNull
pro="udpProxy"
a=`awk '/udpProxy/' 'awk.temp'`
isNull
pro="tcpProxy"
a=`awk '/tcpProxy/' 'awk.temp'`
isNull
pro="sshRelay"
a=`awk '/sshRelay/' 'awk.temp'`
isNull
pro="pro_mimic"
a=`awk '/pro_mimic/' 'awk.temp'`
isNull
pro="rip_mimic"
a=`awk '/rip_mimic/' 'awk.temp'`
isNull

View File

@ -0,0 +1,54 @@
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
import random
#db_ip = "localhost"
db_ip = "192.168.134.84"
# 打开数据库连接
db = MySQLdb.connect(db_ip, "root", "123456", "nosdb", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("select * from masternos order by id DESC limit 1 ")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
# 关闭数据库连接
db.close()
#print " id : %d " % data[0]
#print "type: %d" % data[1]
#print "nos:%d" % data[3]
#print "mark:%s" % data[2]
master_nos = 1; #the default master nos is nos1
if data[1] == 0: # give the nos by admin
master_nos = data[2]
elif data[1] == 1: #give the nos with random
master_nos = random.randint(1,4)
#print "master_nos random:",master_nos
#根据主执行体确定vlanID
if master_nos == 1:
vlanID = 200
elif master_nos == 2:
vlanID = 300
elif master_nos == 3:
vlanID = 400
elif master_nos == 4:
vlanID = 500
else:
vlanID = 200
fileHandle = open ('nos.conf', 'w' )
fileHandle.write (str(master_nos))
fileHandle.close()
fileHandle = open ('nos_vlan.conf', 'w' )
fileHandle.write (str(vlanID))
fileHandle.close()

View File

@ -0,0 +1 @@
2

View File

@ -0,0 +1,78 @@
from scapy.all import *
import pcappy as pcap
import threading
import multiprocessing
import time
import globalvar as GlobalVar
from icmpProxy import getPortIp
conf.use_pcap = True
proxy_interface = str(GlobalVar.get_proxy_interface())
nos1_interface = str(GlobalVar.get_nos1_interface())
nos2_interface = str(GlobalVar.get_nos2_interface())
nos3_interface = str(GlobalVar.get_nos3_interface())
nos4_interface = str(GlobalVar.get_nos4_interface())
master_nos_interface = str(GlobalVar.get_master_nos_interface())
master_nos_vlan = (GlobalVar.get_master_nos_vlan())
def proxy_udploop():
print 'proxy begin receive udp'
sniff(prn=dealProxyPacket, filter="ether[13]>0x00 and ether[13]<0x15 and ether[28]=0x08 and ether[29]=0x00 and ether[39]=0x11", iface=proxy_interface)
def dealProxyPacket(pkt):
pkt_str = str(pkt)
new_pkt = pkt.__class__(pkt_str[16:])
#print new_pkt.show()
pkt_hex = pkt_str[:16].encode('hex')
ftag = int(int(pkt_hex[26], 16)*16) + int(pkt_hex[27], 16)
sourth_pkt = Ether(src=new_pkt[Ether].src, dst=new_pkt[Ether].dst)/Dot1Q(vlan=int(master_nos_vlan)+ftag)/new_pkt.payload
#print pkt4.show()
sendp(sourth_pkt, count=1, iface=master_nos_interface)
def master_nos_udploop():
ipFilterList = getPortIp()
filterStr = "udp and (ip src " + str(GlobalVar.get_nos_ip())
for i in ipFilterList:
filterStr += " or ip src " + i
filterStr += ")"
print 'master nos begin receive udp'
sniff(prn=dealMasterNosPacket, filter=filterStr, iface=master_nos_interface)
#sniff(prn=dealMasterNosPacket,filter="vlan",iface=master_nos_interface)
def dealMasterNosPacket(pkt):
#print pkt.show()
if int(pkt[Dot1Q].vlan) > int(master_nos_vlan) and int(pkt[Dot1Q].vlan) < (int(master_nos_vlan)+18):
portVlan = (int(pkt[Dot1Q].vlan) - int(master_nos_vlan) + 1000)
pkt[Dot1Q].vlan = portVlan
print pkt.show()
sendp(pkt, count=1, iface=proxy_interface)
def main():
p1 = multiprocessing.Process(target = proxy_udploop)
p1.start()
p2 = multiprocessing.Process(target = master_nos_udploop)
p2.start()
#t2 =threading.Thread(target=proxy_udpploop)
#t2.start()
#t4 =threading.Thread(target=master_nos_udpploop)
#t4.start()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,22 @@
# Batch Single C file MakeFile
# 指定CPU架构 Architecture -> ARCH
ARCH ?=
CC = $(ARCH)g++
SUFFIX = .cpp
CFLAGS += -Wall -g -std=c++11
LD = -lcriu
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)

View File

@ -0,0 +1,281 @@
/*
* (C) Copyright 2013 Parallels, Inc. (www.parallels.com).
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, you can find it here:
* www.gnu.org/licenses/lgpl.html
*/
#ifndef __CRIU_LIB_H__
#define __CRIU_LIB_H__
#include <stdbool.h>
//#include "version.h"
#include <linux/version.h>
#ifdef __GNUG__
extern "C" {
#endif
enum criu_service_comm {
CRIU_COMM_SK,
CRIU_COMM_FD,
CRIU_COMM_BIN
};
enum criu_cg_mode {
CRIU_CG_MODE_IGNORE,
CRIU_CG_MODE_NONE,
CRIU_CG_MODE_PROPS,
CRIU_CG_MODE_SOFT,
CRIU_CG_MODE_FULL,
CRIU_CG_MODE_STRICT,
CRIU_CG_MODE_DEFAULT,
};
enum criu_pre_dump_mode {
CRIU_PRE_DUMP_SPLICE = 1,
CRIU_PRE_DUMP_READ = 2
};
int criu_set_service_address(const char *path);
void criu_set_service_fd(int fd);
int criu_set_service_binary(const char *path);
/*
* Set opts to defaults. _Must_ be called first before using any functions from
* the list down below. 0 on success, -1 on fail.
*/
int criu_init_opts(void);
void criu_free_opts(void);
void criu_set_pid(int pid);
void criu_set_images_dir_fd(int fd); /* must be set for dump/restore */
int criu_set_parent_images(const char *path);
void criu_set_work_dir_fd(int fd);
void criu_set_leave_running(bool leave_running);
void criu_set_ext_unix_sk(bool ext_unix_sk);
int criu_add_unix_sk(unsigned int inode);
void criu_set_tcp_established(bool tcp_established);
void criu_set_tcp_skip_in_flight(bool tcp_skip_in_flight);
void criu_set_tcp_close(bool tcp_close);
void criu_set_weak_sysctls(bool val);
void criu_set_evasive_devices(bool evasive_devices);
void criu_set_shell_job(bool shell_job);
void criu_set_orphan_pts_master(bool orphan_pts_master);
void criu_set_file_locks(bool file_locks);
void criu_set_track_mem(bool track_mem);
void criu_set_auto_dedup(bool auto_dedup);
void criu_set_force_irmap(bool force_irmap);
void criu_set_link_remap(bool link_remap);
void criu_set_log_level(int log_level);
int criu_set_log_file(const char *log_file);
void criu_set_cpu_cap(unsigned int cap);
int criu_set_root(const char *root);
void criu_set_manage_cgroups(bool manage);
void criu_set_manage_cgroups_mode(enum criu_cg_mode mode);
int criu_set_freeze_cgroup(const char *name);
int criu_set_lsm_profile(const char *name);
void criu_set_timeout(unsigned int timeout);
void criu_set_auto_ext_mnt(bool val);
void criu_set_ext_sharing(bool val);
void criu_set_ext_masters(bool val);
int criu_set_exec_cmd(int argc, char *argv[]);
int criu_add_ext_mount(const char *key, const char *val);
int criu_add_veth_pair(const char *in, const char *out);
int criu_add_cg_root(const char *ctrl, const char *path);
int criu_add_enable_fs(const char *fs);
int criu_add_skip_mnt(const char *mnt);
void criu_set_ghost_limit(unsigned int limit);
int criu_add_irmap_path(const char *path);
int criu_add_inherit_fd(int fd, const char *key);
int criu_add_external(const char *key);
int criu_set_page_server_address_port(const char *address, int port);
int criu_set_pre_dump_mode(enum criu_pre_dump_mode mode);
/*
* The criu_notify_arg_t na argument is an opaque
* value that callbacks (cb-s) should pass into
* criu_notify_xxx() calls to fetch arbitrary values
* from notification. If the value is not available
* some non-existing one is reported.
*/
typedef struct _CriuNotify *criu_notify_arg_t;
void criu_set_notify_cb(int (*cb)(char *action, criu_notify_arg_t na));
/* Get pid of root task. 0 if not available */
int criu_notify_pid(criu_notify_arg_t na);
/*
* If CRIU sends and FD in the case of 'orphan-pts-master',
* this FD can be retrieved with criu_get_orphan_pts_master_fd().
*
* If no FD has been received this will return -1.
*
* To make sure the FD returned is valid this function has to be
* called after the callback with the 'action' 'orphan-pts-master'.
*/
int criu_get_orphan_pts_master_fd(void);
/* Here is a table of return values and errno's of functions
* from the list down below.
*
* Return value errno Description
* ----------------------------------------------------------------------------
* 0 undefined Success.
*
* >0 undefined Success(criu_restore() only).
*
* -BADE rpc err (0 for now) RPC has returned fail.
*
* -ECONNREFUSED errno Unable to connect to CRIU.
*
* -ECOMM errno Unable to send/recv msg to/from CRIU.
*
* -EINVAL undefined CRIU doesn't support this type of request.
* You should probably update CRIU.
*
* -EBADMSG undefined Unexpected response from CRIU.
* You should probably update CRIU.
*/
int criu_check(void);
int criu_dump(void);
int criu_restore(void);
int criu_restore_child(void);
/*
* Perform dumping but with preliminary iterations. Each
* time an iteration ends the ->more callback is called.
* The callback's return value is
* - positive -- one more iteration starts
* - zero -- final dump is performed and call exits
* - negative -- dump is aborted, the value is returned
* back from criu_dump_iters
*
* The @pi argument is an opaque value that caller may
* use to request pre-dump statistics (not yet implemented).
*/
typedef void *criu_predump_info;
int criu_dump_iters(int (*more)(criu_predump_info pi));
/*
* Get the version of the actual binary used for RPC.
*
* As this library is just forwarding all tasks to an
* independent (of this library) CRIU binary, the actual
* version of the CRIU binary can be different then the
* hardcoded values in the libary (version.h).
* To be able to easily check the version of the CRIU binary
* the function criu_get_version() returns the version
* in the following format:
*
* (major * 10000) + (minor * 100) + sublevel
*
* If the CRIU binary has been built from a git checkout
* minor will increased by one.
*/
int criu_get_version(void);
/*
* Check if the version of the CRIU binary is at least
* 'minimum'. Version has to be in the same format as
* described for criu_get_version().
*
* Returns 1 if CRIU is at least 'minimum'.
* Returns 0 if CRIU is too old.
* Returns < 0 if there was an error.
*/
int criu_check_version(int minimum);
/*
* Same as the list above, but lets you have your very own options
* structure and lets you set individual options in it.
*/
typedef struct criu_opts criu_opts;
int criu_local_init_opts(criu_opts **opts);
void criu_local_free_opts(criu_opts *opts);
int criu_local_set_service_address(criu_opts *opts, const char *path);
void criu_local_set_service_fd(criu_opts *opts, int fd);
void criu_local_set_service_fd(criu_opts *opts, int fd);
void criu_local_set_pid(criu_opts *opts, int pid);
void criu_local_set_images_dir_fd(criu_opts *opts, int fd); /* must be set for dump/restore */
int criu_local_set_parent_images(criu_opts *opts, const char *path);
int criu_local_set_service_binary(criu_opts *opts, const char *path);
void criu_local_set_work_dir_fd(criu_opts *opts, int fd);
void criu_local_set_leave_running(criu_opts *opts, bool leave_running);
void criu_local_set_ext_unix_sk(criu_opts *opts, bool ext_unix_sk);
int criu_local_add_unix_sk(criu_opts *opts, unsigned int inode);
void criu_local_set_tcp_established(criu_opts *opts, bool tcp_established);
void criu_local_set_tcp_skip_in_flight(criu_opts *opts, bool tcp_skip_in_flight);
void criu_local_set_tcp_close(criu_opts *opts, bool tcp_close);
void criu_local_set_weak_sysctls(criu_opts *opts, bool val);
void criu_local_set_evasive_devices(criu_opts *opts, bool evasive_devices);
void criu_local_set_shell_job(criu_opts *opts, bool shell_job);
void criu_local_set_orphan_pts_master(criu_opts *opts, bool orphan_pts_master);
void criu_local_set_file_locks(criu_opts *opts, bool file_locks);
void criu_local_set_track_mem(criu_opts *opts, bool track_mem);
void criu_local_set_auto_dedup(criu_opts *opts, bool auto_dedup);
void criu_local_set_force_irmap(criu_opts *opts, bool force_irmap);
void criu_local_set_link_remap(criu_opts *opts, bool link_remap);
void criu_local_set_log_level(criu_opts *opts, int log_level);
int criu_local_set_log_file(criu_opts *opts, const char *log_file);
void criu_local_set_cpu_cap(criu_opts *opts, unsigned int cap);
int criu_local_set_root(criu_opts *opts, const char *root);
void criu_local_set_manage_cgroups(criu_opts *opts, bool manage);
void criu_local_set_manage_cgroups_mode(criu_opts *opts, enum criu_cg_mode mode);
int criu_local_set_freeze_cgroup(criu_opts *opts, const char *name);
int criu_local_set_lsm_profile(criu_opts *opts, const char *name);
void criu_local_set_timeout(criu_opts *opts, unsigned int timeout);
void criu_local_set_auto_ext_mnt(criu_opts *opts, bool val);
void criu_local_set_ext_sharing(criu_opts *opts, bool val);
void criu_local_set_ext_masters(criu_opts *opts, bool val);
int criu_local_set_exec_cmd(criu_opts *opts, int argc, char *argv[]);
int criu_local_add_ext_mount(criu_opts *opts, const char *key, const char *val);
int criu_local_add_veth_pair(criu_opts *opts, const char *in, const char *out);
int criu_local_add_cg_root(criu_opts *opts, const char *ctrl, const char *path);
int criu_local_add_enable_fs(criu_opts *opts, const char *fs);
int criu_local_add_skip_mnt(criu_opts *opts, const char *mnt);
void criu_local_set_ghost_limit(criu_opts *opts, unsigned int limit);
int criu_local_add_irmap_path(criu_opts *opts, const char *path);
int criu_local_add_cg_props(criu_opts *opts, const char *stream);
int criu_local_add_cg_props_file(criu_opts *opts, const char *path);
int criu_local_add_cg_dump_controller(criu_opts *opts, const char *name);
int criu_local_add_cg_yard(criu_opts *opts, const char *path);
int criu_local_add_inherit_fd(criu_opts *opts, int fd, const char *key);
int criu_local_add_external(criu_opts *opts, const char *key);
int criu_local_set_page_server_address_port(criu_opts *opts, const char *address, int port);
int criu_local_set_pre_dump_mode(criu_opts *opts, enum criu_pre_dump_mode mode);
void criu_local_set_notify_cb(criu_opts *opts, int (*cb)(char *action, criu_notify_arg_t na));
int criu_local_check(criu_opts *opts);
int criu_local_dump(criu_opts *opts);
int criu_local_restore(criu_opts *opts);
int criu_local_restore_child(criu_opts *opts);
int criu_local_dump_iters(criu_opts *opts, int (*more)(criu_predump_info pi));
int criu_local_get_version(criu_opts *opts);
int criu_local_check_version(criu_opts *opts, int minimum);
#ifdef __GNUG__
}
#endif
#endif /* __CRIU_LIB_H__ */

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,387 @@
/*************************************************************************
> File Name: migrate.cpp
> Author: TianLun Song
> Mail: songtianlun@frytea.com
> Blog: https://blog.frytea.com
> Created Time: Wed 23 Dec 2020 07:10:09 PM CST
************************************************************************/
#include<iostream>
#include<algorithm> /* sort() */
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
class CMigrateApp
{
#define CRIU_BINARY "/usr/sbin/criu"
#define CRIU_DIR "/tmp/criu"
#define IMG_DIR "images"
#define DUMP_LOG_FILE "dump.log"
#define RESTORE_LOG_FILE "restore.log"
#define RESTORE_PID_FILE "restore.pid"
#define INHERIT_FD_OPTION "--inherit-fd"
#define OLD_LOG_FILE "/tmp/criu/oldlog"
#define NEW_LOG_FILE "/tmp/criu/newlog"
public:
// CMigrateApp(int iPid = 0);
CMigrateApp(char *sCMD, int iPid = 0);
~CMigrateApp(){}
char *GetCMD();
char *GetImgDir();
int Checkout();
int Restore();
int GetPid();
int GetUnixNum();
private:
int GetPidByCMD(char * sCMD);
int SetPidByCMD(char * sCMD);
void GetCMDByPid(int iPid, char *sCMD);
int isUnixActivity(unsigned int iNode, char * cPid);
int SetUnixByPid(int iPid);
void Mkdir_safe(char *dirname, int mode);
private:
int i_criu_pid;
int i_unix_num;
char s_criu_cmd[64];
char s_criu_pid[8];
char s_criu_img[64];
char s_criu_dump_log[64];
char s_criu_restore_log[64];
char s_criu_restore_pidfile[64];
char s_external_sk_ino[1024];
char s_inh_unixsk_arg[1024];
const char *s_dump_argv[15] = {
"criu", "dump", "-j",
"-D", s_criu_img, "-o", s_criu_dump_log,
"-v4", "-x", "--lib /root/stl/lib",
"--tcp-established",
s_external_sk_ino,
"-t", s_criu_pid,
NULL };
const char *s_restore_argv[18] = {
"criu", "restore", "-d","-j",
"-D", s_criu_img, "-o", s_criu_restore_log,
"--pidfile", s_criu_restore_pidfile,
"-v4", "-x", "--lib /root/stl/lib",
"--tcp-established",
s_inh_unixsk_arg,
NULL };
};
CMigrateApp::CMigrateApp(char* sCMD, int iPid)
{
char sMkdir[64] = {0};
// init data
memset(s_criu_img, 0x00, sizeof s_criu_img);
memset(s_criu_dump_log, 0x00, sizeof s_criu_dump_log);
memset(s_criu_restore_log, 0x00, sizeof s_criu_restore_log);
memset(s_criu_restore_pidfile, 0x00, sizeof s_criu_restore_pidfile);
memset(s_criu_cmd, 0x00, sizeof s_criu_cmd);
i_criu_pid = 0;
i_unix_num = 0;
memset(s_criu_pid, 0x00, sizeof s_criu_pid);
memset(s_external_sk_ino, 0x00, sizeof s_external_sk_ino);
memset(s_inh_unixsk_arg, 0x00, sizeof s_inh_unixsk_arg);
if( 0 != iPid )
{
GetCMDByPid(iPid, s_criu_cmd);
i_criu_pid = iPid;
snprintf(s_criu_pid, sizeof s_criu_pid, "%d", i_criu_pid);
}
else if( NULL != sCMD )
{
strcpy(s_criu_cmd, sCMD);
SetPidByCMD(s_criu_cmd);
}
else
{
printf("Error of [iPid: %d] or [sCMD: %s] ", iPid, sCMD);
}
snprintf(s_criu_img, sizeof s_criu_img, "%s/%s/%s", CRIU_DIR, s_criu_cmd, IMG_DIR);
snprintf(s_criu_dump_log, sizeof s_criu_dump_log, "%s/%s/%s", CRIU_DIR, s_criu_cmd, DUMP_LOG_FILE);
snprintf(s_criu_restore_log, sizeof s_criu_restore_log, "%s/%s/%s", CRIU_DIR, s_criu_cmd, RESTORE_LOG_FILE);
snprintf(s_criu_restore_pidfile, sizeof s_criu_restore_pidfile, "%s/%s/%s", CRIU_DIR, s_criu_cmd, RESTORE_PID_FILE);
i_unix_num = SetUnixByPid(i_criu_pid);
// printf("PCMD: %s, Unix Sum: %d\n",sCMD, i_unix_num);
sprintf(sMkdir,"mkdir -p %s &", s_criu_img);
system(sMkdir);
printf("App will be to Migrate: [iPid: %d] [CMD: %s] [Unix Num: %d]\n", i_criu_pid, s_criu_cmd, i_unix_num);
}
int CMigrateApp::Checkout()
{
char sCmd[2048] = {0};
char sCpCMd[64] = {0};
if(0 >= i_criu_pid)
{
printf("Error Pid! Dump failed!\n");
return -1;
}
for (int i = 0; s_dump_argv[i] != NULL; i++)
sprintf(sCmd, "%s %s", sCmd, s_dump_argv[i]);
strcat(sCmd,"&");
printf("Dump [CMD:%s] [PID:%d] [Unix Num:%d] cmd: %s\n",s_criu_cmd,i_criu_pid, i_unix_num, sCmd);
system(sCmd);
snprintf(sCpCMd, sizeof sCpCMd, "cp /tmp/1 /tmp/criu/%s/", s_criu_cmd);
system(sCpCMd);
return 0;
}
int CMigrateApp::Restore()
{
char sCmd[2048] = {0};
char sCpCmd[64] = {0};
if(0 >= i_criu_pid)
{
printf("Error Pid! Restore neet to right dump!\n");
return -1;
}
for (int i = 0; s_restore_argv[i] != NULL; i++)
sprintf(sCmd, "%s %s", sCmd, s_restore_argv[i]);
strcat(sCmd,"&");
/* 进程有几个socket就创建几次 */
for (int i = 0; i < i_unix_num; i++)
socket(AF_UNIX, SOCK_STREAM, 0);
/* 将该进程转储时的/tmp/1 复制到指定路径下 */
snprintf(sCpCmd, sizeof sCpCmd, "cp /tmp/criu/%s/1 /tmp/1", s_criu_cmd);
system(sCpCmd);
system("chmod 644 /tmp/1");
/* 恢复 */
printf("Restore [CMD:%s] [Unix Num:%d] cmd: %s\n",s_criu_cmd, i_unix_num, sCmd);
system(sCmd);
return 0;
}
int CMigrateApp::GetPidByCMD(char *sCMD)
{
char cPid[62] = {0};
char sSeekCmd[64] = {0};
FILE *fPid = NULL;
int iPid = -1;
sprintf(sSeekCmd, "pgrep %s | head -1",sCMD);
fPid = popen(sSeekCmd, "r");
if(NULL == fPid)
return -1;
fgets(cPid, sizeof(cPid), fPid);
iPid = atoi(cPid);
// printf("SeekCmd: %s, Pid: %d, cPid: %s\n",sSeekCmd,iPid,cPid);
return iPid;
}
void CMigrateApp::GetCMDByPid(int iPid, char *sCMD)
{
FILE *fcmd = NULL;
char sGetCMD[64] = {0};
snprintf(sGetCMD, sizeof sGetCMD, "grep 'Name' /proc/%d/status | awk '{print $2}'", iPid);
fcmd = popen(sGetCMD, "r");
fgets(sCMD, sizeof(sCMD), fcmd);
}
int CMigrateApp::SetPidByCMD(char *sCMD)
{
char cPid[62] = {0};
char sSeekCmd[64] = {0};
FILE *fPid = NULL;
int iPid = -1;
sprintf(sSeekCmd, "pgrep %s | head -1", sCMD);
fPid = popen(sSeekCmd, "r");
if(NULL == fPid)
return -1;
fgets(cPid, sizeof(cPid), fPid);
iPid = atoi(cPid);
i_criu_pid = atoi(cPid);
snprintf(s_criu_pid, sizeof s_criu_pid, "%d", iPid);
// strcpy(s_criu_pid, cPid);
pclose(fPid);
//printf("SeekCmd: %s, Pid: %d, cPid: %s\n",sSeekCmd,iPid,cPid);
return iPid;
}
int CMigrateApp::SetUnixByPid(int iPid)
{
char sUnixStatCmd[64] = {0};
char sNowCriuUnixCmd[64] = {0};
char sNosRestoreUnixCmd[64] = {0};
FILE *fpUnixStat;
int iFdNum = 3;
char tmp[2048]; //存储每一行输出
unsigned int iNode;
int iSumUnix = 0;
// int i = 0;
if( iPid <=0 )
return 0;
sprintf(sUnixStatCmd, "cat /proc/%d/net/unix | awk '{print $7}'", iPid);
fpUnixStat = popen(sUnixStatCmd, "r");
if (fpUnixStat == NULL) {
return -1;
}
// 跳过第一条无效数据
fgets(tmp, sizeof(tmp) - 1, fpUnixStat);
// i = 0;
// 输出检查状态
// printf("check unix ..");
// fflush(stdout);
while (fgets(tmp, sizeof(tmp) - 1, fpUnixStat)) {
// 输出检查状态
// switch(i++){
// case 1:
// printf(".");
// fflush(stdout);
// break;
// case 5:
// printf("\b");
// fflush(stdout);
// break;
// case 10:
// i=0;
// default:
// break;
// };
sscanf(tmp, "%u", &iNode);
if(!isUnixActivity(iNode,s_criu_cmd))
continue;
if(iNode==0)
continue;
// printf("iPid: %d, Unix iNode: %d, is activity.\n", iPid,iNode);
snprintf(sNowCriuUnixCmd, sizeof(sNowCriuUnixCmd), "--ext-unix-sk=%u ",
(unsigned int)iNode);
snprintf(sNowCriuUnixCmd, sizeof(sNowCriuUnixCmd), "--external unix[%u] ",
(unsigned int)iNode);
snprintf(sNosRestoreUnixCmd, sizeof sNosRestoreUnixCmd, "--inherit-fd fd[%d]:socket:[%u] ",
iFdNum++,(unsigned int)iNode);
strcat(s_external_sk_ino, sNowCriuUnixCmd);
strcat(s_inh_unixsk_arg, sNosRestoreUnixCmd);
iSumUnix++;
}
// printf("\r"); // 清空 check unix 状态字符打印
pclose(fpUnixStat);
return iSumUnix;
}
int CMigrateApp::isUnixActivity(unsigned int iNode, char * cPid)
{
char sCheckUnixCmd[64] = {0};
FILE *fpCheckUnix;
char tmp[2048];
// 检查当前 unix socket 是否处于活跃状态
sprintf(sCheckUnixCmd, "netstat -xap | grep %s | grep %u", cPid, iNode);
fpCheckUnix = popen(sCheckUnixCmd, "r");
if (fpCheckUnix == NULL) {
return -1;
}
memset(tmp, 0x0, sizeof(tmp));
fgets(tmp, sizeof(tmp) - 1, fpCheckUnix);
pclose(fpCheckUnix);
printf("Check Cmd: %s, Rst len: %d", sCheckUnixCmd, (int)strlen(tmp));
fflush(stdout);
printf("%40s\r"," "); // 使用空格清理脏字符并回退光标至行首
fflush(stdout);
if(strlen(tmp)>1)
return 1;
return 0;
}
int CMigrateApp::GetPid()
{
return i_criu_pid;
}
int CMigrateApp::GetUnixNum()
{
return i_unix_num;
}
char *CMigrateApp::GetCMD()
{
return s_criu_cmd;
}
char *CMigrateApp::GetImgDir()
{
return s_criu_img;
}
void CMigrateApp::Mkdir_safe(char *dirname, int mode)
{
if (mkdir(dirname, mode) == -1 && errno != EEXIST)
printf("Success to mkdir dirname=%s mode=0x%x\n", dirname, mode);
else
printf("Fail to make dir %s", dirname);
}
// 自定义对象比较函数根据unix个数排序
bool cmp(CMigrateApp a, CMigrateApp b)
{
return a.GetUnixNum() < b.GetUnixNum();
}
void MigrateMySelf()
{
char sRestoreCmd[128] = {0};
CMigrateApp CMigrateMySelf(NULL, getpid());
snprintf(sRestoreCmd, sizeof sRestoreCmd, "criu restore -D %s -j", CMigrateMySelf.GetImgDir());
printf("Run cmd when restore: %s\n", sRestoreCmd);
CMigrateMySelf.Checkout();
}
int main()
{
char piggie_cmd[21][64] = {
/* create ipc unix socket */
"arpd", "dhcp", "lldpd", "ospfd", "ripd", "snmptrap", "rmon", "ripngd", "mstp", "lag","master","zebra","pidmonitor",
"ntpclient", "snmpd", "udpsvd", "brctl", "l2monitor", "vtysh", "configmanage", "udhcpd"};
std::vector <CMigrateApp> vMigrateApps;
// 清空进程检查点数据文件夹,避免遗留文件影响进程恢复
system("rm -rf /tmp/criu/*");
for(int i = 0; i < 21; i++)
{
CMigrateApp iC(piggie_cmd[i]);
vMigrateApps.push_back(iC);
// printf("%s [PID %d] will be push back, vector size: %d\n", iC.GetCMD(),iC.GetPid(), (int)vMigrateApps.size());
}
printf("-----------------------after sort-----------------------\n");
for(auto v : vMigrateApps)
{
printf("[%s:%d] has %d unix socket\n", v.GetCMD(), v.GetPid(), v.GetUnixNum());
}
// sort(vMigrateApps.begin(), vMigrateApps.end(),cmp);
printf("-------------------------- dump -------------------------\n");
for(auto v : vMigrateApps)
{
v.Checkout();
}
for(int j=10;j>0;j--)
{
printf("Waiting for start restore....%d\n",j);
if(j==5)
MigrateMySelf();
sleep(1);
}
printf("Enter any character to continue\n");
getchar();
printf("------------------------ restore ------------------------\n");
for(auto v : vMigrateApps)
{
if(v.GetPid()<=0)
{
printf("failed to dump, jump %s.\n", v.GetCMD());
continue;
}
v.Restore();
}
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,149 @@
/*************************************************************************
> File Name: migrate.cpp
> Author: TianLun Song
> Mail: songtianlun@frytea.com
> Blog: https://blog.frytea.com
> Created Time: Wed 23 Dec 2020 07:10:09 PM CST
************************************************************************/
#include <criu/criu.h>
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class CMigrateApp
{
public:
CMigrateApp(int iPid = 0);
CMigrateApp(char *sPid);
~CMigrateApp();
int Checkout();
int Restore();
int GetPid();
private:
int GetPidByCMD(char * sCMD);
private:
char criu_dir[64];
char criu_server[64];
char criu_log[64];
char criu_cmd[64];
int criu_log_level;
int criu_pid;
};
CMigrateApp::CMigrateApp(int iPid)
{
strcpy(criu_dir, "./migrate_imgs");
strcpy(criu_server, "/root/criu_service.socket");
strcpy(criu_log, "criu.log");
criu_log_level = 4;
criu_pid = iPid;
criu_init_opts();
criu_set_service_address(criu_server);
int fd = open(criu_dir, O_DIRECTORY);
criu_set_images_dir_fd(fd);
criu_set_log_file(criu_log);
criu_set_log_level(criu_log_level);
criu_set_shell_job(true);
}
CMigrateApp::CMigrateApp(char* sPid)
{
char sMkdir[64] = {0};
strcpy(criu_dir, "/root/migrate_imgs/");
strcpy(criu_server, "/root/criu_service.socket");
strcpy(criu_log, "criu.log");
criu_log_level = 4;
strcpy(criu_cmd, sPid);
strcat(criu_dir, sPid);
sprintf(sMkdir,"%s %s", "mkdir -p", criu_dir);
system(sMkdir);
criu_pid = GetPidByCMD(criu_cmd);
//cout << "Pid: " << criu_pid << endl;
criu_init_opts();
criu_set_service_address(criu_server);
int fd = open(criu_dir, O_DIRECTORY);
criu_set_images_dir_fd(fd);
criu_set_log_file(criu_log);
criu_set_log_level(criu_log_level);
criu_set_shell_job(true);
criu_set_ext_unix_sk(true);
}
int CMigrateApp::Checkout()
{
if(0 >= criu_pid)
{
//cout << "Error Pid! Dump failed!" << endl;
return -1;
}
criu_set_pid(criu_pid);
return criu_dump();
}
int CMigrateApp::Restore()
{
return criu_restore();
}
int CMigrateApp::GetPidByCMD(char *sCMD)
{
char cPid[62] = {0};
char sSeekCmd[64] = {0};
FILE *fPid = NULL;
int iPid = -1;
sprintf(sSeekCmd, "%s %s %s", "pgrep", sCMD, "| head -1");
fPid = popen(sSeekCmd, "r");
if(NULL == fPid)
return -1;
fgets(cPid, sizeof(cPid), fPid);
iPid = atoi(cPid);
//cout << "SeekCmd: " << sSeekCmd << ", Pid: " << iPid << ", cPid: " << cPid << endl;
return iPid;
}
int CMigrateApp::GetPid()
{
return criu_pid;
}
int main()
{
char piggie_cmd[21][64] = {
"arpd","dhcp","lldpd","ntpclient","ripd","snmpd","udpsvd",
"brctl","l2monitor","master ","ospfd","ripngd","snmptrap","vtysh",
"configmanage","lag","mstp","pidmonitor","rmon","udhcpd","zebra"};
CMigrateApp * migrate_app[21];
for(int i = 0; i < 21; i++)
{
migrate_app[i] = new CMigrateApp(piggie_cmd[i]);
// int iRet = 0;
cout << "Dump " << piggie_cmd[i] << "[ID:" << migrate_app[i]->GetPid() << "]" << " Result: " << migrate_app[i]->Checkout() << endl;
//sleep(1);
//cout << "Restore " << piggie_cmd[i] << " Result: " << migrate_app[i]->Restore() << endl;
//sleep(5);
}
return 0;
}

BIN
study_clang/Mimic/compress/main Executable file

Binary file not shown.

View File

@ -0,0 +1,141 @@
/*************************************************************************
> File Name : main.c
> Author : FengChao
> EMail : smile.fengchao@gmail.com
> Created Time : Fri 03 Jul 2020 08:38:34 AM CST
************************************************************************/
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <zlib.h>
#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);\
}
int data_compress(char *idata, int ilen, char *odata, int *olen)
{
z_stream z = {0};
z.next_in = idata;
z.avail_in = ilen;
z.next_out = odata;
z.avail_out = *olen;
/* 使用最高压缩比 */
if (deflateInit(&z, Z_BEST_COMPRESSION) != Z_OK) {
printf("deflateInit failed!\n");
return -1;
}
if (deflate(&z, Z_NO_FLUSH) != Z_OK) {
printf("deflate Z_NO_FLUSH failed!\n");
return -1;
}
if (deflate(&z, Z_FINISH) != Z_STREAM_END) {
printf("deflate Z_FINISH failed!\n");
return -1;
}
if (deflateEnd(&z) != Z_OK) {
printf("deflateEnd failed!\n");
return -1;
}
*olen = *olen - z.avail_out;
return 0;
}
int data_decompress(char *idata, int ilen, char *odata, int *olen)
{
z_stream z = {0};
z.next_in = idata;
z.avail_in = ilen;
z.next_out = odata;
z.avail_out = *olen;
if (inflateInit(&z) != Z_OK) {
printf("inflateInit failed!\n");
return -1;
}
if (inflate(&z, Z_NO_FLUSH) != Z_STREAM_END) {
printf("inflate Z_NO_FLUSH failed!\n");
return -1;
}
if (inflate(&z, Z_FINISH) != Z_STREAM_END) {
printf("inflate Z_FINISH failed!\n");
return -1;
}
if (inflateEnd(&z) != Z_OK) {
printf("inflateEnd failed!\n");
return -1;
}
*olen = *olen - z.avail_out;
return 0;
}
//char data[] = "\nYouth\n\nYouth is not a time of life; it is a state of mind; it is not a matter of rosy cheeks, red lips and supple knees; it is a matter of the will, a quality of the imagination, a vigor of the emotions; it is the freshness of the deep springs of life.\n\nYouth means a temperamental predominance of courage over timidity, of the appetite for adventure over the love of ease. This often exists in a man of 60 more than a boy of 20. Nobody grows old merely by a number of years. We grow old by deserting our ideals.\n\nYears may wrinkle the skin, but to give up enthusiasm wrinkles the soul. Worry, fear, self-distrust bows the heart and turns the spirit back to dust.\n\nWhether 60 or 16, there is in every human beings heart the lure of wonders, the unfailing appetite for whats next and the joy of the game of living. In the center of your heart and my heart, there is a wireless station; so long as it receives messages of beauty, hope, courage and power from man and from the infinite, so long as you are young.\n\nWhen your aerials are down, and your spirit is covered with snows of cynicism and the ice of pessimism, then youve grown old, even at 20; but as long as your aerials are up, to catch waves of optimism, theres hope you may die young at 80.";
char data[] = "aaaaaaaabbbbbbbbbbbbbbccccccccccccccc";
int main(int argc, char **argv)
{
int compress_len, decompress_len;
// unsigned char data[1024] = {0};
unsigned char compress_buf[2048] = {0};
unsigned char decompress_buf[4096] = {0};
// memset(data, 0x00, sizeof(data));
memset(compress_buf, 0x00, sizeof(compress_buf));
memset(decompress_buf, 0x00, sizeof(decompress_buf));
// data[0] = 0x01;
// data[777] = 0x02;
dPrint("... origin data ...");
HexPrint(data, sizeof(data));
/* 压缩数据 */
compress_len = sizeof(compress_buf);
if (data_compress(data, sizeof(data),
compress_buf, &compress_len) < 0) {
return -1;
}
dPrint("... compress data ...");
HexPrint(compress_buf, compress_len);
/* 解压缩数据 */
decompress_len = sizeof(decompress_buf);
if (data_decompress(compress_buf, compress_len,
decompress_buf, &decompress_len) < 0) {
return -1;
}
dPrint("... decompress data ...");
HexPrint(decompress_buf, decompress_len);
return 0;
}

View File

@ -0,0 +1,13 @@
/*************************************************************************
> File Name: migrate.cpp
> Author: TianLun Song
> Mail: songtianlun@frytea.com
> Blog: https://blog.frytea.com
> Created Time: Wed 23 Dec 2020 07:10:09 PM CST
************************************************************************/
#include "migrate.h"
CMigrateApp::CMigrateApp()
{
}

View File

@ -0,0 +1,17 @@
/*************************************************************************
> File Name: migrate.h
> Author: TianLun Song
> Mail: songtianlun@frytea.com
> Blog: https://blog.frytea.com
> Created Time: Wed 23 Dec 2020 07:10:09 PM CST
************************************************************************/
#include<iostream>
using namespace std;
class CMigrateApp
{
public:
CMigrateApp();
~CMigrateApp();
};

View File

@ -0,0 +1,19 @@
#!/bin/python
# Author: Tianlun Song
# Blog: https://blog.frytea.com
# Time:2020-12-23 18:48:06
# Name:migrate.py
# Version:V1.0
# Description:This is a production script.
import os
list_apps = [ \
"piggie", \
"while"]
dict_apps = {}
i = 0;

View File

@ -0,0 +1,11 @@
/*************************************************************************
> File Name: CJudgeSysInfo.cpp
> Author: SongTL
> Mail: songtianlun@comleader.com.cn
> Created Time: 20200721 114151
************************************************************************/
#include ""CJudgeSysInfo.h"
using namespace std;

View File

@ -0,0 +1,43 @@
/*************************************************************************
> File Name: CJudgeSysInfo.h
> Author: SongTL
> Mail: songtianlun@comleader.com.cn
> Created Time: 20200721 114409
************************************************************************/
#include<iostream>
using namespace std;
struct Msg
{
uint uiType;
uint uiCpuRate;
uint uiMemRate;
uint uiTcpEstablishNum;
uint uiRunningProcessNum;
uint uiCronNum;
char szPasswdMd5[16];
};
struct stProcessState
{
uint uiType;
uint uiProcessId;
uint uiProcessState;
};
struct stFileNum
{
uint uiType;
uint szPath[32];
uint uiFileNum;
};
struct stLogMsg
{
uint uiType;
char szLogFile[32];
char szMsg[128];
};
class

View File

@ -0,0 +1,13 @@
/*************************************************************************
> File Name: CMessageQueue.cpp
> Author: SongTL
> Mail: songtianlun@comleader.com.cn
> Created Time: 20200721 163821
************************************************************************/
#include<iostream>
using namespace std;

View File

@ -0,0 +1,28 @@
/*************************************************************************
> File Name: CMessageQueue.h
> Author: SongTL
> Mail: songtianlun@comleader.com.cn
> Created Time: 20200721 164637
************************************************************************/
#ifndef CMESSAGEQUEUE_H
#define CMESSAGEQUEUE_H
template<class Type>
class ConcurrentQueue
{
ConcurrentQueue& operator = (const ConcurrentQueue&) = delete;
ConcurrentQueue(const ConcurrentQueue& other) = delete;
public:
ConcurrentQueue() : _queue(), _mutex(), _condition() {}
virtual ~ConcurrentQueue() {}
void Push(Type record)
{
std::lock_guard <std::mutex> lock(_mutex);
_queue.push(record);
_condition.notify_one();
}
}
#endif

Binary file not shown.

View File

@ -0,0 +1,84 @@
/*************************************************************************
> File Name: message_queue.cpp
> Author: SongTL
> Mail: songtianlun@comleader.com.cn
> Created Time: 20200721 161921
************************************************************************/
# ifndef MSGQUEUE_H
# define MSGQUEUE_H
#include <iostream>
#include <cstdlib>
#include <unistd.h> // usleep
#include <fcntl.h> // threads
#include <pthread.h>
#include <string> // messages
#include <queue> // the message queue
using namespace std;
pthread_mutex_t msgmutex = PTHREAD_MUTEX_INITIALIZER;
queue <string> msgq;
void *msgreceiver(void *arg)
{
long qsize;
string nextmsg;
while (true)
{
if (msgq.empty())
{
usleep(10000); // sleep 0.01 sec before trying again
continue;
}
// we end up here because there was something in the msg queue
pthread_mutex_lock( & msgmutex);
qsize = msgq.size();
if (qsize > 5)
cout << "Queue size: " << qsize << endl;
nextmsg = msgq.front(); // get next message in queue
msgq.pop(); // remove it from the queue
pthread_mutex_unlock( & msgmutex);
cout << "Processing value " << nextmsg << endl;
usleep(2000000);
}
pthread_exit((void * )0);
} // msgreceiver()
void *msgtransmitter(void *arg)
{
string nextmsg;
while (true)
{
cin >> nextmsg;
pthread_mutex_lock( & msgmutex);
msgq.push(nextmsg); // push message onto the queue
pthread_mutex_unlock( & msgmutex);
}
pthread_exit((void * )0);
} // msgtransmitter()
int main()
{
pthread_t thr;
// Create threads
if (pthread_create( & thr, NULL, msgreceiver, NULL) ||
pthread_create( & thr, NULL, msgtransmitter, NULL))
{
cout << " cannot make thread\n";
exit(1);
}
/*
* At this point the main thread can perform its actions or end
*/
cout << "** Main thread ends **\n";
pthread_exit((void * )0);
}
# endif // MSGQUEUE_H

View File

@ -0,0 +1,16 @@
; Config file for monitor.cpp
[common]
[key_resources]
cron_sum = ;
cron_dir = ;
[key_files]
path_sum = ;
path_dir = ;
executable_sum = ;
executable_dir = ;
user_dir_sum = ;
user_dir_dir = ;
boot_sum = ;
boot_dir = ;

View File

@ -0,0 +1,5 @@
CC=g++
monirot:monitor.cpp
$(CC) -o monitor monitor.cpp -lpthread
clean:
rm -f *.o

View File

@ -0,0 +1,63 @@
<!--
* @Author: songtl
* @Date: 2020-07-20 09:48:30
* @LastEditors: songtl
* @LastEditTime: 2020-07-20 11:52:36
* @Description: 获取系统运行状态数据,简单处理后送出。
-->
# Monitor System Status
## 详述
监控模块共包含四个进程:
- 关键进程运行状态监控
- 关键系统资源
- 关键路径文件
- 敏感日志信息
关键进程包括:
- 管理进程
- 协议进程
- 本地配置管理器
- 防火墙
关键系统资源包括:
- ~~CPU利用率~~
- ~~内存利用率~~
- ~~TCP Socket 连接数~~
- ~~运行进程数~~
- ~~当前用户及用户组信息(静)~~
- ~~计划任务个数(静)~~
关键路径文件包括:
- PATH下二进制文件
- 关键可执行文件校验值(静)
- 用户目录下文件数目(静)
- 开机启动文件(静)
敏感日志信息包括:
- 开机登录日志
- 历史命令信息
> (静)表示监控信息为静态,只需将该值与预设值做比较;此外的信息均为动态信息,采用阈值比对、执行体间横向比对和执行体历史信息纵向比对等方法。
## 开发日志
- 2020年07月20日
- 实现获取用户组信息
- 实现计划任务获取
- 实现格式化获取当前时间
- 2020年07月18日
- 实现获取运行进程数
- 实现用户信息读取及分词
- 2020年07月17日
- 实现内存利用率计算
- 实现获取TCP Socket 连接数
- 2020年07月16日
- 实现CPU利用率计算
- 2020年07月15日
- 完成主体框架
- 定义部分结构体和函数

View File

@ -0,0 +1,462 @@
// Read an INI file into easy-to-access name/value pairs.
// inih and INIReader are released under the New BSD license (see LICENSE.txt).
// Go to the project home page for more info:
//
// https://github.com/benhoyt/inih
/* inih -- simple .INI file parser
inih is released under the New BSD license (see LICENSE.txt). Go to the project
home page for more info:
https://github.com/benhoyt/inih
*/
#ifndef __INI_H__
#define __INI_H__
/* Make this header file easier to include in C++ code */
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
/* Typedef for prototype of handler function. */
typedef int (*ini_handler)(void* user, const char* section,
const char* name, const char* value);
/* Typedef for prototype of fgets-style reader function. */
typedef char* (*ini_reader)(char* str, int num, void* stream);
/* Parse given INI-style file. May have [section]s, name=value pairs
(whitespace stripped), and comments starting with ';' (semicolon). Section
is "" if name=value pair parsed before any section heading. name:value
pairs are also supported as a concession to Python's configparser.
For each name=value pair parsed, call handler function with given user
pointer as well as section, name, and value (data only valid for duration
of handler call). Handler should return nonzero on success, zero on error.
Returns 0 on success, line number of first error on parse error (doesn't
stop on first error), -1 on file open error, or -2 on memory allocation
error (only when INI_USE_STACK is zero).
*/
int ini_parse(const char* filename, ini_handler handler, void* user);
/* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't
close the file when it's finished -- the caller must do that. */
int ini_parse_file(FILE* file, ini_handler handler, void* user);
/* Same as ini_parse(), but takes an ini_reader function pointer instead of
filename. Used for implementing custom or string-based I/O. */
int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,
void* user);
/* Nonzero to allow multi-line value parsing, in the style of Python's
configparser. If allowed, ini_parse() will call the handler with the same
name for each subsequent line parsed. */
#ifndef INI_ALLOW_MULTILINE
#define INI_ALLOW_MULTILINE 1
#endif
/* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of
the file. See http://code.google.com/p/inih/issues/detail?id=21 */
#ifndef INI_ALLOW_BOM
#define INI_ALLOW_BOM 1
#endif
/* Nonzero to allow inline comments (with valid inline comment characters
specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match
Python 3.2+ configparser behaviour. */
#ifndef INI_ALLOW_INLINE_COMMENTS
#define INI_ALLOW_INLINE_COMMENTS 1
#endif
#ifndef INI_INLINE_COMMENT_PREFIXES
#define INI_INLINE_COMMENT_PREFIXES ";"
#endif
/* Nonzero to use stack, zero to use heap (malloc/free). */
#ifndef INI_USE_STACK
#define INI_USE_STACK 1
#endif
/* Stop parsing on first error (default is to keep parsing). */
#ifndef INI_STOP_ON_FIRST_ERROR
#define INI_STOP_ON_FIRST_ERROR 0
#endif
/* Maximum line length for any line in INI file. */
#ifndef INI_MAX_LINE
#define INI_MAX_LINE 200
#endif
#ifdef __cplusplus
}
#endif
/* inih -- simple .INI file parser
inih is released under the New BSD license (see LICENSE.txt). Go to the project
home page for more info:
https://github.com/benhoyt/inih
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#if !INI_USE_STACK
#include <stdlib.h>
#endif
#define MAX_SECTION 50
#define MAX_NAME 50
/* Strip whitespace chars off end of given string, in place. Return s. */
inline static char* rstrip(char* s)
{
char* p = s + strlen(s);
while (p > s && isspace((unsigned char)(*--p)))
*p = '\0';
return s;
}
/* Return pointer to first non-whitespace char in given string. */
inline static char* lskip(const char* s)
{
while (*s && isspace((unsigned char)(*s)))
s++;
return (char*)s;
}
/* Return pointer to first char (of chars) or inline comment in given string,
or pointer to null at end of string if neither found. Inline comment must
be prefixed by a whitespace character to register as a comment. */
inline static char* find_chars_or_comment(const char* s, const char* chars)
{
#if INI_ALLOW_INLINE_COMMENTS
int was_space = 0;
while (*s && (!chars || !strchr(chars, *s)) &&
!(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) {
was_space = isspace((unsigned char)(*s));
s++;
}
#else
while (*s && (!chars || !strchr(chars, *s))) {
s++;
}
#endif
return (char*)s;
}
/* Version of strncpy that ensures dest (size bytes) is null-terminated. */
inline static char* strncpy0(char* dest, const char* src, size_t size)
{
strncpy(dest, src, size);
dest[size - 1] = '\0';
return dest;
}
/* See documentation in header file. */
inline int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,
void* user)
{
/* Uses a fair bit of stack (use heap instead if you need to) */
#if INI_USE_STACK
char line[INI_MAX_LINE];
#else
char* line;
#endif
char section[MAX_SECTION] = "";
char prev_name[MAX_NAME] = "";
char* start;
char* end;
char* name;
char* value;
int lineno = 0;
int error = 0;
#if !INI_USE_STACK
line = (char*)malloc(INI_MAX_LINE);
if (!line) {
return -2;
}
#endif
/* Scan through stream line by line */
while (reader(line, INI_MAX_LINE, stream) != NULL) {
lineno++;
start = line;
#if INI_ALLOW_BOM
if (lineno == 1 && (unsigned char)start[0] == 0xEF &&
(unsigned char)start[1] == 0xBB &&
(unsigned char)start[2] == 0xBF) {
start += 3;
}
#endif
start = lskip(rstrip(start));
if (*start == ';' || *start == '#') {
/* Per Python configparser, allow both ; and # comments at the
start of a line */
}
#if INI_ALLOW_MULTILINE
else if (*prev_name && *start && start > line) {
#if INI_ALLOW_INLINE_COMMENTS
end = find_chars_or_comment(start, NULL);
if (*end)
*end = '\0';
rstrip(start);
#endif
/* Non-blank line with leading whitespace, treat as continuation
of previous name's value (as per Python configparser). */
if (!handler(user, section, prev_name, start) && !error)
error = lineno;
}
#endif
else if (*start == '[') {
/* A "[section]" line */
end = find_chars_or_comment(start + 1, "]");
if (*end == ']') {
*end = '\0';
strncpy0(section, start + 1, sizeof(section));
*prev_name = '\0';
}
else if (!error) {
/* No ']' found on section line */
error = lineno;
}
}
else if (*start) {
/* Not a comment, must be a name[=:]value pair */
end = find_chars_or_comment(start, "=:");
if (*end == '=' || *end == ':') {
*end = '\0';
name = rstrip(start);
value = lskip(end + 1);
#if INI_ALLOW_INLINE_COMMENTS
end = find_chars_or_comment(value, NULL);
if (*end)
*end = '\0';
#endif
rstrip(value);
/* Valid name[=:]value pair found, call handler */
strncpy0(prev_name, name, sizeof(prev_name));
if (!handler(user, section, name, value) && !error)
error = lineno;
}
else if (!error) {
/* No '=' or ':' found on name[=:]value line */
error = lineno;
}
}
#if INI_STOP_ON_FIRST_ERROR
if (error)
break;
#endif
}
#if !INI_USE_STACK
free(line);
#endif
return error;
}
/* See documentation in header file. */
inline int ini_parse_file(FILE* file, ini_handler handler, void* user)
{
return ini_parse_stream((ini_reader)fgets, file, handler, user);
}
/* See documentation in header file. */
inline int ini_parse(const char* filename, ini_handler handler, void* user)
{
FILE* file;
int error;
file = fopen(filename, "r");
if (!file)
return -1;
error = ini_parse_file(file, handler, user);
fclose(file);
return error;
}
#endif /* __INI_H__ */
#ifndef __INIREADER_H__
#define __INIREADER_H__
#include <map>
#include <set>
#include <string>
// Read an INI file into easy-to-access name/value pairs. (Note that I've gone
// for simplicity here rather than speed, but it should be pretty decent.)
class INIReader
{
public:
// Empty Constructor
INIReader() {};
// Construct INIReader and parse given filename. See ini.h for more info
// about the parsing.
INIReader(std::string filename);
// Construct INIReader and parse given file. See ini.h for more info
// about the parsing.
INIReader(FILE *file);
// Return the result of ini_parse(), i.e., 0 on success, line number of
// first error on parse error, or -1 on file open error.
int ParseError() const;
// Return the list of sections found in ini file
const std::set<std::string>& Sections() const;
// Get a string value from INI file, returning default_value if not found.
std::string Get(std::string section, std::string name,
std::string default_value) const;
// 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").
long GetInteger(std::string section, std::string name, long default_value) const;
// 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(std::string section, std::string name, double default_value) const;
// Get a single precision floating point number value from INI file, returning
// default_value if not found or not a valid floating point value
// according to strtof().
float GetFloat(std::string section, std::string name, float default_value) const;
// 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(std::string section, std::string name, bool default_value) const;
protected:
int _error;
std::map<std::string, std::string> _values;
std::set<std::string> _sections;
static std::string MakeKey(std::string section, std::string name);
static int ValueHandler(void* user, const char* section, const char* name,
const char* value);
};
#endif // __INIREADER_H__
#ifndef __INIREADER__
#define __INIREADER__
#include <algorithm>
#include <cctype>
#include <cstdlib>
inline INIReader::INIReader(std::string filename)
{
_error = ini_parse(filename.c_str(), ValueHandler, this);
}
inline INIReader::INIReader(FILE *file)
{
_error = ini_parse_file(file, ValueHandler, this);
}
inline int INIReader::ParseError() const
{
return _error;
}
inline const std::set<std::string>& INIReader::Sections() const
{
return _sections;
}
inline std::string INIReader::Get(std::string section, std::string name, std::string default_value) const
{
std::string key = MakeKey(section, name);
return _values.count(key) ? _values.at(key) : default_value;
}
inline long INIReader::GetInteger(std::string section, std::string name, long default_value) const
{
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
// This parses "1234" (decimal) and also "0x4D2" (hex)
long n = strtol(value, &end, 0);
return end > value ? n : default_value;
}
inline double INIReader::GetReal(std::string section, std::string name, double default_value) const
{
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
double n = strtod(value, &end);
return end > value ? n : default_value;
}
inline float INIReader::GetFloat(std::string section, std::string name, float default_value) const
{
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
float n = strtof(value, &end);
return end > value ? n : default_value;
}
inline bool INIReader::GetBoolean(std::string section, std::string name, bool default_value) const
{
std::string valstr = Get(section, name, "");
// Convert to lower case to make string comparisons case-insensitive
std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
return true;
else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
return false;
else
return default_value;
}
inline std::string INIReader::MakeKey(std::string section, std::string name)
{
std::string key = section + "=" + name;
// Convert to lower case to make section/name lookups case-insensitive
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
return key;
}
inline int INIReader::ValueHandler(void* user, const char* section, const char* name,
const char* value)
{
INIReader* reader = (INIReader*)user;
std::string key = MakeKey(section, name);
if (reader->_values[key].size() > 0)
reader->_values[key] += "\n";
reader->_values[key] += value;
reader->_sections.insert(section);
return 1;
}
#endif // __INIREADER__

Binary file not shown.

View File

@ -0,0 +1,377 @@
/* ===============================================================================================
*
* Filename: monitor.cpp
*
* Description: Monitor the operating status of the system and publish it.
*
* Version: 0.1
* Created: 20200715 1021
* Revision: none
* Compiler: gcc/g++
* Link: -lpthread
*
* Author: songtianlun, songtianlun@comleader.com.cn
* Organization: IEUCD
*
* ===============================================================================================*/
#include "monitor.h"
int main (void)
{
int key_process_ret, key_sys_value_ret, key_files_ret, key_log_ret;
pthread_t key_process_pth, key_sys_value_pth, key_files_pth, key_log_pth; //线程ID变量
init_config("Config.ini");
// 参数创建的线程ID线程参数调用函数函数参数
key_process_ret = pthread_create(&key_process_pth,NULL,monitor_key_process,NULL);
key_sys_value_ret = pthread_create(&key_sys_value_pth,NULL,monitor_key_sys_value,NULL);
key_files_ret = pthread_create(&key_files_pth,NULL,monitor_key_files,NULL);
key_log_ret = pthread_create(&key_log_pth,NULL,monitor_key_log,NULL);
pthread_join(key_process_pth, NULL); // 等待线程结束
pthread_join(key_sys_value_pth, NULL);
pthread_join(key_files_pth, NULL);
pthread_join(key_log_pth, NULL);
return 0;
}
void *monitor_key_process(void *args)
{
printf("Start the new thread to monitor key process.\n");
}
void *monitor_key_sys_value(void *args)
{
Cpu_info ocpu,ncpu;
Mem_info omem;
User_info users[50];
Group_info groups[50];
char crontabs[100][200];
float cpu_occupy = 0;
float mem_occupy = 0;
int sum_tcp_socket = 0;
int sum_progress = 0;
int sum_user = 0;
int sum_group = 0;
int sum_crontab = 0;
memset(&users,0,sizeof(users));
printf("Start the new thread to monitor key system values.\n");
while(1)
{
// printf("-------------------- CPU occupy -------------------\n");
get_cpu_occupy(&ocpu);
sleep(1);
get_cpu_occupy(&ncpu);
cpu_occupy = cal_cpu_occupy(&ocpu, &ncpu);
// printf("-------------------- Mem occupy -------------------\n");
get_mem_occupy(&omem);
mem_occupy = cal_mem_occupy(&omem);
sum_tcp_socket = get_tcp_socket_sum();
sum_progress = get_progress_sum();
sum_user = get_users(users);
sum_group = get_groups(groups);
sum_crontab = get_crontab(crontabs);
// system("clear");
printf("-------------------- Monitor Info -------------------\n");
print_now_time();
printf("CPU Usage(%) : %4.2f\n", cpu_occupy);
printf("Mem Usage(%) : %4.2f\n", mem_occupy);
printf("Tcp Socket Establish : %d\n", sum_tcp_socket);
printf("Sum of progress : %d\n", sum_progress);
printf("Sum of Users : %d\n", sum_user);
printf("Sum of Groups : %d\n", sum_group);
printf("Sum of Crontabs : %d\n", sum_crontab);
printf("--------------------- User List --------------------\n");
for(int i=0;i<sum_user;i++)
{
printf("user %d name=%s, user id=%s, user group id=%s\n",i, users[i].name,users[i].cid,users[i].cgroup_id);
}
printf("-------------------- Group List --------------------\n");
for(int i=0;i<sum_group;i++)
{
printf("group name=%s, group id=%s\n",groups[i].name,groups[i].gid);
}
printf("------------------- Crontab List -------------------\n");
for(int i=0;i<sum_crontab;i++)
{
printf("%s",crontabs[i]);
}
printf("\n");
}
}
void *monitor_key_files(void *args)
{
printf("Start the new thread to monitor key files.\n");
}
void *monitor_key_log(void *args)
{
printf("Start the new thread to monitor key logs.\n");
}
int init_conf(char *conf_path)
{
}
void get_cpu_occupy (Cpu_info *o)
{
FILE *fd;
char buff[MAXBUFSIZE];
fd = fopen ("/proc/stat", "r"); //这里只读取stat文件的第一行及cpu总信息如需获取每核cpu的使用情况请分析stat文件的接下来几行。
fgets (buff, sizeof(buff), fd);
// printf("get thr cpu info: %s", buff);
sscanf (buff, "%s %u %u %u %u %u %u %u %u %u %u", o->name, &o->user, &o->nice, &o->system, &o->idle, &o->iowait, &o->irq, &o->softirq, &o->stealstolen, &o->guest, &o->guest_nice);
// printf("name=%s, user=%d, nice=%d, system=%d, idle=%d, iowait=%d, irq=%d, softirq=%d, stralstolen=%d, guest=%d, guest_nice=%d\n", o->name, o->user, o->nice, o->system, o->idle, o->iowait, o->irq, o->softirq, o->stealstolen, o->guest, o->guest_nice);
fclose(fd);
}
float cal_cpu_occupy (Cpu_info *o, Cpu_info *n)
{
int ototal, ntotal;
int oused, nused;
ototal = (o->user + o->nice + o->system + o->idle + o->iowait + o-> irq + o-> softirq + o->stealstolen + o->guest + o->guest_nice);
ntotal = (n->user + n->nice + n->system + n->idle + n->iowait + n-> irq + n-> softirq + n->stealstolen + n->guest + n->guest_nice);
oused = ototal - o->idle;
nused = ntotal - n->idle;
// printf("ototal time: %d\n", ototal);
// printf("ntotal time: %d\n", ntotal);
// printf("oused time: %d\n", oused);
// printf("nused time: %d\n", nused);
return (100.0 * (nused - oused) / (ntotal - ototal));
}
void get_mem_occupy (Mem_info *o)
{
FILE* fpMemInfo = fopen("/proc/meminfo", "r");
if (NULL == fpMemInfo)
{
return ;
}
int i = 0;
int value;
char name[1024];
char line[1024];
int nFiledNumber = 2;
int nMemberNumber = 5;
while (fgets(line, sizeof(line) - 1, fpMemInfo))
{
if (sscanf(line, "%s%u", name, &value) != nFiledNumber)
{
continue;
}
if (0 == strcmp(name, "MemTotal:"))
{
++i;
o->total = value;
}
else if (0 == strcmp(name, "MemFree:"))
{
++i;
o->free = value;
}
else if (0 == strcmp(name, "MemAvailable:"))
{
++i;
o->available = value;
}
else if (0 == strcmp(name, "Buffers:"))
{
++i;
o->buffers = value;
}
else if (0 == strcmp(name, "Cached:"))
{
++i;
o->cached = value;
}
if (i == nMemberNumber)
{
break;
}
}
// system("free");
// system("cat /proc/meminfo");
// printf("MemTotal : %d\n",o->total);
// printf("MemFree : %d\n",o->free);
// printf("MemAvailable : %d\n",o->available);
// printf("MemBuffers : %d\n",o->buffers);
// printf("MemCached : %d\n",o->cached);
// printf("MemSwapCached : %d\n",o->swap_cached);
// printf("MemSwapTotal : %d\n",o->swap_total);
// printf("MemSwapFree : %d\n",o->swap_free);
fclose(fpMemInfo);
}
float cal_mem_occupy(Mem_info *o)
{
return (100.0 * (o->total - o->available) / o->total);
}
int get_tcp_socket_sum ()
{
int socket_num=0;
FILE *tcp;
char tmp[1024]; //设置一个合适的长度,以存储每一行输出
int value;
char name[1024];
tcp = popen("netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'", "r");
if (tcp == NULL) {
return 0;
}
while (fgets(tmp, sizeof(tmp) - 1, tcp)) {
if (sscanf(tmp, "%s %u", name, &value) != 2)
{
continue;
}
if (0 == strcmp(name, "ESTABLISHED"))
{
socket_num = value;
break;
}
}
pclose(tcp);
return socket_num;
}
int get_progress_sum ()
{
int progress_num=0;
FILE *progress;
char tmp[1024];
progress = popen("ps -ef| wc -l", "r");
if (progress == NULL) {
return 0;
}
fgets(tmp, sizeof(tmp) - 1, progress);
sscanf(tmp, "%u", &progress_num);
pclose(progress);
return progress_num;
}
int get_users (User_info users[])
{
char line[10240];
char *name = NULL;
char *passwd = NULL;
char *cid;
char *cgroup_id;
int i=0;
FILE* fpUserInfo = fopen("/etc/passwd", "r");
if (NULL == fpUserInfo)
{
return -1;
}
while (fgets(line, sizeof(line) - 1, fpUserInfo))
{
// printf("%s",line);
name = strtok(line, ":");
passwd = strtok(NULL, ":");
cid = strtok(NULL, ":");
cgroup_id = strtok(NULL, ":");
strcpy(users[i].name, name);
strcpy(users[i].passwd, passwd);
strcpy(users[i].cid,cid);
strcpy(users[i].cgroup_id,cgroup_id);
// printf("user name=%s, user id=%s, user group id=%s\n",users[i].name,users[i].cid,users[i].cgroup_id);
i++;
}
fclose(fpUserInfo);
return i;
}
int get_groups (Group_info groups[])
{
char line[10240];
char *name = NULL;
char *passwd = NULL;
char *gid;
int i=0;
FILE* fpGroupInfo = fopen("/etc/group", "r");
if (NULL == fpGroupInfo)
{
return -1;
}
while (fgets(line, sizeof(line) - 1, fpGroupInfo))
{
// printf("%s",line);
name = strtok(line, ":");
passwd = strtok(NULL, ":");
gid = strtok(NULL, ":");
strcpy(groups[i].name, name);
strcpy(groups[i].passwd, passwd);
strcpy(groups[i].gid,gid);
// printf("group name=%s, group id=%s\n",groups[i].name,groups[i].gid);
i++;
}
fclose(fpGroupInfo);
return i;
}
int get_crontab(char crontab[][200])
{
int sum_crontab=0;
FILE *fpCrontab;
char tmp[10240]; //设置一个合适的长度,以存储每一行输出
char info[1024];
fpCrontab = popen("cat /etc/passwd | cut -f 1 -d : |xargs -I {} crontab -l -u {}", "r");
if (fpCrontab == NULL) {
return -1;
}
while (fgets(tmp, sizeof(tmp) - 1, fpCrontab)) {
sscanf(tmp, "%[^ ]", info);
if(!strcmp(info,"no"))
continue;
strcpy(crontab[sum_crontab++],tmp);
}
pclose(fpCrontab);
return sum_crontab;
}
/*
* === FUNCTION ======================================================================
* Name: print_now_time
* Description:
* =====================================================================================
*/
void print_now_time()
{
time_t rawtime;
struct tm * timeinfo;
char buffer [128];
time (&rawtime);
// printf("%ld\n", rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer,sizeof(buffer),"Now is %Y/%m/%d %H:%M:%S",timeinfo);
printf("%s\n", buffer);
}
/*
* === FUNCTION ======================================================================
* Name: split
* Description: str字符以spl分割,dst中
* =====================================================================================
*/
int split(char dst[][80], char* str, const char* spl)
{
int n = 0;
char *result = NULL;
result = strtok(str, spl);
while( result != NULL )
{
strcpy(dst[n++], result);
result = strtok(NULL, spl);
}
return n;
}

View File

@ -0,0 +1,109 @@
/* ===============================================================================================
*
* Filename: monitor.h
*
* Description: Declare monitoring module functions and dependencies.
*
* Version: 0.1
* Created: 20200715 1021
* Revision: none
* Compiler: gcc
* Link: -lpthread
*
* Author: songtianlun, songtianlun@comleader.com.cn
* Organization: IEUCD
*
* ===============================================================================================*/
#include <zmq.h>
#include <string.h>
#include<stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <float.h>
#include <limits.h>
#include <pthread.h>
#include <time.h>
#include "ini/INIReader.h"
#define MAXBUFSIZE 1024
struct KEY_PROCESS
{
int sum_monitor;
int num_normal;
int num_abnormal;
int pid_abnormal[10];
char Char;
short Short;
long Long;
float Float;
double Double;
char String[100];
};
struct CPU_INFO
{
char name[10];
unsigned int user;
unsigned int nice;
unsigned int system;
unsigned int idle;
unsigned int iowait;
unsigned int irq;
unsigned int softirq;
unsigned int stealstolen;
unsigned int guest;
unsigned int guest_nice;
};
struct MEM_INFO
{
unsigned int total;
unsigned int free;
unsigned int buffers;
unsigned int cached;
unsigned int swap_cached;
unsigned int swap_total;
unsigned int swap_free;
unsigned int available;
};
struct USERS_INFO
{
char name[50];
char passwd[10];
char cid[10];
char cgroup_id[10];
};
struct GROUPS_INFO
{
char name[50];
char passwd[10];
char gid[10];
};
typedef struct KEY_PROCESS Key_process;
typedef struct CPU_INFO Cpu_info;
typedef struct MEM_INFO Mem_info;
typedef struct USERS_INFO User_info;
typedef struct GROUPS_INFO Group_info;
void *monitor_key_process(void *args);
void *monitor_key_sys_value(void *args);
void *monitor_key_files(void *args);
void *monitor_key_log(void *args);
int init_config(char *conf_path);
void get_cpu_occupy (Cpu_info *o);
float cal_cpu_occupy(Cpu_info *, Cpu_info *);
void get_mem_occupy (Mem_info *o);
float cal_mem_occupy(Mem_info *);
int get_tcp_socket_sum ();
int get_progress_sum ();
int get_users (User_info users[]);
int get_groups (Group_info groups[]);
int get_crontab (char crontab[][200]);
void print_now_time();
int split(char dst[][80], char* str, const char* spl);

View File

@ -0,0 +1,21 @@
# Author: Tianlun Song, songtianlun@frytea.com, In Nov 22, 2020.
ARCH ?=
CC = $(ARCH)gcc
SUFFIX = .c
CFLAGS += -g -lzmq -lpthread -L/usr/local/lib -std=gnu11
LD = -I/usr/local/include -Wl,-rpath=/usr/local/lib/
CUR_SOURCE = $(wildcard *$(SUFFIX))
# CUR_TARGETS = $(patsubst %$(SUFFIX), %, $(CUR_SOURCE))
CUR_TARGETS = ./monitsys
all:$(CUR_TARGETS)
# %:%.c 是一个表示与目标相同文件的模式变量
$(CUR_TARGETS):%:%$(SUFFIX)
$(CC) $< $(CFLAGS) -o $@ $(LD)
# 指定伪目标
.PHONY:clean all
clean:
-rm -rf $(TARGETS)

View File

@ -0,0 +1,23 @@
# Nos Monitor
The app of Nos System State Monitor.
- Author : Zhanglong Cheng.
- Company: PML.
## Usage
```
# Step 1: Build
$ make
# Step 2: Edit config file, initip.ini
# Step 3: Install
$ mkdir /root/monitor
$ cp monitsys /root/monitor/
$ cp initip.ini /root/monitor/
# Step 4: Run
$ /root/monitor/monitsys &
```

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
no crontab for root

Binary file not shown.

View File

@ -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;
}

Binary file not shown.

View File

@ -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("<p>open file:passwd.txt error</p>");
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;
}

View File

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,111 @@
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <pthread.h>
#include <zmq.h>
#include <sys/inotify.h>
#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;

Binary file not shown.

View File

@ -0,0 +1,4 @@
10.10.10.242
monitsys
top
systemd

BIN
study_clang/Mimic/piggie/piggie Executable file

Binary file not shown.

View File

@ -0,0 +1,55 @@
#define _GNU_SOURCE
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sched.h>
#include <time.h>
#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;
}

View File

@ -0,0 +1,61 @@
#define _GNU_SOURCE
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sched.h>
#include <time.h>
#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;
}

Binary file not shown.

View File

@ -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 <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <pcap.h>
#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;
}

View File

@ -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)

View File

@ -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)

Binary file not shown.

View File

@ -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 <stdio.h>
#include <string.h>
// #include <pthread.h>
#include <pcap.h>
#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;
}

View File

@ -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)

View File

@ -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 <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include "CJudgeUtils.h"
#include "CTypedef.h"
class Config : public CSingleton<Config>
{
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;
};

View File

@ -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 <mutex>
#include "CTypedef.h"
#include "CJudgeUtils.h"
typedef std::map<std::string, std::set<int> > CACHE_MAP;
typedef std::vector<NosConfMsg_ST> MSG_VEC;
struct MsgGroup
{
CACHE_MAP cache_map; // 一组执行体消息的对比缓存
MSG_VEC msg_vec; // 一组执行体消息源
time_t start_ms; // 一组新消息进入起始时间
unsigned int uiPort; // 一组消息的端口
};
class JudgeConf : public CSingleton<JudgeConf>
{
public:
JudgeConf() { }
virtual ~JudgeConf() { }
public:
void Init(int _nos_num, int _running_num);
void Judge();
private:
std::map<int, MsgGroup> group_map; // 按iCmd划分消息组,nos端口相同
int nos_num;
int running_num;
int nos_status; // 各个nos是否running TODO
private:
int GetCacheNosNum(CACHE_MAP& map);
};
#endif

View File

@ -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 <zmq.h>
#include "CZeroMQ.h"
#define MAX_MSG_BUFFER 1024 // 通信消息缓存区
#define getbit(x,y) ((x) >> (y)&1)
#define setbit(x,y) x|=(1<<y)
#define clrbit(x,y) x&=~(1<<y)
/*
typedef std::vector<SysState_T> SysState_MV;
typedef std::vector<SysLog_T> 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<CJudgeSysInfo>
{
public:
CJudgeSysInfo();
virtual ~CJudgeSysInfo();
public:
void Init();
void RcvNosStateMessage();
void Judge();
int GetNosRunning(int nos_id);
private:
void JudgeSysState(std::vector<SysState_T>& sys_state_v, uint& nos_time_out_bit);
void JudgeProcessState();
void JudgeFileState();
void JudgeFileNum();
void JudgeSysLog(std::vector<SysLog_T>& SysShellLog_MV, std::vector<SysLog_T>& 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<SysLog_T>& SysLoginLog_CMV);
void JudgeShellLog(std::vector<SysLog_T>& 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

View File

@ -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 <iostream>
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <stdint.h>
#include <pthread.h>
#include <mutex>
#include <memory>
#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 T>
class CSingleton
{
private:
static std::once_flag SingletonFlag;
static std::unique_ptr<T> 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 <class T> std::unique_ptr<T> CSingleton <T>::Instance = nullptr;
template <class T> std::once_flag CSingleton <T>::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<std::string>& 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<std::string> 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<std::string> m_sections;
std::map<std::string, std::map<std::string, std::string> > m_fields;
};
#endif

View File

@ -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 <syslog.h>
#include <stdarg.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <time.h>
//颜色宏定义
#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

View File

@ -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<CMain>
{
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

View File

@ -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 <typename T>
class CMessageQueue : public CSingleton<CMessageQueue<T> >
{
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<T> m_queue;
pthread_mutex_t ss_QueueMutex;
std::list<T> q_SysState;
pthread_mutex_t ps_QueueMutex;
std::list<T> q_ProcessState;
pthread_mutex_t fs_QueueMutex;
std::list<T> q_FileState;
pthread_mutex_t fn_QueueMutex;
std::list<T> q_FileNum;
pthread_mutex_t sl_QueueMutex;
std::list<T> q_SysLog;
};
template <typename T>
CMessageQueue<T>::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 <typename T>
CMessageQueue<T>::~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 <typename T>
void CMessageQueue<T>::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 <typename T>
void CMessageQueue<T>::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 <typename T>
T& CMessageQueue<T>::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 <typename T>
T& CMessageQueue<T>::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 <typename T>
int CMessageQueue<T>::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 <typename T>
uint CMessageQueue<T>::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 <typename T>
void CMessageQueue<T>::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

View File

@ -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<iostream>
#include<mysql/mysql.h>
#include<queue>
#include<map>
#include<vector>
#include<utility>
#include<string>
#include<mutex>
#include<thread>
#include "CJudgeUtils.h"
struct MysqlResults
{
int field_count;
int record_count;
std::vector<std::vector<std::string>> value;
std::vector<std::string> 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<MysqlPool>
{
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<MYSQL*> 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

View File

@ -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 <string>
#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<CNetManager>
{
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*/

View File

@ -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 | 2A/B/C全部一致的消息
----+----+-----
uiNosIdx = 0;
*/
JUDGE_SUCC_WITH_TWO_STAGE, /*接收到所有执行体消息,有多数一致,但少数也一致*/
/*
----+----+----
| A | B | C 1线A/B/C
----+----+----
| 1 | 1 | 2 2A/B全部一致
----+----+----
uiNosIdx = C;
*/
JUDGE_SUCC_WITH_MANY_STAGE, /*接收到所有执行体消息,有多数一致,但有多个少数群体*/
/*
----+----+----+----+-----
| A | B | C | D | E 1线A/B/C/D/E
----+----+----+----+-----
| 1 | 1 | 1 | 2 | 3 2A/B/C全部一致D/E不一致
----+----+----+----+-----
uiNosIdx = D | E;
*/
JUDGE_SUCC_WITH_TIMEOUT, /*未收到所有执行体消息,全部一致*/
/*
----+----+-----
| A | B | C | 1线A/B/C
----+----+-----
| 1 | 1 | | 2A/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 | 2A/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 | 2A/B/C全部一致D/E不一致G超时
----+----+----+----+----+----+-----
uiNosIdx = E | F | G;
*/
JUDGE_ALL_FAIL_WITH_DIFF, /*收到所有执行体消息,全部不一致*/
/*
----+----+-----
| A | B | C | 1线A/B/C
----+----+-----
| 1 | 2 | 3 | 2A/B/C的消息
----+----+-----
uiNosIdx = A | B | C;
*/
JUDGE_FAIL_WITH_TWO_STAGE, /*收到所有执行体消息,分为数目相同的两个群体*/
/*
----+----+----+----
| A | B | C | D 1线A/B/C/D
----+----+----+----
| 1 | 1 | 2 | 2 2A/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 2A/B全部一致C/D全部一致
----+----+----+----+-----
uiNosIdx = A | B | C | D | E;
*/
JUDGE_FAIL_WITH_TIMEOUT, /*未收到所有执行体消息,达不到裁决条件*/
/*
----+----+-----
| A | B | C | 1线A/B/C
----+----+-----
| 1 | | | 2A/B/C的消息
----+----+-----
uiNosIdx = A;
*/
JUDGE_FAIL_WITH_TIMEOUT_TWO_STAGE, /*未收到所有执行体消息,分为两个少数群体*/
/*
----+----+-----
| A | B | C | 1线A/B/C
----+----+-----
| 1 | 2 | | 2A/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 | 2A/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*/

View File

@ -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 <map>
#include <vector>
#include <queue>
#include <list>
#include <set>
#include <unistd.h>
#include <sys/time.h>
#include <arpa/inet.h>
#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]#)<fZP>iuwR*H5hz.}<AR^RSWunZ8H+oc8l1k"
typedef socklen_t SOCKLEN_T;
typedef struct timeval TIMEVAL_T;
typedef struct sockaddr SOCKADDR_T;
typedef struct sockaddr_in SOCKADDR_IN_T;
typedef unsigned int uint;
typedef struct
{
unsigned int uiNosIdx;
TIMEVAL_T stRcvTime;
unsigned int uiDataLen;
unsigned int uiPort;
int iCmd;
unsigned char ucData[1024];
}NosConfMsg_ST;
typedef struct
{
int iCmd;
unsigned char ucData[1024];
}ConfJudgeMsg_ST;
typedef struct
{
unsigned int uiNosIdx;
unsigned char ucHost[16];
int iState; // 2 start
}NosState_T;
typedef struct
{
uint uiType; // 1
char szIp[32];
TIMEVAL_T stRcvTime;
uint uiCpuRate;
uint uiMemRate;
uint uiTcpEstablishNum;
uint uiRunningProcessNum;
uint uiCronNum;
char szPasswdMd5[64];
char szGroupMd5[64];
}SysState_T;
typedef struct
{
uint uiType; // 2
char szIp[32];
TIMEVAL_T stRcvTime;
char szProcessName[32];
uint uiProcessState;
}ProcessState_T;
typedef struct
{
uint uiType; // 3
char szIp[32];
TIMEVAL_T stRcvTime;
char szFileName[32]; // 被改动的文件名称
char eventType[16]; // 说明
char szFileMd5[64]; // 文件的md5值
}FileState_T;
typedef struct
{
uint uiType; // 4
char szIp[32];
TIMEVAL_T stRcvTime;
char szDirPath[32]; // 监控的的文件路径
char szFileName[32]; //增加或删除的文件名称
uint uiFileNum; // 当前文件夹下文件数量
}FileNum_T;
typedef struct
{
uint uiType; //5
char szIp[32];
TIMEVAL_T stRcvTime;
char szLogFile[32];
char szMsg[5][128];
}SysLog_T;
typedef enum MESSAGE_QUQUQ_TYPE_E{
MQT_CONFIG_E = 1,
MQT_SYS_STATE_E,
MQT_PROCESS_STATE_E,
MQT_FILE_NUM_E,
MQT_FILE_STATE_E,
MQT_SYS_LOG_E
}Message_QueueType_E;
#endif

View File

@ -0,0 +1,52 @@
/*****************************************************************************
* @Descripttion:
* @Author: FengChao
* @Date: 2020-08-05 17:17:15
* @LastEditors: LastEditors
* @LastEditTime: 2020-08-05 17:31:23
*****************************************************************************/
/*************************************************************************
> 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*/

View File

@ -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*/

View File

@ -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 <string>
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*/

Binary file not shown.

View File

@ -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

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More