提交 e976988d 编写于 作者: L longdafeng 提交者: Longda

Format all code by the OceanBase Clang-Format file.

上级 06fa8cf7
...@@ -31,7 +31,7 @@ namespace common { ...@@ -31,7 +31,7 @@ namespace common {
// VARNAME=VALUE // VARNAME=VALUE
class Ini { class Ini {
public: public:
/** /**
* To simplify the logic, no lock's when loading configuration * To simplify the logic, no lock's when loading configuration
* So don't modify the data parallel * So don't modify the data parallel
...@@ -50,24 +50,22 @@ class Ini { ...@@ -50,24 +50,22 @@ class Ini {
* get the map of the section * get the map of the section
* if the section doesn't exist, return one empty section * if the section doesn't exist, return one empty section
*/ */
const std::map<std::string, std::string> & const std::map<std::string, std::string> &get(const std::string &section = DEFAULT_SECTION);
get(const std::string &section = DEFAULT_SECTION);
/** /**
* get the value of the key in the section, * get the value of the key in the section,
* if the key-value doesn't exist, * if the key-value doesn't exist,
* use the input default_value * use the input default_value
*/ */
std::string get(const std::string &key, const std::string &default_value, std::string get(
const std::string &section = DEFAULT_SECTION); const std::string &key, const std::string &default_value, const std::string &section = DEFAULT_SECTION);
/** /**
* put the key-value pair to the section * put the key-value pair to the section
* if the key-value already exist, just replace it * if the key-value already exist, just replace it
* if the section doesn't exist, it will create this section * if the section doesn't exist, it will create this section
*/ */
int put(const std::string &key, const std::string &value, int put(const std::string &key, const std::string &value, const std::string &section = DEFAULT_SECTION);
const std::string &section = DEFAULT_SECTION);
/** /**
* output all configuration to one string * output all configuration to one string
...@@ -92,7 +90,7 @@ class Ini { ...@@ -92,7 +90,7 @@ class Ini {
static const char CFG_SESSION_START_TAG = '['; static const char CFG_SESSION_START_TAG = '[';
static const char CFG_SESSION_END_TAG = ']'; static const char CFG_SESSION_END_TAG = ']';
protected: protected:
/** /**
* insert one empty session to sections_ * insert one empty session to sections_
*/ */
...@@ -102,21 +100,18 @@ class Ini { ...@@ -102,21 +100,18 @@ class Ini {
* switch session according to the session_name * switch session according to the session_name
* if the section doesn't exist, it will create one * if the section doesn't exist, it will create one
*/ */
std::map<std::string, std::string> * std::map<std::string, std::string> *switch_session(const std::string &session_name);
switch_session(const std::string &session_name);
/** /**
* insert one entry to session_map * insert one entry to session_map
* line's format is "key=value" * line's format is "key=value"
* *
*/ */
int insert_entry(std::map<std::string, std::string> *session_map, int insert_entry(std::map<std::string, std::string> *session_map, const std::string &line);
const std::string &line);
typedef std::map<std::string, std::map<std::string, std::string>> typedef std::map<std::string, std::map<std::string, std::string>> SessionsMap;
SessionsMap;
private: private:
static const std::map<std::string, std::string> empty_map_; static const std::map<std::string, std::string> empty_map_;
std::set<std::string> file_names_; std::set<std::string> file_names_;
...@@ -129,5 +124,5 @@ class Ini { ...@@ -129,5 +124,5 @@ class Ini {
Ini *&get_properties(); Ini *&get_properties();
//******************************************************************** //********************************************************************
}// namespace common } // namespace common
#endif //__COMMON_CONF_INI_H__ #endif //__COMMON_CONF_INI_H__
...@@ -36,7 +36,8 @@ namespace common { ...@@ -36,7 +36,8 @@ namespace common {
#endif #endif
inline const std::string &theSwVersion() { inline const std::string &theSwVersion()
{
static const std::string swVersion(VERSION_STR); static const std::string swVersion(VERSION_STR);
return swVersion; return swVersion;
......
...@@ -27,13 +27,11 @@ See the Mulan PSL v2 for more details. */ ...@@ -27,13 +27,11 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
int readFromFile(const std::string &fileName, char *&outputData, size_t &fileSize)
int readFromFile(const std::string &fileName, char *&outputData, {
size_t &fileSize) {
FILE *file = fopen(fileName.c_str(), "rb"); FILE *file = fopen(fileName.c_str(), "rb");
if (file == NULL) { if (file == NULL) {
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
return -1; return -1;
} }
...@@ -50,8 +48,7 @@ int readFromFile(const std::string &fileName, char *&outputData, ...@@ -50,8 +48,7 @@ int readFromFile(const std::string &fileName, char *&outputData,
memset(buffer, 0, sizeof(buffer)); memset(buffer, 0, sizeof(buffer));
oneRead = fread(buffer, 1, sizeof(buffer), file); oneRead = fread(buffer, 1, sizeof(buffer), file);
if (ferror(file)) { if (ferror(file)) {
std::cerr << "Failed to read data" << fileName << SYS_OUTPUT_FILE_POS std::cerr << "Failed to read data" << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
fclose(file); fclose(file);
if (data != NULL) { if (data != NULL) {
lfree(data); lfree(data);
...@@ -62,8 +59,7 @@ int readFromFile(const std::string &fileName, char *&outputData, ...@@ -62,8 +59,7 @@ int readFromFile(const std::string &fileName, char *&outputData,
data = (char *)lrealloc(data, readSize + oneRead); data = (char *)lrealloc(data, readSize + oneRead);
if (data == NULL) { if (data == NULL) {
std::cerr << "Failed to alloc memory for " << fileName std::cerr << "Failed to alloc memory for " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
lfree(data); lfree(data);
fclose(file); fclose(file);
return -1; return -1;
...@@ -81,12 +77,11 @@ int readFromFile(const std::string &fileName, char *&outputData, ...@@ -81,12 +77,11 @@ int readFromFile(const std::string &fileName, char *&outputData,
return 0; return 0;
} }
int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, const char *openMode)
const char *openMode) { {
FILE *file = fopen(fileName.c_str(), openMode); FILE *file = fopen(fileName.c_str(), openMode);
if (file == NULL) { if (file == NULL) {
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
return -1; return -1;
} }
...@@ -95,8 +90,7 @@ int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, ...@@ -95,8 +90,7 @@ int writeToFile(const std::string &fileName, const char *data, u32_t dataSize,
while (leftSize > 0) { while (leftSize > 0) {
int writeCount = fwrite(buffer, 1, leftSize, file); int writeCount = fwrite(buffer, 1, leftSize, file);
if (writeCount <= 0) { if (writeCount <= 0) {
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
fclose(file); fclose(file);
return -1; return -1;
} else { } else {
...@@ -110,7 +104,8 @@ int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, ...@@ -110,7 +104,8 @@ int writeToFile(const std::string &fileName, const char *data, u32_t dataSize,
return 0; return 0;
} }
int getFileLines(const std::string &fileName, u64_t &lineNum) { int getFileLines(const std::string &fileName, u64_t &lineNum)
{
lineNum = 0; lineNum = 0;
char line[4 * ONE_KILO] = {0}; char line[4 * ONE_KILO] = {0};
...@@ -133,14 +128,13 @@ int getFileLines(const std::string &fileName, u64_t &lineNum) { ...@@ -133,14 +128,13 @@ int getFileLines(const std::string &fileName, u64_t &lineNum) {
return 0; return 0;
} }
int getFileNum(u64_t &fileNum, const std::string &path, int getFileNum(u64_t &fileNum, const std::string &path, const std::string &pattern, bool recursive)
const std::string &pattern, bool recursive) { {
try { try {
DIR *dirp = NULL; DIR *dirp = NULL;
dirp = opendir(path.c_str()); dirp = opendir(path.c_str());
if (dirp == NULL) { if (dirp == NULL) {
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
return -1; return -1;
} }
...@@ -160,8 +154,7 @@ int getFileNum(u64_t &fileNum, const std::string &path, ...@@ -160,8 +154,7 @@ int getFileNum(u64_t &fileNum, const std::string &path,
fullPath += entry->d_name; fullPath += entry->d_name;
memset(&fs, 0, sizeof(fs)); memset(&fs, 0, sizeof(fs));
if (stat(fullPath.c_str(), &fs) < 0) { if (stat(fullPath.c_str(), &fs) < 0) {
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
continue; continue;
} }
...@@ -181,8 +174,7 @@ int getFileNum(u64_t &fileNum, const std::string &path, ...@@ -181,8 +174,7 @@ int getFileNum(u64_t &fileNum, const std::string &path,
continue; continue;
} }
if (pattern.empty() == false && if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
regex_match(entry->d_name, pattern.c_str())) {
// Don't match // Don't match
continue; continue;
} }
...@@ -194,20 +186,18 @@ int getFileNum(u64_t &fileNum, const std::string &path, ...@@ -194,20 +186,18 @@ int getFileNum(u64_t &fileNum, const std::string &path,
return 0; return 0;
} catch (...) { } catch (...) {
std::cerr << "Failed to get file num " << path << SYS_OUTPUT_FILE_POS std::cerr << "Failed to get file num " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
} }
return -1; return -1;
} }
int getFileList(std::vector<std::string> &fileList, const std::string &path, int getFileList(std::vector<std::string> &fileList, const std::string &path, const std::string &pattern, bool recursive)
const std::string &pattern, bool recursive) { {
try { try {
DIR *dirp = NULL; DIR *dirp = NULL;
dirp = opendir(path.c_str()); dirp = opendir(path.c_str());
if (dirp == NULL) { if (dirp == NULL) {
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
return -1; return -1;
} }
...@@ -227,8 +217,7 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path, ...@@ -227,8 +217,7 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path,
fullPath += entry->d_name; fullPath += entry->d_name;
memset(&fs, 0, sizeof(fs)); memset(&fs, 0, sizeof(fs));
if (stat(fullPath.c_str(), &fs) < 0) { if (stat(fullPath.c_str(), &fs) < 0) {
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
continue; continue;
} }
...@@ -248,8 +237,7 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path, ...@@ -248,8 +237,7 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path,
continue; continue;
} }
if (pattern.empty() == false && if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
regex_match(entry->d_name, pattern.c_str())) {
// Don't match // Don't match
continue; continue;
} }
...@@ -260,20 +248,18 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path, ...@@ -260,20 +248,18 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path,
closedir(dirp); closedir(dirp);
return 0; return 0;
} catch (...) { } catch (...) {
std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
} }
return -1; return -1;
} }
int getDirList(std::vector<std::string> &dirList, const std::string &path, int getDirList(std::vector<std::string> &dirList, const std::string &path, const std::string &pattern)
const std::string &pattern) { {
try { try {
DIR *dirp = NULL; DIR *dirp = NULL;
dirp = opendir(path.c_str()); dirp = opendir(path.c_str());
if (dirp == NULL) { if (dirp == NULL) {
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
return -1; return -1;
} }
...@@ -293,8 +279,7 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path, ...@@ -293,8 +279,7 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path,
fullPath += entry->d_name; fullPath += entry->d_name;
memset(&fs, 0, sizeof(fs)); memset(&fs, 0, sizeof(fs));
if (stat(fullPath.c_str(), &fs) < 0) { if (stat(fullPath.c_str(), &fs) < 0) {
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
continue; continue;
} }
...@@ -302,8 +287,7 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path, ...@@ -302,8 +287,7 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path,
continue; continue;
} }
if (pattern.empty() == false && if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
regex_match(entry->d_name, pattern.c_str())) {
// Don't match // Don't match
continue; continue;
} }
...@@ -314,13 +298,13 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path, ...@@ -314,13 +298,13 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path,
closedir(dirp); closedir(dirp);
return 0; return 0;
} catch (...) { } catch (...) {
std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
} }
return -1; return -1;
} }
int touch(const std::string &path) { int touch(const std::string &path)
{
// CWE367: A check occurs on a file's attributes before // CWE367: A check occurs on a file's attributes before
// the file is used in a privileged operation, but things // the file is used in a privileged operation, but things
// may have changed // may have changed
...@@ -341,7 +325,8 @@ int touch(const std::string &path) { ...@@ -341,7 +325,8 @@ int touch(const std::string &path) {
return 0; return 0;
} }
int getFileSize(const char *filePath, u64_t &fileLen) { int getFileSize(const char *filePath, u64_t &fileLen)
{
if (filePath == NULL || *filePath == '\0') { if (filePath == NULL || *filePath == '\0') {
std::cerr << "invalid filepath" << std::endl; std::cerr << "invalid filepath" << std::endl;
return -EINVAL; return -EINVAL;
...@@ -351,8 +336,7 @@ int getFileSize(const char *filePath, u64_t &fileLen) { ...@@ -351,8 +336,7 @@ int getFileSize(const char *filePath, u64_t &fileLen) {
int rc = stat(filePath, &statBuf); int rc = stat(filePath, &statBuf);
if (rc) { if (rc) {
std::cerr << "Failed to get stat of " << filePath << "," << errno << ":" std::cerr << "Failed to get stat of " << filePath << "," << errno << ":" << strerror(errno) << std::endl;
<< strerror(errno) << std::endl;
return rc; return rc;
} }
...@@ -365,4 +349,4 @@ int getFileSize(const char *filePath, u64_t &fileLen) { ...@@ -365,4 +349,4 @@ int getFileSize(const char *filePath, u64_t &fileLen) {
return 0; return 0;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -29,8 +29,7 @@ namespace common { ...@@ -29,8 +29,7 @@ namespace common {
*/ */
int readFromFile(const std::string &fileName, char *&data, size_t &fileSize); int readFromFile(const std::string &fileName, char *&data, size_t &fileSize);
int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, const char *openMode);
const char *openMode);
/** /**
* return the line number which line.strip() isn't empty * return the line number which line.strip() isn't empty
...@@ -47,12 +46,10 @@ int getFileLines(const std::string &fileName, u64_t &lineNum); ...@@ -47,12 +46,10 @@ int getFileLines(const std::string &fileName, u64_t &lineNum);
* @param[in] resursion if this has been set, it will search subdirs * @param[in] resursion if this has been set, it will search subdirs
* @return 0 if success, error code otherwise * @return 0 if success, error code otherwise
*/ */
int getFileList(std::vector<std::string> &fileList, const std::string &path, int getFileList(
const std::string &pattern, bool recursive); std::vector<std::string> &fileList, const std::string &path, const std::string &pattern, bool recursive);
int getFileNum(u64_t &fileNum, const std::string &path, int getFileNum(u64_t &fileNum, const std::string &path, const std::string &pattern, bool recursive);
const std::string &pattern, bool recursive); int getDirList(std::vector<std::string> &dirList, const std::string &path, const std::string &pattern);
int getDirList(std::vector<std::string> &dirList, const std::string &path,
const std::string &pattern);
int touch(const std::string &fileName); int touch(const std::string &fileName);
...@@ -61,5 +58,5 @@ int touch(const std::string &fileName); ...@@ -61,5 +58,5 @@ int touch(const std::string &fileName);
*/ */
int getFileSize(const char *filePath, u64_t &fileLen); int getFileSize(const char *filePath, u64_t &fileLen);
} //namespace common } // namespace common
#endif /* __COMMON_IO_IO_H__ */ #endif /* __COMMON_IO_IO_H__ */
...@@ -17,7 +17,8 @@ See the Mulan PSL v2 for more details. */ ...@@ -17,7 +17,8 @@ See the Mulan PSL v2 for more details. */
#include "common/log/log.h" #include "common/log/log.h"
namespace common { namespace common {
void RollSelectDir::setBaseDir(std::string baseDir) { void RollSelectDir::setBaseDir(std::string baseDir)
{
mBaseDir = baseDir; mBaseDir = baseDir;
std::vector<std::string> dirList; std::vector<std::string> dirList;
...@@ -44,7 +45,8 @@ void RollSelectDir::setBaseDir(std::string baseDir) { ...@@ -44,7 +45,8 @@ void RollSelectDir::setBaseDir(std::string baseDir) {
return; return;
} }
std::string RollSelectDir::select() { std::string RollSelectDir::select()
{
std::string ret; std::string ret;
MUTEX_LOCK(&mMutex); MUTEX_LOCK(&mMutex);
...@@ -55,4 +57,4 @@ std::string RollSelectDir::select() { ...@@ -55,4 +57,4 @@ std::string RollSelectDir::select() {
return ret; return ret;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -26,8 +26,14 @@ namespace common { ...@@ -26,8 +26,14 @@ namespace common {
class RollSelectDir : public SelectDir { class RollSelectDir : public SelectDir {
public: public:
RollSelectDir() { MUTEX_INIT(&mMutex, NULL); } RollSelectDir()
~RollSelectDir() { MUTEX_DESTROY(&mMutex); } {
MUTEX_INIT(&mMutex, NULL);
}
~RollSelectDir()
{
MUTEX_DESTROY(&mMutex);
}
public: public:
/** /**
...@@ -43,5 +49,5 @@ public: ...@@ -43,5 +49,5 @@ public:
u32_t mPos; u32_t mPos;
}; };
} //namespace common } // namespace common
#endif /* __COMMON_IO_ROLL_SELECT_DIR__ */ #endif /* __COMMON_IO_ROLL_SELECT_DIR__ */
...@@ -20,9 +20,12 @@ namespace common { ...@@ -20,9 +20,12 @@ namespace common {
class SelectDir { class SelectDir {
public: public:
virtual std::string select() { return std::string(""); }; virtual std::string select()
{
return std::string("");
};
virtual void setBaseDir(std::string baseDir){}; virtual void setBaseDir(std::string baseDir){};
}; };
} //namespace common } // namespace common
#endif /* __COMMON_IO_SELECT_DIR_H__ */ #endif /* __COMMON_IO_SELECT_DIR_H__ */
...@@ -14,10 +14,10 @@ See the Mulan PSL v2 for more details. */ ...@@ -14,10 +14,10 @@ See the Mulan PSL v2 for more details. */
#include "common/lang/bitmap.h" #include "common/lang/bitmap.h"
namespace common namespace common {
{
int find_first_zero(char byte, int start) { int find_first_zero(char byte, int start)
{
for (int i = start; i < 8; i++) { for (int i = start; i < 8; i++) {
if ((byte & (1 << i)) == 0) { if ((byte & (1 << i)) == 0) {
return i; return i;
...@@ -26,7 +26,8 @@ int find_first_zero(char byte, int start) { ...@@ -26,7 +26,8 @@ int find_first_zero(char byte, int start) {
return -1; return -1;
} }
int find_first_setted(char byte, int start) { int find_first_setted(char byte, int start)
{
for (int i = start; i < 8; i++) { for (int i = start; i < 8; i++) {
if ((byte & (1 << i)) != 0) { if ((byte & (1 << i)) != 0) {
return i; return i;
...@@ -35,25 +36,29 @@ int find_first_setted(char byte, int start) { ...@@ -35,25 +36,29 @@ int find_first_setted(char byte, int start) {
return -1; return -1;
} }
Bitmap::Bitmap(char *bitmap, int size) : bitmap_(bitmap), size_(size) { Bitmap::Bitmap(char *bitmap, int size) : bitmap_(bitmap), size_(size)
} {}
bool Bitmap::get_bit(int index) { bool Bitmap::get_bit(int index)
{
char bits = bitmap_[index / 8]; char bits = bitmap_[index / 8];
return (bits & (1 << (index % 8))) != 0; return (bits & (1 << (index % 8))) != 0;
} }
void Bitmap::set_bit(int index) { void Bitmap::set_bit(int index)
{
char &bits = bitmap_[index / 8]; char &bits = bitmap_[index / 8];
bits |= (1 << (index % 8)); bits |= (1 << (index % 8));
} }
void Bitmap::clear_bit(int index) { void Bitmap::clear_bit(int index)
{
char &bits = bitmap_[index / 8]; char &bits = bitmap_[index / 8];
bits &= ~(1 << (index % 8)); bits &= ~(1 << (index % 8));
} }
int Bitmap::next_unsetted_bit(int start) { int Bitmap::next_unsetted_bit(int start)
{
int ret = -1; int ret = -1;
int start_in_byte = start % 8; int start_in_byte = start % 8;
for (int iter = start / 8, end = (size_ % 8 == 0 ? size_ / 8 : size_ / 8 + 1); iter <= end; iter++) { for (int iter = start / 8, end = (size_ % 8 == 0 ? size_ / 8 : size_ / 8 + 1); iter <= end; iter++) {
...@@ -75,7 +80,8 @@ int Bitmap::next_unsetted_bit(int start) { ...@@ -75,7 +80,8 @@ int Bitmap::next_unsetted_bit(int start) {
return ret; return ret;
} }
int Bitmap::next_setted_bit(int start) { int Bitmap::next_setted_bit(int start)
{
int ret = -1; int ret = -1;
int start_in_byte = start % 8; int start_in_byte = start % 8;
for (int iter = start / 8, end = (size_ % 8 == 0 ? size_ / 8 : size_ / 8 + 1); iter <= end; iter++) { for (int iter = start / 8, end = (size_ % 8 == 0 ? size_ / 8 : size_ / 8 + 1); iter <= end; iter++) {
......
...@@ -15,8 +15,7 @@ See the Mulan PSL v2 for more details. */ ...@@ -15,8 +15,7 @@ See the Mulan PSL v2 for more details. */
#ifndef __COMMON_LANG_BITMAP_H__ #ifndef __COMMON_LANG_BITMAP_H__
#define __COMMON_LANG_BITMAP_H__ #define __COMMON_LANG_BITMAP_H__
namespace common namespace common {
{
class Bitmap { class Bitmap {
public: public:
...@@ -30,7 +29,7 @@ public: ...@@ -30,7 +29,7 @@ public:
int next_setted_bit(int start); int next_setted_bit(int start);
private: private:
char * bitmap_; char *bitmap_;
int size_; int size_;
}; };
......
...@@ -27,37 +27,48 @@ int LockTrace::mMaxBlockTids = 8; ...@@ -27,37 +27,48 @@ int LockTrace::mMaxBlockTids = 8;
#define CHECK_UNLOCK 0 #define CHECK_UNLOCK 0
void LockTrace::foundDeadLock(LockID &current, LockTrace::LockID &other, void LockTrace::foundDeadLock(LockID &current, LockTrace::LockID &other, pthread_mutex_t *otherWaitMutex)
pthread_mutex_t *otherWaitMutex) { {
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = mLocks.find(otherWaitMutex);
mLocks.find(otherWaitMutex);
if (itLocks == mLocks.end()) { if (itLocks == mLocks.end()) {
LOG_ERROR("Thread %ld own mutex %p and try to get mutex %s:%d, " LOG_ERROR("Thread %ld own mutex %p and try to get mutex %s:%d, "
"other thread %ld own mutex %s:%d and try to get %p", "other thread %ld own mutex %s:%d and try to get %p",
current.mThreadId, otherWaitMutex, current.mFile.c_str(), current.mThreadId,
current.mLine, other.mThreadId, current.mFile.c_str(), otherWaitMutex,
current.mLine, otherWaitMutex); current.mFile.c_str(),
current.mLine,
other.mThreadId,
current.mFile.c_str(),
current.mLine,
otherWaitMutex);
} else { } else {
LockTrace::LockID &otherRecusive = itLocks->second; LockTrace::LockID &otherRecusive = itLocks->second;
LOG_ERROR("Thread %ld own mutex %p:%s:%d and try to get mutex %s:%d, " LOG_ERROR("Thread %ld own mutex %p:%s:%d and try to get mutex %s:%d, "
"other thread %ld own mutex %s:%d and try to get %p:%s:%d", "other thread %ld own mutex %s:%d and try to get %p:%s:%d",
current.mThreadId, otherWaitMutex, otherRecusive.mFile.c_str(), current.mThreadId,
otherRecusive.mLine, current.mFile.c_str(), current.mLine, otherWaitMutex,
other.mThreadId, current.mFile.c_str(), current.mLine, otherRecusive.mFile.c_str(),
otherWaitMutex, otherRecusive.mFile.c_str(), otherRecusive.mLine); otherRecusive.mLine,
current.mFile.c_str(),
current.mLine,
other.mThreadId,
current.mFile.c_str(),
current.mLine,
otherWaitMutex,
otherRecusive.mFile.c_str(),
otherRecusive.mLine);
} }
} }
bool LockTrace::deadlockCheck(LockID &current, bool LockTrace::deadlockCheck(
std::set<pthread_mutex_t *> &ownMutexs, LockID &current, std::set<pthread_mutex_t *> &ownMutexs, LockTrace::LockID &other, int recusiveNum)
LockTrace::LockID &other, int recusiveNum) { {
if (recusiveNum >= mMaxBlockTids) { if (recusiveNum >= mMaxBlockTids) {
return false; return false;
} }
std::map<long long, pthread_mutex_t *>::iterator otherIt = std::map<long long, pthread_mutex_t *>::iterator otherIt = mWaitLocks.find(other.mThreadId);
mWaitLocks.find(other.mThreadId);
if (otherIt == mWaitLocks.end()) { if (otherIt == mWaitLocks.end()) {
return false; return false;
} }
...@@ -69,8 +80,7 @@ bool LockTrace::deadlockCheck(LockID &current, ...@@ -69,8 +80,7 @@ bool LockTrace::deadlockCheck(LockID &current,
return true; return true;
} }
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = mLocks.find(otherWaitMutex);
mLocks.find(otherWaitMutex);
if (itLocks == mLocks.end()) { if (itLocks == mLocks.end()) {
return false; return false;
} }
...@@ -79,12 +89,11 @@ bool LockTrace::deadlockCheck(LockID &current, ...@@ -79,12 +89,11 @@ bool LockTrace::deadlockCheck(LockID &current,
return deadlockCheck(current, ownMutexs, otherRecusive, recusiveNum + 1); return deadlockCheck(current, ownMutexs, otherRecusive, recusiveNum + 1);
} }
bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId, bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
const char *file, const int line) { {
mWaitLocks[threadId] = mutex; mWaitLocks[threadId] = mutex;
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = mLocks.find(mutex);
mLocks.find(mutex);
if (itLocks == mLocks.end()) { if (itLocks == mLocks.end()) {
return false; return false;
} }
...@@ -101,8 +110,7 @@ bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId, ...@@ -101,8 +110,7 @@ bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId,
} }
} }
std::map<long long, std::set<pthread_mutex_t *>>::iterator it = std::map<long long, std::set<pthread_mutex_t *>>::iterator it = mOwnLocks.find(threadId);
mOwnLocks.find(threadId);
if (it == mOwnLocks.end()) { if (it == mOwnLocks.end()) {
return false; return false;
} }
...@@ -115,8 +123,8 @@ bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId, ...@@ -115,8 +123,8 @@ bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId,
return deadlockCheck(current, ownMutexs, other, 1); return deadlockCheck(current, ownMutexs, other, 1);
} }
bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file, bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file, const int line)
const int line) { {
std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.find(mutex); std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.find(mutex);
if (it == mWaitTimes.end()) { if (it == mWaitTimes.end()) {
mWaitTimes.insert(std::pair<pthread_mutex_t *, int>(mutex, 1)); mWaitTimes.insert(std::pair<pthread_mutex_t *, int>(mutex, 1));
...@@ -132,8 +140,13 @@ bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file, ...@@ -132,8 +140,13 @@ bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file,
LockTrace::LockID &lockId = mLocks[mutex]; LockTrace::LockID &lockId = mLocks[mutex];
LOG_WARN("mutex %p has been already lock %d times, this time %s:%d, first " LOG_WARN("mutex %p has been already lock %d times, this time %s:%d, first "
"time:%ld:%s:%d", "time:%ld:%s:%d",
mutex, lockTimes, file, line, lockId.mThreadId, mutex,
lockId.mFile.c_str(), lockId.mLine); lockTimes,
file,
line,
lockId.mThreadId,
lockId.mFile.c_str(),
lockId.mLine);
return true; return true;
} else { } else {
...@@ -141,8 +154,8 @@ bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file, ...@@ -141,8 +154,8 @@ bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file,
} }
} }
void LockTrace::check(pthread_mutex_t *mutex, const long long threadId, void LockTrace::check(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
const char *file, const int line) { {
MUTEX_LOG("Lock mutex %p, %s:%d", mutex, file, line); MUTEX_LOG("Lock mutex %p, %s:%d", mutex, file, line);
pthread_rwlock_rdlock(&mMapMutex); pthread_rwlock_rdlock(&mMapMutex);
...@@ -153,8 +166,8 @@ void LockTrace::check(pthread_mutex_t *mutex, const long long threadId, ...@@ -153,8 +166,8 @@ void LockTrace::check(pthread_mutex_t *mutex, const long long threadId,
pthread_rwlock_unlock(&mMapMutex); pthread_rwlock_unlock(&mMapMutex);
} }
void LockTrace::insertLock(pthread_mutex_t *mutex, const long long threadId, void LockTrace::insertLock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
const char *file, const int line) { {
LockID lockID(threadId, file, line); LockID lockID(threadId, file, line);
mLocks.insert(std::pair<pthread_mutex_t *, LockID>(mutex, lockID)); mLocks.insert(std::pair<pthread_mutex_t *, LockID>(mutex, lockID));
...@@ -174,16 +187,16 @@ void LockTrace::insertLock(pthread_mutex_t *mutex, const long long threadId, ...@@ -174,16 +187,16 @@ void LockTrace::insertLock(pthread_mutex_t *mutex, const long long threadId,
} }
} }
void LockTrace::lock(pthread_mutex_t *mutex, const long long threadId, void LockTrace::lock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
const char *file, const int line) { {
pthread_rwlock_wrlock(&mMapMutex); pthread_rwlock_wrlock(&mMapMutex);
insertLock(mutex, threadId, file, line); insertLock(mutex, threadId, file, line);
pthread_rwlock_unlock(&mMapMutex); pthread_rwlock_unlock(&mMapMutex);
} }
void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId, void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
const char *file, const int line) { {
pthread_rwlock_wrlock(&mMapMutex); pthread_rwlock_wrlock(&mMapMutex);
if (mLocks.find(mutex) != mLocks.end()) { if (mLocks.find(mutex) != mLocks.end()) {
pthread_rwlock_unlock(&mMapMutex); pthread_rwlock_unlock(&mMapMutex);
...@@ -194,8 +207,8 @@ void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId, ...@@ -194,8 +207,8 @@ void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId,
pthread_rwlock_unlock(&mMapMutex); pthread_rwlock_unlock(&mMapMutex);
} }
void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId, void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId, const char *file, int line)
const char *file, int line) { {
pthread_rwlock_wrlock(&mMapMutex); pthread_rwlock_wrlock(&mMapMutex);
mLocks.erase(mutex); mLocks.erase(mutex);
...@@ -206,13 +219,13 @@ void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId, ...@@ -206,13 +219,13 @@ void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId,
pthread_rwlock_unlock(&mMapMutex); pthread_rwlock_unlock(&mMapMutex);
} }
void LockTrace::toString(std::string &result) { void LockTrace::toString(std::string &result)
{
const int TEMP_PAIR_LEN = 24; const int TEMP_PAIR_LEN = 24;
// pthread_mutex_lock(&mMapMutex); // pthread_mutex_lock(&mMapMutex);
result = " mLocks:\n"; result = " mLocks:\n";
for (std::map<pthread_mutex_t *, LockID>::iterator it = mLocks.begin(); for (std::map<pthread_mutex_t *, LockID>::iterator it = mLocks.begin(); it != mLocks.end(); it++) {
it != mLocks.end(); it++) {
result += it->second.toString(); result += it->second.toString();
char pointerBuf[TEMP_PAIR_LEN] = {0}; char pointerBuf[TEMP_PAIR_LEN] = {0};
...@@ -222,22 +235,21 @@ void LockTrace::toString(std::string &result) { ...@@ -222,22 +235,21 @@ void LockTrace::toString(std::string &result) {
} }
result += "mWaitTimes:\n"; result += "mWaitTimes:\n";
for (std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.begin(); for (std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.begin(); it != mWaitTimes.end(); it++) {
it != mWaitTimes.end(); it++) {
char pointerBuf[TEMP_PAIR_LEN] = {0}; char pointerBuf[TEMP_PAIR_LEN] = {0};
snprintf(pointerBuf, TEMP_PAIR_LEN, ",mutex:%p, times:%d\n", it->first, snprintf(pointerBuf, TEMP_PAIR_LEN, ",mutex:%p, times:%d\n", it->first, it->second);
it->second);
result += pointerBuf; result += pointerBuf;
} }
result += "mWaitLocks:\n"; result += "mWaitLocks:\n";
for (std::map<long long, pthread_mutex_t *>::iterator it = mWaitLocks.begin(); for (std::map<long long, pthread_mutex_t *>::iterator it = mWaitLocks.begin(); it != mWaitLocks.end(); it++) {
it != mWaitLocks.end(); it++) {
char pointerBuf[TEMP_PAIR_LEN] = {0}; char pointerBuf[TEMP_PAIR_LEN] = {0};
snprintf(pointerBuf, TEMP_PAIR_LEN, snprintf(pointerBuf,
TEMP_PAIR_LEN,
"threadID: %llx" "threadID: %llx"
", mutex:%p\n", ", mutex:%p\n",
it->first, it->second); it->first,
it->second);
result += pointerBuf; result += pointerBuf;
} }
// pthread_mutex_unlock(&mMapMutex); // pthread_mutex_unlock(&mMapMutex);
...@@ -246,4 +258,4 @@ void LockTrace::toString(std::string &result) { ...@@ -246,4 +258,4 @@ void LockTrace::toString(std::string &result) {
return; return;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -31,29 +31,26 @@ namespace common { ...@@ -31,29 +31,26 @@ namespace common {
#define MUTEX_LOG LOG_DEBUG #define MUTEX_LOG LOG_DEBUG
class LockTrace { class LockTrace {
public: public:
static void check(pthread_mutex_t *mutex, const long long threadId, static void check(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
const char *file, const int line); static void lock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
static void lock(pthread_mutex_t *mutex, const long long threadId, static void tryLock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
const char *file, const int line); static void unlock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
static void tryLock(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line);
static void unlock(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line);
static void toString(std::string &result); static void toString(std::string &result);
class LockID { class LockID {
public: public:
LockID(const long long threadId, const char *file, const int line) LockID(const long long threadId, const char *file, const int line) : mFile(file), mThreadId(threadId), mLine(line)
: mFile(file), mThreadId(threadId), mLine(line) {} {}
LockID() : mFile(), mThreadId(0), mLine(0) {} LockID() : mFile(), mThreadId(0), mLine(0)
{}
std::string toString() { std::string toString()
{
std::ostringstream oss; std::ostringstream oss;
oss << "threaId:" << mThreadId << ",file name:" << mFile oss << "threaId:" << mThreadId << ",file name:" << mFile << ",line:" << mLine;
<< ",line:" << mLine;
return oss.str(); return oss.str();
} }
...@@ -64,28 +61,25 @@ class LockTrace { ...@@ -64,28 +61,25 @@ class LockTrace {
int mLine; int mLine;
}; };
static void foundDeadLock(LockID &current, LockID &other, static void foundDeadLock(LockID &current, LockID &other, pthread_mutex_t *otherWaitMutex);
pthread_mutex_t *otherWaitMutex);
static bool deadlockCheck(LockID &current, static bool deadlockCheck(LockID &current, std::set<pthread_mutex_t *> &ownMutexs, LockID &other, int recusiveNum);
std::set<pthread_mutex_t *> &ownMutexs,
LockID &other, int recusiveNum);
static bool deadlockCheck(pthread_mutex_t *mutex, const long long threadId, static bool deadlockCheck(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
const char *file, const int line);
static bool checkLockTimes(pthread_mutex_t *mutex, const char *file, static bool checkLockTimes(pthread_mutex_t *mutex, const char *file, const int line);
const int line);
static void insertLock(pthread_mutex_t *mutex, const long long threadId, static void insertLock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
const char *file, const int line);
static void setMaxBlockThreads(int blockNum) { mMaxBlockTids = blockNum; } static void setMaxBlockThreads(int blockNum)
{
mMaxBlockTids = blockNum;
}
public: public:
static std::set<pthread_mutex_t *> mEnableRecurisives; static std::set<pthread_mutex_t *> mEnableRecurisives;
protected: protected:
static std::map<pthread_mutex_t *, LockID> mLocks; static std::map<pthread_mutex_t *, LockID> mLocks;
static std::map<pthread_mutex_t *, int> mWaitTimes; static std::map<pthread_mutex_t *, int> mWaitTimes;
static std::map<long long, pthread_mutex_t *> mWaitLocks; static std::map<long long, pthread_mutex_t *> mWaitLocks;
...@@ -108,14 +102,12 @@ class LockTrace { ...@@ -108,14 +102,12 @@ class LockTrace {
#define COND_INIT(cond, attr) pthread_cond_init(cond, attr) #define COND_INIT(cond, attr) pthread_cond_init(cond, attr)
#define COND_DESTROY(cond) pthread_cond_destroy(cond) #define COND_DESTROY(cond) pthread_cond_destroy(cond)
#define COND_WAIT(cond, mutex) pthread_cond_wait(cond, mutex) #define COND_WAIT(cond, mutex) pthread_cond_wait(cond, mutex)
#define COND_WAIT_TIMEOUT(cond, mutex, time, ret) \ #define COND_WAIT_TIMEOUT(cond, mutex, time, ret) ret = pthread_cond_timedwait(cond, mutex, time)
ret = pthread_cond_timedwait(cond, mutex, time)
#define COND_SIGNAL(cond) pthread_cond_signal(cond) #define COND_SIGNAL(cond) pthread_cond_signal(cond)
#define COND_BRAODCAST(cond) pthread_cond_broadcast(cond) #define COND_BRAODCAST(cond) pthread_cond_broadcast(cond)
#else // DEBUG_LOCK #else // DEBUG_LOCK
#define MUTEX_STATIC_INIT() \ #define MUTEX_STATIC_INIT() \
PTHREAD_MUTEX_INITIALIZER; \ PTHREAD_MUTEX_INITIALIZER; \
LOG_INFO("PTHREAD_MUTEX_INITIALIZER"); LOG_INFO("PTHREAD_MUTEX_INITIALIZER");
...@@ -188,8 +180,7 @@ class LockTrace { ...@@ -188,8 +180,7 @@ class LockTrace {
LockTrace::unlock(lock, gettid(), __FILE__, __LINE__); \ LockTrace::unlock(lock, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("mutex:%p has been ulocked", lock); \ MUTEX_LOG("mutex:%p has been ulocked", lock); \
if (result) { \ if (result) { \
LOG_ERROR("Failed to unlock %p, rc %d:%s", lock, errno, \ LOG_ERROR("Failed to unlock %p, rc %d:%s", lock, errno, strerror(errno)); \
strerror(errno)); \
} \ } \
result; \ result; \
}) })
...@@ -248,5 +239,5 @@ class LockTrace { ...@@ -248,5 +239,5 @@ class LockTrace {
#endif // DEBUG_LOCK #endif // DEBUG_LOCK
} //namespace common } // namespace common
#endif // __COMMON_LANG_MUTEX_H__ #endif // __COMMON_LANG_MUTEX_H__
...@@ -21,11 +21,7 @@ namespace common { ...@@ -21,11 +21,7 @@ namespace common {
/** /**
* Through this type to determine object type * Through this type to determine object type
*/ */
enum { enum { MESSAGE_BASIC = 100, MESSAGE_BASIC_REQUEST = 1000, MESSAGE_BASIC_RESPONSE = -1000 };
MESSAGE_BASIC = 100,
MESSAGE_BASIC_REQUEST = 1000,
MESSAGE_BASIC_RESPONSE = -1000
};
class Deserializable { class Deserializable {
public: public:
...@@ -68,5 +64,5 @@ public: ...@@ -68,5 +64,5 @@ public:
virtual void to_string(std::string &output) const = 0; virtual void to_string(std::string &output) const = 0;
}; };
} //namespace common } // namespace common
#endif /* __COMMON_LANG_SERIALIZABLE_H__ */ #endif /* __COMMON_LANG_SERIALIZABLE_H__ */
...@@ -28,8 +28,9 @@ See the Mulan PSL v2 for more details. */ ...@@ -28,8 +28,9 @@ See the Mulan PSL v2 for more details. */
#include "common/log/log.h" #include "common/log/log.h"
namespace common { namespace common {
char *strip(char *str_) { char *strip(char *str_)
if (str_ == NULL || *str_ == 0){ {
if (str_ == NULL || *str_ == 0) {
LOG_ERROR("The augument is invalid!"); LOG_ERROR("The augument is invalid!");
return str_; return str_;
} }
...@@ -45,7 +46,8 @@ char *strip(char *str_) { ...@@ -45,7 +46,8 @@ char *strip(char *str_) {
return head; return head;
} }
void strip(std::string &str) { void strip(std::string &str)
{
size_t head = 0; size_t head = 0;
while (isspace(str[head])) { while (isspace(str[head])) {
...@@ -61,24 +63,27 @@ void strip(std::string &str) { ...@@ -61,24 +63,27 @@ void strip(std::string &str) {
} }
// Translation functions with templates are defined in the header file // Translation functions with templates are defined in the header file
std::string size_to_pad_str(int size, int pad) { std::string size_to_pad_str(int size, int pad)
{
std::ostringstream ss; std::ostringstream ss;
ss << std::setw(pad) << std::setfill('0') << size; ss << std::setw(pad) << std::setfill('0') << size;
return ss.str(); return ss.str();
} }
std::string &str_to_upper(std::string &s) { std::string &str_to_upper(std::string &s)
{
std::transform(s.begin(), s.end(), s.begin(), (int (*)(int)) & std::toupper); std::transform(s.begin(), s.end(), s.begin(), (int (*)(int)) & std::toupper);
return s; return s;
} }
std::string &str_to_lower(std::string &s) { std::string &str_to_lower(std::string &s)
{
std::transform(s.begin(), s.end(), s.begin(), (int (*)(int)) & std::tolower); std::transform(s.begin(), s.end(), s.begin(), (int (*)(int)) & std::tolower);
return s; return s;
} }
void split_string(const std::string &str, std::string delim, void split_string(const std::string &str, std::string delim, std::set<std::string> &results)
std::set<std::string> &results) { {
int cut_at; int cut_at;
std::string tmp_str(str); std::string tmp_str(str);
while ((cut_at = tmp_str.find_first_of(delim)) != (signed)tmp_str.npos) { while ((cut_at = tmp_str.find_first_of(delim)) != (signed)tmp_str.npos) {
...@@ -93,8 +98,8 @@ void split_string(const std::string &str, std::string delim, ...@@ -93,8 +98,8 @@ void split_string(const std::string &str, std::string delim,
} }
} }
void split_string(const std::string &str, std::string delim, void split_string(const std::string &str, std::string delim, std::vector<std::string> &results)
std::vector<std::string> &results) { {
int cut_at; int cut_at;
std::string tmp_str(str); std::string tmp_str(str);
while ((cut_at = tmp_str.find_first_of(delim)) != (signed)tmp_str.npos) { while ((cut_at = tmp_str.find_first_of(delim)) != (signed)tmp_str.npos) {
...@@ -109,8 +114,8 @@ void split_string(const std::string &str, std::string delim, ...@@ -109,8 +114,8 @@ void split_string(const std::string &str, std::string delim,
} }
} }
void split_string(char *str, char dim, std::vector<char *> &results, void split_string(char *str, char dim, std::vector<char *> &results, bool keep_null)
bool keep_null) { {
char *p = str; char *p = str;
char *l = p; char *l = p;
while (*p) { while (*p) {
...@@ -127,11 +132,11 @@ void split_string(char *str, char dim, std::vector<char *> &results, ...@@ -127,11 +132,11 @@ void split_string(char *str, char dim, std::vector<char *> &results,
return; return;
} }
void merge_string(std::string &str, std::string delim, void merge_string(std::string &str, std::string delim, std::vector<std::string> &source, size_t result_len)
std::vector<std::string> &source, size_t result_len){ {
std::ostringstream ss; std::ostringstream ss;
if (source.empty() ) { if (source.empty()) {
str = ss.str(); str = ss.str();
return; return;
} }
...@@ -143,18 +148,17 @@ void merge_string(std::string &str, std::string delim, ...@@ -143,18 +148,17 @@ void merge_string(std::string &str, std::string delim,
for (unsigned int i = 0; i < result_len; i++) { for (unsigned int i = 0; i < result_len; i++) {
if (i == 0) { if (i == 0) {
ss << source[i]; ss << source[i];
}else { } else {
ss << delim << source[i]; ss << delim << source[i];
} }
} }
str = ss.str(); str = ss.str();
return ; return;
} }
void replace(std::string &str, const std::string &old, void replace(std::string &str, const std::string &old, const std::string &new_str)
const std::string &new_str) { {
if (old.compare(new_str) == 0) { if (old.compare(new_str) == 0) {
return; return;
} }
...@@ -185,7 +189,8 @@ void replace(std::string &str, const std::string &old, ...@@ -185,7 +189,8 @@ void replace(std::string &str, const std::string &old,
return; return;
} }
char *bin_to_hex(const char *s, const int len, char *hex_buff) { char *bin_to_hex(const char *s, const int len, char *hex_buff)
{
int new_len = 0; int new_len = 0;
unsigned char *end = (unsigned char *)s + len; unsigned char *end = (unsigned char *)s + len;
for (unsigned char *p = (unsigned char *)s; p < end; p++) { for (unsigned char *p = (unsigned char *)s; p < end; p++) {
...@@ -196,7 +201,8 @@ char *bin_to_hex(const char *s, const int len, char *hex_buff) { ...@@ -196,7 +201,8 @@ char *bin_to_hex(const char *s, const int len, char *hex_buff) {
return hex_buff; return hex_buff;
} }
char *hex_to_bin(const char *s, char *bin_buff, int *dest_len) { char *hex_to_bin(const char *s, char *bin_buff, int *dest_len)
{
char buff[3]; char buff[3];
char *src; char *src;
int src_len; int src_len;
...@@ -225,7 +231,8 @@ char *hex_to_bin(const char *s, char *bin_buff, int *dest_len) { ...@@ -225,7 +231,8 @@ char *hex_to_bin(const char *s, char *bin_buff, int *dest_len) {
return bin_buff; return bin_buff;
} }
bool is_blank(const char *s) { bool is_blank(const char *s)
{
if (s == nullptr) { if (s == nullptr) {
return true; return true;
} }
...@@ -238,4 +245,4 @@ bool is_blank(const char *s) { ...@@ -238,4 +245,4 @@ bool is_blank(const char *s) {
return true; return true;
} }
} //namespace common } // namespace common
...@@ -65,20 +65,15 @@ std::string &str_to_lower(std::string &s); ...@@ -65,20 +65,15 @@ std::string &str_to_lower(std::string &s);
* @param[in] delims elimiter characters * @param[in] delims elimiter characters
* @param[in,out] results ector containing the split up string * @param[in,out] results ector containing the split up string
*/ */
void split_string(const std::string &str, std::string delim, void split_string(const std::string &str, std::string delim, std::set<std::string> &results);
std::set<std::string> &results); void split_string(const std::string &str, std::string delim, std::vector<std::string> &results);
void split_string(const std::string &str, std::string delim, void split_string(char *str, char dim, std::vector<char *> &results, bool keep_null = false);
std::vector<std::string> &results);
void split_string(char *str, char dim, std::vector<char *> &results, void merge_string(std::string &str, std::string delim, std::vector<std::string> &result, size_t result_len = 0);
bool keep_null = false);
void merge_string(std::string &str, std::string delim,
std::vector<std::string> &result, size_t result_len = 0);
/** /**
* replace old with new in the string * replace old with new in the string
*/ */
void replace(std::string &str, const std::string &old, void replace(std::string &str, const std::string &old, const std::string &new_str);
const std::string &new_str);
/** /**
* binary to hexadecimal * binary to hexadecimal
...@@ -102,8 +97,7 @@ char *hex_to_bin(const char *s, char *bin_buff, int *dest_len); ...@@ -102,8 +97,7 @@ char *hex_to_bin(const char *s, char *bin_buff, int *dest_len);
* number, \c false otherwise * number, \c false otherwise
*/ */
template <class T> template <class T>
bool str_to_val(const std::string &str, T &val, bool str_to_val(const std::string &str, T &val, std::ios_base &(*radix)(std::ios_base &) = std::dec);
std::ios_base &(*radix)(std::ios_base &) = std::dec);
/** /**
* Convert a numeric value into its string representation * Convert a numeric value into its string representation
...@@ -116,17 +110,17 @@ bool str_to_val(const std::string &str, T &val, ...@@ -116,17 +110,17 @@ bool str_to_val(const std::string &str, T &val,
* (hexidecimal). * (hexidecimal).
*/ */
template <class T> template <class T>
void val_to_str(const T &val, std::string &str, void val_to_str(const T &val, std::string &str, std::ios_base &(*radix)(std::ios_base &) = std::dec);
std::ios_base &(*radix)(std::ios_base &) = std::dec);
/** /**
* get type's name * get type's name
*/ */
template <class T> std::string get_type_name(const T &val); template <class T>
std::string get_type_name(const T &val);
template <class T> template <class T>
bool str_to_val(const std::string &str, T &val, bool str_to_val(const std::string &str, T &val, std::ios_base &(*radix)(std::ios_base &)/* = std::dec */)
std::ios_base &(*radix)(std::ios_base &)/* = std::dec */) { {
bool success = true; bool success = true;
std::istringstream is(str); std::istringstream is(str);
if (!(is >> radix >> val)) { if (!(is >> radix >> val)) {
...@@ -137,14 +131,16 @@ bool str_to_val(const std::string &str, T &val, ...@@ -137,14 +131,16 @@ bool str_to_val(const std::string &str, T &val,
} }
template <class T> template <class T>
void val_to_str(const T &val, std::string &str, void val_to_str(const T &val, std::string &str, std::ios_base &(*radix)(std::ios_base &)/* = std::dec */)
std::ios_base &(*radix)(std::ios_base &)/* = std::dec */) { {
std::stringstream strm; std::stringstream strm;
strm << radix << val; strm << radix << val;
str = strm.str(); str = strm.str();
} }
template <class T> std::string get_type_name(const T &val) { template <class T>
std::string get_type_name(const T &val)
{
int status = 0; int status = 0;
char *stmp = abi::__cxa_demangle(typeid(val).name(), 0, 0, &status); char *stmp = abi::__cxa_demangle(typeid(val).name(), 0, 0, &status);
if (!stmp) if (!stmp)
...@@ -158,5 +154,5 @@ template <class T> std::string get_type_name(const T &val) { ...@@ -158,5 +154,5 @@ template <class T> std::string get_type_name(const T &val) {
bool is_blank(const char *s); bool is_blank(const char *s);
} //namespace common } // namespace common
#endif // __COMMON_LANG_STRING_H__ #endif // __COMMON_LANG_STRING_H__
...@@ -23,9 +23,9 @@ namespace common { ...@@ -23,9 +23,9 @@ namespace common {
Log *g_log = nullptr; Log *g_log = nullptr;
Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level, Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level, const LOG_LEVEL console_level)
const LOG_LEVEL console_level) : log_name_(log_file_name), log_level_(log_level), console_level_(console_level)
: log_name_(log_file_name), log_level_(log_level), console_level_(console_level) { {
prefix_map_[LOG_LEVEL_PANIC] = "PANIC:"; prefix_map_[LOG_LEVEL_PANIC] = "PANIC:";
prefix_map_[LOG_LEVEL_ERR] = "ERROR:"; prefix_map_[LOG_LEVEL_ERR] = "ERROR:";
prefix_map_[LOG_LEVEL_WARN] = "WARNNING:"; prefix_map_[LOG_LEVEL_WARN] = "WARNNING:";
...@@ -45,7 +45,8 @@ Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level, ...@@ -45,7 +45,8 @@ Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level,
check_param_valid(); check_param_valid();
} }
Log::~Log(void) { Log::~Log(void)
{
pthread_mutex_lock(&lock_); pthread_mutex_lock(&lock_);
if (ofs_.is_open()) { if (ofs_.is_open()) {
ofs_.close(); ofs_.close();
...@@ -55,7 +56,8 @@ Log::~Log(void) { ...@@ -55,7 +56,8 @@ Log::~Log(void) {
pthread_mutex_destroy(&lock_); pthread_mutex_destroy(&lock_);
} }
void Log::check_param_valid() { void Log::check_param_valid()
{
assert(!log_name_.empty()); assert(!log_name_.empty());
assert(LOG_LEVEL_PANIC <= log_level_ && log_level_ < LOG_LEVEL_LAST); assert(LOG_LEVEL_PANIC <= log_level_ && log_level_ < LOG_LEVEL_LAST);
assert(LOG_LEVEL_PANIC <= console_level_ && console_level_ < LOG_LEVEL_LAST); assert(LOG_LEVEL_PANIC <= console_level_ && console_level_ < LOG_LEVEL_LAST);
...@@ -63,7 +65,8 @@ void Log::check_param_valid() { ...@@ -63,7 +65,8 @@ void Log::check_param_valid() {
return; return;
} }
bool Log::check_output(const LOG_LEVEL level, const char *module) { bool Log::check_output(const LOG_LEVEL level, const char *module)
{
if (LOG_LEVEL_LAST > level && level <= console_level_) { if (LOG_LEVEL_LAST > level && level <= console_level_) {
return true; return true;
} }
...@@ -77,8 +80,8 @@ bool Log::check_output(const LOG_LEVEL level, const char *module) { ...@@ -77,8 +80,8 @@ bool Log::check_output(const LOG_LEVEL level, const char *module) {
return false; return false;
} }
int Log::output(const LOG_LEVEL level, const char *module, const char *prefix, int Log::output(const LOG_LEVEL level, const char *module, const char *prefix, const char *f, ...)
const char *f, ...) { {
bool locked = false; bool locked = false;
try { try {
va_list args; va_list args;
...@@ -127,7 +130,8 @@ int Log::output(const LOG_LEVEL level, const char *module, const char *prefix, ...@@ -127,7 +130,8 @@ int Log::output(const LOG_LEVEL level, const char *module, const char *prefix,
return LOG_STATUS_OK; return LOG_STATUS_OK;
} }
int Log::set_console_level(LOG_LEVEL console_level) { int Log::set_console_level(LOG_LEVEL console_level)
{
if (LOG_LEVEL_PANIC <= console_level && console_level < LOG_LEVEL_LAST) { if (LOG_LEVEL_PANIC <= console_level && console_level < LOG_LEVEL_LAST) {
console_level_ = console_level; console_level_ = console_level;
return LOG_STATUS_OK; return LOG_STATUS_OK;
...@@ -136,9 +140,13 @@ int Log::set_console_level(LOG_LEVEL console_level) { ...@@ -136,9 +140,13 @@ int Log::set_console_level(LOG_LEVEL console_level) {
return LOG_STATUS_ERR; return LOG_STATUS_ERR;
} }
LOG_LEVEL Log::get_console_level() { return console_level_; } LOG_LEVEL Log::get_console_level()
{
return console_level_;
}
int Log::set_log_level(LOG_LEVEL log_level) { int Log::set_log_level(LOG_LEVEL log_level)
{
if (LOG_LEVEL_PANIC <= log_level && log_level < LOG_LEVEL_LAST) { if (LOG_LEVEL_PANIC <= log_level && log_level < LOG_LEVEL_LAST) {
log_level_ = log_level; log_level_ = log_level;
return LOG_STATUS_OK; return LOG_STATUS_OK;
...@@ -147,9 +155,13 @@ int Log::set_log_level(LOG_LEVEL log_level) { ...@@ -147,9 +155,13 @@ int Log::set_log_level(LOG_LEVEL log_level) {
return LOG_STATUS_ERR; return LOG_STATUS_ERR;
} }
LOG_LEVEL Log::get_log_level() { return log_level_; } LOG_LEVEL Log::get_log_level()
{
return log_level_;
}
const char *Log::prefix_msg(LOG_LEVEL level) { const char *Log::prefix_msg(LOG_LEVEL level)
{
if (LOG_LEVEL_PANIC <= level && level < LOG_LEVEL_LAST) { if (LOG_LEVEL_PANIC <= level && level < LOG_LEVEL_LAST) {
return prefix_map_[level].c_str(); return prefix_map_[level].c_str();
} }
...@@ -157,22 +169,27 @@ const char *Log::prefix_msg(LOG_LEVEL level) { ...@@ -157,22 +169,27 @@ const char *Log::prefix_msg(LOG_LEVEL level) {
return empty_prefix; return empty_prefix;
} }
void Log::set_default_module(const std::string &modules) { void Log::set_default_module(const std::string &modules)
{
split_string(modules, ",", default_set_); split_string(modules, ",", default_set_);
} }
int Log::set_rotate_type(LOG_ROTATE rotate_type) { int Log::set_rotate_type(LOG_ROTATE rotate_type)
{
if (LOG_ROTATE_BYDAY <= rotate_type && rotate_type < LOG_ROTATE_LAST) { if (LOG_ROTATE_BYDAY <= rotate_type && rotate_type < LOG_ROTATE_LAST) {
rotate_type_ = rotate_type; rotate_type_ = rotate_type;
} }
return LOG_STATUS_OK; return LOG_STATUS_OK;
} }
LOG_ROTATE Log::get_rotate_type() { return rotate_type_; } LOG_ROTATE Log::get_rotate_type()
{
return rotate_type_;
}
int Log::rotate_by_day(const int year, const int month, const int day) { int Log::rotate_by_day(const int year, const int month, const int day)
if (log_date_.year_ == year && log_date_.mon_ == month && {
log_date_.day_ == day) { if (log_date_.year_ == year && log_date_.mon_ == month && log_date_.day_ == day) {
// Don't need rotate // Don't need rotate
return 0; return 0;
} }
...@@ -196,7 +213,8 @@ int Log::rotate_by_day(const int year, const int month, const int day) { ...@@ -196,7 +213,8 @@ int Log::rotate_by_day(const int year, const int month, const int day) {
return 0; return 0;
} }
int Log::rename_old_logs() { int Log::rename_old_logs()
{
int log_index = 1; int log_index = 1;
int max_log_index = 0; int max_log_index = 0;
char log_index_str[4] = {0}; char log_index_str[4] = {0};
...@@ -234,7 +252,8 @@ int Log::rename_old_logs() { ...@@ -234,7 +252,8 @@ int Log::rename_old_logs() {
return LOG_STATUS_OK; return LOG_STATUS_OK;
} }
int Log::rotate_by_size() { int Log::rotate_by_size()
{
if (log_line_ < 0) { if (log_line_ < 0) {
// The first time open log file // The first time open log file
ofs_.open(log_name_.c_str(), std::ios_base::out | std::ios_base::app); ofs_.open(log_name_.c_str(), std::ios_base::out | std::ios_base::app);
...@@ -260,8 +279,7 @@ int Log::rotate_by_size() { ...@@ -260,8 +279,7 @@ int Log::rotate_by_size() {
std::string log_name_new = log_name_ + "." + log_index_str; std::string log_name_new = log_name_ + "." + log_index_str;
result = rename(log_name_.c_str(), log_name_new.c_str()); result = rename(log_name_.c_str(), log_name_new.c_str());
if (result) { if (result) {
std::cerr << "Failed to rename " << log_name_ << " to " << log_name_new std::cerr << "Failed to rename " << log_name_ << " to " << log_name_new << std::endl;
<< std::endl;
} }
ofs_.open(log_name_.c_str(), std::ios_base::out | std::ios_base::app); ofs_.open(log_name_.c_str(), std::ios_base::out | std::ios_base::app);
...@@ -278,7 +296,8 @@ int Log::rotate_by_size() { ...@@ -278,7 +296,8 @@ int Log::rotate_by_size() {
return LOG_STATUS_OK; return LOG_STATUS_OK;
} }
int Log::rotate(const int year, const int month, const int day) { int Log::rotate(const int year, const int month, const int day)
{
int result = 0; int result = 0;
pthread_mutex_lock(&lock_); pthread_mutex_lock(&lock_);
if (rotate_type_ == LOG_ROTATE_BYDAY) { if (rotate_type_ == LOG_ROTATE_BYDAY) {
...@@ -291,17 +310,19 @@ int Log::rotate(const int year, const int month, const int day) { ...@@ -291,17 +310,19 @@ int Log::rotate(const int year, const int month, const int day) {
return result; return result;
} }
LoggerFactory::LoggerFactory() { LoggerFactory::LoggerFactory()
{
// Auto-generated constructor stub // Auto-generated constructor stub
} }
LoggerFactory::~LoggerFactory() { LoggerFactory::~LoggerFactory()
{
// Auto-generated destructor stub // Auto-generated destructor stub
} }
int LoggerFactory::init(const std::string &log_file, Log **logger, int LoggerFactory::init(
LOG_LEVEL log_level, LOG_LEVEL console_level, const std::string &log_file, Log **logger, LOG_LEVEL log_level, LOG_LEVEL console_level, LOG_ROTATE rotate_type)
LOG_ROTATE rotate_type) { {
Log *log = new (std::nothrow) Log(log_file, log_level, console_level); Log *log = new (std::nothrow) Log(log_file, log_level, console_level);
if (log == nullptr) { if (log == nullptr) {
std::cout << "Error: fail to construct a log object!" << std::endl; std::cout << "Error: fail to construct a log object!" << std::endl;
...@@ -314,8 +335,9 @@ int LoggerFactory::init(const std::string &log_file, Log **logger, ...@@ -314,8 +335,9 @@ int LoggerFactory::init(const std::string &log_file, Log **logger,
return 0; return 0;
} }
int LoggerFactory::init_default(const std::string &log_file, LOG_LEVEL log_level, int LoggerFactory::init_default(
LOG_LEVEL console_level, LOG_ROTATE rotate_type) { const std::string &log_file, LOG_LEVEL log_level, LOG_LEVEL console_level, LOG_ROTATE rotate_type)
{
if (g_log != nullptr) { if (g_log != nullptr) {
LOG_WARN("Default logger has been initialized"); LOG_WARN("Default logger has been initialized");
return 0; return 0;
...@@ -324,4 +346,4 @@ int LoggerFactory::init_default(const std::string &log_file, LOG_LEVEL log_level ...@@ -324,4 +346,4 @@ int LoggerFactory::init_default(const std::string &log_file, LOG_LEVEL log_level
return init(log_file, &g_log, log_level, console_level, rotate_type); return init(log_file, &g_log, log_level, console_level, rotate_type);
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -45,14 +45,10 @@ typedef enum { ...@@ -45,14 +45,10 @@ typedef enum {
LOG_LEVEL_LAST LOG_LEVEL_LAST
} LOG_LEVEL; } LOG_LEVEL;
typedef enum { typedef enum { LOG_ROTATE_BYDAY = 0, LOG_ROTATE_BYSIZE, LOG_ROTATE_LAST } LOG_ROTATE;
LOG_ROTATE_BYDAY = 0,
LOG_ROTATE_BYSIZE,
LOG_ROTATE_LAST
} LOG_ROTATE;
class Log { class Log {
public: public:
Log(const std::string &log_name, const LOG_LEVEL log_level = LOG_LEVEL_INFO, Log(const std::string &log_name, const LOG_LEVEL log_level = LOG_LEVEL_INFO,
const LOG_LEVEL console_level = LOG_LEVEL_WARN); const LOG_LEVEL console_level = LOG_LEVEL_WARN);
~Log(void); ~Log(void);
...@@ -65,29 +61,28 @@ class Log { ...@@ -65,29 +61,28 @@ class Log {
* If the header information should be outputed * If the header information should be outputed
* please use LOG_PANIC, LOG_ERROR ... * please use LOG_PANIC, LOG_ERROR ...
*/ */
template<class T> template <class T>
Log &operator<<(T message); Log &operator<<(T message);
template<class T> template <class T>
int panic(T message); int panic(T message);
template<class T> template <class T>
int error(T message); int error(T message);
template<class T> template <class T>
int warnning(T message); int warnning(T message);
template<class T> template <class T>
int info(T message); int info(T message);
template<class T> template <class T>
int debug(T message); int debug(T message);
template<class T> template <class T>
int trace(T message); int trace(T message);
int output(const LOG_LEVEL level, const char *module, const char *prefix, int output(const LOG_LEVEL level, const char *module, const char *prefix, const char *f, ...);
const char *f, ...);
int set_console_level(const LOG_LEVEL console_level); int set_console_level(const LOG_LEVEL console_level);
LOG_LEVEL get_console_level(); LOG_LEVEL get_console_level();
...@@ -110,17 +105,17 @@ class Log { ...@@ -110,17 +105,17 @@ class Log {
int rotate(const int year = 0, const int month = 0, const int day = 0); int rotate(const int year = 0, const int month = 0, const int day = 0);
private: private:
void check_param_valid(); void check_param_valid();
int rotate_by_size(); int rotate_by_size();
int rename_old_logs(); int rename_old_logs();
int rotate_by_day(const int year, const int month, const int day); int rotate_by_day(const int year, const int month, const int day);
template<class T> template <class T>
int out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &message); int out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &message);
private: private:
pthread_mutex_t lock_; pthread_mutex_t lock_;
std::ofstream ofs_; std::ofstream ofs_;
std::string log_name_; std::string log_name_;
...@@ -145,28 +140,23 @@ class Log { ...@@ -145,28 +140,23 @@ class Log {
}; };
class LoggerFactory { class LoggerFactory {
public: public:
LoggerFactory(); LoggerFactory();
virtual ~LoggerFactory(); virtual ~LoggerFactory();
static int init(const std::string &log_file, Log **logger, static int init(const std::string &log_file, Log **logger, LOG_LEVEL log_level = LOG_LEVEL_INFO,
LOG_LEVEL log_level = LOG_LEVEL_INFO, LOG_LEVEL console_level = LOG_LEVEL_WARN, LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
LOG_LEVEL console_level = LOG_LEVEL_WARN,
LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
static int init_default(const std::string &log_file, static int init_default(const std::string &log_file, LOG_LEVEL log_level = LOG_LEVEL_INFO,
LOG_LEVEL log_level = LOG_LEVEL_INFO, LOG_LEVEL console_level = LOG_LEVEL_WARN, LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
LOG_LEVEL console_level = LOG_LEVEL_WARN,
LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
}; };
extern Log *g_log; extern Log *g_log;
#ifndef __FILE_NAME__ #ifndef __FILE_NAME__
#define __FILE_NAME__ (strrchr(__FILE__,'/')?strrchr(__FILE__,'/')+1:__FILE__) #define __FILE_NAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#endif #endif
#define LOG_HEAD(prefix, level) \ #define LOG_HEAD(prefix, level) \
if (common::g_log) { \ if (common::g_log) { \
time_t now_time; \ time_t now_time; \
...@@ -174,14 +164,26 @@ extern Log *g_log; ...@@ -174,14 +164,26 @@ extern Log *g_log;
struct tm *p = localtime(&now_time); \ struct tm *p = localtime(&now_time); \
char sz_head[64] = {0}; \ char sz_head[64] = {0}; \
if (p) { \ if (p) { \
sprintf(sz_head, "%d-%d-%d %d:%d:%u pid:%u tid:%llx ", p->tm_year + 1900, \ sprintf(sz_head, \
p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, \ "%d-%d-%d %d:%d:%u pid:%u tid:%llx ", \
(u32_t)getpid(), gettid()); \ p->tm_year + 1900, \
p->tm_mon + 1, \
p->tm_mday, \
p->tm_hour, \
p->tm_min, \
p->tm_sec, \
(u32_t)getpid(), \
gettid()); \
common::g_log->rotate(p->tm_year + 1900, p->tm_mon + 1, p->tm_mday); \ common::g_log->rotate(p->tm_year + 1900, p->tm_mon + 1, p->tm_mday); \
} \ } \
snprintf(prefix, sizeof(prefix), "[%s %s %s %s %u]>>", sz_head, \ snprintf(prefix, \
(common::g_log)->prefix_msg(level), __FILE_NAME__, \ sizeof(prefix), \
__FUNCTION__, (u32_t)__LINE__); \ "[%s %s %s %s %u]>>", \
sz_head, \
(common::g_log)->prefix_msg(level), \
__FILE_NAME__, \
__FUNCTION__, \
(u32_t)__LINE__); \
} }
#define LOG_OUTPUT(level, fmt, ...) \ #define LOG_OUTPUT(level, fmt, ...) \
...@@ -194,8 +196,7 @@ extern Log *g_log; ...@@ -194,8 +196,7 @@ extern Log *g_log;
} \ } \
} while (0) } while (0)
#define LOG_DEFAULT(fmt, ...) \ #define LOG_DEFAULT(fmt, ...) LOG_OUTPUT(common::g_log->get_log_level(), fmt, ##__VA_ARGS__)
LOG_OUTPUT(common::g_log->get_log_level(), fmt, ##__VA_ARGS__)
#define LOG_PANIC(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_PANIC, fmt, ##__VA_ARGS__) #define LOG_PANIC(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_PANIC, fmt, ##__VA_ARGS__)
#define LOG_ERROR(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_ERR, fmt, ##__VA_ARGS__) #define LOG_ERROR(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_ERR, fmt, ##__VA_ARGS__)
#define LOG_WARN(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_WARN, fmt, ##__VA_ARGS__) #define LOG_WARN(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_WARN, fmt, ##__VA_ARGS__)
...@@ -203,48 +204,56 @@ extern Log *g_log; ...@@ -203,48 +204,56 @@ extern Log *g_log;
#define LOG_DEBUG(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__) #define LOG_DEBUG(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__)
#define LOG_TRACE(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__) #define LOG_TRACE(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__)
template<class T> template <class T>
Log &Log::operator<<(T msg) { Log &Log::operator<<(T msg)
{
// at this time, the input level is the default log level // at this time, the input level is the default log level
out(console_level_, log_level_, msg); out(console_level_, log_level_, msg);
return *this; return *this;
} }
template<class T> template <class T>
int Log::panic(T message) { int Log::panic(T message)
{
return out(LOG_LEVEL_PANIC, LOG_LEVEL_PANIC, message); return out(LOG_LEVEL_PANIC, LOG_LEVEL_PANIC, message);
} }
template<class T> template <class T>
int Log::error(T message) { int Log::error(T message)
{
return out(LOG_LEVEL_ERR, LOG_LEVEL_ERR, message); return out(LOG_LEVEL_ERR, LOG_LEVEL_ERR, message);
} }
template<class T> template <class T>
int Log::warnning(T message) { int Log::warnning(T message)
{
return out(LOG_LEVEL_WARN, LOG_LEVEL_WARN, message); return out(LOG_LEVEL_WARN, LOG_LEVEL_WARN, message);
} }
template<class T> template <class T>
int Log::info(T message) { int Log::info(T message)
{
return out(LOG_LEVEL_INFO, LOG_LEVEL_INFO, message); return out(LOG_LEVEL_INFO, LOG_LEVEL_INFO, message);
} }
template<class T> template <class T>
int Log::debug(T message) { int Log::debug(T message)
{
return out(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, message); return out(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, message);
} }
template<class T> template <class T>
int Log::trace(T message) { int Log::trace(T message)
{
return out(LOG_LEVEL_TRACE, LOG_LEVEL_TRACE, message); return out(LOG_LEVEL_TRACE, LOG_LEVEL_TRACE, message);
} }
template<class T> template <class T>
int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg) { int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg)
{
bool locked = false; bool locked = false;
if (console_level < LOG_LEVEL_PANIC || console_level > console_level_ || if (console_level < LOG_LEVEL_PANIC || console_level > console_level_ || log_level < LOG_LEVEL_PANIC ||
log_level < LOG_LEVEL_PANIC || log_level > log_level_) { log_level > log_level_) {
return LOG_STATUS_OK; return LOG_STATUS_OK;
} }
try { try {
...@@ -288,9 +297,8 @@ int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg) { ...@@ -288,9 +297,8 @@ int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg) {
} while (0) } while (0)
#endif // ASSERT #endif // ASSERT
#define SYS_OUTPUT_FILE_POS \ #define SYS_OUTPUT_FILE_POS ", File:" << __FILE__ << ", line:" << __LINE__ << ",function:" << __FUNCTION__
", File:" << __FILE__ << ", line:" << __LINE__ << ",function:" << __FUNCTION__
#define SYS_OUTPUT_ERROR ",error:" << errno << ":" << strerror(errno) #define SYS_OUTPUT_ERROR ",error:" << errno << ":" << strerror(errno)
} //namespace common } // namespace common
#endif //__COMMON_LOG_LOG_H__ #endif //__COMMON_LOG_LOG_H__
...@@ -41,10 +41,70 @@ static void Decode(UINT4 *, unsigned char *, unsigned int); ...@@ -41,10 +41,70 @@ static void Decode(UINT4 *, unsigned char *, unsigned int);
static void MD5_memcpy(POINTER, POINTER, unsigned int); static void MD5_memcpy(POINTER, POINTER, unsigned int);
static void MD5_memset(POINTER, int, unsigned int); static void MD5_memset(POINTER, int, unsigned int);
static unsigned char PADDING[64] = { static unsigned char PADDING[64] = {0x80,
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0};
/* /*
* F, G, H and I are basic MD5 functions. * F, G, H and I are basic MD5 functions.
...@@ -91,7 +151,8 @@ static unsigned char PADDING[64] = { ...@@ -91,7 +151,8 @@ static unsigned char PADDING[64] = {
/* /*
* MD5 initialization. Begins an MD5 operation, writing a new context. * MD5 initialization. Begins an MD5 operation, writing a new context.
*/ */
void MD5Init(MD5_CTX *context) { void MD5Init(MD5_CTX *context)
{
context->count[0] = context->count[1] = 0; context->count[0] = context->count[1] = 0;
/* /*
* Load magic initialization constants. * Load magic initialization constants.
...@@ -106,16 +167,17 @@ void MD5Init(MD5_CTX *context) { ...@@ -106,16 +167,17 @@ void MD5Init(MD5_CTX *context) {
* MD5 block update operation. Continues an MD5 message-digest operation, * MD5 block update operation. Continues an MD5 message-digest operation,
* processing another message block, and updating the context. * processing another message block, and updating the context.
*/ */
void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) { void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen)
{
unsigned int i, index, partLen; unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */ /* Compute number of bytes mod 64 */
index = (unsigned int) ((context->count[0] >> 3) & 0x3F); index = (unsigned int)((context->count[0] >> 3) & 0x3F);
/* update number of bits */ /* update number of bits */
if ((context->count[0] += ((UINT4) inputLen << 3)) < ((UINT4) inputLen << 3)) if ((context->count[0] += ((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3))
context->count[1]++; context->count[1]++;
context->count[1] += ((UINT4) inputLen >> 29); context->count[1] += ((UINT4)inputLen >> 29);
partLen = 64 - index; partLen = 64 - index;
...@@ -123,7 +185,7 @@ void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) { ...@@ -123,7 +185,7 @@ void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) {
* Transform as many times as possible. * Transform as many times as possible.
*/ */
if (inputLen >= partLen) { if (inputLen >= partLen) {
MD5_memcpy((POINTER) & context->buffer[index], (POINTER) input, partLen); MD5_memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen);
MD5Transform(context->state, context->buffer); MD5Transform(context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64) for (i = partLen; i + 63 < inputLen; i += 64)
...@@ -134,15 +196,15 @@ void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) { ...@@ -134,15 +196,15 @@ void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) {
i = 0; i = 0;
/* Buffer remaining input */ /* Buffer remaining input */
MD5_memcpy((POINTER) & context->buffer[index], (POINTER) & input[i], MD5_memcpy((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen - i);
inputLen - i);
} }
/* /*
* MD5 finalization. Ends an MD5 message-digest operation, writing the the * MD5 finalization. Ends an MD5 message-digest operation, writing the the
* message digest and zeroizing the context. * message digest and zeroizing the context.
*/ */
void MD5Final(unsigned char digest[16], MD5_CTX *context) { void MD5Final(unsigned char digest[16], MD5_CTX *context)
{
unsigned char bits[8]; unsigned char bits[8];
unsigned int index, padLen; unsigned int index, padLen;
...@@ -152,7 +214,7 @@ void MD5Final(unsigned char digest[16], MD5_CTX *context) { ...@@ -152,7 +214,7 @@ void MD5Final(unsigned char digest[16], MD5_CTX *context) {
/* /*
* Pad out to 56 mod 64. * Pad out to 56 mod 64.
*/ */
index = (unsigned int) ((context->count[0] >> 3) & 0x3f); index = (unsigned int)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index); padLen = (index < 56) ? (56 - index) : (120 - index);
MD5Update(context, PADDING, padLen); MD5Update(context, PADDING, padLen);
...@@ -164,13 +226,14 @@ void MD5Final(unsigned char digest[16], MD5_CTX *context) { ...@@ -164,13 +226,14 @@ void MD5Final(unsigned char digest[16], MD5_CTX *context) {
/* /*
* Zeroize sensitive information. * Zeroize sensitive information.
*/ */
MD5_memset((POINTER) context, 0, sizeof(*context)); MD5_memset((POINTER)context, 0, sizeof(*context));
} }
/* /*
* MD5 basic transformation. Transforms state based on block. * MD5 basic transformation. Transforms state based on block.
*/ */
static void MD5Transform(UINT4 state[4], unsigned char block[64]) { static void MD5Transform(UINT4 state[4], unsigned char block[64])
{
UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode(x, block, 64); Decode(x, block, 64);
...@@ -256,21 +319,22 @@ static void MD5Transform(UINT4 state[4], unsigned char block[64]) { ...@@ -256,21 +319,22 @@ static void MD5Transform(UINT4 state[4], unsigned char block[64]) {
* Zeroize sensitive information. * Zeroize sensitive information.
* *
*/ */
MD5_memset((POINTER) x, 0, sizeof(x)); MD5_memset((POINTER)x, 0, sizeof(x));
} }
/* /*
* Encodes input (UINT4) into output (unsigned char). Assumes len is a * Encodes input (UINT4) into output (unsigned char). Assumes len is a
* multiple of 4. * multiple of 4.
*/ */
static void Encode(unsigned char *output, UINT4 *input, unsigned int len) { static void Encode(unsigned char *output, UINT4 *input, unsigned int len)
{
unsigned int i, j; unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) { for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char) (input[i] & 0xff); output[j] = (unsigned char)(input[i] & 0xff);
output[j + 1] = (unsigned char) ((input[i] >> 8) & 0xff); output[j + 1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j + 2] = (unsigned char) ((input[i] >> 16) & 0xff); output[j + 2] = (unsigned char)((input[i] >> 16) & 0xff);
output[j + 3] = (unsigned char) ((input[i] >> 24) & 0xff); output[j + 3] = (unsigned char)((input[i] >> 24) & 0xff);
} }
} }
...@@ -278,19 +342,21 @@ static void Encode(unsigned char *output, UINT4 *input, unsigned int len) { ...@@ -278,19 +342,21 @@ static void Encode(unsigned char *output, UINT4 *input, unsigned int len) {
* Decodes input (unsigned char) into output (UINT4). Assumes len is a * Decodes input (unsigned char) into output (UINT4). Assumes len is a
* multiple of 4. * multiple of 4.
*/ */
static void Decode(UINT4 *output, unsigned char *input, unsigned int len) { static void Decode(UINT4 *output, unsigned char *input, unsigned int len)
{
unsigned int i, j; unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT4) input[j]) | (((UINT4) input[j + 1]) << 8) | output[i] = ((UINT4)input[j]) | (((UINT4)input[j + 1]) << 8) | (((UINT4)input[j + 2]) << 16) |
(((UINT4) input[j + 2]) << 16) | (((UINT4) input[j + 3]) << 24); (((UINT4)input[j + 3]) << 24);
} }
/* /*
* Note: Replace "for loop" with standard memcpy if possible. * Note: Replace "for loop" with standard memcpy if possible.
*/ */
static void MD5_memcpy(POINTER output, POINTER input, unsigned int len) { static void MD5_memcpy(POINTER output, POINTER input, unsigned int len)
{
unsigned int i; unsigned int i;
for (i = 0; i < len; i++) for (i = 0; i < len; i++)
...@@ -300,36 +366,40 @@ static void MD5_memcpy(POINTER output, POINTER input, unsigned int len) { ...@@ -300,36 +366,40 @@ static void MD5_memcpy(POINTER output, POINTER input, unsigned int len) {
/* /*
* Note: Replace "for loop" with standard memset if possible. * Note: Replace "for loop" with standard memset if possible.
*/ */
static void MD5_memset(POINTER output, int value, unsigned int len) { static void MD5_memset(POINTER output, int value, unsigned int len)
{
unsigned int i; unsigned int i;
for (i = 0; i < len; i++) for (i = 0; i < len; i++)
((char *) output)[i] = (char) value; ((char *)output)[i] = (char)value;
} }
/* /*
* Digests a string * Digests a string
*/ */
int MD5String(char *string, unsigned char digest[16]) { int MD5String(char *string, unsigned char digest[16])
{
MD5_CTX context; MD5_CTX context;
unsigned int len = strlen(string); unsigned int len = strlen(string);
MD5Init(&context); MD5Init(&context);
MD5Update(&context, (unsigned char *) string, len); MD5Update(&context, (unsigned char *)string, len);
MD5Final(digest, &context); MD5Final(digest, &context);
return 0; return 0;
} }
int MD5Buffer(char *buffer, unsigned int len, unsigned char digest[16]) { int MD5Buffer(char *buffer, unsigned int len, unsigned char digest[16])
{
MD5_CTX context; MD5_CTX context;
MD5Init(&context); MD5Init(&context);
MD5Update(&context, (unsigned char *) buffer, len); MD5Update(&context, (unsigned char *)buffer, len);
MD5Final(digest, &context); MD5Final(digest, &context);
return 0; return 0;
} }
int MD5File(char *filename, unsigned char digest[16]) { int MD5File(char *filename, unsigned char digest[16])
{
FILE *file; FILE *file;
MD5_CTX context; MD5_CTX context;
int len; int len;
...@@ -349,4 +419,4 @@ int MD5File(char *filename, unsigned char digest[16]) { ...@@ -349,4 +419,4 @@ int MD5File(char *filename, unsigned char digest[16]) {
return 0; return 0;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -66,5 +66,5 @@ void MD5Final(unsigned char[16], MD5_CTX *); ...@@ -66,5 +66,5 @@ void MD5Final(unsigned char[16], MD5_CTX *);
} }
#endif #endif
} //namespace common } // namespace common
#endif //__COMMON_MATH_MD5_H__ #endif //__COMMON_MATH_MD5_H__
...@@ -12,27 +12,26 @@ See the Mulan PSL v2 for more details. */ ...@@ -12,27 +12,26 @@ See the Mulan PSL v2 for more details. */
// Created by Longda on 2021/4/20. // Created by Longda on 2021/4/20.
// //
#include <chrono> #include <chrono>
#include "common/math/random_generator.h" #include "common/math/random_generator.h"
namespace common { namespace common {
RandomGenerator::RandomGenerator() RandomGenerator::RandomGenerator() : randomData(std::chrono::system_clock::now().time_since_epoch().count())
: randomData(std::chrono::system_clock::now().time_since_epoch().count()) {} {}
RandomGenerator::~RandomGenerator() {}
unsigned int RandomGenerator::next() { RandomGenerator::~RandomGenerator()
{}
unsigned int RandomGenerator::next()
{
return randomData(); return randomData();
} }
unsigned int RandomGenerator::next(unsigned int range) { unsigned int RandomGenerator::next(unsigned int range)
{
if (range > 0) { if (range > 0) {
return next() % range; return next() % range;
} else { } else {
...@@ -40,4 +39,4 @@ unsigned int RandomGenerator::next(unsigned int range) { ...@@ -40,4 +39,4 @@ unsigned int RandomGenerator::next(unsigned int range) {
} }
} }
}//namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -16,13 +16,11 @@ See the Mulan PSL v2 for more details. */ ...@@ -16,13 +16,11 @@ See the Mulan PSL v2 for more details. */
#include <stdlib.h> #include <stdlib.h>
#include <random> #include <random>
namespace common namespace common {
{
#define DEFAULT_RANDOM_BUFF_SIZE 512 #define DEFAULT_RANDOM_BUFF_SIZE 512
class RandomGenerator class RandomGenerator {
{
public: public:
RandomGenerator(); RandomGenerator();
...@@ -37,6 +35,6 @@ private: ...@@ -37,6 +35,6 @@ private:
std::mt19937 randomData; std::mt19937 randomData;
}; };
} } // namespace common
#endif /* __COMMON_MATH_RANDOM_GENERATOR_H_ */ #endif /* __COMMON_MATH_RANDOM_GENERATOR_H_ */
...@@ -19,7 +19,8 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,7 +19,8 @@ See the Mulan PSL v2 for more details. */
#include "common/math/regex.h" #include "common/math/regex.h"
namespace common { namespace common {
int regex_match(const char *str_, const char *pat_) { int regex_match(const char *str_, const char *pat_)
{
regex_t reg; regex_t reg;
if (regcomp(&reg, pat_, REG_EXTENDED | REG_NOSUB)) if (regcomp(&reg, pat_, REG_EXTENDED | REG_NOSUB))
return -1; return -1;
...@@ -29,4 +30,4 @@ int regex_match(const char *str_, const char *pat_) { ...@@ -29,4 +30,4 @@ int regex_match(const char *str_, const char *pat_) {
return ret; return ret;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -18,5 +18,5 @@ namespace common { ...@@ -18,5 +18,5 @@ namespace common {
int regex_match(const char *str_, const char *pat_); int regex_match(const char *str_, const char *pat_);
} //namespace common } // namespace common
#endif /* __COMMON_MATH_REGEX_H__ */ #endif /* __COMMON_MATH_REGEX_H__ */
...@@ -21,13 +21,15 @@ See the Mulan PSL v2 for more details. */ ...@@ -21,13 +21,15 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
ConsoleReporter *get_console_reporter() { ConsoleReporter *get_console_reporter()
{
static ConsoleReporter *instance = new ConsoleReporter(); static ConsoleReporter *instance = new ConsoleReporter();
return instance; return instance;
} }
void ConsoleReporter::report(const std::string &tag, Metric *metric) { void ConsoleReporter::report(const std::string &tag, Metric *metric)
{
Snapshot *snapshot = metric->get_snapshot(); Snapshot *snapshot = metric->get_snapshot();
if (snapshot != NULL) { if (snapshot != NULL) {
......
...@@ -19,12 +19,11 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,12 +19,11 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
class ConsoleReporter : public Reporter { class ConsoleReporter : public Reporter {
public: public:
void report(const std::string &tag, Metric *metric); void report(const std::string &tag, Metric *metric);
}; };
ConsoleReporter* get_console_reporter(); ConsoleReporter *get_console_reporter();
} //namespace common } // namespace common
#endif //__COMMON_METRICS_CONSOLE_REPORTER_H__ #endif //__COMMON_METRICS_CONSOLE_REPORTER_H__
...@@ -24,24 +24,20 @@ See the Mulan PSL v2 for more details. */ ...@@ -24,24 +24,20 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
HistogramSnapShot::HistogramSnapShot() HistogramSnapShot::HistogramSnapShot()
{ {}
}
HistogramSnapShot::HistogramSnapShot(const std::vector<double>& collection) HistogramSnapShot::HistogramSnapShot(const std::vector<double> &collection)
{ {
set_collection(collection); set_collection(collection);
} }
HistogramSnapShot::~HistogramSnapShot() HistogramSnapShot::~HistogramSnapShot()
{ {}
}
void HistogramSnapShot::set_collection(const std::vector<double>& collection) void HistogramSnapShot::set_collection(const std::vector<double> &collection)
{ {
if (collection.empty()) if (collection.empty()) {
{
return; return;
} }
...@@ -56,35 +52,30 @@ size_t HistogramSnapShot::size() const ...@@ -56,35 +52,30 @@ size_t HistogramSnapShot::size() const
double HistogramSnapShot::get_value(double quantile) double HistogramSnapShot::get_value(double quantile)
{ {
if (quantile > 1.0f) if (quantile > 1.0f) {
{
quantile = 1.0f; quantile = 1.0f;
} }
if (quantile < 0.0f) if (quantile < 0.0f) {
{
quantile = 0.0f; quantile = 0.0f;
} }
if (data_.empty()) if (data_.empty()) {
{
return 0.0f; return 0.0f;
} }
double pos = quantile * (data_.size() + 1); double pos = quantile * (data_.size() + 1);
if (pos < 1) if (pos < 1) {
{
return data_[0]; return data_[0];
} }
if (pos >= data_.size()) if (pos >= data_.size()) {
{
return data_[data_.size() - 1]; return data_[data_.size() - 1];
} }
double lower = data_[(int) pos - 1]; double lower = data_[(int)pos - 1];
double upper = data_[(int) pos]; double upper = data_[(int)pos];
return lower + (pos - floor(pos)) * (upper - lower); return lower + (pos - floor(pos)) * (upper - lower);
} }
...@@ -111,7 +102,6 @@ double HistogramSnapShot::get_95th() ...@@ -111,7 +102,6 @@ double HistogramSnapShot::get_95th()
double HistogramSnapShot::get_99th() double HistogramSnapShot::get_99th()
{ {
return get_value(0.99f); return get_value(0.99f);
} }
double HistogramSnapShot::get_999th() double HistogramSnapShot::get_999th()
{ {
...@@ -120,8 +110,7 @@ double HistogramSnapShot::get_999th() ...@@ -120,8 +110,7 @@ double HistogramSnapShot::get_999th()
double HistogramSnapShot::get_max() double HistogramSnapShot::get_max()
{ {
if (data_.empty()) if (data_.empty()) {
{
return 0.0f; return 0.0f;
} }
...@@ -130,8 +119,7 @@ double HistogramSnapShot::get_max() ...@@ -130,8 +119,7 @@ double HistogramSnapShot::get_max()
double HistogramSnapShot::get_min() double HistogramSnapShot::get_min()
{ {
if (data_.empty()) if (data_.empty()) {
{
return 0.0f; return 0.0f;
} }
...@@ -140,29 +128,25 @@ double HistogramSnapShot::get_min() ...@@ -140,29 +128,25 @@ double HistogramSnapShot::get_min()
double HistogramSnapShot::get_mean() double HistogramSnapShot::get_mean()
{ {
if (data_.empty()) if (data_.empty()) {
{
return 0.0f; return 0.0f;
} }
return std::accumulate(data_.begin(), data_.end(), (double)0) * 1.0f / data_.size(); return std::accumulate(data_.begin(), data_.end(), (double)0) * 1.0f / data_.size();
} }
const std::vector<double> &HistogramSnapShot::get_values()
const std::vector<double> & HistogramSnapShot::get_values()
{ {
return data_; return data_;
} }
std::string HistogramSnapShot::to_string() { std::string HistogramSnapShot::to_string()
{
std::stringstream oss; std::stringstream oss;
oss << "mean:" << get_mean() << ",min:" << get_min() << ",max:" << get_max() oss << "mean:" << get_mean() << ",min:" << get_min() << ",max:" << get_max() << ",median:" << get_median()
<< ",median:" << get_median() << ", 75th:" << get_75th() << ", 75th:" << get_75th() << ",90th:" << get_90th() << ",99th:" << get_99th() << ",999th:" << get_999th();
<< ",90th:" << get_90th() << ",99th:" << get_99th()
<< ",999th:" << get_999th();
return oss.str(); return oss.str();
} }
} // namespace common } // namespace common
\ No newline at end of file
...@@ -65,6 +65,7 @@ public: ...@@ -65,6 +65,7 @@ public:
const std::vector<double> &get_values(); const std::vector<double> &get_values();
std::string to_string(); std::string to_string();
protected: protected:
std::vector<double> data_; std::vector<double> data_;
}; };
......
...@@ -19,23 +19,24 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,23 +19,24 @@ See the Mulan PSL v2 for more details. */
#include "common/metrics/metric.h" #include "common/metrics/metric.h"
#include "common/log/log.h" #include "common/log/log.h"
namespace common { namespace common {
LogReporter* get_log_reporter() { LogReporter *get_log_reporter()
static LogReporter* instance = new LogReporter(); {
static LogReporter *instance = new LogReporter();
return instance; return instance;
} }
void LogReporter::report(const std::string &tag, Metric *metric) { void LogReporter::report(const std::string &tag, Metric *metric)
{
Snapshot *snapshot = metric->get_snapshot(); Snapshot *snapshot = metric->get_snapshot();
if (snapshot != NULL) { if (snapshot != NULL) {
LOG_INFO("%s:%s", tag.c_str(), snapshot->to_string().c_str()); LOG_INFO("%s:%s", tag.c_str(), snapshot->to_string().c_str());
}else { } else {
LOG_WARN("There is no snapshot of %s metrics.", tag.c_str()); LOG_WARN("There is no snapshot of %s metrics.", tag.c_str());
} }
} }
}// namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -19,12 +19,11 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,12 +19,11 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
class LogReporter : public Reporter { class LogReporter : public Reporter {
public: public:
void report(const std::string &tag, Metric *metric); void report(const std::string &tag, Metric *metric);
}; };
LogReporter* get_log_reporter(); LogReporter *get_log_reporter();
} //namespace common } // namespace common
#endif //__COMMON_METRICS_LOG_REPORTER_H__ #endif //__COMMON_METRICS_LOG_REPORTER_H__
...@@ -23,11 +23,14 @@ class Metric { ...@@ -23,11 +23,14 @@ class Metric {
public: public:
virtual void snapshot() = 0; virtual void snapshot() = 0;
virtual Snapshot *get_snapshot() { return snapshot_value_; } virtual Snapshot *get_snapshot()
{
return snapshot_value_;
}
protected: protected:
Snapshot *snapshot_value_; Snapshot *snapshot_value_;
}; };
}//namespace common } // namespace common
#endif //__COMMON_METRICS_METRIC_H__ #endif //__COMMON_METRICS_METRIC_H__
...@@ -16,7 +16,8 @@ See the Mulan PSL v2 for more details. */ ...@@ -16,7 +16,8 @@ See the Mulan PSL v2 for more details. */
#include "common/lang/mutex.h" #include "common/lang/mutex.h"
namespace common { namespace common {
Meter::Meter() { Meter::Meter()
{
struct timeval start_time; struct timeval start_time;
gettimeofday(&start_time, NULL); gettimeofday(&start_time, NULL);
...@@ -24,17 +25,26 @@ Meter::Meter() { ...@@ -24,17 +25,26 @@ Meter::Meter() {
value_.store(0l); value_.store(0l);
} }
Meter::~Meter() { Meter::~Meter()
{
if (snapshot_value_ != NULL) { if (snapshot_value_ != NULL) {
delete snapshot_value_; delete snapshot_value_;
snapshot_value_ = NULL; snapshot_value_ = NULL;
} }
} }
void Meter::inc(long increase) { value_.fetch_add(increase); } void Meter::inc(long increase)
void Meter::inc() { inc(1l); } {
value_.fetch_add(increase);
}
void Meter::inc()
{
inc(1l);
}
void Meter::snapshot() { void Meter::snapshot()
{
// lock here // lock here
struct timeval now; struct timeval now;
...@@ -42,8 +52,7 @@ void Meter::snapshot() { ...@@ -42,8 +52,7 @@ void Meter::snapshot() {
long now_tick = now.tv_sec * 1000000 + now.tv_usec; long now_tick = now.tv_sec * 1000000 + now.tv_usec;
double temp_value = double temp_value = ((double)value_.exchange(0l)) / ((now_tick - snapshot_tick_) / 1000000);
((double)value_.exchange(0l)) / ((now_tick - snapshot_tick_ ) / 1000000);
snapshot_tick_ = now_tick; snapshot_tick_ = now_tick;
if (snapshot_value_ == NULL) { if (snapshot_value_ == NULL) {
...@@ -52,21 +61,27 @@ void Meter::snapshot() { ...@@ -52,21 +61,27 @@ void Meter::snapshot() {
((SnapshotBasic<double> *)snapshot_value_)->setValue(temp_value); ((SnapshotBasic<double> *)snapshot_value_)->setValue(temp_value);
} }
SimpleTimer::~SimpleTimer() { SimpleTimer::~SimpleTimer()
{
if (snapshot_value_ != NULL) { if (snapshot_value_ != NULL) {
delete snapshot_value_; delete snapshot_value_;
snapshot_value_ = NULL; snapshot_value_ = NULL;
} }
} }
void SimpleTimer::inc(long increase) { void SimpleTimer::inc(long increase)
{
value_.fetch_add(increase); value_.fetch_add(increase);
times_.fetch_add(1); times_.fetch_add(1);
} }
void SimpleTimer::update(long one) { inc(one); } void SimpleTimer::update(long one)
{
inc(one);
}
void SimpleTimer::snapshot() { void SimpleTimer::snapshot()
{
// lock here // lock here
struct timeval now; struct timeval now;
...@@ -81,7 +96,7 @@ void SimpleTimer::snapshot() { ...@@ -81,7 +96,7 @@ void SimpleTimer::snapshot() {
double mean = 0; double mean = 0;
if (times_snapshot > 0) { if (times_snapshot > 0) {
tps = ((double)times_snapshot )/ ((now_tick - snapshot_tick_) / 1000000); tps = ((double)times_snapshot) / ((now_tick - snapshot_tick_) / 1000000);
mean = ((double)value_snapshot) / times_snapshot; mean = ((double)value_snapshot) / times_snapshot;
} }
...@@ -93,21 +108,22 @@ void SimpleTimer::snapshot() { ...@@ -93,21 +108,22 @@ void SimpleTimer::snapshot() {
((SimplerTimerSnapshot *)snapshot_value_)->setValue(mean, tps); ((SimplerTimerSnapshot *)snapshot_value_)->setValue(mean, tps);
} }
Histogram::Histogram(RandomGenerator &random) : UniformReservoir(random) {} Histogram::Histogram(RandomGenerator &random) : UniformReservoir(random)
{}
Histogram::Histogram(RandomGenerator &random, size_t size)
: UniformReservoir(random, size) {}
Histogram::~Histogram() { Histogram::Histogram(RandomGenerator &random, size_t size) : UniformReservoir(random, size)
{}
} Histogram::~Histogram()
{}
void Histogram::snapshot() { void Histogram::snapshot()
{
UniformReservoir::snapshot(); UniformReservoir::snapshot();
} }
Timer::Timer(RandomGenerator &random) Timer::Timer(RandomGenerator &random) : UniformReservoir(random)
: UniformReservoir(random){ {
struct timeval start_time; struct timeval start_time;
gettimeofday(&start_time, NULL); gettimeofday(&start_time, NULL);
...@@ -115,8 +131,8 @@ Timer::Timer(RandomGenerator &random) ...@@ -115,8 +131,8 @@ Timer::Timer(RandomGenerator &random)
value_.store(0l); value_.store(0l);
} }
Timer::Timer(RandomGenerator &random, size_t size) Timer::Timer(RandomGenerator &random, size_t size) : UniformReservoir(random, size)
: UniformReservoir(random, size){ {
struct timeval start_time; struct timeval start_time;
gettimeofday(&start_time, NULL); gettimeofday(&start_time, NULL);
...@@ -124,19 +140,22 @@ Timer::Timer(RandomGenerator &random, size_t size) ...@@ -124,19 +140,22 @@ Timer::Timer(RandomGenerator &random, size_t size)
value_.store(0l); value_.store(0l);
} }
Timer::~Timer() { Timer::~Timer()
{
if (snapshot_value_ == NULL) { if (snapshot_value_ == NULL) {
delete snapshot_value_; delete snapshot_value_;
snapshot_value_ = NULL; snapshot_value_ = NULL;
} }
} }
void Timer::update(double ms) { void Timer::update(double ms)
{
UniformReservoir::update(ms); UniformReservoir::update(ms);
value_.fetch_add(1l); value_.fetch_add(1l);
} }
void Timer::snapshot() { void Timer::snapshot()
{
if (snapshot_value_ == NULL) { if (snapshot_value_ == NULL) {
snapshot_value_ = new TimerSnapshot(); snapshot_value_ = new TimerSnapshot();
} }
...@@ -147,8 +166,7 @@ void Timer::snapshot() { ...@@ -147,8 +166,7 @@ void Timer::snapshot() {
long now_tick = now.tv_sec * 1000000 + now.tv_usec; long now_tick = now.tv_sec * 1000000 + now.tv_usec;
double tps = double tps = ((double)value_.exchange(0l)) / ((now_tick - snapshot_tick_) / 1000000);
((double)value_.exchange(0l) )/ ((now_tick - snapshot_tick_ ) / 1000000);
snapshot_tick_ = now_tick; snapshot_tick_ = now_tick;
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
...@@ -159,13 +177,14 @@ void Timer::snapshot() { ...@@ -159,13 +177,14 @@ void Timer::snapshot() {
timer_snapshot->set_tps(tps); timer_snapshot->set_tps(tps);
} }
TimerStat::TimerStat(SimpleTimer &other_st) TimerStat::TimerStat(SimpleTimer &other_st) : st_(other_st), start_tick_(0), end_tick_(0)
: st_(other_st), start_tick_(0), end_tick_(0) { {
start(); start();
} }
TimerStat::~TimerStat() { TimerStat::~TimerStat()
{
if (end_tick_ == 0) { if (end_tick_ == 0) {
end(); end();
} }
...@@ -173,14 +192,16 @@ TimerStat::~TimerStat() { ...@@ -173,14 +192,16 @@ TimerStat::~TimerStat() {
st_.update((end_tick_ - start_tick_) / 1000); st_.update((end_tick_ - start_tick_) / 1000);
} }
void TimerStat::start() { void TimerStat::start()
{
struct timeval now; struct timeval now;
gettimeofday(&now, NULL); gettimeofday(&now, NULL);
start_tick_ = now.tv_sec * 1000000 + now.tv_usec; start_tick_ = now.tv_sec * 1000000 + now.tv_usec;
} }
void TimerStat::end() { void TimerStat::end()
{
struct timeval now; struct timeval now;
gettimeofday(&now, NULL); gettimeofday(&now, NULL);
......
...@@ -27,11 +27,17 @@ namespace common { ...@@ -27,11 +27,17 @@ namespace common {
class Gauge : public Metric { class Gauge : public Metric {
public: public:
// user implement snapshot function // user implement snapshot function
void set_snapshot(Snapshot *value) { snapshot_value_ = value; } void set_snapshot(Snapshot *value)
{
snapshot_value_ = value;
}
}; };
class Counter : public Metric { class Counter : public Metric {
void set_snapshot(SnapshotBasic<long> *value) { snapshot_value_ = value; } void set_snapshot(SnapshotBasic<long> *value)
{
snapshot_value_ = value;
}
}; };
class Meter : public Metric { class Meter : public Metric {
...@@ -76,7 +82,6 @@ public: ...@@ -76,7 +82,6 @@ public:
virtual ~Histogram(); virtual ~Histogram();
void snapshot(); void snapshot();
}; };
// timeunit is ms // timeunit is ms
......
...@@ -12,32 +12,33 @@ See the Mulan PSL v2 for more details. */ ...@@ -12,32 +12,33 @@ See the Mulan PSL v2 for more details. */
// Created by Longda on 2021/4/20. // Created by Longda on 2021/4/20.
// //
#include "common/metrics/metrics_registry.h" #include "common/metrics/metrics_registry.h"
#include "common/log/log.h" #include "common/log/log.h"
namespace common { namespace common {
MetricsRegistry& get_metrics_registry() { MetricsRegistry &get_metrics_registry()
{
static MetricsRegistry instance; static MetricsRegistry instance;
return instance; return instance;
} }
void MetricsRegistry::register_metric(const std::string &tag, Metric *metric) { void MetricsRegistry::register_metric(const std::string &tag, Metric *metric)
std::map<std::string, Metric*>::iterator it = metrics.find(tag); {
std::map<std::string, Metric *>::iterator it = metrics.find(tag);
if (it != metrics.end()) { if (it != metrics.end()) {
LOG_WARN("%s has been registered!", tag.c_str()); LOG_WARN("%s has been registered!", tag.c_str());
return; return;
} }
//metrics[tag] = metric; // metrics[tag] = metric;
metrics.insert(std::pair<std::string, Metric *>(tag, metric)); metrics.insert(std::pair<std::string, Metric *>(tag, metric));
LOG_INFO("Successfully register metric :%s", tag.c_str()); LOG_INFO("Successfully register metric :%s", tag.c_str());
} }
void MetricsRegistry::unregister(const std::string &tag) { void MetricsRegistry::unregister(const std::string &tag)
{
unsigned int num = metrics.erase(tag); unsigned int num = metrics.erase(tag);
if (num == 0) { if (num == 0) {
LOG_WARN("There is no %s metric!", tag.c_str()); LOG_WARN("There is no %s metric!", tag.c_str());
...@@ -46,18 +47,18 @@ void MetricsRegistry::unregister(const std::string &tag) { ...@@ -46,18 +47,18 @@ void MetricsRegistry::unregister(const std::string &tag) {
LOG_INFO("Successfully remove metric of %s", tag.c_str()); LOG_INFO("Successfully remove metric of %s", tag.c_str());
} }
void MetricsRegistry::snapshot() { void MetricsRegistry::snapshot()
std::map<std::string, Metric*>::iterator it = metrics.begin(); {
std::map<std::string, Metric *>::iterator it = metrics.begin();
for (; it != metrics.end(); it++) { for (; it != metrics.end(); it++) {
it->second->snapshot(); it->second->snapshot();
} }
} }
void MetricsRegistry::report() { void MetricsRegistry::report()
for (std::list<Reporter *>::iterator reporterIt = reporters.begin(); {
reporterIt != reporters.end(); reporterIt++) { for (std::list<Reporter *>::iterator reporterIt = reporters.begin(); reporterIt != reporters.end(); reporterIt++) {
for (std::map<std::string, Metric*>::iterator it = metrics.begin(); for (std::map<std::string, Metric *>::iterator it = metrics.begin(); it != metrics.end(); it++) {
it != metrics.end(); it++) {
(*reporterIt)->report(it->first, it->second); (*reporterIt)->report(it->first, it->second);
} }
......
...@@ -26,7 +26,7 @@ namespace common { ...@@ -26,7 +26,7 @@ namespace common {
class MetricsRegistry { class MetricsRegistry {
public: public:
MetricsRegistry() {}; MetricsRegistry(){};
virtual ~MetricsRegistry(){}; virtual ~MetricsRegistry(){};
void register_metric(const std::string &tag, Metric *metric); void register_metric(const std::string &tag, Metric *metric);
...@@ -36,18 +36,16 @@ public: ...@@ -36,18 +36,16 @@ public:
void report(); void report();
void add_reporter(Reporter *reporter) { void add_reporter(Reporter *reporter)
{
reporters.push_back(reporter); reporters.push_back(reporter);
} }
protected: protected:
std::map<std::string, Metric *> metrics; std::map<std::string, Metric *> metrics;
std::list<Reporter *> reporters; std::list<Reporter *> reporters;
}; };
MetricsRegistry& get_metrics_registry(); MetricsRegistry &get_metrics_registry();
}//namespace common } // namespace common
#endif //__COMMON_METRICS_METRICS_REGISTRY_H__ #endif //__COMMON_METRICS_METRICS_REGISTRY_H__
...@@ -20,10 +20,9 @@ See the Mulan PSL v2 for more details. */ ...@@ -20,10 +20,9 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
class Reporter { class Reporter {
public: public:
virtual void report(const std::string &tag, Metric *metric) = 0; virtual void report(const std::string &tag, Metric *metric) = 0;
}; };
} // namespace Reporter } // namespace common
#endif //__COMMON_METRICS_REPORTER_H__ #endif //__COMMON_METRICS_REPORTER_H__
...@@ -16,17 +16,13 @@ See the Mulan PSL v2 for more details. */ ...@@ -16,17 +16,13 @@ See the Mulan PSL v2 for more details. */
using namespace common; using namespace common;
Reservoir::Reservoir(RandomGenerator& random) : Reservoir::Reservoir(RandomGenerator &random) : random(random)
random(random) {}
{
}
Reservoir::~Reservoir() Reservoir::~Reservoir()
{ {}
}
size_t Reservoir::next(size_t range) size_t Reservoir::next(size_t range)
{ {
return random.next(range); return random.next(range);
} }
...@@ -21,8 +21,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -21,8 +21,6 @@ See the Mulan PSL v2 for more details. */
#include "common/metrics/metric.h" #include "common/metrics/metric.h"
#include "common/metrics/snapshot.h" #include "common/metrics/snapshot.h"
namespace common { namespace common {
class Reservoir : public Metric { class Reservoir : public Metric {
......
...@@ -19,17 +19,21 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,17 +19,21 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
Sampler *&get_sampler() { Sampler *&get_sampler()
{
static Sampler *g_sampler = new Sampler(); static Sampler *g_sampler = new Sampler();
return g_sampler; return g_sampler;
} }
Sampler::Sampler():random_() {} Sampler::Sampler() : random_()
{}
Sampler::~Sampler() {} Sampler::~Sampler()
{}
bool Sampler::sampling() { bool Sampler::sampling()
{
int v = random_.next(RANGE_SIZE); int v = random_.next(RANGE_SIZE);
if (v <= ratio_num_) { if (v <= ratio_num_) {
return true; return true;
...@@ -38,9 +42,13 @@ bool Sampler::sampling() { ...@@ -38,9 +42,13 @@ bool Sampler::sampling() {
} }
} }
double Sampler::get_ratio() { return ratio_; } double Sampler::get_ratio()
{
return ratio_;
}
void Sampler::set_ratio(double ratio) { void Sampler::set_ratio(double ratio)
{
if (0 <= ratio && ratio <= 1) { if (0 <= ratio && ratio <= 1) {
this->ratio_ = ratio; this->ratio_ = ratio;
ratio_num_ = ratio * RANGE_SIZE; ratio_num_ = ratio * RANGE_SIZE;
...@@ -49,5 +57,4 @@ void Sampler::set_ratio(double ratio) { ...@@ -49,5 +57,4 @@ void Sampler::set_ratio(double ratio) {
} }
} }
}//namespace common } // namespace common
...@@ -19,7 +19,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,7 +19,6 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
/** /**
* The most simple sample function * The most simple sample function
*/ */
...@@ -40,5 +39,5 @@ private: ...@@ -40,5 +39,5 @@ private:
}; };
Sampler *&get_sampler(); Sampler *&get_sampler();
} //namespace common } // namespace common
#endif //__COMMON_METRICS_SAMPLER_H__ #endif //__COMMON_METRICS_SAMPLER_H__
...@@ -20,25 +20,30 @@ See the Mulan PSL v2 for more details. */ ...@@ -20,25 +20,30 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
class Snapshot { class Snapshot {
public: public:
virtual ~Snapshot() {}; virtual ~Snapshot(){};
virtual std::string to_string() = 0; virtual std::string to_string() = 0;
}; };
template <class T> template <class T>
class SnapshotBasic : public Snapshot { class SnapshotBasic : public Snapshot {
public: public:
SnapshotBasic() : value(){ SnapshotBasic()
: value(){
}; };
virtual ~SnapshotBasic() {} virtual ~SnapshotBasic()
{}
void setValue(T &input) { value = input; } void setValue(T &input)
{
value = input;
}
std::string to_string() { std::string to_string()
{
std::string ret; std::string ret;
val_to_str(value, ret); val_to_str(value, ret);
return ret; return ret;
...@@ -48,28 +53,31 @@ private: ...@@ -48,28 +53,31 @@ private:
T value; T value;
}; };
class SimplerTimerSnapshot: public Snapshot{ class SimplerTimerSnapshot : public Snapshot {
public: public:
SimplerTimerSnapshot() { SimplerTimerSnapshot()
{}
} virtual ~SimplerTimerSnapshot()
{}
virtual ~SimplerTimerSnapshot() {} void setValue(double mean, double tps)
{
void setValue(double mean, double tps) {
this->mean = mean; this->mean = mean;
this->tps = tps; this->tps = tps;
} }
std::string to_string() { std::string to_string()
{
std::stringstream oss; std::stringstream oss;
oss << "mean:" << mean << ",tps:"<<tps; oss << "mean:" << mean << ",tps:" << tps;
return oss.str(); return oss.str();
} }
private: private:
double mean = 1.0; double mean = 1.0;
double tps = 1.0; double tps = 1.0;
}; };
} //namespace common } // namespace common
#endif //__COMMON_METRICS_SNAPSHOT_H__ #endif //__COMMON_METRICS_SNAPSHOT_H__
...@@ -17,15 +17,24 @@ See the Mulan PSL v2 for more details. */ ...@@ -17,15 +17,24 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
TimerSnapshot::TimerSnapshot() {} TimerSnapshot::TimerSnapshot()
{}
TimerSnapshot::~TimerSnapshot() {} TimerSnapshot::~TimerSnapshot()
{}
double TimerSnapshot::get_tps() { return tps; } double TimerSnapshot::get_tps()
{
return tps;
}
void TimerSnapshot::set_tps(double tps) { this->tps = tps; } void TimerSnapshot::set_tps(double tps)
{
this->tps = tps;
}
std::string TimerSnapshot::to_string() { std::string TimerSnapshot::to_string()
{
std::stringstream oss; std::stringstream oss;
oss << HistogramSnapShot::to_string() << ",tps:" << tps; oss << HistogramSnapShot::to_string() << ",tps:" << tps;
......
...@@ -27,8 +27,9 @@ public: ...@@ -27,8 +27,9 @@ public:
void set_tps(double tps); void set_tps(double tps);
std::string to_string(); std::string to_string();
protected: protected:
double tps = 1.0; double tps = 1.0;
}; };
}//namespace common } // namespace common
#endif //__COMMON_METRICS_TIMER_SNAPSHOT_H__ #endif //__COMMON_METRICS_TIMER_SNAPSHOT_H__
...@@ -23,8 +23,8 @@ namespace common { ...@@ -23,8 +23,8 @@ namespace common {
#define DEFAULT_SIZE 1023 #define DEFAULT_SIZE 1023
UniformReservoir::UniformReservoir(RandomGenerator &random) UniformReservoir::UniformReservoir(RandomGenerator &random) : Reservoir(random), counter(0)
: Reservoir(random), counter(0) { {
pthread_mutexattr_t mutexatr; pthread_mutexattr_t mutexatr;
pthread_mutexattr_init(&mutexatr); pthread_mutexattr_init(&mutexatr);
pthread_mutexattr_settype(&mutexatr, PTHREAD_MUTEX_RECURSIVE); pthread_mutexattr_settype(&mutexatr, PTHREAD_MUTEX_RECURSIVE);
...@@ -34,8 +34,8 @@ UniformReservoir::UniformReservoir(RandomGenerator &random) ...@@ -34,8 +34,8 @@ UniformReservoir::UniformReservoir(RandomGenerator &random)
init(DEFAULT_SIZE); init(DEFAULT_SIZE);
} }
UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size) UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size) : Reservoir(random), counter(0)
: Reservoir(random), counter(0) { {
pthread_mutexattr_t mutexatr; pthread_mutexattr_t mutexatr;
pthread_mutexattr_init(&mutexatr); pthread_mutexattr_init(&mutexatr);
...@@ -45,35 +45,40 @@ UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size) ...@@ -45,35 +45,40 @@ UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size)
init(size); init(size);
} }
UniformReservoir::~UniformReservoir() { UniformReservoir::~UniformReservoir()
{
if (snapshot_value_ == NULL) { if (snapshot_value_ == NULL) {
delete snapshot_value_; delete snapshot_value_;
snapshot_value_ = NULL; snapshot_value_ = NULL;
} }
} }
void UniformReservoir::init(size_t size) { void UniformReservoir::init(size_t size)
{
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
counter = 0; counter = 0;
data.resize(size); data.resize(size);
MUTEX_UNLOCK(&mutex); MUTEX_UNLOCK(&mutex);
} }
size_t UniformReservoir::size() { size_t UniformReservoir::size()
{
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
size_t size = (counter < data.size()) ? counter : data.size(); size_t size = (counter < data.size()) ? counter : data.size();
MUTEX_UNLOCK(&mutex); MUTEX_UNLOCK(&mutex);
return size; return size;
} }
size_t UniformReservoir::get_count() { size_t UniformReservoir::get_count()
{
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
size_t ret = counter; size_t ret = counter;
MUTEX_UNLOCK(&mutex); MUTEX_UNLOCK(&mutex);
return ret; return ret;
} }
void UniformReservoir::update(double value) { void UniformReservoir::update(double value)
{
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
size_t count = ++counter; size_t count = ++counter;
...@@ -87,7 +92,8 @@ void UniformReservoir::update(double value) { ...@@ -87,7 +92,8 @@ void UniformReservoir::update(double value) {
MUTEX_UNLOCK(&mutex); MUTEX_UNLOCK(&mutex);
} }
void UniformReservoir::snapshot() { void UniformReservoir::snapshot()
{
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
std::vector<double> output = data; std::vector<double> output = data;
MUTEX_UNLOCK(&mutex); MUTEX_UNLOCK(&mutex);
...@@ -98,7 +104,8 @@ void UniformReservoir::snapshot() { ...@@ -98,7 +104,8 @@ void UniformReservoir::snapshot() {
((HistogramSnapShot *)snapshot_value_)->set_collection(output); ((HistogramSnapShot *)snapshot_value_)->set_collection(output);
} }
void UniformReservoir::reset() { void UniformReservoir::reset()
{
MUTEX_LOCK(&mutex); MUTEX_LOCK(&mutex);
counter = 0; counter = 0;
......
...@@ -58,7 +58,8 @@ static new_ptr_list_t *new_ptr_list[DEBUG_NEW_HASHTABLESIZE]; ...@@ -58,7 +58,8 @@ static new_ptr_list_t *new_ptr_list[DEBUG_NEW_HASHTABLESIZE];
bool new_verbose_flag = false; bool new_verbose_flag = false;
bool new_autocheck_flag = true; bool new_autocheck_flag = true;
bool check_leaks() { bool check_leaks()
{
bool fLeaked = false; bool fLeaked = false;
for (int i = 0; i < DEBUG_NEW_HASHTABLESIZE; ++i) { for (int i = 0; i < DEBUG_NEW_HASHTABLESIZE; ++i) {
new_ptr_list_t *ptr = new_ptr_list[i]; new_ptr_list_t *ptr = new_ptr_list[i];
...@@ -68,7 +69,9 @@ bool check_leaks() { ...@@ -68,7 +69,9 @@ bool check_leaks() {
while (ptr) { while (ptr) {
printf("Leaked object at %p (size %llu, %s:%d)\n", printf("Leaked object at %p (size %llu, %s:%d)\n",
(char *)ptr + sizeof(new_ptr_list_t), (char *)ptr + sizeof(new_ptr_list_t),
(unsigned long long)ptr->size, ptr->file, ptr->line); (unsigned long long)ptr->size,
ptr->file,
ptr->line);
ptr = ptr->next; ptr = ptr->next;
} }
} }
...@@ -78,7 +81,8 @@ bool check_leaks() { ...@@ -78,7 +81,8 @@ bool check_leaks() {
return false; return false;
} }
void *operator new(size_t size, const char *file, int line) { void *operator new(size_t size, const char *file, int line)
{
size_t s = size + sizeof(new_ptr_list_t); size_t s = size + sizeof(new_ptr_list_t);
new_ptr_list_t *ptr = (new_ptr_list_t *)malloc(s); new_ptr_list_t *ptr = (new_ptr_list_t *)malloc(s);
if (ptr == NULL) { if (ptr == NULL) {
...@@ -102,23 +106,33 @@ void *operator new(size_t size, const char *file, int line) { ...@@ -102,23 +106,33 @@ void *operator new(size_t size, const char *file, int line) {
return pointer; return pointer;
} }
void *operator new[](size_t size, const char *file, int line) { void *operator new[](size_t size, const char *file, int line)
{
return operator new(size, file, line); return operator new(size, file, line);
} }
void *operator new(size_t size) { return operator new(size, "<Unknown>", 0); } void *operator new(size_t size)
{
return operator new(size, "<Unknown>", 0);
}
void *operator new[](size_t size) { return operator new(size); } void *operator new[](size_t size)
{
return operator new(size);
}
void *operator new(size_t size, const std::nothrow_t &) throw() { void *operator new(size_t size, const std::nothrow_t &) throw()
{
return operator new(size); return operator new(size);
} }
void *operator new[](size_t size, const std::nothrow_t &) throw() { void *operator new[](size_t size, const std::nothrow_t &) throw()
{
return operator new[](size); return operator new[](size);
} }
void operator delete(void *pointer) { void operator delete(void *pointer)
{
if (pointer == NULL) if (pointer == NULL)
return; return;
size_t hash_index = DEBUG_NEW_HASH(pointer); size_t hash_index = DEBUG_NEW_HASH(pointer);
...@@ -142,7 +156,10 @@ void operator delete(void *pointer) { ...@@ -142,7 +156,10 @@ void operator delete(void *pointer) {
abort(); abort();
} }
void operator delete[](void *pointer) { operator delete(pointer); } void operator delete[](void *pointer)
{
operator delete(pointer);
}
// Some older compilers like Borland C++ Compiler 5.5.1 and Digital Mars // Some older compilers like Borland C++ Compiler 5.5.1 and Digital Mars
// Compiler 8.29 do not support placement delete operators. // Compiler 8.29 do not support placement delete operators.
...@@ -151,22 +168,25 @@ void operator delete[](void *pointer) { operator delete(pointer); } ...@@ -151,22 +168,25 @@ void operator delete[](void *pointer) { operator delete(pointer); }
// is thrown in the initialization (constructor) of a dynamically // is thrown in the initialization (constructor) of a dynamically
// created object. // created object.
#ifndef NO_PLACEMENT_DELETE #ifndef NO_PLACEMENT_DELETE
void operator delete(void *pointer, const char *file, int line) { void operator delete(void *pointer, const char *file, int line)
{
if (new_verbose_flag) if (new_verbose_flag)
printf("info: exception thrown on initializing object at %p (%s:%d)\n", printf("info: exception thrown on initializing object at %p (%s:%d)\n", pointer, file, line);
pointer, file, line);
operator delete(pointer); operator delete(pointer);
} }
void operator delete[](void *pointer, const char *file, int line) { void operator delete[](void *pointer, const char *file, int line)
{
operator delete(pointer, file, line); operator delete(pointer, file, line);
} }
void operator delete(void *pointer, const std::nothrow_t &) { void operator delete(void *pointer, const std::nothrow_t &)
{
operator delete(pointer, "<Unknown>", 0); operator delete(pointer, "<Unknown>", 0);
} }
void operator delete[](void *pointer, const std::nothrow_t &) { void operator delete[](void *pointer, const std::nothrow_t &)
{
operator delete(pointer, std::nothrow); operator delete(pointer, std::nothrow);
} }
#endif // NO_PLACEMENT_DELETE #endif // NO_PLACEMENT_DELETE
...@@ -174,8 +194,10 @@ void operator delete[](void *pointer, const std::nothrow_t &) { ...@@ -174,8 +194,10 @@ void operator delete[](void *pointer, const std::nothrow_t &) {
// Proxy class to automatically call check_leaks if new_autocheck_flag is set // Proxy class to automatically call check_leaks if new_autocheck_flag is set
class new_check_t { class new_check_t {
public: public:
new_check_t() {} new_check_t()
~new_check_t() { {}
~new_check_t()
{
if (new_autocheck_flag) { if (new_autocheck_flag) {
// Check for leakage. // Check for leakage.
// If any leaks are found, set new_verbose_flag so that any // If any leaks are found, set new_verbose_flag so that any
......
...@@ -47,5 +47,5 @@ void operator delete[](void *); // MSVC 6 requires this declaration ...@@ -47,5 +47,5 @@ void operator delete[](void *); // MSVC 6 requires this declaration
extern bool new_verbose_flag; // default to false: no verbose information extern bool new_verbose_flag; // default to false: no verbose information
extern bool new_autocheck_flag; // default to true: call check_leaks() on exit extern bool new_autocheck_flag; // default to true: call check_leaks() on exit
} //namespace common } // namespace common
#endif // __COMMON_MM_DEBUG_NEW_H__ #endif // __COMMON_MM_DEBUG_NEW_H__
...@@ -28,8 +28,8 @@ MemID *CLMemTrace::mMemIDs[MEM_HASHTABLE_SIZE] = {0}; ...@@ -28,8 +28,8 @@ MemID *CLMemTrace::mMemIDs[MEM_HASHTABLE_SIZE] = {0};
bool CLMemTrace::mVerbose = false; bool CLMemTrace::mVerbose = false;
; ;
void *CLMemTrace::malloc(size_t size, const char *file, const int line, void *CLMemTrace::malloc(size_t size, const char *file, const int line, bool retry) throw(std::bad_alloc)
bool retry) throw(std::bad_alloc) { {
size_t allocSize = size + sizeof(MemID); size_t allocSize = size + sizeof(MemID);
void *usedPointer = NULL; void *usedPointer = NULL;
...@@ -81,8 +81,8 @@ void *CLMemTrace::malloc(size_t size, const char *file, const int line, ...@@ -81,8 +81,8 @@ void *CLMemTrace::malloc(size_t size, const char *file, const int line,
return NULL; return NULL;
} }
void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, const int line)
const int line) { {
if (pointer == NULL && size == 0) { if (pointer == NULL && size == 0) {
return NULL; return NULL;
} else if (pointer == NULL && size != 0) { } else if (pointer == NULL && size != 0) {
...@@ -172,8 +172,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, ...@@ -172,8 +172,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
/** /**
* Secondly, add the new one to table * Secondly, add the new one to table
*/ */
u64_t newHashIndex = u64_t newHashIndex = (u64_t)MEM_ID_HASH((char *)pNewMemID + sizeof(MemID));
(u64_t)MEM_ID_HASH((char *)pNewMemID + sizeof(MemID));
pNewMemID->mNext = mMemIDs[newHashIndex]; pNewMemID->mNext = mMemIDs[newHashIndex];
mMemIDs[newHashIndex] = pNewMemID; mMemIDs[newHashIndex] = pNewMemID;
...@@ -182,8 +181,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, ...@@ -182,8 +181,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
* Third, do memory copy * Third, do memory copy
* to simplify the old logic, copy memory here * to simplify the old logic, copy memory here
*/ */
memcpy((char *)pNewMemID + sizeof(MemID), memcpy((char *)pNewMemID + sizeof(MemID), (char *)pFreeMemID + sizeof(MemID), pFreeMemID->mSize);
(char *)pFreeMemID + sizeof(MemID), pFreeMemID->mSize);
break; break;
} }
} }
...@@ -191,9 +189,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, ...@@ -191,9 +189,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
MUTEX_UNLOCK(&mMutex); MUTEX_UNLOCK(&mMutex);
if (foundOld == false) { if (foundOld == false) {
LOG_WARN( LOG_WARN("Something is wrong, the old pointer %p isn't found, so alloc new one", pointer);
"Something is wrong, the old pointer %p isn't found, so alloc new one",
pointer);
try { try {
return malloc(size, file, line, false); return malloc(size, file, line, false);
} catch (std::bad_alloc &e) { } catch (std::bad_alloc &e) {
...@@ -203,8 +199,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, ...@@ -203,8 +199,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
} }
if (mVerbose) { if (mVerbose) {
LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, oldMemID.mFile, LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, oldMemID.mFile, oldMemID.mLine, oldMemID.mSize);
oldMemID.mLine, oldMemID.mSize);
} }
if (pFreeMemID) { if (pFreeMemID) {
...@@ -215,8 +210,10 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, ...@@ -215,8 +210,10 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
if (mVerbose) { if (mVerbose) {
LOG_INFO("Alloc %p, file:%s, line:%u, size:%llu", LOG_INFO("Alloc %p, file:%s, line:%u, size:%llu",
(char *)pNewMemID + sizeof(MemID), pNewMemID->mFile, (char *)pNewMemID + sizeof(MemID),
pNewMemID->mLine, pNewMemID->mSize); pNewMemID->mFile,
pNewMemID->mLine,
pNewMemID->mSize);
} }
return pNewMemID; return pNewMemID;
} }
...@@ -224,7 +221,8 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, ...@@ -224,7 +221,8 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
return NULL; return NULL;
} }
void CLMemTrace::free(void *pointer) { void CLMemTrace::free(void *pointer)
{
if (pointer == NULL) { if (pointer == NULL) {
LOG_WARN("Free one empty pointer"); LOG_WARN("Free one empty pointer");
return; return;
...@@ -260,8 +258,7 @@ void CLMemTrace::free(void *pointer) { ...@@ -260,8 +258,7 @@ void CLMemTrace::free(void *pointer) {
if (pMemID) { if (pMemID) {
if (mVerbose) { if (mVerbose) {
LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, pMemID->mFile, LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, pMemID->mFile, pMemID->mLine, pMemID->mSize);
pMemID->mLine, pMemID->mSize);
} }
::free(pMemID); ::free(pMemID);
return; return;
...@@ -273,7 +270,8 @@ void CLMemTrace::free(void *pointer) { ...@@ -273,7 +270,8 @@ void CLMemTrace::free(void *pointer) {
return; return;
} }
std::new_handler CLMemTrace::getNewHandler() { std::new_handler CLMemTrace::getNewHandler()
{
std::new_handler newHandler = NULL; std::new_handler newHandler = NULL;
MUTEX_LOCK(&mMutex); MUTEX_LOCK(&mMutex);
...@@ -285,7 +283,8 @@ std::new_handler CLMemTrace::getNewHandler() { ...@@ -285,7 +283,8 @@ std::new_handler CLMemTrace::getNewHandler() {
return newHandler; return newHandler;
} }
void CLMemTrace::output() { void CLMemTrace::output()
{
for (int i = 0; i < MEM_HASHTABLE_SIZE; ++i) { for (int i = 0; i < MEM_HASHTABLE_SIZE; ++i) {
// Don't lock outside of the loop // Don't lock outside of the loop
// 1. avoid output too long to alloc/free memory // 1. avoid output too long to alloc/free memory
...@@ -298,8 +297,8 @@ void CLMemTrace::output() { ...@@ -298,8 +297,8 @@ void CLMemTrace::output() {
} }
while (ptr) { while (ptr) {
// if LOG_INFO alloc memory, it will easy leading to dead lock // if LOG_INFO alloc memory, it will easy leading to dead lock
LOG_INFO("Exist %p, file:%s, line:%u, size:%llu", LOG_INFO(
(char *)ptr + sizeof(MemID), ptr->mFile, ptr->mLine, ptr->mSize); "Exist %p, file:%s, line:%u, size:%llu", (char *)ptr + sizeof(MemID), ptr->mFile, ptr->mLine, ptr->mSize);
ptr = ptr->mNext; ptr = ptr->mNext;
} }
...@@ -307,23 +306,28 @@ void CLMemTrace::output() { ...@@ -307,23 +306,28 @@ void CLMemTrace::output() {
} }
} }
void *operator new(std::size_t size, const char *file, int line) { void *operator new(std::size_t size, const char *file, int line)
{
return CLMemTrace::malloc(size, file, line, true); return CLMemTrace::malloc(size, file, line, true);
} }
void *operator new[](std::size_t size, const char *file, int line) { void *operator new[](std::size_t size, const char *file, int line)
{
return operator new(size, file, line); return operator new(size, file, line);
} }
void *operator new(std::size_t size) throw(std::bad_alloc) { void *operator new(std::size_t size) throw(std::bad_alloc)
{
return operator new(size, "<Unknown>", 0); return operator new(size, "<Unknown>", 0);
} }
void *operator new[](std::size_t size) throw(std::bad_alloc) { void *operator new[](std::size_t size) throw(std::bad_alloc)
{
return operator new(size); return operator new(size);
} }
void *operator new(std::size_t size, const std::nothrow_t &) throw() { void *operator new(std::size_t size, const std::nothrow_t &) throw()
{
void *pointer = NULL; void *pointer = NULL;
try { try {
pointer = operator new(size); pointer = operator new(size);
...@@ -334,7 +338,8 @@ void *operator new(std::size_t size, const std::nothrow_t &) throw() { ...@@ -334,7 +338,8 @@ void *operator new(std::size_t size, const std::nothrow_t &) throw() {
return pointer; return pointer;
} }
void *operator new[](std::size_t size, const std::nothrow_t &) throw() { void *operator new[](std::size_t size, const std::nothrow_t &) throw()
{
void *pointer = NULL; void *pointer = NULL;
try { try {
pointer = operator[] new(size); pointer = operator[] new(size);
...@@ -345,9 +350,15 @@ void *operator new[](std::size_t size, const std::nothrow_t &) throw() { ...@@ -345,9 +350,15 @@ void *operator new[](std::size_t size, const std::nothrow_t &) throw() {
return pointer; return pointer;
} }
void operator delete(void *pointer) { CLMemTrace::free(pointer); } void operator delete(void *pointer)
{
CLMemTrace::free(pointer);
}
void operator delete[](void *pointer) { operator delete(pointer); } void operator delete[](void *pointer)
{
operator delete(pointer);
}
// Some older compilers like Borland C++ Compiler 5.5.1 and Digital Mars // Some older compilers like Borland C++ Compiler 5.5.1 and Digital Mars
// Compiler 8.29 do not support placement delete operators. // Compiler 8.29 do not support placement delete operators.
...@@ -355,23 +366,28 @@ void operator delete[](void *pointer) { operator delete(pointer); } ...@@ -355,23 +366,28 @@ void operator delete[](void *pointer) { operator delete(pointer); }
// Also note that in that case memory leakage will occur if an exception // Also note that in that case memory leakage will occur if an exception
// is thrown in the initialization (constructor) of a dynamically // is thrown in the initialization (constructor) of a dynamically
// created object. // created object.
void operator delete(void *pointer, const char *file, int line) { void operator delete(void *pointer, const char *file, int line)
{
operator delete(pointer); operator delete(pointer);
} }
void operator delete[](void *pointer, const char *file, int line) { void operator delete[](void *pointer, const char *file, int line)
{
operator delete(pointer, file, line); operator delete(pointer, file, line);
} }
void operator delete(void *pointer, const std::nothrow_t &) { void operator delete(void *pointer, const std::nothrow_t &)
{
operator delete(pointer, "<Unknown>", 0); operator delete(pointer, "<Unknown>", 0);
} }
void operator delete[](void *pointer, const std::nothrow_t &) { void operator delete[](void *pointer, const std::nothrow_t &)
{
operator delete(pointer, std::nothrow); operator delete(pointer, std::nothrow);
} }
void *Lcalloc(size_t nmemb, size_t size, const char *file, const int line) { void *Lcalloc(size_t nmemb, size_t size, const char *file, const int line)
{
try { try {
void *point = CLMemTrace::malloc(size * nmemb, file, line, false); void *point = CLMemTrace::malloc(size * nmemb, file, line, false);
if (point) { if (point) {
...@@ -384,7 +400,8 @@ void *Lcalloc(size_t nmemb, size_t size, const char *file, const int line) { ...@@ -384,7 +400,8 @@ void *Lcalloc(size_t nmemb, size_t size, const char *file, const int line) {
return pointer; return pointer;
} }
void *Lmalloc(size_t size, const char *file, const int line) { void *Lmalloc(size_t size, const char *file, const int line)
{
try { try {
void *point = CLMemTrace::malloc(size, file, line, false); void *point = CLMemTrace::malloc(size, file, line, false);
} catch (std::bad_alloc &e) { } catch (std::bad_alloc &e) {
...@@ -394,8 +411,12 @@ void *Lmalloc(size_t size, const char *file, const int line) { ...@@ -394,8 +411,12 @@ void *Lmalloc(size_t size, const char *file, const int line) {
return pointer; return pointer;
} }
void Lfree(void *ptr) { CLMemTrace::free(pointer); } void Lfree(void *ptr)
void *Lrealloc(void *ptr, size_t size, const char *file, const int line) { {
CLMemTrace::free(pointer);
}
void *Lrealloc(void *ptr, size_t size, const char *file, const int line)
{
// simplify the logic // simplify the logic
return CLMemTrace::realloc(ptr, size, file, line); return CLMemTrace::realloc(ptr, size, file, line);
} }
......
...@@ -31,8 +31,6 @@ namespace common { ...@@ -31,8 +31,6 @@ namespace common {
#else #else
typedef struct MemID_t { typedef struct MemID_t {
public: public:
const static int MEM_FILENAME_LEN = 32; const static int MEM_FILENAME_LEN = 32;
...@@ -44,12 +42,10 @@ public: ...@@ -44,12 +42,10 @@ public:
class CLMemTrace { class CLMemTrace {
public: public:
static void *malloc(size_t size, const char *file, const int line, static void *malloc(size_t size, const char *file, const int line, bool retry = false) throw(std::bad_alloc);
bool retry = false) throw(std::bad_alloc);
// just use for realloc, same functionality as realloc // just use for realloc, same functionality as realloc
static void *realloc(void *ptr, size_t size, const char *file, static void *realloc(void *ptr, size_t size, const char *file, const int line);
const int line);
static void free(void *ptr); static void free(void *ptr);
...@@ -58,7 +54,10 @@ public: ...@@ -58,7 +54,10 @@ public:
/** /**
* set whether show every details * set whether show every details
*/ */
static void setVerbose(bool verbose) { mVerbose = verbose; } static void setVerbose(bool verbose)
{
mVerbose = verbose;
}
protected: protected:
static std::new_handler getNewHandler(); static std::new_handler getNewHandler();
...@@ -132,5 +131,5 @@ static void operator delete[](void *pointer); ...@@ -132,5 +131,5 @@ static void operator delete[](void *pointer);
#endif /* MEM_DEBUG */ #endif /* MEM_DEBUG */
} //namespace common } // namespace common
#endif /* __COMMON_MM_MEM_H__ */ #endif /* __COMMON_MM_MEM_H__ */
...@@ -21,7 +21,8 @@ See the Mulan PSL v2 for more details. */ ...@@ -21,7 +21,8 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
// Don't care windows // Don't care windows
u32_t getCpuNum() { u32_t getCpuNum()
{
return std::thread::hardware_concurrency(); return std::thread::hardware_concurrency();
} }
...@@ -30,14 +31,13 @@ u32_t getCpuNum() { ...@@ -30,14 +31,13 @@ u32_t getCpuNum() {
void print_stacktrace() void print_stacktrace()
{ {
int size = MAX_STACK_SIZE; int size = MAX_STACK_SIZE;
void * array[MAX_STACK_SIZE]; void *array[MAX_STACK_SIZE];
int stack_num = backtrace(array, size); int stack_num = backtrace(array, size);
char ** stacktrace = backtrace_symbols(array, stack_num); char **stacktrace = backtrace_symbols(array, stack_num);
for (int i = 0; i < stack_num; ++i) for (int i = 0; i < stack_num; ++i) {
{
LOG_INFO("%d ----- %s\n", i, stacktrace[i]); LOG_INFO("%d ----- %s\n", i, stacktrace[i]);
} }
free(stacktrace); free(stacktrace);
} }
}//namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -20,5 +20,5 @@ u32_t getCpuNum(); ...@@ -20,5 +20,5 @@ u32_t getCpuNum();
void print_stacktrace(); void print_stacktrace();
} //namespace common } // namespace common
#endif /* __COMMON_OS_OS_H__ */ #endif /* __COMMON_OS_OS_H__ */
...@@ -18,7 +18,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -18,7 +18,6 @@ See the Mulan PSL v2 for more details. */
#include <string> #include <string>
namespace common { namespace common {
/** /**
* get file name from full path * get file name from full path
* example * example
...@@ -68,5 +67,5 @@ bool check_directory(std::string &path); ...@@ -68,5 +67,5 @@ bool check_directory(std::string &path);
*/ */
int list_file(const char *path, const char *filter_pattern, std::vector<std::string> &files); // io/io.h::getFileList int list_file(const char *path, const char *filter_pattern, std::vector<std::string> &files); // io/io.h::getFileList
} //namespace common } // namespace common
#endif //__COMMON_OS_PATH_H__ #endif //__COMMON_OS_PATH_H__
...@@ -26,25 +26,26 @@ See the Mulan PSL v2 for more details. */ ...@@ -26,25 +26,26 @@ See the Mulan PSL v2 for more details. */
#include "common/os/pidfile.h" #include "common/os/pidfile.h"
namespace common { namespace common {
std::string& getPidPath() { std::string &getPidPath()
{
static std::string path; static std::string path;
return path; return path;
} }
void setPidPath(const char *progName) { void setPidPath(const char *progName)
{
std::string &path = getPidPath(); std::string &path = getPidPath();
if (progName != NULL) { if (progName != NULL) {
path = std::string(_PATH_TMP) + progName + ".pid"; path = std::string(_PATH_TMP) + progName + ".pid";
}else { } else {
path = ""; path = "";
} }
} }
int writePidFile(const char *progName)
int writePidFile(const char *progName) { {
assert(progName); assert(progName);
std::ofstream ostr; std::ofstream ostr;
int rv = 1; int rv = 1;
...@@ -58,15 +59,14 @@ int writePidFile(const char *progName) { ...@@ -58,15 +59,14 @@ int writePidFile(const char *progName) {
rv = 0; rv = 0;
} else { } else {
rv = errno; rv = errno;
std::cerr << "error opening PID file " << path.c_str() << SYS_OUTPUT_ERROR std::cerr << "error opening PID file " << path.c_str() << SYS_OUTPUT_ERROR << std::endl;
<< std::endl;
} }
return rv; return rv;
} }
void removePidFile(void)
void removePidFile(void) { {
std::string path = getPidPath(); std::string path = getPidPath();
if (!path.empty()) { if (!path.empty()) {
unlink(path.c_str()); unlink(path.c_str());
...@@ -75,5 +75,4 @@ void removePidFile(void) { ...@@ -75,5 +75,4 @@ void removePidFile(void) {
return; return;
} }
} // namespace common
} //namespace common \ No newline at end of file
\ No newline at end of file
...@@ -16,7 +16,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -16,7 +16,6 @@ See the Mulan PSL v2 for more details. */
#define __COMMON_OS_PIDFILE_H__ #define __COMMON_OS_PIDFILE_H__
namespace common { namespace common {
//! Generates a PID file for the current component //! Generates a PID file for the current component
/** /**
* Gets the process ID (PID) of the calling process and writes a file * Gets the process ID (PID) of the calling process and writes a file
...@@ -35,7 +34,7 @@ int writePidFile(const char *progName); ...@@ -35,7 +34,7 @@ int writePidFile(const char *progName);
*/ */
void removePidFile(void); void removePidFile(void);
std::string& getPidPath(); std::string &getPidPath();
} //namespace common } // namespace common
#endif // __COMMON_OS_PIDFILE_H__ #endif // __COMMON_OS_PIDFILE_H__
...@@ -35,7 +35,8 @@ namespace common { ...@@ -35,7 +35,8 @@ namespace common {
#define RWRR (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) #define RWRR (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
std::string get_process_name(const char *prog_name) { std::string get_process_name(const char *prog_name)
{
std::string process_name; std::string process_name;
int buf_len = strlen(prog_name); int buf_len = strlen(prog_name);
...@@ -44,8 +45,7 @@ std::string get_process_name(const char *prog_name) { ...@@ -44,8 +45,7 @@ std::string get_process_name(const char *prog_name) {
char *buf = new char[buf_len + 1]; char *buf = new char[buf_len + 1];
if (buf == NULL) { if (buf == NULL) {
std::cerr << "Failed to alloc memory for program name." std::cerr << "Failed to alloc memory for program name." << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return ""; return "";
} }
memset(buf, 0, buf_len + 1); memset(buf, 0, buf_len + 1);
...@@ -59,7 +59,8 @@ std::string get_process_name(const char *prog_name) { ...@@ -59,7 +59,8 @@ std::string get_process_name(const char *prog_name) {
// Background the process by detaching it from the console and redirecting // Background the process by detaching it from the console and redirecting
// std in, out, and err to /dev/null // std in, out, and err to /dev/null
int daemonize_service(bool close_std_streams) { int daemonize_service(bool close_std_streams)
{
int nochdir = 1; int nochdir = 1;
int noclose = close_std_streams ? 0 : 1; int noclose = close_std_streams ? 0 : 1;
int rc = daemon(nochdir, noclose); int rc = daemon(nochdir, noclose);
...@@ -70,7 +71,8 @@ int daemonize_service(bool close_std_streams) { ...@@ -70,7 +71,8 @@ int daemonize_service(bool close_std_streams) {
return rc; return rc;
} }
int daemonize_service(const char *std_out_file, const char *std_err_file) { int daemonize_service(const char *std_out_file, const char *std_err_file)
{
int rc = daemonize_service(false); int rc = daemonize_service(false);
if (rc != 0) { if (rc != 0) {
...@@ -83,7 +85,8 @@ int daemonize_service(const char *std_out_file, const char *std_err_file) { ...@@ -83,7 +85,8 @@ int daemonize_service(const char *std_out_file, const char *std_err_file) {
return 0; return 0;
} }
void sys_log_redirect(const char *std_out_file, const char *std_err_file) { void sys_log_redirect(const char *std_out_file, const char *std_err_file)
{
int rc = 0; int rc = 0;
// Redirect stdin to /dev/null // Redirect stdin to /dev/null
...@@ -125,8 +128,7 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) { ...@@ -125,8 +128,7 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) {
close(errfd); close(errfd);
} }
setvbuf(stderr, NULL, _IONBF, 0); // Make sure stderr is not buffering setvbuf(stderr, NULL, _IONBF, 0); // Make sure stderr is not buffering
std::cerr << "Process " << getpid() << " built error output at " << tv.tv_sec std::cerr << "Process " << getpid() << " built error output at " << tv.tv_sec << std::endl;
<< std::endl;
std::string outFile = getAboslutPath(std_out_file); std::string outFile = getAboslutPath(std_out_file);
...@@ -144,10 +146,9 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) { ...@@ -144,10 +146,9 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) {
close(outfd); close(outfd);
} }
setvbuf(stdout, NULL, _IONBF, 0); // Make sure stdout not buffering setvbuf(stdout, NULL, _IONBF, 0); // Make sure stdout not buffering
std::cout << "Process " << getpid() << " built standard output at " std::cout << "Process " << getpid() << " built standard output at " << tv.tv_sec << std::endl;
<< tv.tv_sec << std::endl;
return; return;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -16,7 +16,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -16,7 +16,6 @@ See the Mulan PSL v2 for more details. */
#define __COMMON_OS_PROCESS_H__ #define __COMMON_OS_PROCESS_H__
namespace common { namespace common {
//! Get process Name //! Get process Name
/** /**
* @param[in] prog_full_name process full name with full path * @param[in] prog_full_name process full name with full path
...@@ -43,5 +42,5 @@ int daemonize_service(const char *std_out_file, const char *std_err_file); ...@@ -43,5 +42,5 @@ int daemonize_service(const char *std_out_file, const char *std_err_file);
void sys_log_redirect(const char *std_out_file, const char *std_err_file); void sys_log_redirect(const char *std_out_file, const char *std_err_file);
} //namespace common } // namespace common
#endif //__COMMON_OS_PROCESS_H__ #endif //__COMMON_OS_PROCESS_H__
...@@ -17,14 +17,15 @@ See the Mulan PSL v2 for more details. */ ...@@ -17,14 +17,15 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
//! Global process config //! Global process config
ProcessParam*& the_process_param() ProcessParam *&the_process_param()
{ {
static ProcessParam* process_cfg = new ProcessParam(); static ProcessParam *process_cfg = new ProcessParam();
return process_cfg; return process_cfg;
} }
void ProcessParam::init_default(std::string &process_name) { void ProcessParam::init_default(std::string &process_name)
{
assert(process_name.empty() == false); assert(process_name.empty() == false);
this->process_name_ = process_name; this->process_name_ = process_name;
if (std_out_.empty()) { if (std_out_.empty()) {
...@@ -40,6 +41,4 @@ void ProcessParam::init_default(std::string &process_name) { ...@@ -40,6 +41,4 @@ void ProcessParam::init_default(std::string &process_name) {
demon = false; demon = false;
} }
} // namespace common
\ No newline at end of file
} //namespace common
\ No newline at end of file
...@@ -21,58 +21,96 @@ namespace common { ...@@ -21,58 +21,96 @@ namespace common {
class ProcessParam { class ProcessParam {
public: public:
ProcessParam() {} ProcessParam()
{}
virtual ~ProcessParam() {} virtual ~ProcessParam()
{}
void init_default(std::string &process_name); void init_default(std::string &process_name);
const std::string &get_std_out() const { return std_out_; } const std::string &get_std_out() const
{
return std_out_;
}
void set_std_out(const std::string &std_out) { ProcessParam::std_out_ = std_out; } void set_std_out(const std::string &std_out)
{
ProcessParam::std_out_ = std_out;
}
const std::string &get_std_err() const { return std_err_; } const std::string &get_std_err() const
{
return std_err_;
}
void set_std_err(const std::string &std_err) { ProcessParam::std_err_ = std_err; } void set_std_err(const std::string &std_err)
{
ProcessParam::std_err_ = std_err;
}
const std::string &get_conf() const { return conf; } const std::string &get_conf() const
{
return conf;
}
void set_conf(const std::string &conf) { ProcessParam::conf = conf; } void set_conf(const std::string &conf)
{
ProcessParam::conf = conf;
}
const std::string &get_process_name() const { return process_name_; } const std::string &get_process_name() const
{
return process_name_;
}
void set_process_name(const std::string &processName) { void set_process_name(const std::string &processName)
{
ProcessParam::process_name_ = processName; ProcessParam::process_name_ = processName;
} }
bool is_demon() const { return demon; } bool is_demon() const
{
return demon;
}
void set_demon(bool demon) { ProcessParam::demon = demon; } void set_demon(bool demon)
{
ProcessParam::demon = demon;
}
const std::vector<std::string> &get_args() const { return args; } const std::vector<std::string> &get_args() const
{
return args;
}
void set_args(const std::vector<std::string> &args) { void set_args(const std::vector<std::string> &args)
{
ProcessParam::args = args; ProcessParam::args = args;
} }
void set_server_port(int port) { void set_server_port(int port)
{
server_port_ = port; server_port_ = port;
} }
int get_server_port() const { int get_server_port() const
{
return server_port_; return server_port_;
} }
void set_unix_socket_path(const char *unix_socket_path) { void set_unix_socket_path(const char *unix_socket_path)
{
unix_socket_path_ = unix_socket_path; unix_socket_path_ = unix_socket_path;
} }
const std::string &get_unix_socket_path() const { const std::string &get_unix_socket_path() const
{
return unix_socket_path_; return unix_socket_path_;
} }
private: private:
std::string std_out_; // The output file std::string std_out_; // The output file
std::string std_err_; // The err output file std::string std_err_; // The err output file
std::string conf; // The configuration file std::string conf; // The configuration file
...@@ -83,7 +121,7 @@ class ProcessParam { ...@@ -83,7 +121,7 @@ class ProcessParam {
std::string unix_socket_path_; std::string unix_socket_path_;
}; };
ProcessParam*& the_process_param(); ProcessParam *&the_process_param();
} //namespace common } // namespace common
#endif //__COMMON_OS_PROCESS_PARAM_H__ #endif //__COMMON_OS_PROCESS_PARAM_H__
...@@ -17,29 +17,31 @@ See the Mulan PSL v2 for more details. */ ...@@ -17,29 +17,31 @@ See the Mulan PSL v2 for more details. */
#include "pthread.h" #include "pthread.h"
namespace common { namespace common {
void setSignalHandler(int sig, sighandler_t func) { void setSignalHandler(int sig, sighandler_t func)
{
struct sigaction newsa, oldsa; struct sigaction newsa, oldsa;
sigemptyset(&newsa.sa_mask); sigemptyset(&newsa.sa_mask);
newsa.sa_flags = 0; newsa.sa_flags = 0;
newsa.sa_handler = func; newsa.sa_handler = func;
int rc = sigaction(sig, &newsa, &oldsa); int rc = sigaction(sig, &newsa, &oldsa);
if (rc) { if (rc) {
std::cerr << "Failed to set signal " << sig << SYS_OUTPUT_FILE_POS std::cerr << "Failed to set signal " << sig << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
<< SYS_OUTPUT_ERROR << std::endl;
} }
} }
/* /*
** Set Singal handling Fucntion ** Set Singal handling Fucntion
*/ */
void setSignalHandler(sighandler_t func) { void setSignalHandler(sighandler_t func)
{
setSignalHandler(SIGQUIT, func); setSignalHandler(SIGQUIT, func);
setSignalHandler(SIGINT, func); setSignalHandler(SIGINT, func);
setSignalHandler(SIGHUP, func); setSignalHandler(SIGHUP, func);
setSignalHandler(SIGTERM, func); setSignalHandler(SIGTERM, func);
} }
void blockDefaultSignals(sigset_t *signal_set, sigset_t *old_set) { void blockDefaultSignals(sigset_t *signal_set, sigset_t *old_set)
{
sigemptyset(signal_set); sigemptyset(signal_set);
#ifndef DEBUG #ifndef DEBUG
// SIGINT will effect our gdb debugging // SIGINT will effect our gdb debugging
...@@ -50,7 +52,8 @@ void blockDefaultSignals(sigset_t *signal_set, sigset_t *old_set) { ...@@ -50,7 +52,8 @@ void blockDefaultSignals(sigset_t *signal_set, sigset_t *old_set) {
pthread_sigmask(SIG_BLOCK, signal_set, old_set); pthread_sigmask(SIG_BLOCK, signal_set, old_set);
} }
void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *old_set) { void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *old_set)
{
sigemptyset(signal_set); sigemptyset(signal_set);
#ifndef DEBUG #ifndef DEBUG
sigaddset(signal_set, SIGINT); sigaddset(signal_set, SIGINT);
...@@ -60,7 +63,8 @@ void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *old_set) { ...@@ -60,7 +63,8 @@ void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *old_set) {
pthread_sigmask(SIG_UNBLOCK, signal_set, old_set); pthread_sigmask(SIG_UNBLOCK, signal_set, old_set);
} }
void *waitForSignals(void *args) { void *waitForSignals(void *args)
{
LOG_INFO("Start thread to wait signals."); LOG_INFO("Start thread to wait signals.");
sigset_t *signal_set = (sigset_t *)args; sigset_t *signal_set = (sigset_t *)args;
int sig_number = -1; int sig_number = -1;
...@@ -77,7 +81,8 @@ void *waitForSignals(void *args) { ...@@ -77,7 +81,8 @@ void *waitForSignals(void *args) {
return NULL; return NULL;
} }
void startWaitForSignals(sigset_t *signal_set) { void startWaitForSignals(sigset_t *signal_set)
{
pthread_t pThread; pthread_t pThread;
pthread_attr_t pThreadAttrs; pthread_attr_t pThreadAttrs;
...@@ -86,6 +91,5 @@ void startWaitForSignals(sigset_t *signal_set) { ...@@ -86,6 +91,5 @@ void startWaitForSignals(sigset_t *signal_set) {
pthread_attr_setdetachstate(&pThreadAttrs, PTHREAD_CREATE_DETACHED); pthread_attr_setdetachstate(&pThreadAttrs, PTHREAD_CREATE_DETACHED);
pthread_create(&pThread, &pThreadAttrs, waitForSignals, (void *)signal_set); pthread_create(&pThread, &pThreadAttrs, waitForSignals, (void *)signal_set);
} }
} // namespace common } // namespace common
\ No newline at end of file
...@@ -30,7 +30,6 @@ void blockDefaultSignals(sigset_t *signal_set, sigset_t *old_set); ...@@ -30,7 +30,6 @@ void blockDefaultSignals(sigset_t *signal_set, sigset_t *old_set);
*/ */
void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *old_set); void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *old_set);
void *waitForSignals(sigset_t *signal_set); void *waitForSignals(sigset_t *signal_set);
void startWaitForSignals(sigset_t *signal_set); void startWaitForSignals(sigset_t *signal_set);
...@@ -42,5 +41,5 @@ typedef void (*sighandler_t)(int); ...@@ -42,5 +41,5 @@ typedef void (*sighandler_t)(int);
void setSignalHandler(sighandler_t func); void setSignalHandler(sighandler_t func);
void setSignalHandler(int sig, sighandler_t func); void setSignalHandler(int sig, sighandler_t func);
} //namespace common } // namespace common
#endif /* __COMMON_OS_SIGNAL_H__ */ #endif /* __COMMON_OS_SIGNAL_H__ */
...@@ -33,11 +33,12 @@ extern bool &get_event_history_flag(); ...@@ -33,11 +33,12 @@ extern bool &get_event_history_flag();
// Constructor // Constructor
CompletionCallback::CompletionCallback(Stage *trgt, CallbackContext *ctx) CompletionCallback::CompletionCallback(Stage *trgt, CallbackContext *ctx)
: target_stage_(trgt), context_(ctx), next_cb_(NULL), : target_stage_(trgt), context_(ctx), next_cb_(NULL), ev_hist_flag_(get_event_history_flag())
ev_hist_flag_(get_event_history_flag()) {} {}
// Destructor // Destructor
CompletionCallback::~CompletionCallback() { CompletionCallback::~CompletionCallback()
{
if (context_) { if (context_) {
delete context_; delete context_;
} }
...@@ -47,14 +48,16 @@ CompletionCallback::~CompletionCallback() { ...@@ -47,14 +48,16 @@ CompletionCallback::~CompletionCallback() {
} }
// Push onto a callback stack // Push onto a callback stack
void CompletionCallback::push_callback(CompletionCallback *next) { void CompletionCallback::push_callback(CompletionCallback *next)
{
ASSERT((!next_cb_), "%s", "cannot push a callback twice"); ASSERT((!next_cb_), "%s", "cannot push a callback twice");
next_cb_ = next; next_cb_ = next;
} }
// Pop off of a callback stack // Pop off of a callback stack
CompletionCallback *CompletionCallback::pop_callback() { CompletionCallback *CompletionCallback::pop_callback()
{
CompletionCallback *ret_val = next_cb_; CompletionCallback *ret_val = next_cb_;
next_cb_ = NULL; next_cb_ = NULL;
...@@ -62,7 +65,8 @@ CompletionCallback *CompletionCallback::pop_callback() { ...@@ -62,7 +65,8 @@ CompletionCallback *CompletionCallback::pop_callback() {
} }
// One event is complete // One event is complete
void CompletionCallback::event_done(StageEvent *ev) { void CompletionCallback::event_done(StageEvent *ev)
{
if (ev_hist_flag_) { if (ev_hist_flag_) {
ev->save_stage(target_stage_, StageEvent::CALLBACK_EV); ev->save_stage(target_stage_, StageEvent::CALLBACK_EV);
...@@ -71,11 +75,13 @@ void CompletionCallback::event_done(StageEvent *ev) { ...@@ -71,11 +75,13 @@ void CompletionCallback::event_done(StageEvent *ev) {
} }
// Reschedule callback on target stage thread // Reschedule callback on target stage thread
void CompletionCallback::event_reschedule(StageEvent *ev) { void CompletionCallback::event_reschedule(StageEvent *ev)
{
target_stage_->add_event(ev); target_stage_->add_event(ev);
} }
void CompletionCallback::event_timeout(StageEvent *ev) { void CompletionCallback::event_timeout(StageEvent *ev)
{
LOG_DEBUG("to call event_timeout for stage %s", target_stage_->get_name()); LOG_DEBUG("to call event_timeout for stage %s", target_stage_->get_name());
if (ev_hist_flag_) { if (ev_hist_flag_) {
ev->save_stage(target_stage_, StageEvent::TIMEOUT_EV); ev->save_stage(target_stage_, StageEvent::TIMEOUT_EV);
...@@ -83,4 +89,4 @@ void CompletionCallback::event_timeout(StageEvent *ev) { ...@@ -83,4 +89,4 @@ void CompletionCallback::event_timeout(StageEvent *ev) {
target_stage_->timeout_event(ev, context_); target_stage_->timeout_event(ev, context_);
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -59,7 +59,7 @@ class CompletionCallback { ...@@ -59,7 +59,7 @@ class CompletionCallback {
// public interface operations // public interface operations
public: public:
// Constructor // Constructor
CompletionCallback(Stage *trgt, CallbackContext *ctx = NULL); CompletionCallback(Stage *trgt, CallbackContext *ctx = NULL);
...@@ -84,7 +84,7 @@ class CompletionCallback { ...@@ -84,7 +84,7 @@ class CompletionCallback {
// Complete this event if it has timed out // Complete this event if it has timed out
void event_timeout(StageEvent *ev); void event_timeout(StageEvent *ev);
protected: protected:
// implementation state // implementation state
Stage *target_stage_; // stage which is setting this callback Stage *target_stage_; // stage which is setting this callback
...@@ -101,19 +101,25 @@ class CompletionCallback { ...@@ -101,19 +101,25 @@ class CompletionCallback {
* callback context class from this base. * callback context class from this base.
*/ */
class CallbackContext { class CallbackContext {
public: public:
virtual ~CallbackContext() {} virtual ~CallbackContext()
{}
}; };
class CallbackContextEvent : public CallbackContext { class CallbackContextEvent : public CallbackContext {
public: public:
CallbackContextEvent(StageEvent *event = NULL) : ev_(event) {} CallbackContextEvent(StageEvent *event = NULL) : ev_(event)
~CallbackContextEvent() {} {}
StageEvent *get_event() { return ev_; } ~CallbackContextEvent()
{}
private: StageEvent *get_event()
{
return ev_;
}
private:
StageEvent *ev_; StageEvent *ev_;
}; };
} //namespace common } // namespace common
#endif // __COMMON_SEDA_CALLBACK_H__ #endif // __COMMON_SEDA_CALLBACK_H__
...@@ -21,7 +21,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -21,7 +21,6 @@ See the Mulan PSL v2 for more details. */
#include "common/log/log.h" #include "common/log/log.h"
namespace common { namespace common {
/** /**
* A class to construct arbitrary subclass instances * A class to construct arbitrary subclass instances
* *
...@@ -42,10 +41,10 @@ namespace common { ...@@ -42,10 +41,10 @@ namespace common {
* with static linkage in a global initialization routine. * with static linkage in a global initialization routine.
*/ */
template<class T> template <class T>
class ClassFactory { class ClassFactory {
public: public:
typedef T *(*FactoryFunc)(const std::string &); typedef T *(*FactoryFunc)(const std::string &);
/** /**
...@@ -69,7 +68,7 @@ class ClassFactory { ...@@ -69,7 +68,7 @@ class ClassFactory {
*/ */
static T *make_instance(const std::string &tag); static T *make_instance(const std::string &tag);
private: private:
// Accessor function that gets the head of the factory list // Accessor function that gets the head of the factory list
static ClassFactory<T> *&fact_list_head(); static ClassFactory<T> *&fact_list_head();
...@@ -88,8 +87,9 @@ class ClassFactory { ...@@ -88,8 +87,9 @@ class ClassFactory {
* as static. C++ guarantees that the first time the function is * as static. C++ guarantees that the first time the function is
* invoked (from anywhere) the static local will be initialized. * invoked (from anywhere) the static local will be initialized.
*/ */
template<class T> template <class T>
ClassFactory<T> *&ClassFactory<T>::fact_list_head() { ClassFactory<T> *&ClassFactory<T>::fact_list_head()
{
static ClassFactory<T> *fact_list = NULL; static ClassFactory<T> *fact_list = NULL;
return fact_list; return fact_list;
} }
...@@ -99,16 +99,17 @@ ClassFactory<T> *&ClassFactory<T>::fact_list_head() { ...@@ -99,16 +99,17 @@ ClassFactory<T> *&ClassFactory<T>::fact_list_head() {
* Implementation notes: * Implementation notes:
* constructor places current instance on the global factory list. * constructor places current instance on the global factory list.
*/ */
template<class T> template <class T>
ClassFactory<T>::ClassFactory(const std::string &tag, FactoryFunc func) ClassFactory<T>::ClassFactory(const std::string &tag, FactoryFunc func) : identifier_(tag), fact_func_(func)
: identifier_(tag), fact_func_(func) { {
next_ = fact_list_head(); next_ = fact_list_head();
fact_list_head() = this; fact_list_head() = this;
} }
// Destructor // Destructor
template<class T> template <class T>
ClassFactory<T>::~ClassFactory() {} ClassFactory<T>::~ClassFactory()
{}
/** /**
* Construct an instance of a specified sub-class * Construct an instance of a specified sub-class
...@@ -116,8 +117,9 @@ ClassFactory<T>::~ClassFactory() {} ...@@ -116,8 +117,9 @@ ClassFactory<T>::~ClassFactory() {}
* scan global list to find matching tag and use the factory func to * scan global list to find matching tag and use the factory func to
* create an instance. * create an instance.
*/ */
template<class T> template <class T>
T *ClassFactory<T>::make_instance(const std::string &tag) { T *ClassFactory<T>::make_instance(const std::string &tag)
{
T *instance = NULL; T *instance = NULL;
ClassFactory<T> *current = fact_list_head(); ClassFactory<T> *current = fact_list_head();
...@@ -136,5 +138,5 @@ T *ClassFactory<T>::make_instance(const std::string &tag) { ...@@ -136,5 +138,5 @@ T *ClassFactory<T>::make_instance(const std::string &tag) {
return instance; return instance;
} }
} //namespace common } // namespace common
#endif // __COMMON_SEDA_CLASS_FACTORY_H__ #endif // __COMMON_SEDA_CLASS_FACTORY_H__
...@@ -17,8 +17,8 @@ See the Mulan PSL v2 for more details. */ ...@@ -17,8 +17,8 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
// Constructor // Constructor
EventDispatcher::EventDispatcher(const char *tag) EventDispatcher::EventDispatcher(const char *tag) : Stage(tag), event_store_(), next_stage_(NULL)
: Stage(tag), event_store_(), next_stage_(NULL) { {
LOG_TRACE("enter\n"); LOG_TRACE("enter\n");
pthread_mutexattr_t attr; pthread_mutexattr_t attr;
...@@ -31,7 +31,8 @@ EventDispatcher::EventDispatcher(const char *tag) ...@@ -31,7 +31,8 @@ EventDispatcher::EventDispatcher(const char *tag)
} }
// Destructor // Destructor
EventDispatcher::~EventDispatcher() { EventDispatcher::~EventDispatcher()
{
LOG_TRACE("enter\n"); LOG_TRACE("enter\n");
pthread_mutex_destroy(&event_lock_); pthread_mutex_destroy(&event_lock_);
LOG_TRACE("exit\n"); LOG_TRACE("exit\n");
...@@ -42,7 +43,8 @@ EventDispatcher::~EventDispatcher() { ...@@ -42,7 +43,8 @@ EventDispatcher::~EventDispatcher() {
* Check if the event can be dispatched. If not, hash it and store * Check if the event can be dispatched. If not, hash it and store
* it. If so, send it on to the next stage. * it. If so, send it on to the next stage.
*/ */
void EventDispatcher::handle_event(StageEvent *event) { void EventDispatcher::handle_event(StageEvent *event)
{
LOG_TRACE("enter\n"); LOG_TRACE("enter\n");
std::string hash; std::string hash;
...@@ -67,7 +69,8 @@ void EventDispatcher::handle_event(StageEvent *event) { ...@@ -67,7 +69,8 @@ void EventDispatcher::handle_event(StageEvent *event) {
} }
// Initialize stage params and validate outputs // Initialize stage params and validate outputs
bool EventDispatcher::initialize() { bool EventDispatcher::initialize()
{
bool ret_val = true; bool ret_val = true;
if (next_stage_list_.size() != 1) { if (next_stage_list_.size() != 1) {
...@@ -82,15 +85,15 @@ bool EventDispatcher::initialize() { ...@@ -82,15 +85,15 @@ bool EventDispatcher::initialize() {
* Cleanup stage after disconnection * Cleanup stage after disconnection
* Call done() on any events left over in the event_store_. * Call done() on any events left over in the event_store_.
*/ */
void EventDispatcher::cleanup() { void EventDispatcher::cleanup()
{
pthread_mutex_lock(&event_lock_); pthread_mutex_lock(&event_lock_);
// for each hash chain... // for each hash chain...
for (EventHash::iterator i = event_store_.begin(); i != event_store_.end(); i++) { for (EventHash::iterator i = event_store_.begin(); i != event_store_.end(); i++) {
// for each event on the chain // for each event on the chain
for (std::list<StoredEvent>::iterator j = i->second.begin(); for (std::list<StoredEvent>::iterator j = i->second.begin(); j != i->second.end(); j++) {
j != i->second.end(); j++) {
j->first->done(); j->first->done();
} }
i->second.clear(); i->second.clear();
...@@ -101,7 +104,8 @@ void EventDispatcher::cleanup() { ...@@ -101,7 +104,8 @@ void EventDispatcher::cleanup() {
} }
// Wake up a stored event // Wake up a stored event
bool EventDispatcher::wakeup_event(std::string hashkey) { bool EventDispatcher::wakeup_event(std::string hashkey)
{
bool sent = false; bool sent = false;
EventHash::iterator i; EventHash::iterator i;
...@@ -131,4 +135,4 @@ bool EventDispatcher::wakeup_event(std::string hashkey) { ...@@ -131,4 +135,4 @@ bool EventDispatcher::wakeup_event(std::string hashkey) {
return sent; return sent;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -55,7 +55,7 @@ class EventDispatcher : public Stage { ...@@ -55,7 +55,7 @@ class EventDispatcher : public Stage {
// public interface operations // public interface operations
public: public:
typedef enum { SEND_EVENT = 0, STORE_EVENT, FAIL_EVENT } status_t; typedef enum { SEND_EVENT = 0, STORE_EVENT, FAIL_EVENT } status_t;
/** /**
...@@ -77,7 +77,7 @@ class EventDispatcher : public Stage { ...@@ -77,7 +77,7 @@ class EventDispatcher : public Stage {
// Note, EventDispatcher is an abstract class and needs no make_stage() // Note, EventDispatcher is an abstract class and needs no make_stage()
protected: protected:
/** /**
* Constructor * Constructor
* @param[in] tag The label that identifies this stage. * @param[in] tag The label that identifies this stage.
...@@ -96,7 +96,10 @@ class EventDispatcher : public Stage { ...@@ -96,7 +96,10 @@ class EventDispatcher : public Stage {
bool initialize(); bool initialize();
// set properties for this object // set properties for this object
bool set_properties() { return true; } bool set_properties()
{
return true;
}
/** /**
* Cleanup stage after disconnection * Cleanup stage after disconnection
...@@ -119,8 +122,7 @@ class EventDispatcher : public Stage { ...@@ -119,8 +122,7 @@ class EventDispatcher : public Stage {
* FAIL_EVENT if failure, and event has been completed; * FAIL_EVENT if failure, and event has been completed;
* ctx is NULL * ctx is NULL
*/ */
virtual status_t dispatch_event(StageEvent *ev, DispatchContext *&ctx, virtual status_t dispatch_event(StageEvent *ev, DispatchContext *&ctx, std::string &hash) = 0;
std::string &hash) = 0;
/** /**
* Wake up a stored event * Wake up a stored event
...@@ -140,7 +142,7 @@ class EventDispatcher : public Stage { ...@@ -140,7 +142,7 @@ class EventDispatcher : public Stage {
pthread_mutex_t event_lock_; // protects access to event_store_ pthread_mutex_t event_lock_; // protects access to event_store_
Stage *next_stage_; // target for dispatched events Stage *next_stage_; // target for dispatched events
protected: protected:
}; };
/** /**
...@@ -148,9 +150,10 @@ class EventDispatcher : public Stage { ...@@ -148,9 +150,10 @@ class EventDispatcher : public Stage {
* derive from this base class. * derive from this base class.
*/ */
class DispatchContext { class DispatchContext {
public: public:
virtual ~DispatchContext() {} virtual ~DispatchContext()
{}
}; };
} //namespace common } // namespace common
#endif // __COMMON_SEDA_EVENT_DISPATCHER_H__ #endif // __COMMON_SEDA_EVENT_DISPATCHER_H__
...@@ -26,13 +26,16 @@ See the Mulan PSL v2 for more details. */ ...@@ -26,13 +26,16 @@ See the Mulan PSL v2 for more details. */
using namespace common; using namespace common;
// Constructor // Constructor
ExampleStage::ExampleStage(const char *tag) : Stage(tag) {} ExampleStage::ExampleStage(const char *tag) : Stage(tag)
{}
// Destructor // Destructor
ExampleStage::~ExampleStage() {} ExampleStage::~ExampleStage()
{}
// Parse properties, instantiate a stage object // Parse properties, instantiate a stage object
Stage *ExampleStage::make_stage(const std::string &tag) { Stage *ExampleStage::make_stage(const std::string &tag)
{
ExampleStage *stage = new ExampleStage(tag.c_str()); ExampleStage *stage = new ExampleStage(tag.c_str());
if (stage == NULL) { if (stage == NULL) {
LOG_ERROR("new ExampleStage failed"); LOG_ERROR("new ExampleStage failed");
...@@ -43,7 +46,8 @@ Stage *ExampleStage::make_stage(const std::string &tag) { ...@@ -43,7 +46,8 @@ Stage *ExampleStage::make_stage(const std::string &tag) {
} }
// Set properties for this object set in stage specific properties // Set properties for this object set in stage specific properties
bool ExampleStage::set_properties() { bool ExampleStage::set_properties()
{
// std::string stageNameStr(stage_name_); // std::string stageNameStr(stage_name_);
// std::map<std::string, std::string> section = g_properties()->get( // std::map<std::string, std::string> section = g_properties()->get(
// stageNameStr); // stageNameStr);
...@@ -56,7 +60,8 @@ bool ExampleStage::set_properties() { ...@@ -56,7 +60,8 @@ bool ExampleStage::set_properties() {
} }
// Initialize stage params and validate outputs // Initialize stage params and validate outputs
bool ExampleStage::initialize() { bool ExampleStage::initialize()
{
LOG_TRACE("Enter"); LOG_TRACE("Enter");
// std::list<Stage*>::iterator stgp = next_stage_list_.begin(); // std::list<Stage*>::iterator stgp = next_stage_list_.begin();
...@@ -68,20 +73,23 @@ bool ExampleStage::initialize() { ...@@ -68,20 +73,23 @@ bool ExampleStage::initialize() {
} }
// Cleanup after disconnection // Cleanup after disconnection
void ExampleStage::cleanup() { void ExampleStage::cleanup()
{
LOG_TRACE("Enter"); LOG_TRACE("Enter");
LOG_TRACE("Exit"); LOG_TRACE("Exit");
} }
void ExampleStage::handle_event(StageEvent *event) { void ExampleStage::handle_event(StageEvent *event)
{
LOG_TRACE("Enter\n"); LOG_TRACE("Enter\n");
LOG_TRACE("Exit\n"); LOG_TRACE("Exit\n");
return; return;
} }
void ExampleStage::callback_event(StageEvent *event, CallbackContext *context) { void ExampleStage::callback_event(StageEvent *event, CallbackContext *context)
{
LOG_TRACE("Enter\n"); LOG_TRACE("Enter\n");
LOG_TRACE("Exit\n"); LOG_TRACE("Exit\n");
......
...@@ -33,7 +33,6 @@ protected: ...@@ -33,7 +33,6 @@ protected:
void cleanup(); void cleanup();
void handle_event(StageEvent *event); void handle_event(StageEvent *event);
void callback_event(StageEvent *event, CallbackContext *context); void callback_event(StageEvent *event, CallbackContext *context);
}; };
} // namespace common } // namespace common
#endif //__COMMON_SEDA_EXAMPLE_STAGE_H__ #endif //__COMMON_SEDA_EXAMPLE_STAGE_H__
...@@ -37,17 +37,15 @@ See the Mulan PSL v2 for more details. */ ...@@ -37,17 +37,15 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/timer_stage.h" #include "common/seda/timer_stage.h"
namespace common { namespace common {
int init_seda(ProcessParam *process_cfg)
int init_seda(ProcessParam *process_cfg) { {
// Initialize the static data structures of threadpool // Initialize the static data structures of threadpool
Threadpool::create_pool_key(); Threadpool::create_pool_key();
// initialize class factory instances here // initialize class factory instances here
static StageFactory kill_thread_factory("KillThreads", static StageFactory kill_thread_factory("KillThreads", &KillThreadStage::make_stage);
&KillThreadStage::make_stage);
static StageFactory timer_factory("TimerStage", &TimerStage::make_stage); static StageFactory timer_factory("TimerStage", &TimerStage::make_stage);
static StageFactory seda_stats_factory("MetricsStage", static StageFactory seda_stats_factory("MetricsStage", &MetricsStage::make_stage);
&MetricsStage::make_stage);
// try to parse the seda configuration files // try to parse the seda configuration files
SedaConfig *config = SedaConfig::get_instance(); SedaConfig *config = SedaConfig::get_instance();
...@@ -55,16 +53,14 @@ int init_seda(ProcessParam *process_cfg) { ...@@ -55,16 +53,14 @@ int init_seda(ProcessParam *process_cfg) {
config_stat = config->parse(); config_stat = config->parse();
if (config_stat != SedaConfig::SUCCESS) { if (config_stat != SedaConfig::SUCCESS) {
LOG_ERROR("Error: unable to parse file %s", LOG_ERROR("Error: unable to parse file %s", process_cfg->get_process_name().c_str());
process_cfg->get_process_name().c_str());
return errno; return errno;
} }
// Log a message to indicate that we are restarting, when looking // Log a message to indicate that we are restarting, when looking
// at a log we can see if mmon is restarting us because we keep // at a log we can see if mmon is restarting us because we keep
// crashing. // crashing.
LOG_INFO("(Re)Starting State: Pid: %u Time: %s", (unsigned int)getpid(), LOG_INFO("(Re)Starting State: Pid: %u Time: %s", (unsigned int)getpid(), DateTime::now().to_string_local().c_str());
DateTime::now().to_string_local().c_str());
LOG_INFO("The process Name is %s", process_cfg->get_process_name().c_str()); LOG_INFO("The process Name is %s", process_cfg->get_process_name().c_str());
// try to initialize the seda configuration // try to initialize the seda configuration
...@@ -79,10 +75,11 @@ int init_seda(ProcessParam *process_cfg) { ...@@ -79,10 +75,11 @@ int init_seda(ProcessParam *process_cfg) {
return 0; return 0;
} }
void cleanup_seda() { void cleanup_seda()
{
SedaConfig *seda_config = SedaConfig::get_instance(); SedaConfig *seda_config = SedaConfig::get_instance();
delete seda_config; delete seda_config;
SedaConfig::get_instance() = NULL; SedaConfig::get_instance() = NULL;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -36,5 +36,5 @@ int init_seda(ProcessParam *process_cfg); ...@@ -36,5 +36,5 @@ int init_seda(ProcessParam *process_cfg);
void cleanup_seda(); void cleanup_seda();
} //namespace common } // namespace common
#endif // __COMMON_SEDA_INIT_H__ #endif // __COMMON_SEDA_INIT_H__
...@@ -19,14 +19,14 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,14 +19,14 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/thread_pool.h" #include "common/seda/thread_pool.h"
namespace common { namespace common {
/** /**
* Notify the pool and kill the thread * Notify the pool and kill the thread
* @param[in] event Pointer to event that must be handled. * @param[in] event Pointer to event that must be handled.
* *
* @post Call never returns. Thread is killed. Pool is notified. * @post Call never returns. Thread is killed. Pool is notified.
*/ */
void KillThreadStage::handle_event(StageEvent *event) { void KillThreadStage::handle_event(StageEvent *event)
{
get_pool()->thread_kill(); get_pool()->thread_kill();
event->done(); event->done();
this->release_event(); this->release_event();
...@@ -39,13 +39,15 @@ void KillThreadStage::handle_event(StageEvent *event) { ...@@ -39,13 +39,15 @@ void KillThreadStage::handle_event(StageEvent *event) {
* @post initializing the class members * @post initializing the class members
* @return the class object * @return the class object
*/ */
Stage *KillThreadStage::make_stage(const std::string &tag) { Stage *KillThreadStage::make_stage(const std::string &tag)
{
return new KillThreadStage(tag.c_str()); return new KillThreadStage(tag.c_str());
} }
bool KillThreadStage::set_properties() { bool KillThreadStage::set_properties()
{
// nothing to do // nothing to do
return true; return true;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -21,7 +21,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -21,7 +21,6 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/stage.h" #include "common/seda/stage.h"
namespace common { namespace common {
/** /**
* @file * @file
* @author Longda * @author Longda
...@@ -56,7 +55,8 @@ protected: ...@@ -56,7 +55,8 @@ protected:
* @post event queue is empty * @post event queue is empty
* @post stage is not connected * @post stage is not connected
*/ */
KillThreadStage(const char *tag) : Stage(tag) {} KillThreadStage(const char *tag) : Stage(tag)
{}
/** /**
* Notify the pool and kill the thread * Notify the pool and kill the thread
...@@ -70,7 +70,10 @@ protected: ...@@ -70,7 +70,10 @@ protected:
* Handle the callback * Handle the callback
* Nothing special for callbacks in this stage. * Nothing special for callbacks in this stage.
*/ */
void callback_event(StageEvent *event, CallbackContext *context) { return; } void callback_event(StageEvent *event, CallbackContext *context)
{
return;
}
/** /**
* Initialize stage params * Initialize stage params
...@@ -79,7 +82,10 @@ protected: ...@@ -79,7 +82,10 @@ protected:
* @pre Stage not connected * @pre Stage not connected
* @return true * @return true
*/ */
bool initialize() { return true; } bool initialize()
{
return true;
}
/** /**
* set properties for this object * set properties for this object
...@@ -92,5 +98,5 @@ protected: ...@@ -92,5 +98,5 @@ protected:
friend class Threadpool; friend class Threadpool;
}; };
} //namespace common } // namespace common
#endif // __COMMON_SEDA_KILL_THREAD_H__ #endif // __COMMON_SEDA_KILL_THREAD_H__
...@@ -28,5 +28,5 @@ public: ...@@ -28,5 +28,5 @@ public:
}; };
}; };
} //namespace common } // namespace common
#endif //__COMMON_SEDA_METRICS_REPORT_EVENT_H__ #endif //__COMMON_SEDA_METRICS_REPORT_EVENT_H__
...@@ -29,20 +29,24 @@ See the Mulan PSL v2 for more details. */ ...@@ -29,20 +29,24 @@ See the Mulan PSL v2 for more details. */
using namespace common; using namespace common;
MetricsRegistry &get_metric_registry() { MetricsRegistry &get_metric_registry()
{
static MetricsRegistry metrics_registry; static MetricsRegistry metrics_registry;
return metrics_registry; return metrics_registry;
} }
// Constructor // Constructor
MetricsStage::MetricsStage(const char *tag) : Stage(tag) {} MetricsStage::MetricsStage(const char *tag) : Stage(tag)
{}
// Destructor // Destructor
MetricsStage::~MetricsStage() {} MetricsStage::~MetricsStage()
{}
// Parse properties, instantiate a stage object // Parse properties, instantiate a stage object
Stage *MetricsStage::make_stage(const std::string &tag) { Stage *MetricsStage::make_stage(const std::string &tag)
{
MetricsStage *stage = new MetricsStage(tag.c_str()); MetricsStage *stage = new MetricsStage(tag.c_str());
if (stage == NULL) { if (stage == NULL) {
LOG_ERROR("new MetricsStage failed"); LOG_ERROR("new MetricsStage failed");
...@@ -53,10 +57,10 @@ Stage *MetricsStage::make_stage(const std::string &tag) { ...@@ -53,10 +57,10 @@ Stage *MetricsStage::make_stage(const std::string &tag) {
} }
// Set properties for this object set in stage specific properties // Set properties for this object set in stage specific properties
bool MetricsStage::set_properties() { bool MetricsStage::set_properties()
{
std::string stage_name_str(stage_name_); std::string stage_name_str(stage_name_);
std::map<std::string, std::string> section = std::map<std::string, std::string> section = get_properties()->get(stage_name_str);
get_properties()->get(stage_name_str);
metric_report_interval_ = DateTime::SECONDS_PER_MIN; metric_report_interval_ = DateTime::SECONDS_PER_MIN;
...@@ -70,7 +74,8 @@ bool MetricsStage::set_properties() { ...@@ -70,7 +74,8 @@ bool MetricsStage::set_properties() {
} }
// Initialize stage params and validate outputs // Initialize stage params and validate outputs
bool MetricsStage::initialize() { bool MetricsStage::initialize()
{
LOG_TRACE("Enter"); LOG_TRACE("Enter");
std::list<Stage *>::iterator stgp = next_stage_list_.begin(); std::list<Stage *>::iterator stgp = next_stage_list_.begin();
...@@ -84,13 +89,15 @@ bool MetricsStage::initialize() { ...@@ -84,13 +89,15 @@ bool MetricsStage::initialize() {
} }
// Cleanup after disconnection // Cleanup after disconnection
void MetricsStage::cleanup() { void MetricsStage::cleanup()
{
LOG_TRACE("Enter"); LOG_TRACE("Enter");
LOG_TRACE("Exit"); LOG_TRACE("Exit");
} }
void MetricsStage::handle_event(StageEvent *event) { void MetricsStage::handle_event(StageEvent *event)
{
LOG_TRACE("Enter\n"); LOG_TRACE("Enter\n");
CompletionCallback *cb = new CompletionCallback(this, NULL); CompletionCallback *cb = new CompletionCallback(this, NULL);
...@@ -102,8 +109,7 @@ void MetricsStage::handle_event(StageEvent *event) { ...@@ -102,8 +109,7 @@ void MetricsStage::handle_event(StageEvent *event) {
return; return;
} }
TimerRegisterEvent *tm_event = TimerRegisterEvent *tm_event = new TimerRegisterEvent(event, metric_report_interval_ * USEC_PER_SEC);
new TimerRegisterEvent(event, metric_report_interval_ * USEC_PER_SEC);
if (tm_event == NULL) { if (tm_event == NULL) {
LOG_ERROR("Failed to new TimerRegisterEvent"); LOG_ERROR("Failed to new TimerRegisterEvent");
...@@ -121,7 +127,8 @@ void MetricsStage::handle_event(StageEvent *event) { ...@@ -121,7 +127,8 @@ void MetricsStage::handle_event(StageEvent *event) {
return; return;
} }
void MetricsStage::callback_event(StageEvent *event, CallbackContext *context) { void MetricsStage::callback_event(StageEvent *event, CallbackContext *context)
{
LOG_TRACE("Enter\n"); LOG_TRACE("Enter\n");
MetricsRegistry &metrics_registry = get_metrics_registry(); MetricsRegistry &metrics_registry = get_metrics_registry();
......
...@@ -37,7 +37,7 @@ protected: ...@@ -37,7 +37,7 @@ protected:
protected: protected:
private: private:
Stage *timer_stage_ = nullptr; Stage *timer_stage_ = nullptr;
//report metrics every @metric_report_interval_ seconds // report metrics every @metric_report_interval_ seconds
int metric_report_interval_ = 10; int metric_report_interval_ = 10;
}; };
} // namespace common } // namespace common
......
...@@ -28,9 +28,8 @@ namespace common { ...@@ -28,9 +28,8 @@ namespace common {
SedaConfig *SedaConfig::instance_ = NULL; SedaConfig *SedaConfig::instance_ = NULL;
SedaConfig *&SedaConfig::get_instance()
{
SedaConfig *&SedaConfig::get_instance() {
if (instance_ == NULL) { if (instance_ == NULL) {
instance_ = new SedaConfig(); instance_ = new SedaConfig();
ASSERT((instance_ != NULL), "failed to allocate SedaConfig"); ASSERT((instance_ != NULL), "failed to allocate SedaConfig");
...@@ -39,12 +38,14 @@ SedaConfig *&SedaConfig::get_instance() { ...@@ -39,12 +38,14 @@ SedaConfig *&SedaConfig::get_instance() {
} }
// Constructor // Constructor
SedaConfig::SedaConfig() : cfg_file_(), cfg_str_(), thread_pools_(), stages_() { SedaConfig::SedaConfig() : cfg_file_(), cfg_str_(), thread_pools_(), stages_()
{
return; return;
} }
// Destructor // Destructor
SedaConfig::~SedaConfig() { SedaConfig::~SedaConfig()
{
ASSERT(instance_, "Instance should not be null"); ASSERT(instance_, "Instance should not be null");
// check to see if clean-up is necessary // check to see if clean-up is necessary
if ((!thread_pools_.empty()) || (!stages_.empty())) { if ((!thread_pools_.empty()) || (!stages_.empty())) {
...@@ -55,7 +56,8 @@ SedaConfig::~SedaConfig() { ...@@ -55,7 +56,8 @@ SedaConfig::~SedaConfig() {
} }
// Set the file holding the configuration // Set the file holding the configuration
void SedaConfig::set_cfg_filename(const char *filename) { void SedaConfig::set_cfg_filename(const char *filename)
{
cfg_str_.clear(); cfg_str_.clear();
cfg_file_.clear(); cfg_file_.clear();
if (filename != NULL) { if (filename != NULL) {
...@@ -65,7 +67,8 @@ void SedaConfig::set_cfg_filename(const char *filename) { ...@@ -65,7 +67,8 @@ void SedaConfig::set_cfg_filename(const char *filename) {
} }
// Set the string holding the configuration // Set the string holding the configuration
void SedaConfig::set_cfg_string(const char *config_str) { void SedaConfig::set_cfg_string(const char *config_str)
{
cfg_str_.clear(); cfg_str_.clear();
cfg_file_.clear(); cfg_file_.clear();
if (config_str != NULL) { if (config_str != NULL) {
...@@ -75,7 +78,8 @@ void SedaConfig::set_cfg_string(const char *config_str) { ...@@ -75,7 +78,8 @@ void SedaConfig::set_cfg_string(const char *config_str) {
} }
// Parse config file or string // Parse config file or string
SedaConfig::status_t SedaConfig::parse() { SedaConfig::status_t SedaConfig::parse()
{
// first parse the config // first parse the config
try { try {
// skip parse in this implementation // skip parse in this implementation
...@@ -91,7 +95,8 @@ SedaConfig::status_t SedaConfig::parse() { ...@@ -91,7 +95,8 @@ SedaConfig::status_t SedaConfig::parse() {
} }
// instantiate the parsed SEDA configuration // instantiate the parsed SEDA configuration
SedaConfig::status_t SedaConfig::instantiate_cfg() { SedaConfig::status_t SedaConfig::instantiate_cfg()
{
status_t stat = SUCCESS; status_t stat = SUCCESS;
// instantiate the configuration // instantiate the configuration
...@@ -101,7 +106,8 @@ SedaConfig::status_t SedaConfig::instantiate_cfg() { ...@@ -101,7 +106,8 @@ SedaConfig::status_t SedaConfig::instantiate_cfg() {
} }
// start the configuration - puts the stages_ into action // start the configuration - puts the stages_ into action
SedaConfig::status_t SedaConfig::start() { SedaConfig::status_t SedaConfig::start()
{
status_t stat = SUCCESS; status_t stat = SUCCESS;
ASSERT(thread_pools_.size(), "Configuration not yet instantiated"); ASSERT(thread_pools_.size(), "Configuration not yet instantiated");
...@@ -127,7 +133,8 @@ SedaConfig::status_t SedaConfig::start() { ...@@ -127,7 +133,8 @@ SedaConfig::status_t SedaConfig::start() {
} }
// Initialize the thread_pools_ and stages_ // Initialize the thread_pools_ and stages_
SedaConfig::status_t SedaConfig::init() { SedaConfig::status_t SedaConfig::init()
{
status_t stat = SUCCESS; status_t stat = SUCCESS;
// check the preconditions // check the preconditions
...@@ -150,7 +157,8 @@ SedaConfig::status_t SedaConfig::init() { ...@@ -150,7 +157,8 @@ SedaConfig::status_t SedaConfig::init() {
} }
// Clean-up the threadpool and stages_ // Clean-up the threadpool and stages_
void SedaConfig::cleanup() { void SedaConfig::cleanup()
{
// first disconnect all stages_ // first disconnect all stages_
if (stages_.empty() == false) { if (stages_.empty() == false) {
std::map<std::string, Stage *>::iterator iter = stages_.begin(); std::map<std::string, Stage *>::iterator iter = stages_.begin();
...@@ -171,9 +179,9 @@ void SedaConfig::cleanup() { ...@@ -171,9 +179,9 @@ void SedaConfig::cleanup() {
clear_config(); clear_config();
} }
void SedaConfig::init_event_history() { void SedaConfig::init_event_history()
std::map<std::string, std::string> base_section = {
get_properties()->get(SEDA_BASE_NAME); std::map<std::string, std::string> base_section = get_properties()->get(SEDA_BASE_NAME);
std::map<std::string, std::string>::iterator it; std::map<std::string, std::string>::iterator it;
std::string key; std::string key;
...@@ -198,16 +206,15 @@ void SedaConfig::init_event_history() { ...@@ -198,16 +206,15 @@ void SedaConfig::init_event_history() {
} }
get_max_event_hops() = max_event_hops; get_max_event_hops() = max_event_hops;
LOG_INFO("Successfully init_event_history, EventHistory:%d, MaxEventHops:%u", LOG_INFO("Successfully init_event_history, EventHistory:%d, MaxEventHops:%u", (int)ev_hist, max_event_hops);
(int) ev_hist, max_event_hops);
return; return;
} }
SedaConfig::status_t SedaConfig::init_thread_pool() { SedaConfig::status_t SedaConfig::init_thread_pool()
{
try { try {
std::map<std::string, std::string> base_section = std::map<std::string, std::string> base_section = get_properties()->get(SEDA_BASE_NAME);
get_properties()->get(SEDA_BASE_NAME);
std::map<std::string, std::string>::iterator it; std::map<std::string, std::string>::iterator it;
std::string key; std::string key;
...@@ -239,8 +246,7 @@ SedaConfig::status_t SedaConfig::init_thread_pool() { ...@@ -239,8 +246,7 @@ SedaConfig::status_t SedaConfig::init_thread_pool() {
int thread_count = 1; int thread_count = 1;
str_to_val(count_str, thread_count); str_to_val(count_str, thread_count);
if (thread_count < 1) { if (thread_count < 1) {
LOG_INFO("Thread number of %s is %d, it is same as cpu's cores.", LOG_INFO("Thread number of %s is %d, it is same as cpu's cores.", thread_name.c_str(), cpu_num);
thread_name.c_str(), cpu_num);
thread_count = cpu_num; thread_count = cpu_num;
} }
const int max_thread_count = 1000000; const int max_thread_count = 1000000;
...@@ -249,7 +255,7 @@ SedaConfig::status_t SedaConfig::init_thread_pool() { ...@@ -249,7 +255,7 @@ SedaConfig::status_t SedaConfig::init_thread_pool() {
return INITFAIL; return INITFAIL;
} }
Threadpool * thread_pool = new Threadpool(thread_count, thread_name); Threadpool *thread_pool = new Threadpool(thread_count, thread_name);
if (thread_pool == NULL) { if (thread_pool == NULL) {
LOG_ERROR("Failed to new %s threadpool\n", thread_name.c_str()); LOG_ERROR("Failed to new %s threadpool\n", thread_name.c_str());
return INITFAIL; return INITFAIL;
...@@ -258,8 +264,7 @@ SedaConfig::status_t SedaConfig::init_thread_pool() { ...@@ -258,8 +264,7 @@ SedaConfig::status_t SedaConfig::init_thread_pool() {
} }
if (thread_pools_.find(DEFAULT_THREAD_POOL) == thread_pools_.end()) { if (thread_pools_.find(DEFAULT_THREAD_POOL) == thread_pools_.end()) {
LOG_ERROR("There is no default thread pool %s, please add it.", LOG_ERROR("There is no default thread pool %s, please add it.", DEFAULT_THREAD_POOL);
DEFAULT_THREAD_POOL);
return INITFAIL; return INITFAIL;
} }
...@@ -279,39 +284,42 @@ SedaConfig::status_t SedaConfig::init_thread_pool() { ...@@ -279,39 +284,42 @@ SedaConfig::status_t SedaConfig::init_thread_pool() {
return SUCCESS; return SUCCESS;
} }
std::string SedaConfig::get_thread_pool(std::string &stage_name) { std::string SedaConfig::get_thread_pool(std::string &stage_name)
{
std::string ret = DEFAULT_THREAD_POOL; std::string ret = DEFAULT_THREAD_POOL;
// Get thread pool // Get thread pool
std::map<std::string, std::string> stage_section = std::map<std::string, std::string> stage_section = get_properties()->get(stage_name);
get_properties()->get(stage_name);
std::map<std::string, std::string>::iterator itt; std::map<std::string, std::string>::iterator itt;
std::string thread_pool_id = THREAD_POOL_ID; std::string thread_pool_id = THREAD_POOL_ID;
itt = stage_section.find(thread_pool_id); itt = stage_section.find(thread_pool_id);
if (itt == stage_section.end()) { if (itt == stage_section.end()) {
LOG_INFO("Not set thread_pool_id for %s, use default threadpool %s", LOG_INFO("Not set thread_pool_id for %s, use default threadpool %s", stage_name.c_str(), DEFAULT_THREAD_POOL);
stage_name.c_str(), DEFAULT_THREAD_POOL);
return ret; return ret;
} }
std::string thread_name = itt->second; std::string thread_name = itt->second;
if (thread_name.empty()) { if (thread_name.empty()) {
LOG_ERROR("Failed to set %s of the %s, use the default threadpool %s", LOG_ERROR("Failed to set %s of the %s, use the default threadpool %s",
thread_pool_id.c_str(), stage_name.c_str(), DEFAULT_THREAD_POOL); thread_pool_id.c_str(),
stage_name.c_str(),
DEFAULT_THREAD_POOL);
return ret; return ret;
} }
if (thread_pools_.find(thread_name) == thread_pools_.end()) { if (thread_pools_.find(thread_name) == thread_pools_.end()) {
LOG_ERROR("The stage %s's threadpool %s is invalid, use the default " LOG_ERROR("The stage %s's threadpool %s is invalid, use the default "
"threadpool %s", "threadpool %s",
stage_name.c_str(), thread_name.c_str(), DEFAULT_THREAD_POOL); stage_name.c_str(),
thread_name.c_str(),
DEFAULT_THREAD_POOL);
} }
return ret; return ret;
} }
SedaConfig::status_t SedaConfig::init_stages() { SedaConfig::status_t SedaConfig::init_stages()
{
try { try {
std::map<std::string, std::string> base_section = std::map<std::string, std::string> base_section = get_properties()->get(SEDA_BASE_NAME);
get_properties()->get(SEDA_BASE_NAME);
std::map<std::string, std::string>::iterator it; std::map<std::string, std::string>::iterator it;
std::string key; std::string key;
...@@ -328,8 +336,7 @@ SedaConfig::status_t SedaConfig::init_stages() { ...@@ -328,8 +336,7 @@ SedaConfig::status_t SedaConfig::init_stages() {
split_tag.assign(1, Ini::CFG_DELIMIT_TAG); split_tag.assign(1, Ini::CFG_DELIMIT_TAG);
split_string(it->second, split_tag, stage_names_); split_string(it->second, split_tag, stage_names_);
for (std::vector<std::string>::iterator it = stage_names_.begin(); for (std::vector<std::string>::iterator it = stage_names_.begin(); it != stage_names_.end(); it++) {
it != stage_names_.end(); it++) {
std::string stage_name(*it); std::string stage_name(*it);
std::string thread_name = get_thread_pool(stage_name); std::string thread_name = get_thread_pool(stage_name);
...@@ -344,13 +351,11 @@ SedaConfig::status_t SedaConfig::init_stages() { ...@@ -344,13 +351,11 @@ SedaConfig::status_t SedaConfig::init_stages() {
stages_[stage_name] = stage; stages_[stage_name] = stage;
stage->set_pool(t); stage->set_pool(t);
LOG_INFO("Stage %s use threadpool %s.", LOG_INFO("Stage %s use threadpool %s.", stage_name.c_str(), thread_name.c_str());
stage_name.c_str(), thread_name.c_str());
} // end for stage } // end for stage
} catch (std::exception &e) { } catch (std::exception &e) {
LOG_ERROR("Failed to parse stages information, please check, err:%s", LOG_ERROR("Failed to parse stages information, please check, err:%s", e.what());
e.what());
clear_config(); clear_config();
return INITFAIL; return INITFAIL;
} }
...@@ -364,16 +369,15 @@ SedaConfig::status_t SedaConfig::init_stages() { ...@@ -364,16 +369,15 @@ SedaConfig::status_t SedaConfig::init_stages() {
return SUCCESS; return SUCCESS;
} }
SedaConfig::status_t SedaConfig::gen_next_stages() { SedaConfig::status_t SedaConfig::gen_next_stages()
{
try { try {
for (std::vector<std::string>::iterator it_name = stage_names_.begin(); for (std::vector<std::string>::iterator it_name = stage_names_.begin(); it_name != stage_names_.end(); it_name++) {
it_name != stage_names_.end(); it_name++) {
std::string stage_name(*it_name); std::string stage_name(*it_name);
Stage *stage = stages_[stage_name]; Stage *stage = stages_[stage_name];
std::map<std::string, std::string> stage_section = std::map<std::string, std::string> stage_section = get_properties()->get(stage_name);
get_properties()->get(stage_name);
std::map<std::string, std::string>::iterator it; std::map<std::string, std::string>::iterator it;
std::string next_stage_id = NEXT_STAGES; std::string next_stage_id = NEXT_STAGES;
it = stage_section.find(next_stage_id); it = stage_section.find(next_stage_id);
...@@ -388,9 +392,9 @@ SedaConfig::status_t SedaConfig::gen_next_stages() { ...@@ -388,9 +392,9 @@ SedaConfig::status_t SedaConfig::gen_next_stages() {
split_tag.assign(1, Ini::CFG_DELIMIT_TAG); split_tag.assign(1, Ini::CFG_DELIMIT_TAG);
split_string(next_stage_names, split_tag, next_stage_name_list); split_string(next_stage_names, split_tag, next_stage_name_list);
for (std::vector<std::string>::iterator next_it = for (std::vector<std::string>::iterator next_it = next_stage_name_list.begin();
next_stage_name_list.begin(); next_it != next_stage_name_list.end();
next_it != next_stage_name_list.end(); next_it++) { next_it++) {
std::string &next_stage_name = *next_it; std::string &next_stage_name = *next_it;
Stage *next_stage = stages_[next_stage_name]; Stage *next_stage = stages_[next_stage_name];
stage->push_stage(next_stage); stage->push_stage(next_stage);
...@@ -406,7 +410,8 @@ SedaConfig::status_t SedaConfig::gen_next_stages() { ...@@ -406,7 +410,8 @@ SedaConfig::status_t SedaConfig::gen_next_stages() {
} }
// instantiate the thread_pools_ and stages_ // instantiate the thread_pools_ and stages_
SedaConfig::status_t SedaConfig::instantiate() { SedaConfig::status_t SedaConfig::instantiate()
{
init_event_history(); init_event_history();
...@@ -432,7 +437,8 @@ SedaConfig::status_t SedaConfig::instantiate() { ...@@ -432,7 +437,8 @@ SedaConfig::status_t SedaConfig::instantiate() {
} }
// delete all thread_pools_ and stages_ // delete all thread_pools_ and stages_
void SedaConfig::clear_config() { void SedaConfig::clear_config()
{
// delete stages_ // delete stages_
std::map<std::string, Stage *>::iterator s_iter = stages_.begin(); std::map<std::string, Stage *>::iterator s_iter = stages_.begin();
std::map<std::string, Stage *>::iterator s_end = stages_.end(); std::map<std::string, Stage *>::iterator s_end = stages_.end();
...@@ -441,8 +447,7 @@ void SedaConfig::clear_config() { ...@@ -441,8 +447,7 @@ void SedaConfig::clear_config() {
Stage *stg = s_iter->second; Stage *stg = s_iter->second;
LOG_INFO("Stage %s deleted.", stg->get_name()); LOG_INFO("Stage %s deleted.", stg->get_name());
ASSERT((!stg->is_connected()), "%s%s", "Stage connected in clear_config ", ASSERT((!stg->is_connected()), "%s%s", "Stage connected in clear_config ", stg->get_name());
stg->get_name());
delete stg; delete stg;
s_iter->second = NULL; s_iter->second = NULL;
} }
...@@ -466,23 +471,25 @@ void SedaConfig::clear_config() { ...@@ -466,23 +471,25 @@ void SedaConfig::clear_config() {
LOG_INFO("Seda thread pools released"); LOG_INFO("Seda thread pools released");
} }
void SedaConfig::get_stage_names(std::vector<std::string> &names) const { void SedaConfig::get_stage_names(std::vector<std::string> &names) const
{
names = stage_names_; names = stage_names_;
} }
void SedaConfig::get_stage_queue_status(std::vector<int> &stats) const { void SedaConfig::get_stage_queue_status(std::vector<int> &stats) const
for (std::map<std::string, Stage *>::const_iterator i = stages_.begin(); {
i != stages_.end(); ++i) { for (std::map<std::string, Stage *>::const_iterator i = stages_.begin(); i != stages_.end(); ++i) {
Stage *stg = (*i).second; Stage *stg = (*i).second;
stats.push_back(stg->qlen()); stats.push_back(stg->qlen());
} }
} }
// Global seda config object // Global seda config object
SedaConfig *&get_seda_config() { SedaConfig *&get_seda_config()
{
static SedaConfig *seda_config = NULL; static SedaConfig *seda_config = NULL;
return seda_config; return seda_config;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -26,8 +26,7 @@ See the Mulan PSL v2 for more details. */ ...@@ -26,8 +26,7 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
//keywords of sedaconfig // keywords of sedaconfig
/** /**
* A class to configure seda stages * A class to configure seda stages
...@@ -45,7 +44,7 @@ namespace common { ...@@ -45,7 +44,7 @@ namespace common {
class SedaConfig { class SedaConfig {
public: public:
typedef enum { SUCCESS = 0, INITFAIL, PARSEFAIL } status_t; typedef enum { SUCCESS = 0, INITFAIL, PARSEFAIL } status_t;
static SedaConfig *&get_instance(); static SedaConfig *&get_instance();
...@@ -157,7 +156,7 @@ class SedaConfig { ...@@ -157,7 +156,7 @@ class SedaConfig {
std::map<std::string, Stage *>::iterator begin(); std::map<std::string, Stage *>::iterator begin();
std::map<std::string, Stage *>::iterator end(); std::map<std::string, Stage *>::iterator end();
private: private:
// Constructor // Constructor
SedaConfig(); SedaConfig();
...@@ -203,18 +202,20 @@ class SedaConfig { ...@@ -203,18 +202,20 @@ class SedaConfig {
std::map<std::string, Threadpool *> thread_pools_; std::map<std::string, Threadpool *> thread_pools_;
std::map<std::string, Stage *> stages_; std::map<std::string, Stage *> stages_;
std::vector<std::string> stage_names_; std::vector<std::string> stage_names_;
}; };
inline std::map<std::string, Stage *>::iterator SedaConfig::begin() { inline std::map<std::string, Stage *>::iterator SedaConfig::begin()
{
return stages_.begin(); return stages_.begin();
} }
inline std::map<std::string, Stage *>::iterator SedaConfig::end() { inline std::map<std::string, Stage *>::iterator SedaConfig::end()
{
return stages_.end(); return stages_.end();
} }
inline Stage *SedaConfig::get_stage(const char *stagename) { inline Stage *SedaConfig::get_stage(const char *stagename)
{
if (stagename) { if (stagename) {
std::string sname(stagename); std::string sname(stagename);
return stages_[stagename]; return stages_[stagename];
...@@ -228,5 +229,5 @@ SedaConfig *&get_seda_config(); ...@@ -228,5 +229,5 @@ SedaConfig *&get_seda_config();
bool &get_event_history_flag(); bool &get_event_history_flag();
u32_t &get_max_event_hops(); u32_t &get_max_event_hops();
} //namespace common } // namespace common
#endif //__COMMON_SEDA_SEDA_CONFIG_H__ #endif //__COMMON_SEDA_SEDA_CONFIG_H__
...@@ -26,7 +26,6 @@ See the Mulan PSL v2 for more details. */ ...@@ -26,7 +26,6 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/thread_pool.h" #include "common/seda/thread_pool.h"
namespace common { namespace common {
/** /**
* Constructor * Constructor
* @param[in] tag The label that identifies this stage. * @param[in] tag The label that identifies this stage.
...@@ -35,8 +34,8 @@ namespace common { ...@@ -35,8 +34,8 @@ namespace common {
* @post event queue is empty * @post event queue is empty
* @post stage is not connected * @post stage is not connected
*/ */
Stage::Stage(const char *tag) Stage::Stage(const char *tag) : next_stage_list_(), event_list_(), connected_(false), event_ref_(0)
: next_stage_list_(), event_list_(), connected_(false), event_ref_(0) { {
LOG_TRACE("%s", "enter"); LOG_TRACE("%s", "enter");
assert(tag != NULL); assert(tag != NULL);
...@@ -52,7 +51,8 @@ Stage::Stage(const char *tag) ...@@ -52,7 +51,8 @@ Stage::Stage(const char *tag)
* @pre stage is not connected * @pre stage is not connected
* @post pending events are deleted and stage is destroyed * @post pending events are deleted and stage is destroyed
*/ */
Stage::~Stage() { Stage::~Stage()
{
LOG_TRACE("%s", "enter"); LOG_TRACE("%s", "enter");
assert(!connected_); assert(!connected_);
MUTEX_LOCK(&list_mutex_); MUTEX_LOCK(&list_mutex_);
...@@ -85,7 +85,8 @@ Stage::~Stage() { ...@@ -85,7 +85,8 @@ Stage::~Stage() {
* @post th_pool_ == pool * @post th_pool_ == pool
* @return true if the connection succeeded, else false * @return true if the connection succeeded, else false
*/ */
bool Stage::connect() { bool Stage::connect()
{
LOG_TRACE("%s%s", "enter", stage_name_); LOG_TRACE("%s%s", "enter", stage_name_);
assert(!connected_); assert(!connected_);
assert(th_pool_ != NULL); assert(th_pool_ != NULL);
...@@ -126,7 +127,8 @@ bool Stage::connect() { ...@@ -126,7 +127,8 @@ bool Stage::connect() {
* @post th_pool_ NULL * @post th_pool_ NULL
* @post stage is not connected * @post stage is not connected
*/ */
void Stage::disconnect() { void Stage::disconnect()
{
assert(connected_ == true); assert(connected_ == true);
LOG_TRACE("%s%s", "enter", stage_name_); LOG_TRACE("%s%s", "enter", stage_name_);
...@@ -151,7 +153,8 @@ void Stage::disconnect() { ...@@ -151,7 +153,8 @@ void Stage::disconnect() {
* @post event added to the end of event queue * @post event added to the end of event queue
* @post event must not be de-referenced by caller after return * @post event must not be de-referenced by caller after return
*/ */
void Stage::add_event(StageEvent *event) { void Stage::add_event(StageEvent *event)
{
assert(event != NULL); assert(event != NULL);
MUTEX_LOCK(&list_mutex_); MUTEX_LOCK(&list_mutex_);
...@@ -174,7 +177,8 @@ void Stage::add_event(StageEvent *event) { ...@@ -174,7 +177,8 @@ void Stage::add_event(StageEvent *event) {
* Query length of queue * Query length of queue
* @return length of event queue. * @return length of event queue.
*/ */
unsigned long Stage::qlen() const { unsigned long Stage::qlen() const
{
unsigned long res; unsigned long res;
MUTEX_LOCK(&list_mutex_); MUTEX_LOCK(&list_mutex_);
...@@ -187,7 +191,8 @@ unsigned long Stage::qlen() const { ...@@ -187,7 +191,8 @@ unsigned long Stage::qlen() const {
* Query whether the queue is empty * Query whether the queue is empty
* @return \c true if the queue is empty; \c false otherwise * @return \c true if the queue is empty; \c false otherwise
*/ */
bool Stage::qempty() const { bool Stage::qempty() const
{
bool empty = false; bool empty = false;
MUTEX_LOCK(&list_mutex_); MUTEX_LOCK(&list_mutex_);
...@@ -203,7 +208,8 @@ bool Stage::qempty() const { ...@@ -203,7 +208,8 @@ bool Stage::qempty() const {
* @return first event on queue. * @return first event on queue.
* @post first event on queue is removed from queue. * @post first event on queue is removed from queue.
*/ */
StageEvent *Stage::remove_event() { StageEvent *Stage::remove_event()
{
MUTEX_LOCK(&list_mutex_); MUTEX_LOCK(&list_mutex_);
assert(!event_list_.empty()); assert(!event_list_.empty());
...@@ -220,7 +226,8 @@ StageEvent *Stage::remove_event() { ...@@ -220,7 +226,8 @@ StageEvent *Stage::remove_event() {
* *
* @post event ref count on stage is decremented * @post event ref count on stage is decremented
*/ */
void Stage::release_event() { void Stage::release_event()
{
MUTEX_LOCK(&list_mutex_); MUTEX_LOCK(&list_mutex_);
event_ref_--; event_ref_--;
if (!connected_ && event_ref_ == 0) { if (!connected_ && event_ref_ == 0) {
...@@ -229,4 +236,4 @@ void Stage::release_event() { ...@@ -229,4 +236,4 @@ void Stage::release_event() {
MUTEX_UNLOCK(&list_mutex_); MUTEX_UNLOCK(&list_mutex_);
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -89,7 +89,7 @@ class Stage { ...@@ -89,7 +89,7 @@ class Stage {
// public interface operations // public interface operations
public: public:
/** /**
* Destructor * Destructor
* @pre stage is not connected * @pre stage is not connected
...@@ -109,7 +109,10 @@ class Stage { ...@@ -109,7 +109,10 @@ class Stage {
* Return the Threadpool object * Return the Threadpool object
* @return reference to the Threadpool for this Stage * @return reference to the Threadpool for this Stage
*/ */
Threadpool *get_pool() { return th_pool_; } Threadpool *get_pool()
{
return th_pool_;
}
/** /**
* Push stage to the list of the next stages * Push stage to the list of the next stages
...@@ -195,7 +198,10 @@ class Stage { ...@@ -195,7 +198,10 @@ class Stage {
* Query whether stage is connected * Query whether stage is connected
* @return true if stage is connected * @return true if stage is connected
*/ */
bool is_connected() const { return connected_; } bool is_connected() const
{
return connected_;
}
/** /**
* Perform Stage-specific processing for an event * Perform Stage-specific processing for an event
...@@ -223,12 +229,13 @@ class Stage { ...@@ -223,12 +229,13 @@ class Stage {
* A stage only need to implement this interface if the down-stream * A stage only need to implement this interface if the down-stream
* stages support event timeout detection. * stages support event timeout detection.
*/ */
virtual void timeout_event(StageEvent *event, CallbackContext *context) { virtual void timeout_event(StageEvent *event, CallbackContext *context)
{
LOG_INFO("get a timed out evnet in %s timeout_event\n", stage_name_); LOG_INFO("get a timed out evnet in %s timeout_event\n", stage_name_);
this->callback_event(event, context); this->callback_event(event, context);
} }
protected: protected:
/** /**
* Constructor * Constructor
* @param[in] tag The label that identifies this stage. * @param[in] tag The label that identifies this stage.
...@@ -264,7 +271,10 @@ class Stage { ...@@ -264,7 +271,10 @@ class Stage {
* @pre Stage not connected * @pre Stage not connected
* @return TRUE if and only if outputs are valid and init succeeded. * @return TRUE if and only if outputs are valid and init succeeded.
*/ */
virtual bool initialize() { return true; } virtual bool initialize()
{
return true;
}
/** /**
* set properties for this object * set properties for this object
...@@ -272,7 +282,10 @@ class Stage { ...@@ -272,7 +282,10 @@ class Stage {
* @post initializing the class members * @post initializing the class members
* @return Stage instantiated object * @return Stage instantiated object
*/ */
virtual bool set_properties() { return true; } virtual bool set_properties()
{
return true;
}
/** /**
* Prepare to disconnect the stage. * Prepare to disconnect the stage.
...@@ -281,14 +294,20 @@ class Stage { ...@@ -281,14 +294,20 @@ class Stage {
* from the pipeline. Most stages will not need to implement * from the pipeline. Most stages will not need to implement
* this function. * this function.
*/ */
virtual void disconnect_prepare() { return; } virtual void disconnect_prepare()
{
return;
}
/** /**
* Cleanup stage after disconnection * Cleanup stage after disconnection
* After disconnection is completed, cleanup any resources held by the * After disconnection is completed, cleanup any resources held by the
* stage and prepare for destruction or re-initialization. * stage and prepare for destruction or re-initialization.
*/ */
virtual void cleanup() { return; } virtual void cleanup()
{
return;
}
// pipeline state // pipeline state
std::list<Stage *> next_stage_list_; // next stage(s) in the pipeline std::list<Stage *> next_stage_list_; // next stage(s) in the pipeline
...@@ -298,33 +317,33 @@ class Stage { ...@@ -298,33 +317,33 @@ class Stage {
friend class Threadpool; friend class Threadpool;
private: private:
std::deque<StageEvent *> event_list_; // event queue std::deque<StageEvent *> event_list_; // event queue
mutable pthread_mutex_t list_mutex_; // protects the event queue mutable pthread_mutex_t list_mutex_; // protects the event queue
pthread_cond_t disconnect_cond_; // wait here for disconnect pthread_cond_t disconnect_cond_; // wait here for disconnect
bool connected_; // is stage connected to pool? bool connected_; // is stage connected to pool?
unsigned long event_ref_; // # of outstanding events unsigned long event_ref_; // # of outstanding events
Threadpool *th_pool_ = nullptr; // Threadpool for this stage Threadpool *th_pool_ = nullptr; // Threadpool for this stage
}; };
inline void Stage::set_pool(Threadpool *th) { inline void Stage::set_pool(Threadpool *th)
ASSERT((th != NULL), "threadpool not available for stage %s", {
this->get_name()); ASSERT((th != NULL), "threadpool not available for stage %s", this->get_name());
ASSERT(!connected_, "attempt to set threadpool while connected: %s", ASSERT(!connected_, "attempt to set threadpool while connected: %s", this->get_name());
this->get_name());
th_pool_ = th; th_pool_ = th;
} }
inline void Stage::push_stage(Stage *st) { inline void Stage::push_stage(Stage *st)
ASSERT((st != NULL), "next stage not available for stage %s", {
this->get_name()); ASSERT((st != NULL), "next stage not available for stage %s", this->get_name());
ASSERT(!connected_, "attempt to set push stage while connected: %s", ASSERT(!connected_, "attempt to set push stage while connected: %s", this->get_name());
this->get_name());
next_stage_list_.push_back(st); next_stage_list_.push_back(st);
} }
inline const char *Stage::get_name() { return stage_name_; } inline const char *Stage::get_name()
{
return stage_name_;
}
} //namespace common } // namespace common
#endif // __COMMON_SEDA_STAGE_H__ #endif // __COMMON_SEDA_STAGE_H__
...@@ -26,12 +26,12 @@ See the Mulan PSL v2 for more details. */ ...@@ -26,12 +26,12 @@ See the Mulan PSL v2 for more details. */
namespace common { namespace common {
// Constructor // Constructor
StageEvent::StageEvent() StageEvent::StageEvent() : comp_cb_(NULL), ud_(NULL), cb_flag_(false), history_(NULL), stage_hops_(0), tm_info_(NULL)
: comp_cb_(NULL), ud_(NULL), cb_flag_(false), history_(NULL), stage_hops_(0), {}
tm_info_(NULL) {}
// Destructor // Destructor
StageEvent::~StageEvent() { StageEvent::~StageEvent()
{
// clear all pending callbacks // clear all pending callbacks
while (comp_cb_) { while (comp_cb_) {
CompletionCallback *top = comp_cb_; CompletionCallback *top = comp_cb_;
...@@ -52,7 +52,8 @@ StageEvent::~StageEvent() { ...@@ -52,7 +52,8 @@ StageEvent::~StageEvent() {
} }
// Processing for this event is done; callbacks executed // Processing for this event is done; callbacks executed
void StageEvent::done() { void StageEvent::done()
{
CompletionCallback *top; CompletionCallback *top;
if (comp_cb_) { if (comp_cb_) {
...@@ -65,7 +66,8 @@ void StageEvent::done() { ...@@ -65,7 +66,8 @@ void StageEvent::done() {
} }
// Processing for this event is done; callbacks executed immediately // Processing for this event is done; callbacks executed immediately
void StageEvent::done_immediate() { void StageEvent::done_immediate()
{
CompletionCallback *top; CompletionCallback *top;
if (comp_cb_) { if (comp_cb_) {
...@@ -79,7 +81,8 @@ void StageEvent::done_immediate() { ...@@ -79,7 +81,8 @@ void StageEvent::done_immediate() {
} }
} }
void StageEvent::done_timeout() { void StageEvent::done_timeout()
{
CompletionCallback *top; CompletionCallback *top;
if (comp_cb_) { if (comp_cb_) {
...@@ -94,20 +97,26 @@ void StageEvent::done_timeout() { ...@@ -94,20 +97,26 @@ void StageEvent::done_timeout() {
} }
// Push the completion callback onto the stack // Push the completion callback onto the stack
void StageEvent::push_callback(CompletionCallback *cb) { void StageEvent::push_callback(CompletionCallback *cb)
{
cb->push_callback(comp_cb_); cb->push_callback(comp_cb_);
comp_cb_ = cb; comp_cb_ = cb;
} }
void StageEvent::set_user_data(UserData *u) { void StageEvent::set_user_data(UserData *u)
{
ud_ = u; ud_ = u;
return; return;
} }
UserData *StageEvent::get_user_data() { return ud_; } UserData *StageEvent::get_user_data()
{
return ud_;
}
// Add stage to list of stages which have handled this event // Add stage to list of stages which have handled this event
void StageEvent::save_stage(Stage *stg, HistType type) { void StageEvent::save_stage(Stage *stg, HistType type)
{
if (!history_) { if (!history_) {
history_ = new std::list<HistEntry>; history_ = new std::list<HistEntry>;
} }
...@@ -118,16 +127,19 @@ void StageEvent::save_stage(Stage *stg, HistType type) { ...@@ -118,16 +127,19 @@ void StageEvent::save_stage(Stage *stg, HistType type) {
} }
} }
void StageEvent::set_timeout_info(time_t deadline) { void StageEvent::set_timeout_info(time_t deadline)
{
TimeoutInfo *tmi = new TimeoutInfo(deadline); TimeoutInfo *tmi = new TimeoutInfo(deadline);
set_timeout_info(tmi); set_timeout_info(tmi);
} }
void StageEvent::set_timeout_info(const StageEvent &ev) { void StageEvent::set_timeout_info(const StageEvent &ev)
{
set_timeout_info(ev.tm_info_); set_timeout_info(ev.tm_info_);
} }
void StageEvent::set_timeout_info(TimeoutInfo *tmi) { void StageEvent::set_timeout_info(TimeoutInfo *tmi)
{
// release the previous timeout info // release the previous timeout info
if (tm_info_) { if (tm_info_) {
tm_info_->detach(); tm_info_->detach();
...@@ -139,7 +151,8 @@ void StageEvent::set_timeout_info(TimeoutInfo *tmi) { ...@@ -139,7 +151,8 @@ void StageEvent::set_timeout_info(TimeoutInfo *tmi) {
} }
} }
bool StageEvent::has_timed_out() { bool StageEvent::has_timed_out()
{
if (!tm_info_) { if (!tm_info_) {
return false; return false;
} }
...@@ -148,15 +161,17 @@ bool StageEvent::has_timed_out() { ...@@ -148,15 +161,17 @@ bool StageEvent::has_timed_out() {
} }
// Accessor function which wraps value for max hops an event is allowed // Accessor function which wraps value for max hops an event is allowed
u32_t &get_max_event_hops() { u32_t &get_max_event_hops()
{
static u32_t max_event_hops = 0; static u32_t max_event_hops = 0;
return max_event_hops; return max_event_hops;
} }
// Accessor function which wraps value for event history flag // Accessor function which wraps value for event history flag
bool &get_event_history_flag() { bool &get_event_history_flag()
{
static bool event_history_flag = false; static bool event_history_flag = false;
return event_history_flag; return event_history_flag;
} }
} //namespace common } // namespace common
\ No newline at end of file \ No newline at end of file
...@@ -58,7 +58,7 @@ class TimeoutInfo; ...@@ -58,7 +58,7 @@ class TimeoutInfo;
class StageEvent { class StageEvent {
public: public:
// Interface for collecting debugging information // Interface for collecting debugging information
typedef enum { HANDLE_EV = 0, CALLBACK_EV, TIMEOUT_EV } HistType; typedef enum { HANDLE_EV = 0, CALLBACK_EV, TIMEOUT_EV } HistType;
...@@ -106,7 +106,10 @@ class StageEvent { ...@@ -106,7 +106,10 @@ class StageEvent {
UserData *get_user_data(); UserData *get_user_data();
// True if event represents a callback // True if event represents a callback
bool is_callback() { return cb_flag_; } bool is_callback()
{
return cb_flag_;
}
// Add stage to list of stages which have handled this event // Add stage to list of stages which have handled this event
void save_stage(Stage *stg, HistType type); void save_stage(Stage *stg, HistType type);
...@@ -123,12 +126,18 @@ class StageEvent { ...@@ -123,12 +126,18 @@ class StageEvent {
// If the event has timed out (and should be dropped) // If the event has timed out (and should be dropped)
bool has_timed_out(); bool has_timed_out();
private: private:
typedef std::pair<Stage *, HistType> HistEntry; typedef std::pair<Stage *, HistType> HistEntry;
// Interface to allow callbacks to be run on target stage's threads // Interface to allow callbacks to be run on target stage's threads
void mark_callback() { cb_flag_ = true; } void mark_callback()
void clear_callback() { cb_flag_ = false; } {
cb_flag_ = true;
}
void clear_callback()
{
cb_flag_ = false;
}
// Set a timeout info into the event // Set a timeout info into the event
void set_timeout_info(TimeoutInfo *tmi); void set_timeout_info(TimeoutInfo *tmi);
...@@ -139,7 +148,6 @@ class StageEvent { ...@@ -139,7 +148,6 @@ class StageEvent {
std::list<HistEntry> *history_; // List of stages which have handled ev std::list<HistEntry> *history_; // List of stages which have handled ev
u32_t stage_hops_; // Number of stages which have handled ev u32_t stage_hops_; // Number of stages which have handled ev
TimeoutInfo *tm_info_; // the timeout info for this event TimeoutInfo *tm_info_; // the timeout info for this event
}; };
/** /**
...@@ -155,15 +163,18 @@ class StageEvent { ...@@ -155,15 +163,18 @@ class StageEvent {
* originating stage can access the \c UserData member to recover its state. * originating stage can access the \c UserData member to recover its state.
*/ */
class UserData { class UserData {
public: public:
/** /**
* \brief A virtual destructor to enable the use of dynamic casts. * \brief A virtual destructor to enable the use of dynamic casts.
*/ */
virtual ~UserData() { return; } virtual ~UserData()
{
return;
}
}; };
bool &get_event_history_flag(); bool &get_event_history_flag();
u32_t &get_max_event_hops(); u32_t &get_max_event_hops();
} //namespace common } // namespace common
#endif // __COMMON_SEDA_STAGE_EVENT_H__ #endif // __COMMON_SEDA_STAGE_EVENT_H__
...@@ -19,10 +19,9 @@ See the Mulan PSL v2 for more details. */ ...@@ -19,10 +19,9 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/stage.h" #include "common/seda/stage.h"
namespace common { namespace common {
class Stage; class Stage;
typedef ClassFactory<Stage> StageFactory; typedef ClassFactory<Stage> StageFactory;
} //namespace common } // namespace common
#endif // __COMMON_SEDA_STAGE_FACTORY_H__ #endif // __COMMON_SEDA_STAGE_FACTORY_H__
此差异已折叠。
...@@ -42,7 +42,7 @@ class Stage; ...@@ -42,7 +42,7 @@ class Stage;
*/ */
class Threadpool { class Threadpool {
public: public:
// Initialize the static data structures of ThreadPool // Initialize the static data structures of ThreadPool
static void create_pool_key(); static void create_pool_key();
...@@ -109,8 +109,7 @@ class Threadpool { ...@@ -109,8 +109,7 @@ class Threadpool {
// Get name of thread pool // Get name of thread pool
const std::string &get_name(); const std::string &get_name();
protected:
protected:
/** /**
* Internal thread kill. * Internal thread kill.
* Internal operation called only when a thread kill event is processed. * Internal operation called only when a thread kill event is processed.
...@@ -130,7 +129,7 @@ class Threadpool { ...@@ -130,7 +129,7 @@ class Threadpool {
*/ */
unsigned int gen_kill_thread_events(unsigned int to_kill); unsigned int gen_kill_thread_events(unsigned int to_kill);
private: private:
/** /**
* Internal thread control function * Internal thread control function
* Function which contains the control loop for each service thread. * Function which contains the control loop for each service thread.
...@@ -166,5 +165,5 @@ class Threadpool { ...@@ -166,5 +165,5 @@ class Threadpool {
friend class KillThreadStage; friend class KillThreadStage;
}; };
} //namespace common } // namespace common
#endif // __COMMON_SEDA_THREAD_POOL_H__ #endif // __COMMON_SEDA_THREAD_POOL_H__
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册