diff --git a/.clang-format b/.clang-format index 2947afef1..b66517444 100644 --- a/.clang-format +++ b/.clang-format @@ -1,17 +1,15 @@ -# Format Style Options - Created with Clang Power Tools --- -BasedOnStyle: Google -AlignAfterOpenBracket: DontAlign -AllowAllArgumentsOnNextLine: false -AllowShortBlocksOnASingleLine: Always -BreakBeforeBraces: Linux -BreakStringLiterals: false -ColumnLimit: 150 -ContinuationIndentWidth: 2 -IncludeBlocks: Preserve -MaxEmptyLinesToKeep: 2 -ReflowComments: false +Language: Cpp +AccessModifierOffset: -2 +ColumnLimit: 100 +DerivePointerAlignment: false +PointerAlignment: Left SortIncludes: false -SpaceAfterCStyleCast: true -UseTab: Always -... +TypenameMacros: ['STACK_OF'] + +--- +Language: Proto +ColumnLimit: 100 +SpacesInContainerLiterals: false +AllowShortFunctionsOnASingleLine: false +ReflowComments: false \ No newline at end of file diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 17ca09796..d17c1cce2 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -28,7 +28,7 @@ RUN groupadd --gid $USER_GID $USERNAME \ RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone -RUN apt update && apt install -y gcc g++ gdb pkg-config libxml2-dev libsqlite3-dev libcurl4-openssl-dev zlib1g-dev make cmake wget autoconf git clangd python3-pip +RUN apt update && apt install -y gcc g++ gdb pkg-config libxml2-dev libsqlite3-dev libcurl4-openssl-dev zlib1g-dev make cmake wget autoconf git clangd python3-pip clang-format ## enable php-7.4 ENV PHP_VESION=php-7.4.33 RUN cd ~ && wget https://www.php.net/distributions/${PHP_VESION}.tar.gz && tar xvf ${PHP_VESION}.tar.gz && cd ${PHP_VESION} && ./configure --prefix=/opt/${PHP_VESION} --enable-fpm --enable-opcache --enable-debug && make -j && make install diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index d4fbe0a68..db5b1068c 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -35,13 +35,13 @@ "containerUser": "pinpoint", "postCreateCommand": ".devcontainer/setup.sh", "extensions": [ - "github.vscode-pull-request-github", "zxh404.vscode-proto3", "llvm-vs-code-extensions.vscode-clangd", "vadimcn.vscode-lldb", "webfreak.debug", "ms-python.python", "xaver.clang-format", - "zxh404.vscode-proto3" + "zxh404.vscode-proto3", + "Gruntfuggly.todo-tree" ] } \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3eee7055a..411a31c83 100644 --- a/.gitignore +++ b/.gitignore @@ -72,4 +72,5 @@ collector-agent/collector-agent common/include/common.h .cache compile_commands.json -wheelhouse/ \ No newline at end of file +wheelhouse/ +.clangd \ No newline at end of file diff --git a/common/src/ConnectionPool/TransLayer.cpp b/common/src/ConnectionPool/TransLayer.cpp index 35c6bee5b..020700af2 100644 --- a/common/src/ConnectionPool/TransLayer.cpp +++ b/common/src/ConnectionPool/TransLayer.cpp @@ -15,13 +15,11 @@ ******************************************************************************/ #include "TransLayer.h" #include -namespace ConnectionPool -{ +namespace ConnectionPool { /** - * remote: localhost:port - */ -int TransLayer::connect_stream_remote(const char *remote) -{ + * remote: localhost:port + */ +int TransLayer::connect_stream_remote(const char* remote) { int offset = strlen(remote) - 1; while (remote[offset] != ':') { @@ -33,13 +31,13 @@ int TransLayer::connect_stream_remote(const char *remote) } std::string hostname(remote, offset); - const char *port_str = remote + offset + 1; + const char* port_str = remote + offset + 1; // int port = atoi(remote+offset+1); struct addrinfo hints; struct addrinfo *result, *rp; memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM; /* Datagram socket */ hints.ai_flags = 0; hints.ai_protocol = 0; /* Any protocol */ @@ -54,17 +52,19 @@ int TransLayer::connect_stream_remote(const char *remote) for (rp = result; rp != NULL; rp = rp->ai_next) { sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - struct linger fd_linger = {1, 1}; // open and 1 second + struct linger fd_linger = {1, 1}; // open and 1 second // mark it as nonblock fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL, 0) | O_NONBLOCK); setsockopt(sfd, SOL_SOCKET, SO_LINGER, &fd_linger, sizeof(fd_linger)); - if (sfd == -1) continue; + if (sfd == -1) + continue; int ret = connect(sfd, rp->ai_addr, rp->ai_addrlen); if (ret == 0) { break; } else if (ret == -1) { - if (errno == EALREADY || errno == EINPROGRESS) break; + if (errno == EALREADY || errno == EINPROGRESS) + break; } close(sfd); @@ -75,15 +75,14 @@ int TransLayer::connect_stream_remote(const char *remote) return sfd; } -int TransLayer::connect_unix_remote(const char *remote) -{ +int TransLayer::connect_unix_remote(const char* remote) { int fd = -1; #if defined(__APPLE__) struct sockaddr_un u_sock = {0, 0, {0}}; #else struct sockaddr_un u_sock = {0, {0}}; #endif - struct linger fd_linger = {1, 1}; // open and 1 second + struct linger fd_linger = {1, 1}; // open and 1 second if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { pp_trace(" get socket error,(%s)", strerror(errno)); goto ERROR; @@ -97,7 +96,7 @@ int TransLayer::connect_unix_remote(const char *remote) setsockopt(fd, SOL_SOCKET, SO_LINGER, &fd_linger, sizeof(fd_linger)); - if (connect(fd, (struct sockaddr *) &u_sock, sizeof(u_sock)) != 0) { + if (connect(fd, (struct sockaddr*)&u_sock, sizeof(u_sock)) != 0) { if (errno != EALREADY || errno != EINPROGRESS) { pp_trace("connect:(%s) failed as (%s)", remote, strerror(errno)); goto ERROR; @@ -108,18 +107,21 @@ int TransLayer::connect_unix_remote(const char *remote) return fd; ERROR: - if (fd > 0) { close(fd); } + if (fd > 0) { + close(fd); + } return -1; } -size_t TransLayer::trans_layer_pool(uint32_t timeout) -{ +size_t TransLayer::trans_layer_pool(uint32_t timeout) { if (c_fd == -1) { pp_trace("agent try to connect:(%s)", this->co_host.c_str()); connect_remote(this->co_host.c_str()); - if (c_fd == -1) { return -1; } + if (c_fd == -1) { + return -1; + } } int fd = c_fd; @@ -129,13 +131,19 @@ size_t TransLayer::trans_layer_pool(uint32_t timeout) FD_ZERO(&wfds); FD_ZERO(&rfds); - if (this->_state & S_ERROR) { FD_SET(fd, &efds); } + if (this->_state & S_ERROR) { + FD_SET(fd, &efds); + } - if (this->_state & S_WRITING) { FD_SET(fd, &wfds); } + if (this->_state & S_WRITING) { + FD_SET(fd, &wfds); + } - if (this->_state & S_READING) { FD_SET(fd, &rfds); } + if (this->_state & S_READING) { + FD_SET(fd, &rfds); + } - struct timeval tv = {0, (int) timeout * 1000}; + struct timeval tv = {0, (int)timeout * 1000}; int retval = select(fd + 1, &rfds, &wfds, &efds, &tv); if (retval == -1) { @@ -149,13 +157,15 @@ size_t TransLayer::trans_layer_pool(uint32_t timeout) } if ((this->_state & S_WRITING) && FD_ISSET(fd, &wfds)) { - if (_send_msg_to_collector() == -1) { goto ERROR; } + if (_send_msg_to_collector() == -1) { + goto ERROR; + } } if ((this->_state & S_READING) && FD_ISSET(fd, &rfds)) { if (_recv_msg_from_collector() == -1) { - pp_trace("recv_msg_from_collector error"); - goto ERROR; + pp_trace("recv_msg_from_collector error"); + goto ERROR; } } } else { @@ -173,8 +183,7 @@ size_t TransLayer::trans_layer_pool(uint32_t timeout) return -1; } -bool TransLayer::copy_into_send_buffer(const std::string &data) -{ +bool TransLayer::copy_into_send_buffer(const std::string& data) { Header header; header.length = htonl(data.size()); header.type = htonl(REQ_UPDATE_SPAN); @@ -184,7 +193,7 @@ bool TransLayer::copy_into_send_buffer(const std::string &data) return false; } // copy header - this->chunks.copyDataIntoChunks((const char *) &header, sizeof(header)); + this->chunks.copyDataIntoChunks((const char*)&header, sizeof(header)); // copy body this->chunks.copyDataIntoChunks(data.data(), data.size()); // enable write event @@ -192,6 +201,6 @@ bool TransLayer::copy_into_send_buffer(const std::string &data) return true; } -const char *TransLayer::UNIX_SOCKET = "unix:"; -const char *TransLayer::TCP_SOCKET = "tcp:"; -} // namespace ConnectionPool \ No newline at end of file +const char* TransLayer::UNIX_SOCKET = "unix:"; +const char* TransLayer::TCP_SOCKET = "tcp:"; +} // namespace ConnectionPool \ No newline at end of file diff --git a/common/src/ConnectionPool/TransLayer.h b/common/src/ConnectionPool/TransLayer.h index e038566a7..4be1bd700 100644 --- a/common/src/ConnectionPool/TransLayer.h +++ b/common/src/ConnectionPool/TransLayer.h @@ -38,9 +38,7 @@ #include "common.h" #include "Cache/Chunk.h" - namespace ConnectionPool { - using Cache::Chunks; // note update chunk watermark size @@ -50,77 +48,60 @@ using Cache::Chunks; const uint32_t _chunk_max_size = 10 * 1024 * 1024; // 10M const uint32_t _chunk_hold_size = 40 * 1024; // 40k -class TransLayer -{ - - enum E_STATE - { - S_WRITING = 0x1, - S_READING = 0x2, - S_ERROR = 0x4 - }; +class TransLayer { + enum E_STATE { S_WRITING = 0x1, S_READING = 0x2, S_ERROR = 0x4 }; public: - explicit TransLayer(const std::string &co_host) : co_host(co_host), - chunks(_chunk_max_size, _chunk_hold_size), - _state(0), - lastConnectTime(0), - c_fd(-1) - { + explicit TransLayer(const std::string& co_host) + : co_host(co_host), chunks(_chunk_max_size, _chunk_hold_size), _state(0), lastConnectTime(0), + c_fd(-1) {} + + void registerPeerMsgCallback( + std::function _peerMsgCallback, + std::function chann_error_cb) { + if (_peerMsgCallback) { + this->peerMsgCallback = _peerMsgCallback; } - void registerPeerMsgCallback(std::function _peerMsgCallback, - std::function chann_error_cb ) - { - if(_peerMsgCallback){ - this->peerMsgCallback = _peerMsgCallback; - } - - if(chann_error_cb) - { - this->chann_error_cb =chann_error_cb; - } - + if (chann_error_cb) { + this->chann_error_cb = chann_error_cb; } - - size_t trans_layer_pool(uint32_t); - - bool copy_into_send_buffer(const std::string &data); - - // void sendMsgToAgent(const char* pbuf,uint32_t len) - // { - // if ( this->chunks.copyDataIntoChunks(pbuf,len) != 0) - // { - // pp_trace("Send buffer is full. size:[%d]",len); - // return ; - // } - // this->_state |= S_WRITING; - // } - - /** - * retry in three times - * @param timeout - */ - void forceFlushMsg(uint32_t timeout) - { + } + + size_t trans_layer_pool(uint32_t); + + bool copy_into_send_buffer(const std::string& data); + + // void sendMsgToAgent(const char* pbuf,uint32_t len) + // { + // if ( this->chunks.copyDataIntoChunks(pbuf,len) != 0) + // { + // pp_trace("Send buffer is full. size:[%d]",len); + // return ; + // } + // this->_state |= S_WRITING; + // } + + /** + * retry in three times + * @param timeout + */ + void forceFlushMsg(uint32_t timeout) { #define MAX_RETRY_TIEMS 3 - int retry =0; - timeout = (timeout >3) ?(timeout):(3); - while( (this->_state & S_WRITING) && retry < MAX_RETRY_TIEMS ) - { - this->trans_layer_pool(timeout/3); - retry ++; - } -#undef MAX_RETRY_TIEMS + int retry = 0; + timeout = (timeout > 3) ? (timeout) : (3); + while ((this->_state & S_WRITING) && retry < MAX_RETRY_TIEMS) { + this->trans_layer_pool(timeout / 3); + retry++; } +#undef MAX_RETRY_TIEMS + } - ~TransLayer() - { - if(this->c_fd != -1) - { - close(this->c_fd); - } + ~TransLayer() { + if (this->c_fd != -1) { + close(this->c_fd); } + } #ifdef UTEST @@ -128,189 +109,176 @@ class TransLayer private: #endif - static int connect_stream_remote(const char* remote); - - static int connect_unix_remote(const char* remote); - - int connect_remote(const char* statement) - { - int fd = -1; - const char* substring = NULL; - if(statement == NULL || statement[0] == '\0') - { - goto ERROR; - } + static int connect_stream_remote(const char* remote); - // check last connect time - if( time(NULL) < this->lastConnectTime + RECONNECT_TIME_SEC){ - goto RECONNECT_WAITING; - }else{ - this->lastConnectTime = time(NULL); - } - - /// unix - substring = strcasestr(statement,UNIX_SOCKET); - if( substring == statement ) - { - // sizeof = len +1, so substring -> /tmp/collector.sock - substring = substring + strlen(UNIX_SOCKET); - fd = connect_unix_remote(substring); - c_fd = fd; - goto DONE; - } - - /// tcp tcp:localhost:port - substring = strcasestr(statement,TCP_SOCKET); - if( substring == statement ) - { - // sizeof = len +1, so substring -> /tmp/collector.sock - substring = substring + strlen(TCP_SOCKET); - fd = TransLayer::connect_stream_remote(substring); - c_fd = fd; - goto DONE; - } + static int connect_unix_remote(const char* remote); -ERROR: - pp_trace("remote is not valid:%s",statement); - return -1; -RECONNECT_WAITING: - return -1; -DONE: - this->_state |= (S_ERROR|S_READING|S_WRITING); - return fd; + int connect_remote(const char* statement) { + int fd = -1; + const char* substring = NULL; + if (statement == NULL || statement[0] == '\0') { + goto ERROR; } - int _send_msg_to_collector() - { - return chunks.drainOutWithPipe(std::bind(&TransLayer::_do_write_data,this,std::placeholders::_1,std::placeholders::_2)); + // check last connect time + if (time(NULL) < this->lastConnectTime + RECONNECT_TIME_SEC) { + goto RECONNECT_WAITING; + } else { + this->lastConnectTime = time(NULL); } - void _reset_remote( ) - { - if(c_fd > 0) - { - pp_trace("reset peer:%d",c_fd); - close(c_fd); - c_fd = -1; - this->_state = 0; - } - - if(chann_error_cb) - { - chann_error_cb(E_OFFLINE); - } - - chunks.resetChunks(); + /// unix + substring = strcasestr(statement, UNIX_SOCKET); + if (substring == statement) { + // sizeof = len +1, so substring -> /tmp/collector.sock + substring = substring + strlen(UNIX_SOCKET); + fd = connect_unix_remote(substring); + c_fd = fd; + goto DONE; } - int _do_write_data(const char *data,uint32_t length) - { - const char* buf = data; - uint32_t buf_ofs = 0; - while(buf_ofs < length){ - #ifdef __APPLE__ - ssize_t ret = send(c_fd,buf + buf_ofs,length -buf_ofs ,0); - #else - ssize_t ret = send(c_fd,buf + buf_ofs,length -buf_ofs ,MSG_NOSIGNAL); - #endif - - if(ret > 0){ - buf_ofs += (uint32_t) ret; - pp_trace("fd %d send size %ld",c_fd,ret); - }else if(ret == -1){ - if(errno == EAGAIN || errno == EWOULDBLOCK || errno== EINTR){ - this->_state |= S_WRITING; - return buf_ofs; - } - pp_trace("_do_write_data@%d send data error:(%s) fd:(%d)",__LINE__,strerror(errno),c_fd); - return -1; - } - else{ - pp_trace("_do_write_data@%d send data return 0 error:(%s) fd:(%d)",__LINE__,strerror(errno),c_fd); - return -1; - } - } - //current task is done - this->_state &= (~S_WRITING); - return length; + /// tcp tcp:localhost:port + substring = strcasestr(statement, TCP_SOCKET); + if (substring == statement) { + // sizeof = len +1, so substring -> /tmp/collector.sock + substring = substring + strlen(TCP_SOCKET); + fd = TransLayer::connect_stream_remote(substring); + c_fd = fd; + goto DONE; } - int _recv_msg_from_collector() - { - int next_size = 0; - while(next_size < IN_MSG_BUF_SIZE){ - int ret = recv(c_fd,in_buf + next_size,IN_MSG_BUF_SIZE -next_size ,0); - if (ret > 0){ - int total = ret + next_size; - int msg_offset = handle_msg_from_collector(in_buf,total); - if(msg_offset < total){ - next_size = total - msg_offset; - memcpy(in_buf,in_buf + msg_offset ,next_size); - }else{ - next_size = 0 ; - } - }else if(ret == 0){ - // peer close - return -1; - }else{ - if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR){ - return 0; - } - pp_trace("recv with error:%s",strerror(errno)); - return -1; - } - } - return 0; + ERROR: + pp_trace("remote is not valid:%s", statement); + return -1; + RECONNECT_WAITING: + return -1; + DONE: + this->_state |= (S_ERROR | S_READING | S_WRITING); + return fd; + } + + int _send_msg_to_collector() { + return chunks.drainOutWithPipe( + std::bind(&TransLayer::_do_write_data, this, std::placeholders::_1, std::placeholders::_2)); + } + + void _reset_remote() { + if (c_fd > 0) { + pp_trace("reset peer:%d", c_fd); + close(c_fd); + c_fd = -1; + this->_state = 0; } - int handle_msg_from_collector(const char* buf,size_t len) - { - size_t offset = 0; - while( offset + 8 <= len ){ - - Header * header= (Header*)buf; + if (chann_error_cb) { + chann_error_cb(E_OFFLINE); + } - uint32_t body_len = ntohl(header->length); + chunks.resetChunks(); + } - if( 8+ body_len > len ){ - return offset ; - } + int _do_write_data(const char* data, uint32_t length) { + const char* buf = data; + uint32_t buf_ofs = 0; + while (buf_ofs < length) { +#ifdef __APPLE__ + ssize_t ret = send(c_fd, buf + buf_ofs, length - buf_ofs, 0); +#else + ssize_t ret = send(c_fd, buf + buf_ofs, length - buf_ofs, MSG_NOSIGNAL); +#endif - uint32_t type = ntohl(header->type); - if(peerMsgCallback) - { - peerMsgCallback(type, buf+8,len - 8); - } + if (ret > 0) { + buf_ofs += (uint32_t)ret; + pp_trace("fd %d send size %ld", c_fd, ret); + } else if (ret == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + this->_state |= S_WRITING; + return buf_ofs; + } + pp_trace("_do_write_data@%d send data error:(%s) fd:(%d)", __LINE__, strerror(errno), c_fd); + return -1; + } else { + pp_trace("_do_write_data@%d send data return 0 error:(%s) fd:(%d)", __LINE__, + strerror(errno), c_fd); + return -1; + } + } + // current task is done + this->_state &= (~S_WRITING); + return length; + } + + int _recv_msg_from_collector() { + int next_size = 0; + while (next_size < IN_MSG_BUF_SIZE) { + int ret = recv(c_fd, in_buf + next_size, IN_MSG_BUF_SIZE - next_size, 0); + if (ret > 0) { + int total = ret + next_size; + int msg_offset = handle_msg_from_collector(in_buf, total); + if (msg_offset < total) { + next_size = total - msg_offset; + memcpy(in_buf, in_buf + msg_offset, next_size); + } else { + next_size = 0; + } + } else if (ret == 0) { + // peer close + return -1; + } else { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + return 0; + } + pp_trace("recv with error:%s", strerror(errno)); + return -1; + } + } + return 0; + } - // switch(type){ - // case RESPONSE_AGENT_INFO: - // // TODO add agent_info update - // // handle_agent_info(RESPONSE_AGENT_INFO, buf+8,len - 8); - // break; - // default: - // pp_trace("unsupport type:%d",type); - // } + int handle_msg_from_collector(const char* buf, size_t len) { + size_t offset = 0; + while (offset + 8 <= len) { + Header* header = (Header*)buf; - offset += (8 +body_len ); + uint32_t body_len = ntohl(header->length); - } + if (8 + body_len > len) { return offset; + } + + uint32_t type = ntohl(header->type); + if (peerMsgCallback) { + peerMsgCallback(type, buf + 8, len - 8); + } + + // switch(type){ + // case RESPONSE_AGENT_INFO: + // // TODO add agent_info update + // // handle_agent_info(RESPONSE_AGENT_INFO, buf+8,len - 8); + // break; + // default: + // pp_trace("unsupport type:%d",type); + // } + + offset += (8 + body_len); } + return offset; + } private: - const std::string& co_host; - Chunks chunks; - int32_t _state; - char in_buf[IN_MSG_BUF_SIZE]= {0}; - std::function chann_error_cb; - std::function peerMsgCallback; - const static char* UNIX_SOCKET; - const static char* TCP_SOCKET; - time_t lastConnectTime; + const std::string& co_host; + Chunks chunks; + int32_t _state; + char in_buf[IN_MSG_BUF_SIZE] = {0}; + std::function chann_error_cb; + std::function peerMsgCallback; + const static char* UNIX_SOCKET; + const static char* TCP_SOCKET; + time_t lastConnectTime; public: - int c_fd; + int c_fd; }; -} +} // namespace ConnectionPool #endif /* INCLUDE_PPTRANSLAYER_H_ */ diff --git a/common/src/Context/ContextType.h b/common/src/Context/ContextType.h index 6329e6b2d..6353d2295 100644 --- a/common/src/Context/ContextType.h +++ b/common/src/Context/ContextType.h @@ -27,67 +27,44 @@ #include #include -namespace Context -{ - - typedef const char *ctype; - - class ContextType - { - public: - ContextType() {} - virtual ~ContextType() {} - - virtual ctype typeIs() { throw std::logic_error("not implementation"); } - virtual std::string asStringValue() { throw std::logic_error("not implementation"); } - virtual long asLongValue() { throw std::logic_error("not implementation"); } - }; - - class StringContextType : public ContextType - { - public: - StringContextType(std::string &&value) : _value(std::move(value)) - { - } - - virtual ctype typeIs() override - { - return "String"; - } - - virtual std::string asStringValue() override - { - return this->_value; - } - - virtual ~StringContextType() - { - } - - private: - std::string _value; - }; - - class LongContextType : public ContextType - { - public: - LongContextType(long l) : l(l) - { - } - - virtual ctype typeIs() override - { - return "Long"; - } - - virtual long asLongValue() override - { - return this->l; - } - - private: - long l; - }; +namespace Context { +typedef const char* ctype; + +class ContextType { +public: + ContextType() {} + virtual ~ContextType() {} + + virtual ctype typeIs() { throw std::logic_error("not implementation"); } + virtual std::string asStringValue() { throw std::logic_error("not implementation"); } + virtual long asLongValue() { throw std::logic_error("not implementation"); } +}; + +class StringContextType : public ContextType { +public: + StringContextType(std::string&& value) : _value(std::move(value)) {} + + virtual ctype typeIs() override { return "String"; } + + virtual std::string asStringValue() override { return this->_value; } + + virtual ~StringContextType() {} + +private: + std::string _value; +}; + +class LongContextType : public ContextType { +public: + LongContextType(long l) : l(l) {} + + virtual ctype typeIs() override { return "Long"; } + + virtual long asLongValue() override { return this->l; } + +private: + long l; +}; } /* namespace Context */ diff --git a/common/src/Logging.c b/common/src/Logging.c index 2798c1f64..c8c469a5a 100644 --- a/common/src/Logging.c +++ b/common/src/Logging.c @@ -1,12 +1,12 @@ //////////////////////////////////////////////////////////////////////////////// // Copyright 2020 NAVER Corp -// +// // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -18,62 +18,56 @@ #include -#if defined(__linux__) || defined(_UNIX) - #include - #include - #include - #include - #define gettid() syscall(SYS_gettid) - #define getOSPid getpid +#if defined(__linux__) || defined(_UNIX) +#include +#include +#include +#include +#define gettid() syscall(SYS_gettid) +#define getOSPid getpid #endif #if defined(__APPLE__) - #include - #include - #include - #include - #define gettid() (long)getpid() - #define getOSPid getpid +#include +#include +#include +#include +#define gettid() (long) getpid() +#define getOSPid getpid #endif #if defined(_WIN32) - #include - #define getOSPid GetCurrentProcessId +#include +#define getOSPid GetCurrentProcessId #endif static log_msg_cb _error_cb; -static void log_format_out(const char *format,va_list* args) +static void log_format_out(const char *format, va_list *args) { - char buf[LOG_SIZE]={0}; - int n = snprintf(buf,LOG_SIZE,"[pinpoint] [%d] [%ld]",getOSPid(),gettid()); - vsnprintf(buf+n, LOG_SIZE -n - 1 ,format, *args); - - if (_error_cb){ - _error_cb(buf); - }else{ - fprintf(stderr,"%s\n",buf); - } + char buf[LOG_SIZE] = {0}; + int n = snprintf(buf, LOG_SIZE, "[pinpoint] [%d] [%ld]", getOSPid(), gettid()); + vsnprintf(buf + n, LOG_SIZE - n - 1, format, *args); + + if (_error_cb) { + _error_cb(buf); + } else { + fprintf(stderr, "%s\n", buf); + } } /** * Note: the logging should be disable when in Real env */ -void pp_trace(const char *format,...) +void pp_trace(const char *format, ...) { - if( (global_agent_info.inter_flag & E_LOGGING) == 0) - { - return ; - } - va_list args; - va_start(args, format); - // there is no need to create a LOG_SIZE in every call - log_format_out(format,&args); - va_end(args); + if ((global_agent_info.inter_flag & E_LOGGING) == 0) { return; } + va_list args; + va_start(args, format); + // there is no need to create a LOG_SIZE in every call + log_format_out(format, &args); + va_end(args); } // register when thread/module/process start -void register_error_cb(log_msg_cb error_cb) -{ - _error_cb = error_cb; -} +void register_error_cb(log_msg_cb error_cb) { _error_cb = error_cb; } diff --git a/common/src/NodePool/PoolManager.cpp b/common/src/NodePool/PoolManager.cpp index b7b06bc45..9b6947cca 100644 --- a/common/src/NodePool/PoolManager.cpp +++ b/common/src/NodePool/PoolManager.cpp @@ -30,34 +30,30 @@ #define UINT32_MAX (0xfffffff) #endif -namespace NodePool -{ -void freeNodeTree(NodeID nodeId) -{ - if (nodeId == E_INVALID_NODE || nodeId == E_ROOT_NODE) { return; } +namespace NodePool { +void freeNodeTree(NodeID nodeId) { + if (nodeId == E_INVALID_NODE || nodeId == E_ROOT_NODE) { + return; + } NodeID child_id, next_id; if (PoolManager::getInstance().Restore(nodeId, child_id, next_id)) { - if (next_id != E_INVALID_NODE) { freeNodeTree(next_id); } + if (next_id != E_INVALID_NODE) { + freeNodeTree(next_id); + } - if (child_id != E_INVALID_NODE) { freeNodeTree(child_id); } + if (child_id != E_INVALID_NODE) { + freeNodeTree(child_id); + } } - - // while (child_id != E_INVALID_NODE) - // { - // WrapperTraceNode r_node = PoolManager::getInstance().GetWrapperNode(child_id); - // next_id = r_node->mNextId; - // freeNodeTree(child_id); - // child_id = next_id; - // } - - // PoolManager::getInstance().Restore(rootId); } -bool PoolManager::Restore(NodeID id, NodeID &child_id, NodeID &next_id) -{ +bool PoolManager::Restore(NodeID id, NodeID& child_id, NodeID& next_id) { for (int i = 0; i < 1000; i++) { - if (this->_restore(id, child_id, next_id, false)) { return true; } + // this node was in using: ref is not zero + if (this->_restore(id, child_id, next_id, false)) { + return true; + } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } pp_trace("[🐛]Restore node failed: #%d; node restore forcefully", id); @@ -65,11 +61,10 @@ bool PoolManager::Restore(NodeID id, NodeID &child_id, NodeID &next_id) } // avoiding `locking and waitting` -bool PoolManager::_restore(NodeID id, NodeID &child_id, NodeID &next_id, bool force) -{ +bool PoolManager::_restore(NodeID id, NodeID& child_id, NodeID& next_id, bool force) { std::lock_guard _safe(this->_lock); - int32_t index = (int32_t) id - 1; + int32_t index = (int32_t)id - 1; if (this->indexInAliveVec(index) == false) { pp_trace("%d not alive !!!", id); @@ -79,10 +74,10 @@ bool PoolManager::_restore(NodeID id, NodeID &child_id, NodeID &next_id, bool fo } // check refcount - TraceNode &node = this->_fetchNodeBy(id); + TraceNode& node = this->_fetchNodeBy(id); if (node.checkZoreRef() == false && force == false) { - // DO NOT TOUCH out id + // DO NOT TOUCH THis Node return false; } else { this->_aliveNodeSet[index] = false; @@ -93,10 +88,11 @@ bool PoolManager::_restore(NodeID id, NodeID &child_id, NodeID &next_id, bool fo } } -TraceNode &PoolManager::_fetchNodeBy(NodeID id) -{ +TraceNode& PoolManager::_fetchNodeBy(NodeID id) { // assert(id != E_INVALID_NODE); - if (id == E_ROOT_NODE) { throw std::out_of_range("id should not be 0"); } + if (id == E_ROOT_NODE) { + throw std::out_of_range("id should not be 0"); + } int32_t index = int32_t(id) - 1; @@ -109,9 +105,10 @@ TraceNode &PoolManager::_fetchNodeBy(NodeID id) return this->nodeIndexVec[index / CELL_SIZE][index % CELL_SIZE]; } -TraceNode &PoolManager::_getInitNode() noexcept -{ // create a new node - if (this->_freeNodeList.empty()) { this->expandOnce(); } +TraceNode& PoolManager::_getInitNode() noexcept { // create a new node + if (this->_freeNodeList.empty()) { + this->expandOnce(); + } // as it holds a _lock, so no more _freeNodeList is empty int32_t index = this->_freeNodeList.top(); this->_freeNodeList.pop(); @@ -119,8 +116,7 @@ TraceNode &PoolManager::_getInitNode() noexcept return this->nodeIndexVec[index / CELL_SIZE][index % CELL_SIZE].reset(NodeID(index + 1)); } -TraceNode &PoolManager::_take(NodeID id) -{ +TraceNode& PoolManager::_take(NodeID id) { if (id != E_ROOT_NODE) { return this->_fetchNodeBy(id); } else { @@ -128,18 +124,20 @@ TraceNode &PoolManager::_take(NodeID id) } } -void PoolManager::expandOnce() -{ +void PoolManager::expandOnce() { ADDTRACE(); // pp_trace("Node pool expanding self! Old size:%ld", this->nodeIndexVec.size() * CELL_SIZE); // append new nodes into nodeIndexVec this->nodeIndexVec.push_back(std::unique_ptr(new TraceNode[CELL_SIZE])); // this->nodeIndexVec.push_back(std::make_unique(CELL_SIZE)); // append new bitflag into aliveNodeSet - this->_aliveNodeSet.insert(this->_aliveNodeSet.end(), this->_emptyAliveSet.begin(), this->_emptyAliveSet.end()); - for (int32_t id = this->maxId; id < (this->maxId + CELL_SIZE); id++) { this->_freeNodeList.push(id); } + this->_aliveNodeSet.insert(this->_aliveNodeSet.end(), this->_emptyAliveSet.begin(), + this->_emptyAliveSet.end()); + for (int32_t id = this->maxId; id < (this->maxId + CELL_SIZE); id++) { + this->_freeNodeList.push(id); + } this->maxId += CELL_SIZE; // pp_trace("Node pool expanding is done! news size:%ld", this->nodeIndexVec.size() * CELL_SIZE); assert(this->nodeIndexVec.size() * CELL_SIZE == this->_aliveNodeSet.size()); } -} // namespace NodePool +} // namespace NodePool diff --git a/common/src/Util/Helper.h b/common/src/Util/Helper.h index 08477b1d6..0adf326ca 100644 --- a/common/src/Util/Helper.h +++ b/common/src/Util/Helper.h @@ -37,48 +37,44 @@ #include "NodePool/TraceNode.h" #include "ConnectionPool/SpanConnectionPool.h" -namespace Helper -{ - namespace Json = AliasJson; - using ConnectionPool::TransConnection; - using NodePool::TraceNode; - using NodePool::WrapperTraceNode; - using std::chrono::duration; - using std::chrono::duration_cast; - using std::chrono::milliseconds; - using std::chrono::steady_clock; - using std::chrono::system_clock; - using std::chrono::time_point; - using std::chrono::time_point_cast; - typedef struct scope_time_trace - { - steady_clock::time_point _start_time; - std::string _funcName; - scope_time_trace(const char *cfunc) - { - _start_time = steady_clock::now(); - _funcName = cfunc; - } - ~scope_time_trace() - { - milliseconds elapsed = duration_cast(steady_clock::now() - _start_time); - pp_trace(" [%s] it's take [%ld] miliseconds", _funcName.c_str(), elapsed.count()); - } - } STT; - - uint64_t get_current_msec_stamp() noexcept; - - std::string node_tree_to_string(const Json::Value &value); - - Json::Value mergeTraceNodeTree(TraceNode &root); - Json::Value mergeTraceNodeTree(WrapperTraceNode &root); - - Json::Value mergeTraceNodeTree(NodeID Id) noexcept; - TransConnection getConnection(); - - void freeConnection(TransConnection &); - -} +namespace Helper { +namespace Json = AliasJson; +using ConnectionPool::TransConnection; +using NodePool::TraceNode; +using NodePool::WrapperTraceNode; +using std::chrono::duration; +using std::chrono::duration_cast; +using std::chrono::milliseconds; +using std::chrono::steady_clock; +using std::chrono::system_clock; +using std::chrono::time_point; +using std::chrono::time_point_cast; +typedef struct scope_time_trace { + steady_clock::time_point _start_time; + std::string _funcName; + scope_time_trace(const char* cfunc) { + _start_time = steady_clock::now(); + _funcName = cfunc; + } + ~scope_time_trace() { + milliseconds elapsed = duration_cast(steady_clock::now() - _start_time); + pp_trace(" [%s] it's take [%ld] miliseconds", _funcName.c_str(), elapsed.count()); + } +} STT; + +uint64_t get_current_msec_stamp() noexcept; + +std::string node_tree_to_string(const Json::Value& value); + +Json::Value mergeTraceNodeTree(TraceNode& root); +Json::Value mergeTraceNodeTree(WrapperTraceNode& root); + +Json::Value mergeTraceNodeTree(NodeID Id) noexcept; +TransConnection getConnection(); + +void freeConnection(TransConnection&); + +} // namespace Helper #ifndef NDEBUG diff --git a/common/src/common.cpp b/common/src/common.cpp index 54241a240..cbdcd10fa 100644 --- a/common/src/common.cpp +++ b/common/src/common.cpp @@ -43,23 +43,23 @@ using NodePool::PoolManager; using NodePool::TraceNode; using NodePool::WrapperTraceNode; -const static char *CLUSE = "clues"; +const static char* CLUSE = "clues"; static thread_local NodeID __tls_id = E_ROOT_NODE; -PPAgentT global_agent_info = {"unix:./pinpoint_test.sock", 1, 10, 1500, 1, nullptr, nullptr, nullptr}; +PPAgentT global_agent_info = { + "unix:./pinpoint_test.sock", 1, 10, 1500, 1, nullptr, nullptr, nullptr}; // send current span with timeout static thread_local int _span_timeout = global_agent_info.timeout_ms; -static std::function _SpanHandler_; +static std::function _SpanHandler_; NodeID pinpoint_get_per_thread_id() { return __tls_id; } void pinpoint_update_per_thread_id(NodeID id) { __tls_id = id; } -static NodeID do_start_trace(NodeID id, const char *opt = nullptr, va_list *args = nullptr) -{ +static NodeID do_start_trace(NodeID id, const char* opt = nullptr, va_list* args = nullptr) { if (id <= E_INVALID_NODE) { throw std::out_of_range("invalid node id"); } else if (id == E_ROOT_NODE) { - TraceNode &r_node = PoolManager::getInstance().Take(); + TraceNode& r_node = PoolManager::getInstance().Take(); r_node.startTimer(); return r_node.mPoolIndex; } else { @@ -68,30 +68,32 @@ static NodeID do_start_trace(NodeID id, const char *opt = nullptr, va_list *args // get root node WrapperTraceNode root = PoolManager::getInstance().GetWrapperNode(parent->mRootIndex); + // check subnode limit root->updateRootSubTraceSize(); - // todo check subnode limit WrapperTraceNode trace = PoolManager::getInstance().GetWrapperNode(); trace->startTimer(); parent->addChild(trace); // pass opt - if (opt != nullptr) { trace->setOpt(opt, args); } + if (opt != nullptr) { + trace->setOpt(opt, args); + } return trace->mPoolIndex; } } -static void flush_to_agent(std::string &span) -{ +static void flush_to_agent(std::string& span) { TransConnection trans = Helper::getConnection(); - if (!trans->copy_into_send_buffer(span)) { pp_trace("drop current span as it's too heavy! size:%lu", span.length()); } + if (!trans->copy_into_send_buffer(span)) { + pp_trace("drop current span as it's too heavy! size:%lu", span.length()); + } trans->trans_layer_pool(_span_timeout); // if network not ready, span will send in next time. Helper::freeConnection(trans); } -void sendSpan(NodeID rootId) -{ +void sendSpan(NodeID rootId) { const Json::Value trace = Helper::mergeTraceNodeTree(rootId); std::string spanStr = Helper::node_tree_to_string(trace); if (unlikely(_SpanHandler_ != nullptr)) { @@ -102,8 +104,7 @@ void sendSpan(NodeID rootId) } } -NodeID do_end_trace(NodeID Id) -{ +NodeID do_end_trace(NodeID Id) { WrapperTraceNode r_node = PoolManager::getInstance().GetWrapperNode(Id); if (r_node->isRoot()) { if (r_node->limit == E_TRACE_PASS) { @@ -119,51 +120,27 @@ NodeID do_end_trace(NodeID Id) r_node->endTimer(); r_node->convertToSpanEvent(); return r_node->mParentId; - // check opt - // if (r_node->checkOpt() == true) - // { - // try - // { - // WrapperTraceNode r_parent = PoolManager::getInstance().GetWrapperNode(parentId); - // r_parent->addChild(r_node); - // return r_parent->mPoolIndex; - // } - // catch (const std::out_of_range &ex) - // { - // pp_trace("current#%d dropped,due to parent is end", Id); - // } - // catch (const std::exception &ex) - // { - // pp_trace("current#%d dropped,due to exception: %s", Id, ex.what()); - // } - // } - // else - // { - // pp_trace("current#%d dropped,due to checkOpt false", Id); - // } } // free current ndde tree return E_ROOT_NODE; } -NodeID pinpoint_start_trace(NodeID parentId) -{ +NodeID pinpoint_start_trace(NodeID parentId) { try { NodeID childId = do_start_trace(parentId); pp_trace("#%d pinpoint_start child #%d", parentId, childId); return childId; - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" start_trace#%d failed with %s", parentId, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" start_trace#%d failed with %s", parentId, ex.what()); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" start_trace#%d failed with %s", parentId, ex.what()); } return E_INVALID_NODE; } -static NodeID do_wake_trace(NodeID &id) -{ +static NodeID do_wake_trace(NodeID& id) { // routine // 1. check id alive // 2. check if it's a root node @@ -181,14 +158,13 @@ static NodeID do_wake_trace(NodeID &id) return id; } -int pinpoint_wake_trace(NodeID traceId) -{ +int pinpoint_wake_trace(NodeID traceId) { try { pp_trace("wake_trace #%d ", traceId); return do_wake_trace(traceId); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" wake_trace#%d failed with %s", traceId, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" wake_trace#%d failed with %s", traceId, ex.what()); } catch (...) { pp_trace(" wake_trace#%d failed with unkonw reason", traceId); @@ -196,50 +172,50 @@ int pinpoint_wake_trace(NodeID traceId) return 0; } -int pinpoint_force_end_trace(NodeID id, int32_t timeout) -{ +int pinpoint_force_end_trace(NodeID id, int32_t timeout) { try { _span_timeout = timeout; while (id != E_ROOT_NODE) { id = pinpoint_end_trace(id); - if (id == E_INVALID_NODE) break; + if (id == E_INVALID_NODE) + break; } // back to normal _span_timeout = global_agent_info.timeout_ms; return 0; - } catch (const std::out_of_range &) { + } catch (const std::out_of_range&) { pp_trace("#%d not found", id); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace("#%d end trace failed. %s", id, ex.what()); } return -1; } -int pinpoint_trace_is_root(NodeID _id) -{ +int pinpoint_trace_is_root(NodeID _id) { try { WrapperTraceNode node = PoolManager::getInstance().GetWrapperNode(_id); return node->isRoot() ? (1) : (0); - } catch (const std::out_of_range &) { + } catch (const std::out_of_range&) { pp_trace("#%d not found", _id); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace("#%d end trace failed. %s", _id, ex.what()); } return -1; } -NodeID pinpoint_end_trace(NodeID traceId) -{ +NodeID pinpoint_end_trace(NodeID traceId) { try { NodeID ret = do_end_trace(traceId); - if (ret == E_ROOT_NODE) { freeNodeTree(traceId); } + if (ret == E_ROOT_NODE) { + freeNodeTree(traceId); + } pp_trace("#%d pinpoint_end_trace Done!", traceId); return ret; - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace("end_trace %d out_of_range exception: %s", traceId, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace("end_trace %d runtime_error: %s", traceId, ex.what()); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace("end_trace #%d end trace failed. %s", traceId, ex.what()); } @@ -269,27 +245,25 @@ NodeID pinpoint_end_trace(NodeID traceId) // } // } -uint64_t pinpoint_start_time(void) { return (uint64_t) SafeSharedState::instance().getStartTime(); } +uint64_t pinpoint_start_time(void) { return (uint64_t)SafeSharedState::instance().getStartTime(); } int64_t generate_unique_id() { return SafeSharedState::instance().generateUniqueId(); } void reset_unique_id(void) { return SafeSharedState::instance().resetUniqueId(); } -uint64_t inline do_mark_current_trace_status(NodeID &_id, E_AGENT_STATUS status) -{ +uint64_t inline do_mark_current_trace_status(NodeID& _id, E_AGENT_STATUS status) { WrapperTraceNode w_node = PoolManager::getInstance().GetWrapperNode(_id); WrapperTraceNode w_root = PoolManager::getInstance().GetWrapperNode(w_node->mRootIndex); pp_trace("change current#%d status, before:%lld,now:%d", w_root->getId(), w_root->limit, status); return __sync_lock_test_and_set(&w_root->limit, status); } -uint64_t mark_current_trace_status(NodeID _id, int status) -{ +uint64_t mark_current_trace_status(NodeID _id, int status) { try { - return do_mark_current_trace_status(_id, (E_AGENT_STATUS) status); - } catch (const std::out_of_range &ex) { + return do_mark_current_trace_status(_id, (E_AGENT_STATUS)status); + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); } catch (...) { pp_trace(" %s#%d failed with unkonw reason", __func__, _id); @@ -297,10 +271,11 @@ uint64_t mark_current_trace_status(NodeID _id, int status) return 0; } -int check_tracelimit(int64_t timestamp) { return SafeSharedState::instance().checkTraceLimit(timestamp) ? (1) : (0); } +int check_tracelimit(int64_t timestamp) { + return SafeSharedState::instance().checkTraceLimit(timestamp) ? (1) : (0); +} -static inline WrapperTraceNode locate_node_by_loc(NodeID _id, E_NODE_LOC flag) -{ +static inline WrapperTraceNode locate_node_by_loc(NodeID _id, E_NODE_LOC flag) { WrapperTraceNode w_node = PoolManager::getInstance().GetWrapperNode(_id); if (flag == E_LOC_ROOT) { return PoolManager::getInstance().GetWrapperNode(w_node->mRootIndex); @@ -309,15 +284,13 @@ static inline WrapperTraceNode locate_node_by_loc(NodeID _id, E_NODE_LOC flag) } } -static void do_add_clue(NodeID _id, const char *key, const char *value, E_NODE_LOC flag) -{ +static void do_add_clue(NodeID _id, const char* key, const char* value, E_NODE_LOC flag) { WrapperTraceNode w_node = locate_node_by_loc(_id, flag); w_node->AddTraceDetail(key, value); pp_trace("#%d add clue key:%s value:%s", _id, key, value); } -static void do_add_clues(NodeID _id, const char *key, const char *value, E_NODE_LOC flag) -{ +static void do_add_clues(NodeID _id, const char* key, const char* value, E_NODE_LOC flag) { WrapperTraceNode w_node = locate_node_by_loc(_id, flag); std::string cvalue = ""; @@ -328,86 +301,80 @@ static void do_add_clues(NodeID _id, const char *key, const char *value, E_NODE_ pp_trace("#%d add clues:%s:%s", _id, key, value); } -void pinpoint_add_clues(NodeID _id, const char *key, const char *value, E_NODE_LOC flag) -{ +void pinpoint_add_clues(NodeID _id, const char* key, const char* value, E_NODE_LOC flag) { try { do_add_clues(_id, key, value, flag); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed.Reason %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed.Reason %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); } catch (...) { pp_trace(" %s#%d failed.Reason: unknown reason,parameters:%s:%s", __func__, _id, key, value); } } -void pinpoint_add_clue(NodeID _id, const char *key, const char *value, E_NODE_LOC flag) -{ +void pinpoint_add_clue(NodeID _id, const char* key, const char* value, E_NODE_LOC flag) { try { do_add_clue(_id, key, value, flag); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed. Reason: %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed. Reason: %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); } catch (...) { pp_trace(" %s#%d failed. Reason: unknow reason,parameters:%s:%s", __func__, _id, key, value); } } -static inline void do_set_context_key(NodeID _id, const char *key, const char *value) -{ +static inline void do_set_context_key(NodeID _id, const char* key, const char* value) { WrapperTraceNode w_node = locate_node_by_loc(_id, E_LOC_ROOT); w_node->setContext(key, value); } -static int do_get_context_key(NodeID _id, const char *key, char *pbuf, int buf_size) -{ +static int do_get_context_key(NodeID _id, const char* key, char* pbuf, int buf_size) { WrapperTraceNode w_node = locate_node_by_loc(_id, E_LOC_ROOT); std::string value; w_node->getContext(key, value); - if (pbuf != nullptr && buf_size > (int) value.size()) { + if (pbuf != nullptr && buf_size > (int)value.size()) { strncpy(pbuf, value.c_str(), buf_size); - return (int) value.size(); + return (int)value.size(); } else { pp_trace("#%d get context key:%s failed. buffer is not enough", _id, key); return -1; } } -void pinpoint_set_context_key(NodeID _id, const char *key, const char *value) -{ +void pinpoint_set_context_key(NodeID _id, const char* key, const char* value) { try { do_set_context_key(_id, key, value); - } catch (const std::out_of_range &ex) { - pp_trace(" %s#%d failed with out_of_range. %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); - } catch (const std::runtime_error &ex) { - pp_trace(" %s#%d failed with runtime_error. %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); - } catch (const std::exception &ex) { + } catch (const std::out_of_range& ex) { + pp_trace(" %s#%d failed with out_of_range. %s,parameters:%s:%s", __func__, _id, ex.what(), key, + value); + } catch (const std::runtime_error& ex) { + pp_trace(" %s#%d failed with runtime_error. %s,parameters:%s:%s", __func__, _id, ex.what(), key, + value); + } catch (const std::exception& ex) { pp_trace(" %s#%d failed with %s,parameters:%s:%s", __func__, _id, ex.what(), key, value); } } -static void do_set_long_key(NodeID id, const char *key, long l) -{ +static void do_set_long_key(NodeID id, const char* key, long l) { WrapperTraceNode w_node = locate_node_by_loc(id, E_LOC_ROOT); w_node->setContext(key, l); } -void pinpoint_set_context_long(NodeID _id, const char *key, long l) -{ +void pinpoint_set_context_long(NodeID _id, const char* key, long l) { try { do_set_long_key(_id, key, l); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); } } -static int do_get_long_key(NodeID _id, const char *key, long *l) -{ +static int do_get_long_key(NodeID _id, const char* key, long* l) { WrapperTraceNode w_node = locate_node_by_loc(_id, E_LOC_ROOT); if (l != nullptr) { long v; @@ -417,37 +384,35 @@ static int do_get_long_key(NodeID _id, const char *key, long *l) return 0; } -int pinpoint_get_context_long(NodeID _id, const char *key, long *l) -{ +int pinpoint_get_context_long(NodeID _id, const char* key, long* l) { try { do_get_long_key(_id, key, l); return 0; - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); } return 1; } -int pinpoint_get_context_key(NodeID _id, const char *key, char *pbuf, int buf_size) -{ +int pinpoint_get_context_key(NodeID _id, const char* key, char* pbuf, int buf_size) { try { return do_get_context_key(_id, key, pbuf, buf_size); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed with %s, parameters:%s", __func__, _id, ex.what(), key); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed with %s, parameters:%s", __func__, _id, ex.what(), key); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" %s#%d failed with %s, parameters:%s", __func__, _id, ex.what(), key); } return -1; } -void do_catch_error(NodeID _id, const char *msg, const char *error_filename, uint32_t error_lineno) -{ +void do_catch_error(NodeID _id, const char* msg, const char* error_filename, + uint32_t error_lineno) { WrapperTraceNode w_node = locate_node_by_loc(_id, E_LOC_ROOT); Json::Value eMsg; @@ -457,31 +422,28 @@ void do_catch_error(NodeID _id, const char *msg, const char *error_filename, uin w_node->AddTraceDetail("ERR", eMsg); } -void catch_error(NodeID _id, const char *msg, const char *error_filename, uint32_t error_lineno) -{ +void catch_error(NodeID _id, const char* msg, const char* error_filename, uint32_t error_lineno) { try { do_catch_error(_id, msg, error_filename, error_lineno); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" %s#%d failed with %s", __func__, _id, ex.what()); } } -const char *pinpoint_agent_version() -{ +const char* pinpoint_agent_version() { #ifdef AGENT_VERSION - static const char *_version_ = AGENT_VERSION; + static const char* _version_ = AGENT_VERSION; #else - static const char *_version_ = "x.x.x"; + static const char* _version_ = "x.x.x"; #endif return _version_; } -NodeID pinpoint_start_traceV1(NodeID parentId, const char *opt, ...) -{ +NodeID pinpoint_start_traceV1(NodeID parentId, const char* opt, ...) { try { va_list args; va_start(args, opt); @@ -489,9 +451,9 @@ NodeID pinpoint_start_traceV1(NodeID parentId, const char *opt, ...) va_end(args); pp_trace("#%d pinpoint_start_traceV1 child #%d", parentId, childId); return childId; - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" start_trace#%d failed with %s", parentId, ex.what()); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" start_trace#%d failed with %s", parentId, ex.what()); } catch (...) { pp_trace(" start_trace#%d failed with unkonw reason", parentId); @@ -499,50 +461,49 @@ NodeID pinpoint_start_traceV1(NodeID parentId, const char *opt, ...) return E_INVALID_NODE; } -static void do_add_exp(NodeID _id, const char *value) -{ +static void do_add_exp(NodeID _id, const char* value) { WrapperTraceNode w_root = locate_node_by_loc(_id, E_LOC_CURRENT); w_root->AddTraceDetail("EXP", value); w_root->mHasExp = true; pp_trace("#%d add exp value:%s", _id, value); } -void pinpoint_add_exception(NodeID traceId, const char *exp) -{ +void pinpoint_add_exception(NodeID traceId, const char* exp) { try { do_add_exp(traceId, exp); - } catch (const std::out_of_range &ex) { + } catch (const std::out_of_range& ex) { pp_trace(" %s#%d failed. Reason: %s,parameters:%s", __func__, traceId, ex.what(), exp); - } catch (const std::runtime_error &ex) { + } catch (const std::runtime_error& ex) { pp_trace(" %s#%d failed. Reason: %s,parameters:%s", __func__, traceId, ex.what(), exp); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" %s#%d failed. Reason: %s,parameters:%s", __func__, traceId, ex.what(), exp); } } -void register_span_handler(void (*handler)(const char *)) -{ - if (likely(handler != nullptr)) { _SpanHandler_ = std::bind(handler, std::placeholders::_1); } +void register_span_handler(void (*handler)(const char*)) { + if (likely(handler != nullptr)) { + _SpanHandler_ = std::bind(handler, std::placeholders::_1); + } } -void show_status(void) -{ +void show_status(void) { Json::Value status; status["pool_total_node"] = PoolManager::getInstance().totoalNodesCount(); status["pool_free_node"] = PoolManager::getInstance().freeNodesCount(); status["common_libary_version"] = pinpoint_agent_version(); - auto add_alive_node_fun = [&status](TraceNode &node) { status["pool_alive_nodes"].append(node.mPoolIndex); }; + auto add_alive_node_fun = [&status](TraceNode& node) { + status["pool_alive_nodes"].append(node.mPoolIndex); + }; PoolManager::getInstance().foreachAliveNode(std::bind(add_alive_node_fun, std::placeholders::_1)); fprintf(stderr, "%s\n", status.toStyledString().c_str()); } -void debug_nodeid(NodeID id) -{ +void debug_nodeid(NodeID id) { try { WrapperTraceNode r_node = PoolManager::getInstance().GetWrapperNode(id); fprintf(stderr, "nodeid#%d: { value:%s }", id, r_node->ToString().c_str()); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { pp_trace(" debug_nodeid:#%d Reason: %s", id, ex.what()); } } \ No newline at end of file