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

Format all code by the OceanBase Clang-Format file.

上级 06fa8cf7
......@@ -31,7 +31,7 @@ namespace common {
// VARNAME=VALUE
class Ini {
public:
public:
/**
* To simplify the logic, no lock's when loading configuration
* So don't modify the data parallel
......@@ -50,24 +50,22 @@ class Ini {
* get the map of the section
* if the section doesn't exist, return one empty section
*/
const std::map<std::string, std::string> &
get(const std::string &section = DEFAULT_SECTION);
const std::map<std::string, std::string> &get(const std::string &section = DEFAULT_SECTION);
/**
* get the value of the key in the section,
* if the key-value doesn't exist,
* use the input default_value
*/
std::string get(const std::string &key, const std::string &default_value,
const std::string &section = DEFAULT_SECTION);
std::string get(
const std::string &key, const std::string &default_value, const std::string &section = DEFAULT_SECTION);
/**
* put the key-value pair to the section
* if the key-value already exist, just replace it
* if the section doesn't exist, it will create this section
*/
int put(const std::string &key, const std::string &value,
const std::string &section = DEFAULT_SECTION);
int put(const std::string &key, const std::string &value, const std::string &section = DEFAULT_SECTION);
/**
* output all configuration to one string
......@@ -92,7 +90,7 @@ class Ini {
static const char CFG_SESSION_START_TAG = '[';
static const char CFG_SESSION_END_TAG = ']';
protected:
protected:
/**
* insert one empty session to sections_
*/
......@@ -102,21 +100,18 @@ class Ini {
* switch session according to the session_name
* if the section doesn't exist, it will create one
*/
std::map<std::string, std::string> *
switch_session(const std::string &session_name);
std::map<std::string, std::string> *switch_session(const std::string &session_name);
/**
* insert one entry to session_map
* line's format is "key=value"
*
*/
int insert_entry(std::map<std::string, std::string> *session_map,
const std::string &line);
int insert_entry(std::map<std::string, std::string> *session_map, const std::string &line);
typedef std::map<std::string, std::map<std::string, std::string>>
SessionsMap;
typedef std::map<std::string, std::map<std::string, std::string>> SessionsMap;
private:
private:
static const std::map<std::string, std::string> empty_map_;
std::set<std::string> file_names_;
......@@ -129,5 +124,5 @@ class Ini {
Ini *&get_properties();
//********************************************************************
}// namespace common
#endif //__COMMON_CONF_INI_H__
} // namespace common
#endif //__COMMON_CONF_INI_H__
......@@ -36,7 +36,8 @@ namespace common {
#endif
inline const std::string &theSwVersion() {
inline const std::string &theSwVersion()
{
static const std::string swVersion(VERSION_STR);
return swVersion;
......@@ -44,24 +45,24 @@ inline const std::string &theSwVersion() {
enum {
// General Error Codes
STATUS_SUCCESS = 0, //!< Success status should be zero,
STATUS_INVALID_PARAM, //!< Invalid parameter
STATUS_FAILED_INIT, //!< Failed to init program
STATUS_PROPERTY_ERR, //!< Property error
STATUS_INIT_LOG, //!< log error
STATUS_INIT_THREAD, //!< failed to init thread
STATUS_FAILED_JOB, //!< Failed to do job
STATUS_FAILED_NETWORK, //!< Network failure
STATUS_SUCCESS = 0, //!< Success status should be zero,
STATUS_INVALID_PARAM, //!< Invalid parameter
STATUS_FAILED_INIT, //!< Failed to init program
STATUS_PROPERTY_ERR, //!< Property error
STATUS_INIT_LOG, //!< log error
STATUS_INIT_THREAD, //!< failed to init thread
STATUS_FAILED_JOB, //!< Failed to do job
STATUS_FAILED_NETWORK, //!< Network failure
STATUS_UNKNOW_ERROR,
STATUS_LAST_ERR //!< last error code
STATUS_LAST_ERR //!< last error code
};
const unsigned int ONE_KILO = 1024;
const unsigned int ONE_MILLION = ONE_KILO * ONE_KILO;
const unsigned int ONE_GIGA = ONE_MILLION * ONE_KILO;
const unsigned int FILENAME_LENGTH_MAX = 256; // the max filename length
const unsigned int FILENAME_LENGTH_MAX = 256; // the max filename length
static const char FILE_PATH_SPLIT = '/';
static const char FILE_PATH_SPLIT_STR[] = "/";
......@@ -82,5 +83,5 @@ typedef long long s64_t;
#define LOCAL_HOST "localhost"
} // namespace common
#endif //__COMMON_DEFS_H__
} // namespace common
#endif //__COMMON_DEFS_H__
......@@ -27,13 +27,11 @@ See the Mulan PSL v2 for more details. */
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");
if (file == NULL) {
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return -1;
}
......@@ -50,8 +48,7 @@ int readFromFile(const std::string &fileName, char *&outputData,
memset(buffer, 0, sizeof(buffer));
oneRead = fread(buffer, 1, sizeof(buffer), file);
if (ferror(file)) {
std::cerr << "Failed to read data" << fileName << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to read data" << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
fclose(file);
if (data != NULL) {
lfree(data);
......@@ -62,8 +59,7 @@ int readFromFile(const std::string &fileName, char *&outputData,
data = (char *)lrealloc(data, readSize + oneRead);
if (data == NULL) {
std::cerr << "Failed to alloc memory for " << fileName
<< SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to alloc memory for " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
lfree(data);
fclose(file);
return -1;
......@@ -81,12 +77,11 @@ int readFromFile(const std::string &fileName, char *&outputData,
return 0;
}
int writeToFile(const std::string &fileName, const char *data, u32_t dataSize,
const char *openMode) {
int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, const char *openMode)
{
FILE *file = fopen(fileName.c_str(), openMode);
if (file == NULL) {
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return -1;
}
......@@ -95,8 +90,7 @@ int writeToFile(const std::string &fileName, const char *data, u32_t dataSize,
while (leftSize > 0) {
int writeCount = fwrite(buffer, 1, leftSize, file);
if (writeCount <= 0) {
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
fclose(file);
return -1;
} else {
......@@ -110,7 +104,8 @@ int writeToFile(const std::string &fileName, const char *data, u32_t dataSize,
return 0;
}
int getFileLines(const std::string &fileName, u64_t &lineNum) {
int getFileLines(const std::string &fileName, u64_t &lineNum)
{
lineNum = 0;
char line[4 * ONE_KILO] = {0};
......@@ -133,14 +128,13 @@ int getFileLines(const std::string &fileName, u64_t &lineNum) {
return 0;
}
int getFileNum(u64_t &fileNum, const std::string &path,
const std::string &pattern, bool recursive) {
int getFileNum(u64_t &fileNum, const std::string &path, const std::string &pattern, bool recursive)
{
try {
DIR *dirp = NULL;
dirp = opendir(path.c_str());
if (dirp == NULL) {
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return -1;
}
......@@ -160,8 +154,7 @@ int getFileNum(u64_t &fileNum, const std::string &path,
fullPath += entry->d_name;
memset(&fs, 0, sizeof(fs));
if (stat(fullPath.c_str(), &fs) < 0) {
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
continue;
}
......@@ -181,8 +174,7 @@ int getFileNum(u64_t &fileNum, const std::string &path,
continue;
}
if (pattern.empty() == false &&
regex_match(entry->d_name, pattern.c_str())) {
if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
// Don't match
continue;
}
......@@ -194,20 +186,18 @@ int getFileNum(u64_t &fileNum, const std::string &path,
return 0;
} catch (...) {
std::cerr << "Failed to get file num " << path << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to get file num " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
}
return -1;
}
int getFileList(std::vector<std::string> &fileList, const std::string &path,
const std::string &pattern, bool recursive) {
int getFileList(std::vector<std::string> &fileList, const std::string &path, const std::string &pattern, bool recursive)
{
try {
DIR *dirp = NULL;
dirp = opendir(path.c_str());
if (dirp == NULL) {
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return -1;
}
......@@ -227,8 +217,7 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path,
fullPath += entry->d_name;
memset(&fs, 0, sizeof(fs));
if (stat(fullPath.c_str(), &fs) < 0) {
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
continue;
}
......@@ -248,8 +237,7 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path,
continue;
}
if (pattern.empty() == false &&
regex_match(entry->d_name, pattern.c_str())) {
if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
// Don't match
continue;
}
......@@ -260,20 +248,18 @@ int getFileList(std::vector<std::string> &fileList, const std::string &path,
closedir(dirp);
return 0;
} catch (...) {
std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
}
return -1;
}
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)
{
try {
DIR *dirp = NULL;
dirp = opendir(path.c_str());
if (dirp == NULL) {
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return -1;
}
......@@ -293,8 +279,7 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path,
fullPath += entry->d_name;
memset(&fs, 0, sizeof(fs));
if (stat(fullPath.c_str(), &fs) < 0) {
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
continue;
}
......@@ -302,8 +287,7 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path,
continue;
}
if (pattern.empty() == false &&
regex_match(entry->d_name, pattern.c_str())) {
if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
// Don't match
continue;
}
......@@ -314,15 +298,15 @@ int getDirList(std::vector<std::string> &dirList, const std::string &path,
closedir(dirp);
return 0;
} catch (...) {
std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
}
return -1;
}
int touch(const std::string &path) {
// CWE367: A check occurs on a file's attributes before
// the file is used in a privileged operation, but things
int touch(const std::string &path)
{
// CWE367: A check occurs on a file's attributes before
// the file is used in a privileged operation, but things
// may have changed
// struct stat fs;
......@@ -341,7 +325,8 @@ int touch(const std::string &path) {
return 0;
}
int getFileSize(const char *filePath, u64_t &fileLen) {
int getFileSize(const char *filePath, u64_t &fileLen)
{
if (filePath == NULL || *filePath == '\0') {
std::cerr << "invalid filepath" << std::endl;
return -EINVAL;
......@@ -351,8 +336,7 @@ int getFileSize(const char *filePath, u64_t &fileLen) {
int rc = stat(filePath, &statBuf);
if (rc) {
std::cerr << "Failed to get stat of " << filePath << "," << errno << ":"
<< strerror(errno) << std::endl;
std::cerr << "Failed to get stat of " << filePath << "," << errno << ":" << strerror(errno) << std::endl;
return rc;
}
......@@ -365,4 +349,4 @@ int getFileSize(const char *filePath, u64_t &fileLen) {
return 0;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -29,8 +29,7 @@ namespace common {
*/
int readFromFile(const std::string &fileName, char *&data, size_t &fileSize);
int writeToFile(const std::string &fileName, const char *data, u32_t dataSize,
const char *openMode);
int writeToFile(const std::string &fileName, const char *data, u32_t dataSize, const char *openMode);
/**
* return the line number which line.strip() isn't empty
......@@ -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
* @return 0 if success, error code otherwise
*/
int getFileList(std::vector<std::string> &fileList, const std::string &path,
const std::string &pattern, bool recursive);
int getFileNum(u64_t &fileNum, const std::string &path,
const std::string &pattern, bool recursive);
int getDirList(std::vector<std::string> &dirList, const std::string &path,
const std::string &pattern);
int getFileList(
std::vector<std::string> &fileList, const std::string &path, const std::string &pattern, bool recursive);
int getFileNum(u64_t &fileNum, const std::string &path, const std::string &pattern, bool recursive);
int getDirList(std::vector<std::string> &dirList, const std::string &path, const std::string &pattern);
int touch(const std::string &fileName);
......@@ -61,5 +58,5 @@ int touch(const std::string &fileName);
*/
int getFileSize(const char *filePath, u64_t &fileLen);
} //namespace common
} // namespace common
#endif /* __COMMON_IO_IO_H__ */
......@@ -17,7 +17,8 @@ See the Mulan PSL v2 for more details. */
#include "common/log/log.h"
namespace common {
void RollSelectDir::setBaseDir(std::string baseDir) {
void RollSelectDir::setBaseDir(std::string baseDir)
{
mBaseDir = baseDir;
std::vector<std::string> dirList;
......@@ -44,7 +45,8 @@ void RollSelectDir::setBaseDir(std::string baseDir) {
return;
}
std::string RollSelectDir::select() {
std::string RollSelectDir::select()
{
std::string ret;
MUTEX_LOCK(&mMutex);
......@@ -55,4 +57,4 @@ std::string RollSelectDir::select() {
return ret;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -26,8 +26,14 @@ namespace common {
class RollSelectDir : public SelectDir {
public:
RollSelectDir() { MUTEX_INIT(&mMutex, NULL); }
~RollSelectDir() { MUTEX_DESTROY(&mMutex); }
RollSelectDir()
{
MUTEX_INIT(&mMutex, NULL);
}
~RollSelectDir()
{
MUTEX_DESTROY(&mMutex);
}
public:
/**
......@@ -43,5 +49,5 @@ public:
u32_t mPos;
};
} //namespace common
} // namespace common
#endif /* __COMMON_IO_ROLL_SELECT_DIR__ */
......@@ -20,9 +20,12 @@ namespace common {
class SelectDir {
public:
virtual std::string select() { return std::string(""); };
virtual std::string select()
{
return std::string("");
};
virtual void setBaseDir(std::string baseDir){};
};
} //namespace common
} // namespace common
#endif /* __COMMON_IO_SELECT_DIR_H__ */
......@@ -14,10 +14,10 @@ See the Mulan PSL v2 for more details. */
#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++) {
if ((byte & (1 << i)) == 0) {
return i;
......@@ -26,7 +26,8 @@ int find_first_zero(char byte, int start) {
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++) {
if ((byte & (1 << i)) != 0) {
return i;
......@@ -35,25 +36,29 @@ int find_first_setted(char byte, int start) {
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];
return (bits & (1 << (index % 8))) != 0;
}
void Bitmap::set_bit(int index) {
void Bitmap::set_bit(int index)
{
char &bits = bitmap_[index / 8];
bits |= (1 << (index % 8));
}
void Bitmap::clear_bit(int index) {
void Bitmap::clear_bit(int index)
{
char &bits = bitmap_[index / 8];
bits &= ~(1 << (index % 8));
}
int Bitmap::next_unsetted_bit(int start) {
int Bitmap::next_unsetted_bit(int start)
{
int ret = -1;
int start_in_byte = start % 8;
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) {
return ret;
}
int Bitmap::next_setted_bit(int start) {
int Bitmap::next_setted_bit(int start)
{
int ret = -1;
int start_in_byte = start % 8;
for (int iter = start / 8, end = (size_ % 8 == 0 ? size_ / 8 : size_ / 8 + 1); iter <= end; iter++) {
......@@ -97,4 +103,4 @@ int Bitmap::next_setted_bit(int start) {
return ret;
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -15,8 +15,7 @@ See the Mulan PSL v2 for more details. */
#ifndef __COMMON_LANG_BITMAP_H__
#define __COMMON_LANG_BITMAP_H__
namespace common
{
namespace common {
class Bitmap {
public:
......@@ -26,14 +25,14 @@ public:
void set_bit(int index);
void clear_bit(int index);
int next_unsetted_bit(int start);
int next_setted_bit(int start);
int next_unsetted_bit(int start);
int next_setted_bit(int start);
private:
char * bitmap_;
int size_;
char *bitmap_;
int size_;
};
} // namespace common
} // namespace common
#endif // __COMMON_LANG_BITMAP_H__
\ No newline at end of file
#endif // __COMMON_LANG_BITMAP_H__
\ No newline at end of file
......@@ -27,37 +27,48 @@ int LockTrace::mMaxBlockTids = 8;
#define CHECK_UNLOCK 0
void LockTrace::foundDeadLock(LockID &current, LockTrace::LockID &other,
pthread_mutex_t *otherWaitMutex) {
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks =
mLocks.find(otherWaitMutex);
void LockTrace::foundDeadLock(LockID &current, LockTrace::LockID &other, pthread_mutex_t *otherWaitMutex)
{
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = mLocks.find(otherWaitMutex);
if (itLocks == mLocks.end()) {
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",
current.mThreadId, otherWaitMutex, current.mFile.c_str(),
current.mLine, other.mThreadId, current.mFile.c_str(),
current.mLine, otherWaitMutex);
current.mThreadId,
otherWaitMutex,
current.mFile.c_str(),
current.mLine,
other.mThreadId,
current.mFile.c_str(),
current.mLine,
otherWaitMutex);
} else {
LockTrace::LockID &otherRecusive = itLocks->second;
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",
current.mThreadId, otherWaitMutex, otherRecusive.mFile.c_str(),
otherRecusive.mLine, current.mFile.c_str(), current.mLine,
other.mThreadId, current.mFile.c_str(), current.mLine,
otherWaitMutex, otherRecusive.mFile.c_str(), otherRecusive.mLine);
current.mThreadId,
otherWaitMutex,
otherRecusive.mFile.c_str(),
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,
std::set<pthread_mutex_t *> &ownMutexs,
LockTrace::LockID &other, int recusiveNum) {
bool LockTrace::deadlockCheck(
LockID &current, std::set<pthread_mutex_t *> &ownMutexs, LockTrace::LockID &other, int recusiveNum)
{
if (recusiveNum >= mMaxBlockTids) {
return false;
}
std::map<long long, pthread_mutex_t *>::iterator otherIt =
mWaitLocks.find(other.mThreadId);
std::map<long long, pthread_mutex_t *>::iterator otherIt = mWaitLocks.find(other.mThreadId);
if (otherIt == mWaitLocks.end()) {
return false;
}
......@@ -69,8 +80,7 @@ bool LockTrace::deadlockCheck(LockID &current,
return true;
}
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks =
mLocks.find(otherWaitMutex);
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = mLocks.find(otherWaitMutex);
if (itLocks == mLocks.end()) {
return false;
}
......@@ -79,12 +89,11 @@ bool LockTrace::deadlockCheck(LockID &current,
return deadlockCheck(current, ownMutexs, otherRecusive, recusiveNum + 1);
}
bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line) {
bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
{
mWaitLocks[threadId] = mutex;
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks =
mLocks.find(mutex);
std::map<pthread_mutex_t *, LockTrace::LockID>::iterator itLocks = mLocks.find(mutex);
if (itLocks == mLocks.end()) {
return false;
}
......@@ -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 =
mOwnLocks.find(threadId);
std::map<long long, std::set<pthread_mutex_t *>>::iterator it = mOwnLocks.find(threadId);
if (it == mOwnLocks.end()) {
return false;
}
......@@ -115,8 +123,8 @@ bool LockTrace::deadlockCheck(pthread_mutex_t *mutex, const long long threadId,
return deadlockCheck(current, ownMutexs, other, 1);
}
bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file,
const int line) {
bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file, const int line)
{
std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.find(mutex);
if (it == mWaitTimes.end()) {
mWaitTimes.insert(std::pair<pthread_mutex_t *, int>(mutex, 1));
......@@ -132,8 +140,13 @@ bool LockTrace::checkLockTimes(pthread_mutex_t *mutex, const char *file,
LockTrace::LockID &lockId = mLocks[mutex];
LOG_WARN("mutex %p has been already lock %d times, this time %s:%d, first "
"time:%ld:%s:%d",
mutex, lockTimes, file, line, lockId.mThreadId,
lockId.mFile.c_str(), lockId.mLine);
mutex,
lockTimes,
file,
line,
lockId.mThreadId,
lockId.mFile.c_str(),
lockId.mLine);
return true;
} else {
......@@ -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,
const char *file, const int line) {
void LockTrace::check(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
{
MUTEX_LOG("Lock mutex %p, %s:%d", mutex, file, line);
pthread_rwlock_rdlock(&mMapMutex);
......@@ -153,8 +166,8 @@ void LockTrace::check(pthread_mutex_t *mutex, const long long threadId,
pthread_rwlock_unlock(&mMapMutex);
}
void LockTrace::insertLock(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line) {
void LockTrace::insertLock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
{
LockID lockID(threadId, file, line);
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,
}
}
void LockTrace::lock(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line) {
void LockTrace::lock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
{
pthread_rwlock_wrlock(&mMapMutex);
insertLock(mutex, threadId, file, line);
pthread_rwlock_unlock(&mMapMutex);
}
void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line) {
void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line)
{
pthread_rwlock_wrlock(&mMapMutex);
if (mLocks.find(mutex) != mLocks.end()) {
pthread_rwlock_unlock(&mMapMutex);
......@@ -194,8 +207,8 @@ void LockTrace::tryLock(pthread_mutex_t *mutex, const long long threadId,
pthread_rwlock_unlock(&mMapMutex);
}
void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId,
const char *file, int line) {
void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId, const char *file, int line)
{
pthread_rwlock_wrlock(&mMapMutex);
mLocks.erase(mutex);
......@@ -206,13 +219,13 @@ void LockTrace::unlock(pthread_mutex_t *mutex, long long threadId,
pthread_rwlock_unlock(&mMapMutex);
}
void LockTrace::toString(std::string &result) {
void LockTrace::toString(std::string &result)
{
const int TEMP_PAIR_LEN = 24;
// pthread_mutex_lock(&mMapMutex);
result = " mLocks:\n";
for (std::map<pthread_mutex_t *, LockID>::iterator it = mLocks.begin();
it != mLocks.end(); it++) {
for (std::map<pthread_mutex_t *, LockID>::iterator it = mLocks.begin(); it != mLocks.end(); it++) {
result += it->second.toString();
char pointerBuf[TEMP_PAIR_LEN] = {0};
......@@ -222,22 +235,21 @@ void LockTrace::toString(std::string &result) {
}
result += "mWaitTimes:\n";
for (std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.begin();
it != mWaitTimes.end(); it++) {
for (std::map<pthread_mutex_t *, int>::iterator it = mWaitTimes.begin(); it != mWaitTimes.end(); it++) {
char pointerBuf[TEMP_PAIR_LEN] = {0};
snprintf(pointerBuf, TEMP_PAIR_LEN, ",mutex:%p, times:%d\n", it->first,
it->second);
snprintf(pointerBuf, TEMP_PAIR_LEN, ",mutex:%p, times:%d\n", it->first, it->second);
result += pointerBuf;
}
result += "mWaitLocks:\n";
for (std::map<long long, pthread_mutex_t *>::iterator it = mWaitLocks.begin();
it != mWaitLocks.end(); it++) {
for (std::map<long long, pthread_mutex_t *>::iterator it = mWaitLocks.begin(); it != mWaitLocks.end(); it++) {
char pointerBuf[TEMP_PAIR_LEN] = {0};
snprintf(pointerBuf, TEMP_PAIR_LEN,
"threadID: %llx"
", mutex:%p\n",
it->first, it->second);
snprintf(pointerBuf,
TEMP_PAIR_LEN,
"threadID: %llx"
", mutex:%p\n",
it->first,
it->second);
result += pointerBuf;
}
// pthread_mutex_unlock(&mMapMutex);
......@@ -246,4 +258,4 @@ void LockTrace::toString(std::string &result) {
return;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -31,61 +31,55 @@ namespace common {
#define MUTEX_LOG LOG_DEBUG
class LockTrace {
public:
static void check(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,
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);
public:
static void check(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, 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);
class LockID {
public:
LockID(const long long threadId, const char *file, const int line)
: mFile(file), mThreadId(threadId), mLine(line) {}
LockID() : mFile(), mThreadId(0), mLine(0) {}
std::string toString() {
public:
LockID(const long long threadId, const char *file, const int line) : mFile(file), mThreadId(threadId), mLine(line)
{}
LockID() : mFile(), mThreadId(0), mLine(0)
{}
std::string toString()
{
std::ostringstream oss;
oss << "threaId:" << mThreadId << ",file name:" << mFile
<< ",line:" << mLine;
oss << "threaId:" << mThreadId << ",file name:" << mFile << ",line:" << mLine;
return oss.str();
}
public:
public:
std::string mFile;
const long long mThreadId;
int mLine;
};
static void foundDeadLock(LockID &current, LockID &other,
pthread_mutex_t *otherWaitMutex);
static void foundDeadLock(LockID &current, LockID &other, pthread_mutex_t *otherWaitMutex);
static bool deadlockCheck(LockID &current,
std::set<pthread_mutex_t *> &ownMutexs,
LockID &other, int recusiveNum);
static bool deadlockCheck(LockID &current, std::set<pthread_mutex_t *> &ownMutexs, LockID &other, int recusiveNum);
static bool deadlockCheck(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line);
static bool deadlockCheck(pthread_mutex_t *mutex, const long long threadId, const char *file, const int line);
static bool checkLockTimes(pthread_mutex_t *mutex, const char *file,
const int line);
static bool checkLockTimes(pthread_mutex_t *mutex, const char *file, const int line);
static void insertLock(pthread_mutex_t *mutex, const long long threadId,
const char *file, const int line);
static void insertLock(pthread_mutex_t *mutex, const long long threadId, 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;
protected:
protected:
static std::map<pthread_mutex_t *, LockID> mLocks;
static std::map<pthread_mutex_t *, int> mWaitTimes;
static std::map<long long, pthread_mutex_t *> mWaitLocks;
......@@ -108,57 +102,55 @@ class LockTrace {
#define COND_INIT(cond, attr) pthread_cond_init(cond, attr)
#define COND_DESTROY(cond) pthread_cond_destroy(cond)
#define COND_WAIT(cond, mutex) pthread_cond_wait(cond, mutex)
#define COND_WAIT_TIMEOUT(cond, mutex, time, ret) \
ret = pthread_cond_timedwait(cond, mutex, time)
#define COND_WAIT_TIMEOUT(cond, mutex, time, ret) ret = pthread_cond_timedwait(cond, mutex, time)
#define COND_SIGNAL(cond) pthread_cond_signal(cond)
#define COND_BRAODCAST(cond) pthread_cond_broadcast(cond)
#else // DEBUG_LOCK
#else // DEBUG_LOCK
#define MUTEX_STATIC_INIT() \
PTHREAD_MUTEX_INITIALIZER; \
#define MUTEX_STATIC_INIT() \
PTHREAD_MUTEX_INITIALIZER; \
LOG_INFO("PTHREAD_MUTEX_INITIALIZER");
#if defined(__MACH__)
#define MUTEX_INIT(lock, attr) \
({ \
LOG_INFO("pthread_mutex_init %p", lock); \
if (attr != NULL) { \
int type; \
pthread_mutexattr_gettype(attr, &type); \
if (type == PTHREAD_MUTEX_RECURSIVE) { \
LockTrace::mEnableRecurisives.insert(lock); \
} \
} \
int result = pthread_mutex_init(lock, attr); \
result; \
#define MUTEX_INIT(lock, attr) \
({ \
LOG_INFO("pthread_mutex_init %p", lock); \
if (attr != NULL) { \
int type; \
pthread_mutexattr_gettype(attr, &type); \
if (type == PTHREAD_MUTEX_RECURSIVE) { \
LockTrace::mEnableRecurisives.insert(lock); \
} \
} \
int result = pthread_mutex_init(lock, attr); \
result; \
})
#else
#define MUTEX_INIT(lock, attr) \
({ \
LOG_INFO("pthread_mutex_init %p", lock); \
if (attr != NULL) { \
int type; \
pthread_mutexattr_gettype(attr, &type); \
if (type == PTHREAD_MUTEX_RECURSIVE_NP) { \
LockTrace::mEnableRecurisives.insert(lock); \
} \
} \
int result = pthread_mutex_init(lock, attr); \
result; \
#define MUTEX_INIT(lock, attr) \
({ \
LOG_INFO("pthread_mutex_init %p", lock); \
if (attr != NULL) { \
int type; \
pthread_mutexattr_gettype(attr, &type); \
if (type == PTHREAD_MUTEX_RECURSIVE_NP) { \
LockTrace::mEnableRecurisives.insert(lock); \
} \
} \
int result = pthread_mutex_init(lock, attr); \
result; \
})
#endif
#define MUTEX_DESTROY(lock) \
({ \
LockTrace::mEnableRecurisives.erase(lock); \
int result = pthread_mutex_destroy(lock); \
LOG_INFO("pthread_mutex_destroy %p", lock); \
result; \
#define MUTEX_DESTROY(lock) \
({ \
LockTrace::mEnableRecurisives.erase(lock); \
int result = pthread_mutex_destroy(lock); \
LOG_INFO("pthread_mutex_destroy %p", lock); \
result; \
})
#define MUTEX_LOCK(mutex) \
......@@ -172,81 +164,80 @@ class LockTrace {
result; \
})
#define MUTEX_TRYLOCK(mutex) \
({ \
LockTrace::check(mutex, gettid(), __FILE__, __LINE__); \
int result = pthread_mutex_trylock(mutex); \
if (result == 0) { \
LockTrace::lock(mutex, gettid(), __FILE__, __LINE__); \
} \
result; \
#define MUTEX_TRYLOCK(mutex) \
({ \
LockTrace::check(mutex, gettid(), __FILE__, __LINE__); \
int result = pthread_mutex_trylock(mutex); \
if (result == 0) { \
LockTrace::lock(mutex, gettid(), __FILE__, __LINE__); \
} \
result; \
})
#define MUTEX_UNLOCK(lock) \
({ \
int result = pthread_mutex_unlock(lock); \
LockTrace::unlock(lock, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("mutex:%p has been ulocked", lock); \
if (result) { \
LOG_ERROR("Failed to unlock %p, rc %d:%s", lock, errno, \
strerror(errno)); \
} \
result; \
#define MUTEX_UNLOCK(lock) \
({ \
int result = pthread_mutex_unlock(lock); \
LockTrace::unlock(lock, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("mutex:%p has been ulocked", lock); \
if (result) { \
LOG_ERROR("Failed to unlock %p, rc %d:%s", lock, errno, strerror(errno)); \
} \
result; \
})
#define COND_INIT(cond, attr) \
({ \
LOG_INFO("pthread_cond_init"); \
int result = pthread_cond_init(cond, attr); \
result; \
#define COND_INIT(cond, attr) \
({ \
LOG_INFO("pthread_cond_init"); \
int result = pthread_cond_init(cond, attr); \
result; \
})
#define COND_DESTROY(cond) \
({ \
int result = pthread_cond_destroy(cond); \
LOG_INFO("pthread_cond_destroy"); \
result; \
#define COND_DESTROY(cond) \
({ \
int result = pthread_cond_destroy(cond); \
LOG_INFO("pthread_cond_destroy"); \
result; \
})
#define COND_WAIT(cond, mutex) \
({ \
MUTEX_LOG("pthread_cond_wait, cond:%p, mutex:%p", cond, mutex); \
LockTrace::unlock(mutex, gettid(), __FILE__, __LINE__); \
int result = pthread_cond_wait(cond, mutex); \
LockTrace::check(mutex, gettid(), __FILE__, __LINE__); \
LockTrace::lock(mutex, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("Lock %p under pthread_cond_wait", mutex); \
result; \
#define COND_WAIT(cond, mutex) \
({ \
MUTEX_LOG("pthread_cond_wait, cond:%p, mutex:%p", cond, mutex); \
LockTrace::unlock(mutex, gettid(), __FILE__, __LINE__); \
int result = pthread_cond_wait(cond, mutex); \
LockTrace::check(mutex, gettid(), __FILE__, __LINE__); \
LockTrace::lock(mutex, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("Lock %p under pthread_cond_wait", mutex); \
result; \
})
#define COND_WAIT_TIMEOUT(cond, mutex, time, ret) \
({ \
MUTEX_LOG("pthread_cond_timedwait, cond:%p, mutex:%p", cond, mutex); \
LockTrace::unlock(mutex, gettid(), __FILE__, __LINE__); \
int result = pthread_cond_timedwait(cond, mutex, time); \
if (result == 0) { \
LockTrace::check(mutex, gettid(), __FILE__, __LINE__); \
LockTrace::lock(mutex, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("Lock %p under pthread_cond_wait", mutex); \
} \
result; \
#define COND_WAIT_TIMEOUT(cond, mutex, time, ret) \
({ \
MUTEX_LOG("pthread_cond_timedwait, cond:%p, mutex:%p", cond, mutex); \
LockTrace::unlock(mutex, gettid(), __FILE__, __LINE__); \
int result = pthread_cond_timedwait(cond, mutex, time); \
if (result == 0) { \
LockTrace::check(mutex, gettid(), __FILE__, __LINE__); \
LockTrace::lock(mutex, gettid(), __FILE__, __LINE__); \
MUTEX_LOG("Lock %p under pthread_cond_wait", mutex); \
} \
result; \
})
#define COND_SIGNAL(cond) \
({ \
int result = pthread_cond_signal(cond); \
MUTEX_LOG("pthread_cond_signal, cond:%p", cond); \
result; \
#define COND_SIGNAL(cond) \
({ \
int result = pthread_cond_signal(cond); \
MUTEX_LOG("pthread_cond_signal, cond:%p", cond); \
result; \
})
#define COND_BRAODCAST(cond) \
({ \
int result = pthread_cond_broadcast(cond); \
MUTEX_LOG("pthread_cond_broadcast, cond:%p", cond); \
result; \
#define COND_BRAODCAST(cond) \
({ \
int result = pthread_cond_broadcast(cond); \
MUTEX_LOG("pthread_cond_broadcast, cond:%p", cond); \
result; \
})
#endif // DEBUG_LOCK
#endif // DEBUG_LOCK
} //namespace common
#endif // __COMMON_LANG_MUTEX_H__
} // namespace common
#endif // __COMMON_LANG_MUTEX_H__
......@@ -21,11 +21,7 @@ namespace common {
/**
* Through this type to determine object type
*/
enum {
MESSAGE_BASIC = 100,
MESSAGE_BASIC_REQUEST = 1000,
MESSAGE_BASIC_RESPONSE = -1000
};
enum { MESSAGE_BASIC = 100, MESSAGE_BASIC_REQUEST = 1000, MESSAGE_BASIC_RESPONSE = -1000 };
class Deserializable {
public:
......@@ -68,5 +64,5 @@ public:
virtual void to_string(std::string &output) const = 0;
};
} //namespace common
} // namespace common
#endif /* __COMMON_LANG_SERIALIZABLE_H__ */
......@@ -28,8 +28,9 @@ See the Mulan PSL v2 for more details. */
#include "common/log/log.h"
namespace common {
char *strip(char *str_) {
if (str_ == NULL || *str_ == 0){
char *strip(char *str_)
{
if (str_ == NULL || *str_ == 0) {
LOG_ERROR("The augument is invalid!");
return str_;
}
......@@ -45,7 +46,8 @@ char *strip(char *str_) {
return head;
}
void strip(std::string &str) {
void strip(std::string &str)
{
size_t head = 0;
while (isspace(str[head])) {
......@@ -61,24 +63,27 @@ void strip(std::string &str) {
}
// 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;
ss << std::setw(pad) << std::setfill('0') << size;
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);
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);
return s;
}
void split_string(const std::string &str, std::string delim,
std::set<std::string> &results) {
void split_string(const std::string &str, std::string delim, std::set<std::string> &results)
{
int cut_at;
std::string tmp_str(str);
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,
}
}
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, std::vector<std::string> &results)
{
int cut_at;
std::string tmp_str(str);
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,
}
}
void split_string(char *str, char dim, std::vector<char *> &results,
bool keep_null) {
void split_string(char *str, char dim, std::vector<char *> &results, bool keep_null)
{
char *p = str;
char *l = p;
while (*p) {
......@@ -127,11 +132,11 @@ void split_string(char *str, char dim, std::vector<char *> &results,
return;
}
void merge_string(std::string &str, std::string delim,
std::vector<std::string> &source, size_t result_len){
void merge_string(std::string &str, std::string delim, std::vector<std::string> &source, size_t result_len)
{
std::ostringstream ss;
if (source.empty() ) {
if (source.empty()) {
str = ss.str();
return;
}
......@@ -143,18 +148,17 @@ void merge_string(std::string &str, std::string delim,
for (unsigned int i = 0; i < result_len; i++) {
if (i == 0) {
ss << source[i];
}else {
} else {
ss << delim << source[i];
}
}
str = ss.str();
return ;
return;
}
void replace(std::string &str, const std::string &old,
const std::string &new_str) {
void replace(std::string &str, const std::string &old, const std::string &new_str)
{
if (old.compare(new_str) == 0) {
return;
}
......@@ -185,7 +189,8 @@ void replace(std::string &str, const std::string &old,
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;
unsigned char *end = (unsigned char *)s + len;
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) {
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 *src;
int src_len;
......@@ -225,7 +231,8 @@ char *hex_to_bin(const char *s, char *bin_buff, int *dest_len) {
return bin_buff;
}
bool is_blank(const char *s) {
bool is_blank(const char *s)
{
if (s == nullptr) {
return true;
}
......@@ -238,4 +245,4 @@ bool is_blank(const char *s) {
return true;
}
} //namespace common
} // namespace common
......@@ -65,20 +65,15 @@ std::string &str_to_lower(std::string &s);
* @param[in] delims elimiter characters
* @param[in,out] results ector containing the split up string
*/
void split_string(const std::string &str, std::string delim,
std::set<std::string> &results);
void split_string(const std::string &str, std::string delim,
std::vector<std::string> &results);
void split_string(char *str, char dim, std::vector<char *> &results,
bool keep_null = false);
void merge_string(std::string &str, std::string delim,
std::vector<std::string> &result, size_t result_len = 0);
void split_string(const std::string &str, std::string delim, std::set<std::string> &results);
void split_string(const std::string &str, std::string delim, std::vector<std::string> &results);
void split_string(char *str, char dim, std::vector<char *> &results, 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
*/
void replace(std::string &str, const std::string &old,
const std::string &new_str);
void replace(std::string &str, const std::string &old, const std::string &new_str);
/**
* binary to hexadecimal
......@@ -102,8 +97,7 @@ char *hex_to_bin(const char *s, char *bin_buff, int *dest_len);
* number, \c false otherwise
*/
template <class T>
bool str_to_val(const std::string &str, T &val,
std::ios_base &(*radix)(std::ios_base &) = std::dec);
bool str_to_val(const std::string &str, T &val, std::ios_base &(*radix)(std::ios_base &) = std::dec);
/**
* Convert a numeric value into its string representation
......@@ -116,17 +110,17 @@ bool str_to_val(const std::string &str, T &val,
* (hexidecimal).
*/
template <class T>
void val_to_str(const T &val, std::string &str,
std::ios_base &(*radix)(std::ios_base &) = std::dec);
void val_to_str(const T &val, std::string &str, std::ios_base &(*radix)(std::ios_base &) = std::dec);
/**
* 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>
bool str_to_val(const std::string &str, T &val,
std::ios_base &(*radix)(std::ios_base &)/* = std::dec */) {
bool str_to_val(const std::string &str, T &val, std::ios_base &(*radix)(std::ios_base &)/* = std::dec */)
{
bool success = true;
std::istringstream is(str);
if (!(is >> radix >> val)) {
......@@ -137,14 +131,16 @@ bool str_to_val(const std::string &str, T &val,
}
template <class T>
void val_to_str(const T &val, std::string &str,
std::ios_base &(*radix)(std::ios_base &)/* = std::dec */) {
void val_to_str(const T &val, std::string &str, std::ios_base &(*radix)(std::ios_base &)/* = std::dec */)
{
std::stringstream strm;
strm << radix << val;
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;
char *stmp = abi::__cxa_demangle(typeid(val).name(), 0, 0, &status);
if (!stmp)
......@@ -158,5 +154,5 @@ template <class T> std::string get_type_name(const T &val) {
bool is_blank(const char *s);
} //namespace common
#endif // __COMMON_LANG_STRING_H__
} // namespace common
#endif // __COMMON_LANG_STRING_H__
......@@ -23,9 +23,9 @@ namespace common {
Log *g_log = nullptr;
Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level,
const LOG_LEVEL console_level)
: log_name_(log_file_name), log_level_(log_level), console_level_(console_level) {
Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level, const LOG_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_ERR] = "ERROR:";
prefix_map_[LOG_LEVEL_WARN] = "WARNNING:";
......@@ -45,7 +45,8 @@ Log::Log(const std::string &log_file_name, const LOG_LEVEL log_level,
check_param_valid();
}
Log::~Log(void) {
Log::~Log(void)
{
pthread_mutex_lock(&lock_);
if (ofs_.is_open()) {
ofs_.close();
......@@ -55,7 +56,8 @@ Log::~Log(void) {
pthread_mutex_destroy(&lock_);
}
void Log::check_param_valid() {
void Log::check_param_valid()
{
assert(!log_name_.empty());
assert(LOG_LEVEL_PANIC <= log_level_ && log_level_ < LOG_LEVEL_LAST);
assert(LOG_LEVEL_PANIC <= console_level_ && console_level_ < LOG_LEVEL_LAST);
......@@ -63,7 +65,8 @@ void Log::check_param_valid() {
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_) {
return true;
}
......@@ -77,8 +80,8 @@ bool Log::check_output(const LOG_LEVEL level, const char *module) {
return false;
}
int Log::output(const LOG_LEVEL level, const char *module, const char *prefix,
const char *f, ...) {
int Log::output(const LOG_LEVEL level, const char *module, const char *prefix, const char *f, ...)
{
bool locked = false;
try {
va_list args;
......@@ -127,7 +130,8 @@ int Log::output(const LOG_LEVEL level, const char *module, const char *prefix,
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) {
console_level_ = console_level;
return LOG_STATUS_OK;
......@@ -136,9 +140,13 @@ int Log::set_console_level(LOG_LEVEL console_level) {
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) {
log_level_ = log_level;
return LOG_STATUS_OK;
......@@ -147,9 +155,13 @@ int Log::set_log_level(LOG_LEVEL log_level) {
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) {
return prefix_map_[level].c_str();
}
......@@ -157,22 +169,27 @@ const char *Log::prefix_msg(LOG_LEVEL level) {
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_);
}
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) {
rotate_type_ = rotate_type;
}
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) {
if (log_date_.year_ == year && log_date_.mon_ == month &&
log_date_.day_ == 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) {
// Don't need rotate
return 0;
}
......@@ -196,7 +213,8 @@ int Log::rotate_by_day(const int year, const int month, const int day) {
return 0;
}
int Log::rename_old_logs() {
int Log::rename_old_logs()
{
int log_index = 1;
int max_log_index = 0;
char log_index_str[4] = {0};
......@@ -234,7 +252,8 @@ int Log::rename_old_logs() {
return LOG_STATUS_OK;
}
int Log::rotate_by_size() {
int Log::rotate_by_size()
{
if (log_line_ < 0) {
// The first time open log file
ofs_.open(log_name_.c_str(), std::ios_base::out | std::ios_base::app);
......@@ -260,8 +279,7 @@ int Log::rotate_by_size() {
std::string log_name_new = log_name_ + "." + log_index_str;
result = rename(log_name_.c_str(), log_name_new.c_str());
if (result) {
std::cerr << "Failed to rename " << log_name_ << " to " << log_name_new
<< std::endl;
std::cerr << "Failed to rename " << log_name_ << " to " << log_name_new << std::endl;
}
ofs_.open(log_name_.c_str(), std::ios_base::out | std::ios_base::app);
......@@ -278,7 +296,8 @@ int Log::rotate_by_size() {
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;
pthread_mutex_lock(&lock_);
if (rotate_type_ == LOG_ROTATE_BYDAY) {
......@@ -291,17 +310,19 @@ int Log::rotate(const int year, const int month, const int day) {
return result;
}
LoggerFactory::LoggerFactory() {
LoggerFactory::LoggerFactory()
{
// Auto-generated constructor stub
}
LoggerFactory::~LoggerFactory() {
LoggerFactory::~LoggerFactory()
{
// Auto-generated destructor stub
}
int LoggerFactory::init(const std::string &log_file, Log **logger,
LOG_LEVEL log_level, LOG_LEVEL console_level,
LOG_ROTATE rotate_type) {
int LoggerFactory::init(
const std::string &log_file, Log **logger, LOG_LEVEL log_level, LOG_LEVEL console_level, LOG_ROTATE rotate_type)
{
Log *log = new (std::nothrow) Log(log_file, log_level, console_level);
if (log == nullptr) {
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,
return 0;
}
int LoggerFactory::init_default(const std::string &log_file, LOG_LEVEL log_level,
LOG_LEVEL console_level, LOG_ROTATE rotate_type) {
int LoggerFactory::init_default(
const std::string &log_file, LOG_LEVEL log_level, LOG_LEVEL console_level, LOG_ROTATE rotate_type)
{
if (g_log != nullptr) {
LOG_WARN("Default logger has been initialized");
return 0;
......@@ -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);
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -45,14 +45,10 @@ typedef enum {
LOG_LEVEL_LAST
} LOG_LEVEL;
typedef enum {
LOG_ROTATE_BYDAY = 0,
LOG_ROTATE_BYSIZE,
LOG_ROTATE_LAST
} LOG_ROTATE;
typedef enum { LOG_ROTATE_BYDAY = 0, LOG_ROTATE_BYSIZE, LOG_ROTATE_LAST } LOG_ROTATE;
class Log {
public:
public:
Log(const std::string &log_name, const LOG_LEVEL log_level = LOG_LEVEL_INFO,
const LOG_LEVEL console_level = LOG_LEVEL_WARN);
~Log(void);
......@@ -65,29 +61,28 @@ class Log {
* If the header information should be outputed
* please use LOG_PANIC, LOG_ERROR ...
*/
template<class T>
template <class T>
Log &operator<<(T message);
template<class T>
template <class T>
int panic(T message);
template<class T>
template <class T>
int error(T message);
template<class T>
template <class T>
int warnning(T message);
template<class T>
template <class T>
int info(T message);
template<class T>
template <class T>
int debug(T message);
template<class T>
template <class T>
int trace(T message);
int output(const LOG_LEVEL level, const char *module, const char *prefix,
const char *f, ...);
int output(const LOG_LEVEL level, const char *module, const char *prefix, const char *f, ...);
int set_console_level(const LOG_LEVEL console_level);
LOG_LEVEL get_console_level();
......@@ -110,17 +105,17 @@ class Log {
int rotate(const int year = 0, const int month = 0, const int day = 0);
private:
private:
void check_param_valid();
int rotate_by_size();
int rename_old_logs();
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);
private:
private:
pthread_mutex_t lock_;
std::ofstream ofs_;
std::string log_name_;
......@@ -145,57 +140,63 @@ class Log {
};
class LoggerFactory {
public:
public:
LoggerFactory();
virtual ~LoggerFactory();
static int init(const std::string &log_file, Log **logger,
LOG_LEVEL log_level = LOG_LEVEL_INFO,
LOG_LEVEL console_level = LOG_LEVEL_WARN,
LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
static int init(const std::string &log_file, Log **logger, LOG_LEVEL log_level = LOG_LEVEL_INFO,
LOG_LEVEL console_level = LOG_LEVEL_WARN, LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
static int init_default(const std::string &log_file,
LOG_LEVEL log_level = LOG_LEVEL_INFO,
LOG_LEVEL console_level = LOG_LEVEL_WARN,
LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
static int init_default(const std::string &log_file, LOG_LEVEL log_level = LOG_LEVEL_INFO,
LOG_LEVEL console_level = LOG_LEVEL_WARN, LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
};
extern Log *g_log;
#ifndef __FILE_NAME__
#define __FILE_NAME__ (strrchr(__FILE__,'/')?strrchr(__FILE__,'/')+1:__FILE__)
#define __FILE_NAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#endif
#define LOG_HEAD(prefix, level) \
if (common::g_log) { \
time_t now_time; \
time(&now_time); \
struct tm *p = localtime(&now_time); \
char sz_head[64] = {0}; \
if (p) { \
sprintf(sz_head, "%d-%d-%d %d:%d:%u pid:%u tid:%llx ", 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); \
} \
snprintf(prefix, sizeof(prefix), "[%s %s %s %s %u]>>", sz_head, \
(common::g_log)->prefix_msg(level), __FILE_NAME__, \
__FUNCTION__, (u32_t)__LINE__); \
#define LOG_HEAD(prefix, level) \
if (common::g_log) { \
time_t now_time; \
time(&now_time); \
struct tm *p = localtime(&now_time); \
char sz_head[64] = {0}; \
if (p) { \
sprintf(sz_head, \
"%d-%d-%d %d:%d:%u pid:%u tid:%llx ", \
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); \
} \
snprintf(prefix, \
sizeof(prefix), \
"[%s %s %s %s %u]>>", \
sz_head, \
(common::g_log)->prefix_msg(level), \
__FILE_NAME__, \
__FUNCTION__, \
(u32_t)__LINE__); \
}
#define LOG_OUTPUT(level, fmt, ...) \
do { \
using namespace common; \
if (g_log && g_log->check_output(level, __FILE_NAME__)) { \
char prefix[ONE_KILO] = {0}; \
LOG_HEAD(prefix, level); \
g_log->output(level, __FILE_NAME__, prefix, fmt, ##__VA_ARGS__); \
} \
#define LOG_OUTPUT(level, fmt, ...) \
do { \
using namespace common; \
if (g_log && g_log->check_output(level, __FILE_NAME__)) { \
char prefix[ONE_KILO] = {0}; \
LOG_HEAD(prefix, level); \
g_log->output(level, __FILE_NAME__, prefix, fmt, ##__VA_ARGS__); \
} \
} while (0)
#define LOG_DEFAULT(fmt, ...) \
LOG_OUTPUT(common::g_log->get_log_level(), fmt, ##__VA_ARGS__)
#define LOG_DEFAULT(fmt, ...) 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_ERROR(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_ERR, fmt, ##__VA_ARGS__)
#define LOG_WARN(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_WARN, fmt, ##__VA_ARGS__)
......@@ -203,48 +204,56 @@ extern Log *g_log;
#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__)
template<class T>
Log &Log::operator<<(T msg) {
template <class T>
Log &Log::operator<<(T msg)
{
// at this time, the input level is the default log level
out(console_level_, log_level_, msg);
return *this;
}
template<class T>
int Log::panic(T message) {
template <class T>
int Log::panic(T message)
{
return out(LOG_LEVEL_PANIC, LOG_LEVEL_PANIC, message);
}
template<class T>
int Log::error(T message) {
template <class T>
int Log::error(T message)
{
return out(LOG_LEVEL_ERR, LOG_LEVEL_ERR, message);
}
template<class T>
int Log::warnning(T message) {
template <class T>
int Log::warnning(T message)
{
return out(LOG_LEVEL_WARN, LOG_LEVEL_WARN, message);
}
template<class T>
int Log::info(T message) {
template <class T>
int Log::info(T message)
{
return out(LOG_LEVEL_INFO, LOG_LEVEL_INFO, message);
}
template<class T>
int Log::debug(T message) {
template <class T>
int Log::debug(T message)
{
return out(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, message);
}
template<class T>
int Log::trace(T message) {
template <class T>
int Log::trace(T message)
{
return out(LOG_LEVEL_TRACE, LOG_LEVEL_TRACE, message);
}
template<class T>
int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg) {
template <class T>
int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg)
{
bool locked = false;
if (console_level < LOG_LEVEL_PANIC || console_level > console_level_ ||
log_level < LOG_LEVEL_PANIC || log_level > log_level_) {
if (console_level < LOG_LEVEL_PANIC || console_level > console_level_ || log_level < LOG_LEVEL_PANIC ||
log_level > log_level_) {
return LOG_STATUS_OK;
}
try {
......@@ -276,21 +285,20 @@ int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg) {
}
#ifndef ASSERT
#define ASSERT(expression, description, ...) \
do { \
if (!(expression)) { \
if (common::g_log) { \
LOG_PANIC(description, ##__VA_ARGS__); \
LOG_PANIC("\n"); \
} \
assert(expression); \
} \
#define ASSERT(expression, description, ...) \
do { \
if (!(expression)) { \
if (common::g_log) { \
LOG_PANIC(description, ##__VA_ARGS__); \
LOG_PANIC("\n"); \
} \
assert(expression); \
} \
} while (0)
#endif // ASSERT
#endif // ASSERT
#define SYS_OUTPUT_FILE_POS \
", File:" << __FILE__ << ", line:" << __LINE__ << ",function:" << __FUNCTION__
#define SYS_OUTPUT_FILE_POS ", File:" << __FILE__ << ", line:" << __LINE__ << ",function:" << __FUNCTION__
#define SYS_OUTPUT_ERROR ",error:" << errno << ":" << strerror(errno)
} //namespace common
#endif //__COMMON_LOG_LOG_H__
} // namespace common
#endif //__COMMON_LOG_LOG_H__
......@@ -41,10 +41,70 @@ static void Decode(UINT4 *, unsigned char *, unsigned int);
static void MD5_memcpy(POINTER, POINTER, unsigned int);
static void MD5_memset(POINTER, int, unsigned int);
static unsigned char PADDING[64] = {
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};
static unsigned char PADDING[64] = {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};
/*
* F, G, H and I are basic MD5 functions.
......@@ -63,35 +123,36 @@ static unsigned char PADDING[64] = {
* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is
* separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) \
{ \
(a) += F((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
#define FF(a, b, c, d, x, s, ac) \
{ \
(a) += F((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) \
{ \
(a) += G((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
#define GG(a, b, c, d, x, s, ac) \
{ \
(a) += G((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) \
{ \
(a) += H((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
#define HH(a, b, c, d, x, s, ac) \
{ \
(a) += H((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) \
{ \
(a) += I((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
#define II(a, b, c, d, x, s, ac) \
{ \
(a) += I((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT((a), (s)); \
(a) += (b); \
}
/*
* 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;
/*
* Load magic initialization constants.
......@@ -106,16 +167,17 @@ void MD5Init(MD5_CTX *context) {
* MD5 block update operation. Continues an MD5 message-digest operation,
* 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;
/* 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 */
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] += ((UINT4) inputLen >> 29);
context->count[1] += ((UINT4)inputLen >> 29);
partLen = 64 - index;
......@@ -123,7 +185,7 @@ void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) {
* Transform as many times as possible.
*/
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);
for (i = partLen; i + 63 < inputLen; i += 64)
......@@ -134,15 +196,15 @@ void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen) {
i = 0;
/* Buffer remaining input */
MD5_memcpy((POINTER) & context->buffer[index], (POINTER) & input[i],
inputLen - i);
MD5_memcpy((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen - i);
}
/*
* MD5 finalization. Ends an MD5 message-digest operation, writing the the
* 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 int index, padLen;
......@@ -152,7 +214,7 @@ void MD5Final(unsigned char digest[16], MD5_CTX *context) {
/*
* 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);
MD5Update(context, PADDING, padLen);
......@@ -164,13 +226,14 @@ void MD5Final(unsigned char digest[16], MD5_CTX *context) {
/*
* 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.
*/
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];
Decode(x, block, 64);
......@@ -256,21 +319,22 @@ static void MD5Transform(UINT4 state[4], unsigned char block[64]) {
* 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
* 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;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char) (input[i] & 0xff);
output[j + 1] = (unsigned char) ((input[i] >> 8) & 0xff);
output[j + 2] = (unsigned char) ((input[i] >> 16) & 0xff);
output[j + 3] = (unsigned char) ((input[i] >> 24) & 0xff);
output[j] = (unsigned char)(input[i] & 0xff);
output[j + 1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j + 2] = (unsigned char)((input[i] >> 16) & 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) {
* Decodes input (unsigned char) into output (UINT4). Assumes len is a
* 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;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT4) input[j]) | (((UINT4) input[j + 1]) << 8) |
(((UINT4) input[j + 2]) << 16) | (((UINT4) input[j + 3]) << 24);
output[i] = ((UINT4)input[j]) | (((UINT4)input[j + 1]) << 8) | (((UINT4)input[j + 2]) << 16) |
(((UINT4)input[j + 3]) << 24);
}
/*
* 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;
for (i = 0; i < len; i++)
......@@ -300,36 +366,40 @@ static void MD5_memcpy(POINTER output, POINTER input, unsigned int len) {
/*
* 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;
for (i = 0; i < len; i++)
((char *) output)[i] = (char) value;
((char *)output)[i] = (char)value;
}
/*
* Digests a string
*/
int MD5String(char *string, unsigned char digest[16]) {
int MD5String(char *string, unsigned char digest[16])
{
MD5_CTX context;
unsigned int len = strlen(string);
MD5Init(&context);
MD5Update(&context, (unsigned char *) string, len);
MD5Update(&context, (unsigned char *)string, len);
MD5Final(digest, &context);
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;
MD5Init(&context);
MD5Update(&context, (unsigned char *) buffer, len);
MD5Update(&context, (unsigned char *)buffer, len);
MD5Final(digest, &context);
return 0;
}
int MD5File(char *filename, unsigned char digest[16]) {
int MD5File(char *filename, unsigned char digest[16])
{
FILE *file;
MD5_CTX context;
int len;
......@@ -349,4 +419,4 @@ int MD5File(char *filename, unsigned char digest[16]) {
return 0;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -66,5 +66,5 @@ void MD5Final(unsigned char[16], MD5_CTX *);
}
#endif
} //namespace common
#endif //__COMMON_MATH_MD5_H__
} // namespace common
#endif //__COMMON_MATH_MD5_H__
......@@ -12,27 +12,26 @@ See the Mulan PSL v2 for more details. */
// Created by Longda on 2021/4/20.
//
#include <chrono>
#include "common/math/random_generator.h"
namespace common {
RandomGenerator::RandomGenerator()
: randomData(std::chrono::system_clock::now().time_since_epoch().count()) {}
RandomGenerator::~RandomGenerator() {}
RandomGenerator::RandomGenerator() : randomData(std::chrono::system_clock::now().time_since_epoch().count())
{}
unsigned int RandomGenerator::next() {
RandomGenerator::~RandomGenerator()
{}
unsigned int RandomGenerator::next()
{
return randomData();
}
unsigned int RandomGenerator::next(unsigned int range) {
unsigned int RandomGenerator::next(unsigned int range)
{
if (range > 0) {
return next() % range;
} else {
......@@ -40,4 +39,4 @@ unsigned int RandomGenerator::next(unsigned int range) {
}
}
}//namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -16,27 +16,25 @@ See the Mulan PSL v2 for more details. */
#include <stdlib.h>
#include <random>
namespace common
{
namespace common {
#define DEFAULT_RANDOM_BUFF_SIZE 512
class RandomGenerator
{
class RandomGenerator {
public:
RandomGenerator();
virtual ~RandomGenerator();
RandomGenerator();
virtual ~RandomGenerator();
public:
unsigned int next();
unsigned int next(unsigned int range);
unsigned int next();
unsigned int next(unsigned int range);
private:
// The GUN Extended TLS Version
std::mt19937 randomData;
// The GUN Extended TLS Version
std::mt19937 randomData;
};
}
} // namespace common
#endif /* __COMMON_MATH_RANDOM_GENERATOR_H_ */
......@@ -19,7 +19,8 @@ See the Mulan PSL v2 for more details. */
#include "common/math/regex.h"
namespace common {
int regex_match(const char *str_, const char *pat_) {
int regex_match(const char *str_, const char *pat_)
{
regex_t reg;
if (regcomp(&reg, pat_, REG_EXTENDED | REG_NOSUB))
return -1;
......@@ -29,4 +30,4 @@ int regex_match(const char *str_, const char *pat_) {
return ret;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -18,5 +18,5 @@ namespace common {
int regex_match(const char *str_, const char *pat_);
} //namespace common
} // namespace common
#endif /* __COMMON_MATH_REGEX_H__ */
......@@ -21,13 +21,15 @@ See the Mulan PSL v2 for more details. */
namespace common {
ConsoleReporter *get_console_reporter() {
ConsoleReporter *get_console_reporter()
{
static ConsoleReporter *instance = new ConsoleReporter();
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();
if (snapshot != NULL) {
......@@ -37,4 +39,4 @@ void ConsoleReporter::report(const std::string &tag, Metric *metric) {
}
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -19,12 +19,11 @@ See the Mulan PSL v2 for more details. */
namespace common {
class ConsoleReporter : public Reporter {
public:
void report(const std::string &tag, Metric *metric);
};
ConsoleReporter* get_console_reporter();
} //namespace common
#endif //__COMMON_METRICS_CONSOLE_REPORTER_H__
ConsoleReporter *get_console_reporter();
} // namespace common
#endif //__COMMON_METRICS_CONSOLE_REPORTER_H__
......@@ -24,145 +24,129 @@ See the Mulan PSL v2 for more details. */
namespace common {
HistogramSnapShot::HistogramSnapShot()
{
}
{}
HistogramSnapShot::HistogramSnapShot(const std::vector<double>& collection)
HistogramSnapShot::HistogramSnapShot(const std::vector<double> &collection)
{
set_collection(collection);
}
HistogramSnapShot::~HistogramSnapShot()
{
}
{}
void HistogramSnapShot::set_collection(const std::vector<double>& collection)
void HistogramSnapShot::set_collection(const std::vector<double> &collection)
{
if (collection.empty())
{
return;
}
data_ = collection;
std::sort(data_.begin(), data_.end());
if (collection.empty()) {
return;
}
data_ = collection;
std::sort(data_.begin(), data_.end());
}
size_t HistogramSnapShot::size() const
{
return data_.size();
return data_.size();
}
double HistogramSnapShot::get_value(double quantile)
{
if (quantile > 1.0f)
{
quantile = 1.0f;
}
if (quantile < 0.0f)
{
quantile = 0.0f;
}
if (data_.empty())
{
return 0.0f;
}
double pos = quantile * (data_.size() + 1);
if (pos < 1)
{
return data_[0];
}
if (pos >= data_.size())
{
return data_[data_.size() - 1];
}
double lower = data_[(int) pos - 1];
double upper = data_[(int) pos];
return lower + (pos - floor(pos)) * (upper - lower);
if (quantile > 1.0f) {
quantile = 1.0f;
}
if (quantile < 0.0f) {
quantile = 0.0f;
}
if (data_.empty()) {
return 0.0f;
}
double pos = quantile * (data_.size() + 1);
if (pos < 1) {
return data_[0];
}
if (pos >= data_.size()) {
return data_[data_.size() - 1];
}
double lower = data_[(int)pos - 1];
double upper = data_[(int)pos];
return lower + (pos - floor(pos)) * (upper - lower);
}
double HistogramSnapShot::get_median()
{
return get_value(0.5f);
return get_value(0.5f);
}
double HistogramSnapShot::get_75th()
{
return get_value(0.75f);
return get_value(0.75f);
}
double HistogramSnapShot::get_90th()
{
return get_value(0.90f);
return get_value(0.90f);
}
double HistogramSnapShot::get_95th()
{
return get_value(0.95f);
return get_value(0.95f);
}
double HistogramSnapShot::get_99th()
{
return get_value(0.99f);
return get_value(0.99f);
}
double HistogramSnapShot::get_999th()
{
return get_value(0.999f);
return get_value(0.999f);
}
double HistogramSnapShot::get_max()
{
if (data_.empty())
{
return 0.0f;
}
return static_cast<double>(*data_.rbegin());
if (data_.empty()) {
return 0.0f;
}
return static_cast<double>(*data_.rbegin());
}
double HistogramSnapShot::get_min()
{
if (data_.empty())
{
return 0.0f;
}
return static_cast<double>(*data_.begin());
if (data_.empty()) {
return 0.0f;
}
return static_cast<double>(*data_.begin());
}
double HistogramSnapShot::get_mean()
{
if (data_.empty())
{
return 0.0f;
}
return std::accumulate(data_.begin(), data_.end(), (double)0) * 1.0f / data_.size();
}
if (data_.empty()) {
return 0.0f;
}
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;
oss << "mean:" << get_mean() << ",min:" << get_min() << ",max:" << get_max()
<< ",median:" << get_median() << ", 75th:" << get_75th()
<< ",90th:" << get_90th() << ",99th:" << get_99th()
<< ",999th:" << get_999th();
oss << "mean:" << get_mean() << ",min:" << get_min() << ",max:" << get_max() << ",median:" << get_median()
<< ", 75th:" << get_75th() << ",90th:" << get_90th() << ",99th:" << get_99th() << ",999th:" << get_999th();
return oss.str();
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -65,10 +65,11 @@ public:
const std::vector<double> &get_values();
std::string to_string();
protected:
std::vector<double> data_;
};
} // namespace common
} // namespace common
#endif /* __COMMON_METRICS_HISTOGRAM_SNAPSHOT_H_ */
......@@ -19,23 +19,24 @@ See the Mulan PSL v2 for more details. */
#include "common/metrics/metric.h"
#include "common/log/log.h"
namespace common {
LogReporter* get_log_reporter() {
static LogReporter* instance = new LogReporter();
LogReporter *get_log_reporter()
{
static LogReporter *instance = new LogReporter();
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();
if (snapshot != NULL) {
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());
}
}
}// namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -19,12 +19,11 @@ See the Mulan PSL v2 for more details. */
namespace common {
class LogReporter : public Reporter {
public:
void report(const std::string &tag, Metric *metric);
};
LogReporter* get_log_reporter();
} //namespace common
#endif //__COMMON_METRICS_LOG_REPORTER_H__
LogReporter *get_log_reporter();
} // namespace common
#endif //__COMMON_METRICS_LOG_REPORTER_H__
......@@ -23,11 +23,14 @@ class Metric {
public:
virtual void snapshot() = 0;
virtual Snapshot *get_snapshot() { return snapshot_value_; }
virtual Snapshot *get_snapshot()
{
return snapshot_value_;
}
protected:
Snapshot *snapshot_value_;
};
}//namespace common
#endif //__COMMON_METRICS_METRIC_H__
} // namespace common
#endif //__COMMON_METRICS_METRIC_H__
......@@ -16,7 +16,8 @@ See the Mulan PSL v2 for more details. */
#include "common/lang/mutex.h"
namespace common {
Meter::Meter() {
Meter::Meter()
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
......@@ -24,17 +25,26 @@ Meter::Meter() {
value_.store(0l);
}
Meter::~Meter() {
Meter::~Meter()
{
if (snapshot_value_ != NULL) {
delete snapshot_value_;
snapshot_value_ = NULL;
}
}
void Meter::inc(long increase) { value_.fetch_add(increase); }
void Meter::inc() { inc(1l); }
void Meter::inc(long increase)
{
value_.fetch_add(increase);
}
void Meter::inc()
{
inc(1l);
}
void Meter::snapshot() {
void Meter::snapshot()
{
// lock here
struct timeval now;
......@@ -42,8 +52,7 @@ void Meter::snapshot() {
long now_tick = now.tv_sec * 1000000 + now.tv_usec;
double temp_value =
((double)value_.exchange(0l)) / ((now_tick - snapshot_tick_ ) / 1000000);
double temp_value = ((double)value_.exchange(0l)) / ((now_tick - snapshot_tick_) / 1000000);
snapshot_tick_ = now_tick;
if (snapshot_value_ == NULL) {
......@@ -52,21 +61,27 @@ void Meter::snapshot() {
((SnapshotBasic<double> *)snapshot_value_)->setValue(temp_value);
}
SimpleTimer::~SimpleTimer() {
SimpleTimer::~SimpleTimer()
{
if (snapshot_value_ != NULL) {
delete snapshot_value_;
snapshot_value_ = NULL;
}
}
void SimpleTimer::inc(long increase) {
void SimpleTimer::inc(long increase)
{
value_.fetch_add(increase);
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
struct timeval now;
......@@ -81,7 +96,7 @@ void SimpleTimer::snapshot() {
double mean = 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;
}
......@@ -93,21 +108,22 @@ void SimpleTimer::snapshot() {
((SimplerTimerSnapshot *)snapshot_value_)->setValue(mean, tps);
}
Histogram::Histogram(RandomGenerator &random) : UniformReservoir(random) {}
Histogram::Histogram(RandomGenerator &random, size_t size)
: UniformReservoir(random, size) {}
Histogram::Histogram(RandomGenerator &random) : UniformReservoir(random)
{}
Histogram::~Histogram() {
Histogram::Histogram(RandomGenerator &random, size_t size) : UniformReservoir(random, size)
{}
}
Histogram::~Histogram()
{}
void Histogram::snapshot() {
void Histogram::snapshot()
{
UniformReservoir::snapshot();
}
Timer::Timer(RandomGenerator &random)
: UniformReservoir(random){
Timer::Timer(RandomGenerator &random) : UniformReservoir(random)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
......@@ -115,8 +131,8 @@ Timer::Timer(RandomGenerator &random)
value_.store(0l);
}
Timer::Timer(RandomGenerator &random, size_t size)
: UniformReservoir(random, size){
Timer::Timer(RandomGenerator &random, size_t size) : UniformReservoir(random, size)
{
struct timeval start_time;
gettimeofday(&start_time, NULL);
......@@ -124,19 +140,22 @@ Timer::Timer(RandomGenerator &random, size_t size)
value_.store(0l);
}
Timer::~Timer() {
Timer::~Timer()
{
if (snapshot_value_ == NULL) {
delete snapshot_value_;
snapshot_value_ = NULL;
}
}
void Timer::update(double ms) {
void Timer::update(double ms)
{
UniformReservoir::update(ms);
value_.fetch_add(1l);
}
void Timer::snapshot() {
void Timer::snapshot()
{
if (snapshot_value_ == NULL) {
snapshot_value_ = new TimerSnapshot();
}
......@@ -147,8 +166,7 @@ void Timer::snapshot() {
long now_tick = now.tv_sec * 1000000 + now.tv_usec;
double tps =
((double)value_.exchange(0l) )/ ((now_tick - snapshot_tick_ ) / 1000000);
double tps = ((double)value_.exchange(0l)) / ((now_tick - snapshot_tick_) / 1000000);
snapshot_tick_ = now_tick;
MUTEX_LOCK(&mutex);
......@@ -159,13 +177,14 @@ void Timer::snapshot() {
timer_snapshot->set_tps(tps);
}
TimerStat::TimerStat(SimpleTimer &other_st)
: st_(other_st), start_tick_(0), end_tick_(0) {
TimerStat::TimerStat(SimpleTimer &other_st) : st_(other_st), start_tick_(0), end_tick_(0)
{
start();
}
TimerStat::~TimerStat() {
TimerStat::~TimerStat()
{
if (end_tick_ == 0) {
end();
}
......@@ -173,18 +192,20 @@ TimerStat::~TimerStat() {
st_.update((end_tick_ - start_tick_) / 1000);
}
void TimerStat::start() {
void TimerStat::start()
{
struct timeval now;
gettimeofday(&now, NULL);
start_tick_ = now.tv_sec * 1000000 + now.tv_usec;
}
void TimerStat::end() {
void TimerStat::end()
{
struct timeval now;
gettimeofday(&now, NULL);
end_tick_ = now.tv_sec * 1000000 + now.tv_usec;
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -27,17 +27,23 @@ namespace common {
class Gauge : public Metric {
public:
// user implement snapshot function
void set_snapshot(Snapshot *value) { snapshot_value_ = value; }
void set_snapshot(Snapshot *value)
{
snapshot_value_ = value;
}
};
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 {
public:
Meter();
virtual ~Meter();
virtual ~Meter();
void inc(long increase);
void inc();
......@@ -76,7 +82,6 @@ public:
virtual ~Histogram();
void snapshot();
};
// timeunit is ms
......@@ -109,5 +114,5 @@ public:
long end_tick_;
};
} // namespace common
#endif //__COMMON_METRICS_METRICS_H__
} // namespace common
#endif //__COMMON_METRICS_METRICS_H__
......@@ -12,32 +12,33 @@ See the Mulan PSL v2 for more details. */
// Created by Longda on 2021/4/20.
//
#include "common/metrics/metrics_registry.h"
#include "common/log/log.h"
namespace common {
MetricsRegistry& get_metrics_registry() {
MetricsRegistry &get_metrics_registry()
{
static MetricsRegistry instance;
return instance;
}
void MetricsRegistry::register_metric(const std::string &tag, Metric *metric) {
std::map<std::string, Metric*>::iterator it = metrics.find(tag);
void MetricsRegistry::register_metric(const std::string &tag, Metric *metric)
{
std::map<std::string, Metric *>::iterator it = metrics.find(tag);
if (it != metrics.end()) {
LOG_WARN("%s has been registered!", tag.c_str());
return;
}
//metrics[tag] = metric;
// metrics[tag] = metric;
metrics.insert(std::pair<std::string, Metric *>(tag, metric));
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);
if (num == 0) {
LOG_WARN("There is no %s metric!", tag.c_str());
......@@ -46,22 +47,22 @@ void MetricsRegistry::unregister(const std::string &tag) {
LOG_INFO("Successfully remove metric of %s", tag.c_str());
}
void MetricsRegistry::snapshot() {
std::map<std::string, Metric*>::iterator it = metrics.begin();
void MetricsRegistry::snapshot()
{
std::map<std::string, Metric *>::iterator it = metrics.begin();
for (; it != metrics.end(); it++) {
it->second->snapshot();
}
}
void MetricsRegistry::report() {
for (std::list<Reporter *>::iterator reporterIt = reporters.begin();
reporterIt != reporters.end(); reporterIt++) {
for (std::map<std::string, Metric*>::iterator it = metrics.begin();
it != metrics.end(); it++) {
void MetricsRegistry::report()
{
for (std::list<Reporter *>::iterator reporterIt = reporters.begin(); reporterIt != reporters.end(); reporterIt++) {
for (std::map<std::string, Metric *>::iterator it = metrics.begin(); it != metrics.end(); it++) {
(*reporterIt)->report(it->first, it->second);
}
}
}
} // namespace common
} // namespace common
......@@ -26,7 +26,7 @@ namespace common {
class MetricsRegistry {
public:
MetricsRegistry() {};
MetricsRegistry(){};
virtual ~MetricsRegistry(){};
void register_metric(const std::string &tag, Metric *metric);
......@@ -36,18 +36,16 @@ public:
void report();
void add_reporter(Reporter *reporter) {
void add_reporter(Reporter *reporter)
{
reporters.push_back(reporter);
}
protected:
std::map<std::string, Metric *> metrics;
std::list<Reporter *> reporters;
};
MetricsRegistry& get_metrics_registry();
}//namespace common
#endif //__COMMON_METRICS_METRICS_REGISTRY_H__
MetricsRegistry &get_metrics_registry();
} // namespace common
#endif //__COMMON_METRICS_METRICS_REGISTRY_H__
......@@ -20,10 +20,9 @@ See the Mulan PSL v2 for more details. */
namespace common {
class Reporter {
public:
virtual void report(const std::string &tag, Metric *metric) = 0;
};
} // namespace Reporter
#endif //__COMMON_METRICS_REPORTER_H__
} // namespace common
#endif //__COMMON_METRICS_REPORTER_H__
......@@ -16,17 +16,13 @@ See the Mulan PSL v2 for more details. */
using namespace common;
Reservoir::Reservoir(RandomGenerator& random) :
random(random)
{
}
Reservoir::Reservoir(RandomGenerator &random) : random(random)
{}
Reservoir::~Reservoir()
{
}
{}
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. */
#include "common/metrics/metric.h"
#include "common/metrics/snapshot.h"
namespace common {
class Reservoir : public Metric {
......@@ -45,6 +43,6 @@ private:
RandomGenerator &random;
};
} // namespace common
} // namespace common
#endif /* __COMMON_METRICS_RESERVOIR_H_ */
......@@ -19,17 +19,21 @@ See the Mulan PSL v2 for more details. */
namespace common {
Sampler *&get_sampler() {
Sampler *&get_sampler()
{
static Sampler *g_sampler = new 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);
if (v <= ratio_num_) {
return true;
......@@ -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) {
this->ratio_ = ratio;
ratio_num_ = ratio * RANGE_SIZE;
......@@ -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. */
namespace common {
/**
* The most simple sample function
*/
......@@ -40,5 +39,5 @@ private:
};
Sampler *&get_sampler();
} //namespace common
#endif //__COMMON_METRICS_SAMPLER_H__
} // namespace common
#endif //__COMMON_METRICS_SAMPLER_H__
......@@ -20,25 +20,30 @@ See the Mulan PSL v2 for more details. */
namespace common {
class Snapshot {
public:
virtual ~Snapshot() {};
virtual ~Snapshot(){};
virtual std::string to_string() = 0;
};
template <class T>
class SnapshotBasic : public Snapshot {
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;
val_to_str(value, ret);
return ret;
......@@ -48,28 +53,31 @@ private:
T value;
};
class SimplerTimerSnapshot: public Snapshot{
class SimplerTimerSnapshot : public Snapshot {
public:
SimplerTimerSnapshot() {
SimplerTimerSnapshot()
{}
}
virtual ~SimplerTimerSnapshot()
{}
virtual ~SimplerTimerSnapshot() {}
void setValue(double mean, double tps) {
void setValue(double mean, double tps)
{
this->mean = mean;
this->tps = tps;
}
std::string to_string() {
std::string to_string()
{
std::stringstream oss;
oss << "mean:" << mean << ",tps:"<<tps;
oss << "mean:" << mean << ",tps:" << tps;
return oss.str();
}
private:
double mean = 1.0;
double tps = 1.0;
};
} //namespace common
#endif //__COMMON_METRICS_SNAPSHOT_H__
} // namespace common
#endif //__COMMON_METRICS_SNAPSHOT_H__
......@@ -17,19 +17,28 @@ See the Mulan PSL v2 for more details. */
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;
oss << HistogramSnapShot::to_string() << ",tps:" << tps;
return oss.str();
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -27,8 +27,9 @@ public:
void set_tps(double tps);
std::string to_string();
protected:
double tps = 1.0;
};
}//namespace common
#endif //__COMMON_METRICS_TIMER_SNAPSHOT_H__
} // namespace common
#endif //__COMMON_METRICS_TIMER_SNAPSHOT_H__
......@@ -23,8 +23,8 @@ namespace common {
#define DEFAULT_SIZE 1023
UniformReservoir::UniformReservoir(RandomGenerator &random)
: Reservoir(random), counter(0) {
UniformReservoir::UniformReservoir(RandomGenerator &random) : Reservoir(random), counter(0)
{
pthread_mutexattr_t mutexatr;
pthread_mutexattr_init(&mutexatr);
pthread_mutexattr_settype(&mutexatr, PTHREAD_MUTEX_RECURSIVE);
......@@ -34,8 +34,8 @@ UniformReservoir::UniformReservoir(RandomGenerator &random)
init(DEFAULT_SIZE);
}
UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size)
: Reservoir(random), counter(0) {
UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size) : Reservoir(random), counter(0)
{
pthread_mutexattr_t mutexatr;
pthread_mutexattr_init(&mutexatr);
......@@ -45,35 +45,40 @@ UniformReservoir::UniformReservoir(RandomGenerator &random, size_t size)
init(size);
}
UniformReservoir::~UniformReservoir() {
UniformReservoir::~UniformReservoir()
{
if (snapshot_value_ == NULL) {
delete snapshot_value_;
snapshot_value_ = NULL;
}
}
void UniformReservoir::init(size_t size) {
void UniformReservoir::init(size_t size)
{
MUTEX_LOCK(&mutex);
counter = 0;
data.resize(size);
MUTEX_UNLOCK(&mutex);
}
size_t UniformReservoir::size() {
size_t UniformReservoir::size()
{
MUTEX_LOCK(&mutex);
size_t size = (counter < data.size()) ? counter : data.size();
MUTEX_UNLOCK(&mutex);
return size;
}
size_t UniformReservoir::get_count() {
size_t UniformReservoir::get_count()
{
MUTEX_LOCK(&mutex);
size_t ret = counter;
MUTEX_UNLOCK(&mutex);
return ret;
}
void UniformReservoir::update(double value) {
void UniformReservoir::update(double value)
{
MUTEX_LOCK(&mutex);
size_t count = ++counter;
......@@ -87,7 +92,8 @@ void UniformReservoir::update(double value) {
MUTEX_UNLOCK(&mutex);
}
void UniformReservoir::snapshot() {
void UniformReservoir::snapshot()
{
MUTEX_LOCK(&mutex);
std::vector<double> output = data;
MUTEX_UNLOCK(&mutex);
......@@ -98,7 +104,8 @@ void UniformReservoir::snapshot() {
((HistogramSnapShot *)snapshot_value_)->set_collection(output);
}
void UniformReservoir::reset() {
void UniformReservoir::reset()
{
MUTEX_LOCK(&mutex);
counter = 0;
......@@ -108,4 +115,4 @@ void UniformReservoir::reset() {
MUTEX_UNLOCK(&mutex);
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -38,8 +38,8 @@ public:
virtual ~UniformReservoir();
public:
size_t size(); // data buffer size
size_t get_count(); // how many items have been insert?
size_t size(); // data buffer size
size_t get_count(); // how many items have been insert?
void update(double one);
void snapshot();
......@@ -51,11 +51,11 @@ protected:
protected:
pthread_mutex_t mutex;
size_t counter; // counter is likely to be bigger than data.size()
size_t counter; // counter is likely to be bigger than data.size()
std::vector<double> data;
RandomGenerator random;
};
} // namespace common
} // namespace common
#endif /* __COMMON_METRICS_UNIFORM_RESERVOIR_H_ */
......@@ -58,7 +58,8 @@ static new_ptr_list_t *new_ptr_list[DEBUG_NEW_HASHTABLESIZE];
bool new_verbose_flag = false;
bool new_autocheck_flag = true;
bool check_leaks() {
bool check_leaks()
{
bool fLeaked = false;
for (int i = 0; i < DEBUG_NEW_HASHTABLESIZE; ++i) {
new_ptr_list_t *ptr = new_ptr_list[i];
......@@ -67,8 +68,10 @@ bool check_leaks() {
fLeaked = true;
while (ptr) {
printf("Leaked object at %p (size %llu, %s:%d)\n",
(char *)ptr + sizeof(new_ptr_list_t),
(unsigned long long)ptr->size, ptr->file, ptr->line);
(char *)ptr + sizeof(new_ptr_list_t),
(unsigned long long)ptr->size,
ptr->file,
ptr->line);
ptr = ptr->next;
}
}
......@@ -78,7 +81,8 @@ bool check_leaks() {
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);
new_ptr_list_t *ptr = (new_ptr_list_t *)malloc(s);
if (ptr == NULL) {
......@@ -102,23 +106,33 @@ void *operator new(size_t size, const char *file, int line) {
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);
}
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);
}
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);
}
void operator delete(void *pointer) {
void operator delete(void *pointer)
{
if (pointer == NULL)
return;
size_t hash_index = DEBUG_NEW_HASH(pointer);
......@@ -142,7 +156,10 @@ void operator delete(void *pointer) {
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
// Compiler 8.29 do not support placement delete operators.
......@@ -151,31 +168,36 @@ void operator delete[](void *pointer) { operator delete(pointer); }
// is thrown in the initialization (constructor) of a dynamically
// created object.
#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)
printf("info: exception thrown on initializing object at %p (%s:%d)\n",
pointer, file, line);
printf("info: exception thrown on initializing object at %p (%s:%d)\n", pointer, file, line);
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);
}
void operator delete(void *pointer, const std::nothrow_t &) {
void operator delete(void *pointer, const std::nothrow_t &)
{
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);
}
#endif // NO_PLACEMENT_DELETE
#endif // NO_PLACEMENT_DELETE
// Proxy class to automatically call check_leaks if new_autocheck_flag is set
class new_check_t {
public:
new_check_t() {}
~new_check_t() {
new_check_t()
{}
~new_check_t()
{
if (new_autocheck_flag) {
// Check for leakage.
// If any leaks are found, set new_verbose_flag so that any
......
......@@ -26,8 +26,8 @@ void *operator new[](size_t size, const char *file, int line);
#ifndef NO_PLACEMENT_DELETE
void operator delete(void *pointer, const char *file, int line);
void operator delete[](void *pointer, const char *file, int line);
#endif // NO_PLACEMENT_DELETE
void operator delete[](void *); // MSVC 6 requires this declaration
#endif // NO_PLACEMENT_DELETE
void operator delete[](void *); // MSVC 6 requires this declaration
/* Macros */
#ifndef DEBUG_NEW_NO_NEW_REDEFINITION
......@@ -36,16 +36,16 @@ void operator delete[](void *); // MSVC 6 requires this declaration
#define debug_new new
#else
#define debug_new new (__FILE__, __LINE__)
#endif // DEBUG_NEW_NO_NEW_REDEFINITION
#endif // DEBUG_NEW_NO_NEW_REDEFINITION
#ifdef DEBUG_NEW_EMULATE_MALLOC
#define malloc(s) ((void *)(debug_new char[s]))
#define free(p) delete[](char *)(p)
#endif // DEBUG_NEW_EMULATE_MALLOC
#endif // DEBUG_NEW_EMULATE_MALLOC
/* Control flags */
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_verbose_flag; // default to false: no verbose information
extern bool new_autocheck_flag; // default to true: call check_leaks() on exit
} //namespace common
#endif // __COMMON_MM_DEBUG_NEW_H__
} // namespace common
#endif // __COMMON_MM_DEBUG_NEW_H__
......@@ -28,8 +28,8 @@ MemID *CLMemTrace::mMemIDs[MEM_HASHTABLE_SIZE] = {0};
bool CLMemTrace::mVerbose = false;
;
void *CLMemTrace::malloc(size_t size, const char *file, const int line,
bool retry) throw(std::bad_alloc) {
void *CLMemTrace::malloc(size_t size, const char *file, const int line, bool retry) throw(std::bad_alloc)
{
size_t allocSize = size + sizeof(MemID);
void *usedPointer = NULL;
......@@ -81,8 +81,8 @@ void *CLMemTrace::malloc(size_t size, const char *file, const int line,
return NULL;
}
void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
const int line) {
void *CLMemTrace::realloc(void *pointer, size_t size, const char *file, const int line)
{
if (pointer == NULL && size == 0) {
return NULL;
} else if (pointer == NULL && size != 0) {
......@@ -172,8 +172,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
/**
* Secondly, add the new one to table
*/
u64_t newHashIndex =
(u64_t)MEM_ID_HASH((char *)pNewMemID + sizeof(MemID));
u64_t newHashIndex = (u64_t)MEM_ID_HASH((char *)pNewMemID + sizeof(MemID));
pNewMemID->mNext = mMemIDs[newHashIndex];
mMemIDs[newHashIndex] = pNewMemID;
......@@ -182,8 +181,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
* Third, do memory copy
* to simplify the old logic, copy memory here
*/
memcpy((char *)pNewMemID + sizeof(MemID),
(char *)pFreeMemID + sizeof(MemID), pFreeMemID->mSize);
memcpy((char *)pNewMemID + sizeof(MemID), (char *)pFreeMemID + sizeof(MemID), pFreeMemID->mSize);
break;
}
}
......@@ -191,9 +189,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
MUTEX_UNLOCK(&mMutex);
if (foundOld == false) {
LOG_WARN(
"Something is wrong, the old pointer %p isn't found, so alloc new one",
pointer);
LOG_WARN("Something is wrong, the old pointer %p isn't found, so alloc new one", pointer);
try {
return malloc(size, file, line, false);
} catch (std::bad_alloc &e) {
......@@ -203,8 +199,7 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
}
if (mVerbose) {
LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, oldMemID.mFile,
oldMemID.mLine, oldMemID.mSize);
LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, oldMemID.mFile, oldMemID.mLine, oldMemID.mSize);
}
if (pFreeMemID) {
......@@ -215,8 +210,10 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
if (mVerbose) {
LOG_INFO("Alloc %p, file:%s, line:%u, size:%llu",
(char *)pNewMemID + sizeof(MemID), pNewMemID->mFile,
pNewMemID->mLine, pNewMemID->mSize);
(char *)pNewMemID + sizeof(MemID),
pNewMemID->mFile,
pNewMemID->mLine,
pNewMemID->mSize);
}
return pNewMemID;
}
......@@ -224,7 +221,8 @@ void *CLMemTrace::realloc(void *pointer, size_t size, const char *file,
return NULL;
}
void CLMemTrace::free(void *pointer) {
void CLMemTrace::free(void *pointer)
{
if (pointer == NULL) {
LOG_WARN("Free one empty pointer");
return;
......@@ -260,8 +258,7 @@ void CLMemTrace::free(void *pointer) {
if (pMemID) {
if (mVerbose) {
LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, pMemID->mFile,
pMemID->mLine, pMemID->mSize);
LOG_INFO("Delete %p, file:%s, line:%u, size:%llu", pointer, pMemID->mFile, pMemID->mLine, pMemID->mSize);
}
::free(pMemID);
return;
......@@ -273,7 +270,8 @@ void CLMemTrace::free(void *pointer) {
return;
}
std::new_handler CLMemTrace::getNewHandler() {
std::new_handler CLMemTrace::getNewHandler()
{
std::new_handler newHandler = NULL;
MUTEX_LOCK(&mMutex);
......@@ -285,7 +283,8 @@ std::new_handler CLMemTrace::getNewHandler() {
return newHandler;
}
void CLMemTrace::output() {
void CLMemTrace::output()
{
for (int i = 0; i < MEM_HASHTABLE_SIZE; ++i) {
// Don't lock outside of the loop
// 1. avoid output too long to alloc/free memory
......@@ -298,8 +297,8 @@ void CLMemTrace::output() {
}
while (ptr) {
// if LOG_INFO alloc memory, it will easy leading to dead lock
LOG_INFO("Exist %p, file:%s, line:%u, size:%llu",
(char *)ptr + sizeof(MemID), ptr->mFile, ptr->mLine, ptr->mSize);
LOG_INFO(
"Exist %p, file:%s, line:%u, size:%llu", (char *)ptr + sizeof(MemID), ptr->mFile, ptr->mLine, ptr->mSize);
ptr = ptr->mNext;
}
......@@ -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);
}
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);
}
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);
}
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);
}
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;
try {
pointer = operator new(size);
......@@ -334,7 +338,8 @@ void *operator new(std::size_t size, const std::nothrow_t &) throw() {
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;
try {
pointer = operator[] new(size);
......@@ -345,9 +350,15 @@ void *operator new[](std::size_t size, const std::nothrow_t &) throw() {
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
// Compiler 8.29 do not support placement delete operators.
......@@ -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
// is thrown in the initialization (constructor) of a dynamically
// 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);
}
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);
}
void operator delete(void *pointer, const std::nothrow_t &) {
void operator delete(void *pointer, const std::nothrow_t &)
{
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);
}
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 {
void *point = CLMemTrace::malloc(size * nmemb, file, line, false);
if (point) {
......@@ -384,7 +400,8 @@ void *Lcalloc(size_t nmemb, size_t size, const char *file, const int line) {
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 {
void *point = CLMemTrace::malloc(size, file, line, false);
} catch (std::bad_alloc &e) {
......@@ -394,8 +411,12 @@ void *Lmalloc(size_t size, const char *file, const int line) {
return pointer;
}
void Lfree(void *ptr) { CLMemTrace::free(pointer); }
void *Lrealloc(void *ptr, size_t size, const char *file, const int line) {
void Lfree(void *ptr)
{
CLMemTrace::free(pointer);
}
void *Lrealloc(void *ptr, size_t size, const char *file, const int line)
{
// simplify the logic
return CLMemTrace::realloc(ptr, size, file, line);
}
......
......@@ -31,8 +31,6 @@ namespace common {
#else
typedef struct MemID_t {
public:
const static int MEM_FILENAME_LEN = 32;
......@@ -44,12 +42,10 @@ public:
class CLMemTrace {
public:
static void *malloc(size_t size, const char *file, const int line,
bool retry = false) throw(std::bad_alloc);
static void *malloc(size_t size, const char *file, const int line, bool retry = false) throw(std::bad_alloc);
// just use for realloc, same functionality as realloc
static void *realloc(void *ptr, size_t size, const char *file,
const int line);
static void *realloc(void *ptr, size_t size, const char *file, const int line);
static void free(void *ptr);
......@@ -58,7 +54,10 @@ public:
/**
* set whether show every details
*/
static void setVerbose(bool verbose) { mVerbose = verbose; }
static void setVerbose(bool verbose)
{
mVerbose = verbose;
}
protected:
static std::new_handler getNewHandler();
......@@ -132,5 +131,5 @@ static void operator delete[](void *pointer);
#endif /* MEM_DEBUG */
} //namespace common
} // namespace common
#endif /* __COMMON_MM_MEM_H__ */
......@@ -21,7 +21,8 @@ See the Mulan PSL v2 for more details. */
namespace common {
// Don't care windows
u32_t getCpuNum() {
u32_t getCpuNum()
{
return std::thread::hardware_concurrency();
}
......@@ -30,14 +31,13 @@ u32_t getCpuNum() {
void print_stacktrace()
{
int size = MAX_STACK_SIZE;
void * array[MAX_STACK_SIZE];
void *array[MAX_STACK_SIZE];
int stack_num = backtrace(array, size);
char ** stacktrace = backtrace_symbols(array, stack_num);
for (int i = 0; i < stack_num; ++i)
{
char **stacktrace = backtrace_symbols(array, stack_num);
for (int i = 0; i < stack_num; ++i) {
LOG_INFO("%d ----- %s\n", i, stacktrace[i]);
}
free(stacktrace);
}
}//namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -20,5 +20,5 @@ u32_t getCpuNum();
void print_stacktrace();
} //namespace common
} // namespace common
#endif /* __COMMON_OS_OS_H__ */
......@@ -18,7 +18,6 @@ See the Mulan PSL v2 for more details. */
#include <string>
namespace common {
/**
* get file name from full path
* example
......@@ -66,7 +65,7 @@ bool check_directory(std::string &path);
* @param filter_pattern 示例 ^miniob.*bin$
* @return 成功返回找到的文件个数,否则返回-1
*/
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
#endif //__COMMON_OS_PATH_H__
} // namespace common
#endif //__COMMON_OS_PATH_H__
......@@ -26,25 +26,26 @@ See the Mulan PSL v2 for more details. */
#include "common/os/pidfile.h"
namespace common {
std::string& getPidPath() {
std::string &getPidPath()
{
static std::string path;
return path;
}
void setPidPath(const char *progName) {
void setPidPath(const char *progName)
{
std::string &path = getPidPath();
if (progName != NULL) {
path = std::string(_PATH_TMP) + progName + ".pid";
}else {
} else {
path = "";
}
}
int writePidFile(const char *progName) {
int writePidFile(const char *progName)
{
assert(progName);
std::ofstream ostr;
int rv = 1;
......@@ -58,15 +59,14 @@ int writePidFile(const char *progName) {
rv = 0;
} else {
rv = errno;
std::cerr << "error opening PID file " << path.c_str() << SYS_OUTPUT_ERROR
<< std::endl;
std::cerr << "error opening PID file " << path.c_str() << SYS_OUTPUT_ERROR << std::endl;
}
return rv;
}
void removePidFile(void) {
void removePidFile(void)
{
std::string path = getPidPath();
if (!path.empty()) {
unlink(path.c_str());
......@@ -75,5 +75,4 @@ void removePidFile(void) {
return;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -16,7 +16,6 @@ See the Mulan PSL v2 for more details. */
#define __COMMON_OS_PIDFILE_H__
namespace common {
//! Generates a PID file for the current component
/**
* Gets the process ID (PID) of the calling process and writes a file
......@@ -35,7 +34,7 @@ int writePidFile(const char *progName);
*/
void removePidFile(void);
std::string& getPidPath();
std::string &getPidPath();
} //namespace common
#endif // __COMMON_OS_PIDFILE_H__
} // namespace common
#endif // __COMMON_OS_PIDFILE_H__
......@@ -30,12 +30,13 @@ namespace common {
#include <libgen.h>
#endif
#define MAX_ERR_OUTPUT 10000000 // 10M
#define MAX_STD_OUTPUT 10000000 // 10M
#define MAX_ERR_OUTPUT 10000000 // 10M
#define MAX_STD_OUTPUT 10000000 // 10M
#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;
int buf_len = strlen(prog_name);
......@@ -44,8 +45,7 @@ std::string get_process_name(const char *prog_name) {
char *buf = new char[buf_len + 1];
if (buf == NULL) {
std::cerr << "Failed to alloc memory for program name."
<< SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to alloc memory for program name." << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
return "";
}
memset(buf, 0, buf_len + 1);
......@@ -59,7 +59,8 @@ std::string get_process_name(const char *prog_name) {
// Background the process by detaching it from the console and redirecting
// 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 noclose = close_std_streams ? 0 : 1;
int rc = daemon(nochdir, noclose);
......@@ -70,7 +71,8 @@ int daemonize_service(bool close_std_streams) {
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);
if (rc != 0) {
......@@ -83,7 +85,8 @@ int daemonize_service(const char *std_out_file, const char *std_err_file) {
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;
// Redirect stdin to /dev/null
......@@ -107,7 +110,7 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) {
std::string err_file = getAboslutPath(std_err_file);
// CWE367: A check occurs on a file's attributes before the file is
// CWE367: A check occurs on a file's attributes before the file is
// used in a privileged operation, but things may have changed
// Redirect stderr to std_err_file
// struct stat st;
......@@ -117,16 +120,15 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) {
// std_err_flag |= O_TRUNC; // Remove old content if any.
// }
std_err_flag |= O_TRUNC; // Remove old content if any.
std_err_flag |= O_TRUNC; // Remove old content if any.
int errfd = open(err_file.c_str(), std_err_flag, RWRR);
if (errfd >= 0) {
dup2(errfd, STDERR_FILENO);
close(errfd);
}
setvbuf(stderr, NULL, _IONBF, 0); // Make sure stderr is not buffering
std::cerr << "Process " << getpid() << " built error output at " << tv.tv_sec
<< std::endl;
setvbuf(stderr, NULL, _IONBF, 0); // Make sure stderr is not buffering
std::cerr << "Process " << getpid() << " built error output at " << tv.tv_sec << std::endl;
std::string outFile = getAboslutPath(std_out_file);
......@@ -137,17 +139,16 @@ void sys_log_redirect(const char *std_out_file, const char *std_err_file) {
// std_out_flag |= O_TRUNC; // Remove old content if any.
// }
std_out_flag |= O_TRUNC; // Remove old content if any.
std_out_flag |= O_TRUNC; // Remove old content if any.
int outfd = open(outFile.c_str(), std_out_flag, RWRR);
if (outfd >= 0) {
dup2(outfd, STDOUT_FILENO);
close(outfd);
}
setvbuf(stdout, NULL, _IONBF, 0); // Make sure stdout not buffering
std::cout << "Process " << getpid() << " built standard output at "
<< tv.tv_sec << std::endl;
setvbuf(stdout, NULL, _IONBF, 0); // Make sure stdout not buffering
std::cout << "Process " << getpid() << " built standard output at " << tv.tv_sec << std::endl;
return;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -16,7 +16,6 @@ See the Mulan PSL v2 for more details. */
#define __COMMON_OS_PROCESS_H__
namespace common {
//! Get process Name
/**
* @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);
void sys_log_redirect(const char *std_out_file, const char *std_err_file);
} //namespace common
#endif //__COMMON_OS_PROCESS_H__
} // namespace common
#endif //__COMMON_OS_PROCESS_H__
......@@ -17,14 +17,15 @@ See the Mulan PSL v2 for more details. */
namespace common {
//! 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;
}
void ProcessParam::init_default(std::string &process_name) {
void ProcessParam::init_default(std::string &process_name)
{
assert(process_name.empty() == false);
this->process_name_ = process_name;
if (std_out_.empty()) {
......@@ -40,6 +41,4 @@ void ProcessParam::init_default(std::string &process_name) {
demon = false;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -21,69 +21,107 @@ namespace common {
class ProcessParam {
public:
ProcessParam() {}
public:
ProcessParam()
{}
virtual ~ProcessParam() {}
virtual ~ProcessParam()
{}
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;
}
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;
}
void set_server_port(int port) {
void set_server_port(int port)
{
server_port_ = port;
}
int get_server_port() const {
int get_server_port() const
{
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;
}
const std::string &get_unix_socket_path() const {
const std::string &get_unix_socket_path() const
{
return unix_socket_path_;
}
private:
std::string std_out_; // The output file
std::string std_err_; // The err output file
std::string conf; // The configuration file
std::string process_name_; // The process name
bool demon = false; // whether demon or not
std::vector<std::string> args; // arguments
int server_port_ = -1; // server port(if valid, will overwrite the port in the config file)
private:
std::string std_out_; // The output file
std::string std_err_; // The err output file
std::string conf; // The configuration file
std::string process_name_; // The process name
bool demon = false; // whether demon or not
std::vector<std::string> args; // arguments
int server_port_ = -1; // server port(if valid, will overwrite the port in the config file)
std::string unix_socket_path_;
};
ProcessParam*& the_process_param();
ProcessParam *&the_process_param();
} //namespace common
#endif //__COMMON_OS_PROCESS_PARAM_H__
} // namespace common
#endif //__COMMON_OS_PROCESS_PARAM_H__
......@@ -17,29 +17,31 @@ See the Mulan PSL v2 for more details. */
#include "pthread.h"
namespace common {
void setSignalHandler(int sig, sighandler_t func) {
void setSignalHandler(int sig, sighandler_t func)
{
struct sigaction newsa, oldsa;
sigemptyset(&newsa.sa_mask);
newsa.sa_flags = 0;
newsa.sa_handler = func;
int rc = sigaction(sig, &newsa, &oldsa);
if (rc) {
std::cerr << "Failed to set signal " << sig << SYS_OUTPUT_FILE_POS
<< SYS_OUTPUT_ERROR << std::endl;
std::cerr << "Failed to set signal " << sig << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
}
}
/*
** Set Singal handling Fucntion
*/
void setSignalHandler(sighandler_t func) {
void setSignalHandler(sighandler_t func)
{
setSignalHandler(SIGQUIT, func);
setSignalHandler(SIGINT, func);
setSignalHandler(SIGHUP, 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);
#ifndef DEBUG
// SIGINT will effect our gdb debugging
......@@ -50,7 +52,8 @@ void blockDefaultSignals(sigset_t *signal_set, sigset_t *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);
#ifndef DEBUG
sigaddset(signal_set, SIGINT);
......@@ -60,7 +63,8 @@ void unBlockDefaultSignals(sigset_t *signal_set, sigset_t *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.");
sigset_t *signal_set = (sigset_t *)args;
int sig_number = -1;
......@@ -68,7 +72,7 @@ void *waitForSignals(void *args) {
errno = 0;
int ret = sigwait(signal_set, &sig_number);
LOG_INFO("sigwait return value: %d, %d \n", ret, sig_number);
if (ret != 0) {
if (ret != 0) {
char errstr[256];
strerror_r(errno, errstr, sizeof(errstr));
LOG_ERROR("error (%d) %s\n", errno, errstr);
......@@ -77,7 +81,8 @@ void *waitForSignals(void *args) {
return NULL;
}
void startWaitForSignals(sigset_t *signal_set) {
void startWaitForSignals(sigset_t *signal_set)
{
pthread_t pThread;
pthread_attr_t pThreadAttrs;
......@@ -86,6 +91,5 @@ void startWaitForSignals(sigset_t *signal_set) {
pthread_attr_setdetachstate(&pThreadAttrs, PTHREAD_CREATE_DETACHED);
pthread_create(&pThread, &pThreadAttrs, waitForSignals, (void *)signal_set);
}
} // namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -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 *waitForSignals(sigset_t *signal_set);
void startWaitForSignals(sigset_t *signal_set);
......@@ -42,5 +41,5 @@ typedef void (*sighandler_t)(int);
void setSignalHandler(sighandler_t func);
void setSignalHandler(int sig, sighandler_t func);
} //namespace common
} // namespace common
#endif /* __COMMON_OS_SIGNAL_H__ */
......@@ -33,11 +33,12 @@ extern bool &get_event_history_flag();
// Constructor
CompletionCallback::CompletionCallback(Stage *trgt, CallbackContext *ctx)
: target_stage_(trgt), context_(ctx), next_cb_(NULL),
ev_hist_flag_(get_event_history_flag()) {}
: target_stage_(trgt), context_(ctx), next_cb_(NULL), ev_hist_flag_(get_event_history_flag())
{}
// Destructor
CompletionCallback::~CompletionCallback() {
CompletionCallback::~CompletionCallback()
{
if (context_) {
delete context_;
}
......@@ -47,14 +48,16 @@ CompletionCallback::~CompletionCallback() {
}
// 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");
next_cb_ = next;
}
// Pop off of a callback stack
CompletionCallback *CompletionCallback::pop_callback() {
CompletionCallback *CompletionCallback::pop_callback()
{
CompletionCallback *ret_val = next_cb_;
next_cb_ = NULL;
......@@ -62,7 +65,8 @@ CompletionCallback *CompletionCallback::pop_callback() {
}
// One event is complete
void CompletionCallback::event_done(StageEvent *ev) {
void CompletionCallback::event_done(StageEvent *ev)
{
if (ev_hist_flag_) {
ev->save_stage(target_stage_, StageEvent::CALLBACK_EV);
......@@ -71,11 +75,13 @@ void CompletionCallback::event_done(StageEvent *ev) {
}
// Reschedule callback on target stage thread
void CompletionCallback::event_reschedule(StageEvent *ev) {
void CompletionCallback::event_reschedule(StageEvent *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());
if (ev_hist_flag_) {
ev->save_stage(target_stage_, StageEvent::TIMEOUT_EV);
......@@ -83,4 +89,4 @@ void CompletionCallback::event_timeout(StageEvent *ev) {
target_stage_->timeout_event(ev, context_);
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -59,7 +59,7 @@ class CompletionCallback {
// public interface operations
public:
public:
// Constructor
CompletionCallback(Stage *trgt, CallbackContext *ctx = NULL);
......@@ -84,12 +84,12 @@ class CompletionCallback {
// Complete this event if it has timed out
void event_timeout(StageEvent *ev);
protected:
protected:
// implementation state
Stage *target_stage_; // stage which is setting this callback
CallbackContext *context_; // argument to pass when invoking cb
CompletionCallback *next_cb_; // next event in the chain
Stage *target_stage_; // stage which is setting this callback
CallbackContext *context_; // argument to pass when invoking cb
CompletionCallback *next_cb_; // next event in the chain
bool ev_hist_flag_; // true if event histories are enabled
};
......@@ -101,19 +101,25 @@ class CompletionCallback {
* callback context class from this base.
*/
class CallbackContext {
public:
virtual ~CallbackContext() {}
public:
virtual ~CallbackContext()
{}
};
class CallbackContextEvent : public CallbackContext {
public:
CallbackContextEvent(StageEvent *event = NULL) : ev_(event) {}
~CallbackContextEvent() {}
StageEvent *get_event() { return ev_; }
private:
public:
CallbackContextEvent(StageEvent *event = NULL) : ev_(event)
{}
~CallbackContextEvent()
{}
StageEvent *get_event()
{
return ev_;
}
private:
StageEvent *ev_;
};
} //namespace common
#endif // __COMMON_SEDA_CALLBACK_H__
} // namespace common
#endif // __COMMON_SEDA_CALLBACK_H__
......@@ -21,7 +21,6 @@ See the Mulan PSL v2 for more details. */
#include "common/log/log.h"
namespace common {
/**
* A class to construct arbitrary subclass instances
*
......@@ -42,10 +41,10 @@ namespace common {
* with static linkage in a global initialization routine.
*/
template<class T>
template <class T>
class ClassFactory {
public:
public:
typedef T *(*FactoryFunc)(const std::string &);
/**
......@@ -69,13 +68,13 @@ class ClassFactory {
*/
static T *make_instance(const std::string &tag);
private:
private:
// Accessor function that gets the head of the factory list
static ClassFactory<T> *&fact_list_head();
std::string identifier_; // identifier for this factory
std::string identifier_; // identifier for this factory
FactoryFunc fact_func_; // factory function for this class
ClassFactory<T> *next_; // next factory in global list
ClassFactory<T> *next_; // next factory in global list
};
/**
......@@ -88,8 +87,9 @@ class ClassFactory {
* as static. C++ guarantees that the first time the function is
* invoked (from anywhere) the static local will be initialized.
*/
template<class T>
ClassFactory<T> *&ClassFactory<T>::fact_list_head() {
template <class T>
ClassFactory<T> *&ClassFactory<T>::fact_list_head()
{
static ClassFactory<T> *fact_list = NULL;
return fact_list;
}
......@@ -99,16 +99,17 @@ ClassFactory<T> *&ClassFactory<T>::fact_list_head() {
* Implementation notes:
* constructor places current instance on the global factory list.
*/
template<class T>
ClassFactory<T>::ClassFactory(const std::string &tag, FactoryFunc func)
: identifier_(tag), fact_func_(func) {
template <class T>
ClassFactory<T>::ClassFactory(const std::string &tag, FactoryFunc func) : identifier_(tag), fact_func_(func)
{
next_ = fact_list_head();
fact_list_head() = this;
}
// Destructor
template<class T>
ClassFactory<T>::~ClassFactory() {}
template <class T>
ClassFactory<T>::~ClassFactory()
{}
/**
* Construct an instance of a specified sub-class
......@@ -116,8 +117,9 @@ ClassFactory<T>::~ClassFactory() {}
* scan global list to find matching tag and use the factory func to
* create an instance.
*/
template<class T>
T *ClassFactory<T>::make_instance(const std::string &tag) {
template <class T>
T *ClassFactory<T>::make_instance(const std::string &tag)
{
T *instance = NULL;
ClassFactory<T> *current = fact_list_head();
......@@ -136,5 +138,5 @@ T *ClassFactory<T>::make_instance(const std::string &tag) {
return instance;
}
} //namespace common
#endif // __COMMON_SEDA_CLASS_FACTORY_H__
} // namespace common
#endif // __COMMON_SEDA_CLASS_FACTORY_H__
......@@ -17,8 +17,8 @@ See the Mulan PSL v2 for more details. */
namespace common {
// Constructor
EventDispatcher::EventDispatcher(const char *tag)
: Stage(tag), event_store_(), next_stage_(NULL) {
EventDispatcher::EventDispatcher(const char *tag) : Stage(tag), event_store_(), next_stage_(NULL)
{
LOG_TRACE("enter\n");
pthread_mutexattr_t attr;
......@@ -31,7 +31,8 @@ EventDispatcher::EventDispatcher(const char *tag)
}
// Destructor
EventDispatcher::~EventDispatcher() {
EventDispatcher::~EventDispatcher()
{
LOG_TRACE("enter\n");
pthread_mutex_destroy(&event_lock_);
LOG_TRACE("exit\n");
......@@ -42,7 +43,8 @@ EventDispatcher::~EventDispatcher() {
* Check if the event can be dispatched. If not, hash it and store
* 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");
std::string hash;
......@@ -67,7 +69,8 @@ void EventDispatcher::handle_event(StageEvent *event) {
}
// Initialize stage params and validate outputs
bool EventDispatcher::initialize() {
bool EventDispatcher::initialize()
{
bool ret_val = true;
if (next_stage_list_.size() != 1) {
......@@ -82,15 +85,15 @@ bool EventDispatcher::initialize() {
* Cleanup stage after disconnection
* Call done() on any events left over in the event_store_.
*/
void EventDispatcher::cleanup() {
void EventDispatcher::cleanup()
{
pthread_mutex_lock(&event_lock_);
// for each hash chain...
for (EventHash::iterator i = event_store_.begin(); i != event_store_.end(); i++) {
// for each event on the chain
for (std::list<StoredEvent>::iterator j = i->second.begin();
j != i->second.end(); j++) {
for (std::list<StoredEvent>::iterator j = i->second.begin(); j != i->second.end(); j++) {
j->first->done();
}
i->second.clear();
......@@ -101,7 +104,8 @@ void EventDispatcher::cleanup() {
}
// Wake up a stored event
bool EventDispatcher::wakeup_event(std::string hashkey) {
bool EventDispatcher::wakeup_event(std::string hashkey)
{
bool sent = false;
EventHash::iterator i;
......@@ -131,4 +135,4 @@ bool EventDispatcher::wakeup_event(std::string hashkey) {
return sent;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -55,7 +55,7 @@ class EventDispatcher : public Stage {
// public interface operations
public:
public:
typedef enum { SEND_EVENT = 0, STORE_EVENT, FAIL_EVENT } status_t;
/**
......@@ -77,7 +77,7 @@ class EventDispatcher : public Stage {
// Note, EventDispatcher is an abstract class and needs no make_stage()
protected:
protected:
/**
* Constructor
* @param[in] tag The label that identifies this stage.
......@@ -96,7 +96,10 @@ class EventDispatcher : public Stage {
bool initialize();
// set properties for this object
bool set_properties() { return true; }
bool set_properties()
{
return true;
}
/**
* Cleanup stage after disconnection
......@@ -119,8 +122,7 @@ class EventDispatcher : public Stage {
* FAIL_EVENT if failure, and event has been completed;
* ctx is NULL
*/
virtual status_t dispatch_event(StageEvent *ev, DispatchContext *&ctx,
std::string &hash) = 0;
virtual status_t dispatch_event(StageEvent *ev, DispatchContext *&ctx, std::string &hash) = 0;
/**
* Wake up a stored event
......@@ -136,11 +138,11 @@ class EventDispatcher : public Stage {
typedef std::pair<StageEvent *, DispatchContext *> StoredEvent;
typedef std::map<std::string, std::list<StoredEvent>> EventHash;
EventHash event_store_; // events stored here while waiting
pthread_mutex_t event_lock_; // protects access to event_store_
Stage *next_stage_; // target for dispatched events
EventHash event_store_; // events stored here while waiting
pthread_mutex_t event_lock_; // protects access to event_store_
Stage *next_stage_; // target for dispatched events
protected:
protected:
};
/**
......@@ -148,9 +150,10 @@ class EventDispatcher : public Stage {
* derive from this base class.
*/
class DispatchContext {
public:
virtual ~DispatchContext() {}
public:
virtual ~DispatchContext()
{}
};
} //namespace common
#endif // __COMMON_SEDA_EVENT_DISPATCHER_H__
} // namespace common
#endif // __COMMON_SEDA_EVENT_DISPATCHER_H__
......@@ -26,13 +26,16 @@ See the Mulan PSL v2 for more details. */
using namespace common;
// Constructor
ExampleStage::ExampleStage(const char *tag) : Stage(tag) {}
ExampleStage::ExampleStage(const char *tag) : Stage(tag)
{}
// Destructor
ExampleStage::~ExampleStage() {}
ExampleStage::~ExampleStage()
{}
// 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());
if (stage == NULL) {
LOG_ERROR("new ExampleStage failed");
......@@ -43,7 +46,8 @@ Stage *ExampleStage::make_stage(const std::string &tag) {
}
// Set properties for this object set in stage specific properties
bool ExampleStage::set_properties() {
bool ExampleStage::set_properties()
{
// std::string stageNameStr(stage_name_);
// std::map<std::string, std::string> section = g_properties()->get(
// stageNameStr);
......@@ -56,7 +60,8 @@ bool ExampleStage::set_properties() {
}
// Initialize stage params and validate outputs
bool ExampleStage::initialize() {
bool ExampleStage::initialize()
{
LOG_TRACE("Enter");
// std::list<Stage*>::iterator stgp = next_stage_list_.begin();
......@@ -68,20 +73,23 @@ bool ExampleStage::initialize() {
}
// Cleanup after disconnection
void ExampleStage::cleanup() {
void ExampleStage::cleanup()
{
LOG_TRACE("Enter");
LOG_TRACE("Exit");
}
void ExampleStage::handle_event(StageEvent *event) {
void ExampleStage::handle_event(StageEvent *event)
{
LOG_TRACE("Enter\n");
LOG_TRACE("Exit\n");
return;
}
void ExampleStage::callback_event(StageEvent *event, CallbackContext *context) {
void ExampleStage::callback_event(StageEvent *event, CallbackContext *context)
{
LOG_TRACE("Enter\n");
LOG_TRACE("Exit\n");
......
......@@ -33,7 +33,6 @@ protected:
void cleanup();
void handle_event(StageEvent *event);
void callback_event(StageEvent *event, CallbackContext *context);
};
} // namespace common
#endif //__COMMON_SEDA_EXAMPLE_STAGE_H__
} // namespace common
#endif //__COMMON_SEDA_EXAMPLE_STAGE_H__
......@@ -37,17 +37,15 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/timer_stage.h"
namespace common {
int init_seda(ProcessParam *process_cfg) {
int init_seda(ProcessParam *process_cfg)
{
// Initialize the static data structures of threadpool
Threadpool::create_pool_key();
// initialize class factory instances here
static StageFactory kill_thread_factory("KillThreads",
&KillThreadStage::make_stage);
static StageFactory kill_thread_factory("KillThreads", &KillThreadStage::make_stage);
static StageFactory timer_factory("TimerStage", &TimerStage::make_stage);
static StageFactory seda_stats_factory("MetricsStage",
&MetricsStage::make_stage);
static StageFactory seda_stats_factory("MetricsStage", &MetricsStage::make_stage);
// try to parse the seda configuration files
SedaConfig *config = SedaConfig::get_instance();
......@@ -55,16 +53,14 @@ int init_seda(ProcessParam *process_cfg) {
config_stat = config->parse();
if (config_stat != SedaConfig::SUCCESS) {
LOG_ERROR("Error: unable to parse file %s",
process_cfg->get_process_name().c_str());
LOG_ERROR("Error: unable to parse file %s", process_cfg->get_process_name().c_str());
return errno;
}
// 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
// crashing.
LOG_INFO("(Re)Starting State: Pid: %u Time: %s", (unsigned int)getpid(),
DateTime::now().to_string_local().c_str());
LOG_INFO("(Re)Starting State: Pid: %u Time: %s", (unsigned int)getpid(), DateTime::now().to_string_local().c_str());
LOG_INFO("The process Name is %s", process_cfg->get_process_name().c_str());
// try to initialize the seda configuration
......@@ -79,10 +75,11 @@ int init_seda(ProcessParam *process_cfg) {
return 0;
}
void cleanup_seda() {
void cleanup_seda()
{
SedaConfig *seda_config = SedaConfig::get_instance();
delete seda_config;
SedaConfig::get_instance() = NULL;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -36,5 +36,5 @@ int init_seda(ProcessParam *process_cfg);
void cleanup_seda();
} //namespace common
#endif // __COMMON_SEDA_INIT_H__
} // namespace common
#endif // __COMMON_SEDA_INIT_H__
......@@ -19,14 +19,14 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/thread_pool.h"
namespace common {
/**
* Notify the pool and kill the thread
* @param[in] event Pointer to event that must be handled.
*
* @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();
event->done();
this->release_event();
......@@ -39,13 +39,15 @@ void KillThreadStage::handle_event(StageEvent *event) {
* @post initializing the class members
* @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());
}
bool KillThreadStage::set_properties() {
bool KillThreadStage::set_properties()
{
// nothing to do
return true;
}
} //namespace common
\ No newline at end of file
} // namespace common
\ No newline at end of file
......@@ -21,7 +21,6 @@ See the Mulan PSL v2 for more details. */
#include "common/seda/stage.h"
namespace common {
/**
* @file
* @author Longda
......@@ -56,7 +55,8 @@ protected:
* @post event queue is empty
* @post stage is not connected
*/
KillThreadStage(const char *tag) : Stage(tag) {}
KillThreadStage(const char *tag) : Stage(tag)
{}
/**
* Notify the pool and kill the thread
......@@ -70,7 +70,10 @@ protected:
* Handle the callback
* 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
......@@ -79,7 +82,10 @@ protected:
* @pre Stage not connected
* @return true
*/
bool initialize() { return true; }
bool initialize()
{
return true;
}
/**
* set properties for this object
......@@ -92,5 +98,5 @@ protected:
friend class Threadpool;
};
} //namespace common
#endif // __COMMON_SEDA_KILL_THREAD_H__
} // namespace common
#endif // __COMMON_SEDA_KILL_THREAD_H__
......@@ -28,5 +28,5 @@ public:
};
};
} //namespace common
#endif //__COMMON_SEDA_METRICS_REPORT_EVENT_H__
} // namespace common
#endif //__COMMON_SEDA_METRICS_REPORT_EVENT_H__
......@@ -29,20 +29,24 @@ See the Mulan PSL v2 for more details. */
using namespace common;
MetricsRegistry &get_metric_registry() {
MetricsRegistry &get_metric_registry()
{
static MetricsRegistry metrics_registry;
return metrics_registry;
}
// Constructor
MetricsStage::MetricsStage(const char *tag) : Stage(tag) {}
MetricsStage::MetricsStage(const char *tag) : Stage(tag)
{}
// Destructor
MetricsStage::~MetricsStage() {}
MetricsStage::~MetricsStage()
{}
// 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());
if (stage == NULL) {
LOG_ERROR("new MetricsStage failed");
......@@ -53,10 +57,10 @@ Stage *MetricsStage::make_stage(const std::string &tag) {
}
// 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::map<std::string, std::string> section =
get_properties()->get(stage_name_str);
std::map<std::string, std::string> section = get_properties()->get(stage_name_str);
metric_report_interval_ = DateTime::SECONDS_PER_MIN;
......@@ -70,7 +74,8 @@ bool MetricsStage::set_properties() {
}
// Initialize stage params and validate outputs
bool MetricsStage::initialize() {
bool MetricsStage::initialize()
{
LOG_TRACE("Enter");
std::list<Stage *>::iterator stgp = next_stage_list_.begin();
......@@ -84,13 +89,15 @@ bool MetricsStage::initialize() {
}
// Cleanup after disconnection
void MetricsStage::cleanup() {
void MetricsStage::cleanup()
{
LOG_TRACE("Enter");
LOG_TRACE("Exit");
}
void MetricsStage::handle_event(StageEvent *event) {
void MetricsStage::handle_event(StageEvent *event)
{
LOG_TRACE("Enter\n");
CompletionCallback *cb = new CompletionCallback(this, NULL);
......@@ -102,8 +109,7 @@ void MetricsStage::handle_event(StageEvent *event) {
return;
}
TimerRegisterEvent *tm_event =
new TimerRegisterEvent(event, metric_report_interval_ * USEC_PER_SEC);
TimerRegisterEvent *tm_event = new TimerRegisterEvent(event, metric_report_interval_ * USEC_PER_SEC);
if (tm_event == NULL) {
LOG_ERROR("Failed to new TimerRegisterEvent");
......@@ -121,7 +127,8 @@ void MetricsStage::handle_event(StageEvent *event) {
return;
}
void MetricsStage::callback_event(StageEvent *event, CallbackContext *context) {
void MetricsStage::callback_event(StageEvent *event, CallbackContext *context)
{
LOG_TRACE("Enter\n");
MetricsRegistry &metrics_registry = get_metrics_registry();
......
......@@ -37,8 +37,8 @@ protected:
protected:
private:
Stage *timer_stage_ = nullptr;
//report metrics every @metric_report_interval_ seconds
int metric_report_interval_ = 10;
// report metrics every @metric_report_interval_ seconds
int metric_report_interval_ = 10;
};
} // namespace common
#endif //__COMMON_SEDA_METRICS_STAGE_H__
} // namespace common
#endif //__COMMON_SEDA_METRICS_STAGE_H__
此差异已折叠。
......@@ -26,8 +26,7 @@ See the Mulan PSL v2 for more details. */
namespace common {
//keywords of sedaconfig
// keywords of sedaconfig
/**
* A class to configure seda stages
......@@ -45,7 +44,7 @@ namespace common {
class SedaConfig {
public:
public:
typedef enum { SUCCESS = 0, INITFAIL, PARSEFAIL } status_t;
static SedaConfig *&get_instance();
......@@ -157,7 +156,7 @@ class SedaConfig {
std::map<std::string, Stage *>::iterator begin();
std::map<std::string, Stage *>::iterator end();
private:
private:
// Constructor
SedaConfig();
......@@ -192,7 +191,7 @@ class SedaConfig {
void init_event_history();
SedaConfig &operator=(const SedaConfig &cevtout);
static SedaConfig *instance_;
// In old logic, SedaConfig will parse seda configure file
......@@ -203,18 +202,20 @@ class SedaConfig {
std::map<std::string, Threadpool *> thread_pools_;
std::map<std::string, Stage *> stages_;
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();
}
inline std::map<std::string, Stage *>::iterator SedaConfig::end() {
inline std::map<std::string, Stage *>::iterator SedaConfig::end()
{
return stages_.end();
}
inline Stage *SedaConfig::get_stage(const char *stagename) {
inline Stage *SedaConfig::get_stage(const char *stagename)
{
if (stagename) {
std::string sname(stagename);
return stages_[stagename];
......@@ -228,5 +229,5 @@ SedaConfig *&get_seda_config();
bool &get_event_history_flag();
u32_t &get_max_event_hops();
} //namespace common
#endif //__COMMON_SEDA_SEDA_CONFIG_H__
} // namespace common
#endif //__COMMON_SEDA_SEDA_CONFIG_H__
......@@ -15,7 +15,7 @@ See the Mulan PSL v2 for more details. */
#ifndef __COMMON_SEDA_SEDA_DEFS_H__
#define __COMMON_SEDA_SEDA_DEFS_H__
#define SEDA_BASE_NAME "SEDA_BASE"
#define SEDA_BASE_NAME "SEDA_BASE"
#define THREAD_POOLS_NAME "ThreadPools"
#define STAGES "STAGES"
......@@ -30,4 +30,4 @@ See the Mulan PSL v2 for more details. */
#define DEFAULT_THREAD_POOL "DefaultThreads"
#define METRCS_REPORT_INTERVAL "MetricsReportInterval"
#endif //__COMMON_SEDA_SEDA_DEFS_H__
#endif //__COMMON_SEDA_SEDA_DEFS_H__
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -58,7 +58,7 @@ class TimeoutInfo;
class StageEvent {
public:
public:
// Interface for collecting debugging information
typedef enum { HANDLE_EV = 0, CALLBACK_EV, TIMEOUT_EV } HistType;
......@@ -106,7 +106,10 @@ class StageEvent {
UserData *get_user_data();
// 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
void save_stage(Stage *stg, HistType type);
......@@ -123,23 +126,28 @@ class StageEvent {
// If the event has timed out (and should be dropped)
bool has_timed_out();
private:
private:
typedef std::pair<Stage *, HistType> HistEntry;
// Interface to allow callbacks to be run on target stage's threads
void mark_callback() { cb_flag_ = true; }
void clear_callback() { cb_flag_ = false; }
void mark_callback()
{
cb_flag_ = true;
}
void clear_callback()
{
cb_flag_ = false;
}
// Set a timeout info into the event
void set_timeout_info(TimeoutInfo *tmi);
CompletionCallback *comp_cb_; // completion callback stack for this event
UserData *ud_; // user data associated with event by caller
bool cb_flag_; // true if this event is a callback
std::list<HistEntry> *history_; // List of stages which have handled ev
CompletionCallback *comp_cb_; // completion callback stack for this event
UserData *ud_; // user data associated with event by caller
bool cb_flag_; // true if this event is a callback
std::list<HistEntry> *history_; // List 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 {
* originating stage can access the \c UserData member to recover its state.
*/
class UserData {
public:
public:
/**
* \brief A virtual destructor to enable the use of dynamic casts.
*/
virtual ~UserData() { return; }
virtual ~UserData()
{
return;
}
};
bool &get_event_history_flag();
u32_t &get_max_event_hops();
} //namespace common
#endif // __COMMON_SEDA_STAGE_EVENT_H__
} // namespace common
#endif // __COMMON_SEDA_STAGE_EVENT_H__
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册