diff --git a/README.md b/README.md index dce6ee3..4f2adbc 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Create a file named IntegratingIntoYourProject.cpp: #include "PropertyKeyConst.h" #include "DebugAssertion.h" #include "ResourceGuard.h" -#include "Debug.h" +#include "Logger.h" #include "NacosString.h" using namespace std; @@ -98,7 +98,7 @@ or you can use ldconfig to add libnacos-cli.so to your lib path. #include "PropertyKeyConst.h" #include "DebugAssertion.h" #include "ResourceGuard.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -136,7 +136,7 @@ int main() { #include "ResourceGuard.h" #include "PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -187,7 +187,7 @@ int main() { #include "listen/Listener.h" #include "PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -246,7 +246,7 @@ int main() { #include "utils/UtilAndComs.h" #include "http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" #include "NacosString.h" #include "Properties.h" #include "PropertyKeyConst.h" @@ -310,7 +310,7 @@ int main() { #include "naming/subscribe/EventListener.h" #include "PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -337,7 +337,7 @@ int main() { props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848"; //Interval for poller to check the status of subscribed services(unit:Ms), 30000 by default //Here we set it to 5000 to see the output more quick - props[PropertyKeyConst::TCP_NAMING_POLL_INTERVAL] = "5000"; + props[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "5000"; NacosServiceFactory *factory = new NacosServiceFactory(props); ResourceGuard _guardFactory(factory); NamingService *n = factory->CreateNamingService(); @@ -375,7 +375,7 @@ int main() { #include "utils/UtilAndComs.h" #include "http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" #include "NacosString.h" #include "Properties.h" #include "PropertyKeyConst.h" diff --git a/README_zh_CN.md b/README_zh_CN.md index aae4550..b4c5ecd 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -35,7 +35,7 @@ Nacos-sdk-cpp是nacos客戶端的C++版本,它支持服务发现和动态配 #include "PropertyKeyConst.h" #include "DebugAssertion.h" #include "ResourceGuard.h" -#include "Debug.h" +#include "Logger.h" #include "NacosString.h" using namespace std; @@ -93,7 +93,7 @@ int main() { #include "PropertyKeyConst.h" #include "DebugAssertion.h" #include "ResourceGuard.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -131,7 +131,7 @@ int main() { #include "ResourceGuard.h" #include "PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -182,7 +182,7 @@ int main() { #include "listen/Listener.h" #include "PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -241,7 +241,7 @@ int main() { #include "utils/UtilAndComs.h" #include "http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" #include "NacosString.h" #include "Properties.h" #include "PropertyKeyConst.h" @@ -305,7 +305,7 @@ int main() { #include "naming/subscribe/EventListener.h" #include "PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" using namespace std; using namespace nacos; @@ -332,7 +332,7 @@ int main() { props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848"; //Interval for poller to check the status of subscribed services(unit:Ms), 30000 by default //Here we set it to 5000 to see the output more quick - props[PropertyKeyConst::TCP_NAMING_POLL_INTERVAL] = "5000"; + props[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "5000"; NacosServiceFactory *factory = new NacosServiceFactory(props); ResourceGuard _guardFactory(factory); NamingService *n = factory->CreateNamingService(); @@ -370,7 +370,7 @@ int main() { #include "utils/UtilAndComs.h" #include "http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "Logger.h" #include "NacosString.h" #include "Properties.h" #include "PropertyKeyConst.h" diff --git a/include/Constants.h b/include/Constants.h deleted file mode 100644 index c082c8a..0000000 --- a/include/Constants.h +++ /dev/null @@ -1,132 +0,0 @@ -#ifndef __CONSTANTS_H_ -#define __CONSTANTS_H_ - -#include "NacosString.h" - -/** - * Constant - * - * @author Nacos - */ - -namespace nacos{ -class Constants { -public: - const static NacosString CLIENT_VERSION; - - const static int DATA_IN_BODY_VERSION; - - const static NacosString DEFAULT_GROUP; - - const static NacosString DEFAULT_CONTEXT_PATH; - - const static NacosString PROTOCOL_VERSION; - - const static NacosString GET_SERVERS_PATH; - - const static NacosString APPNAME; - - const static NacosString UNKNOWN_APP; - - const static NacosString DEFAULT_DOMAINNAME; - - const static NacosString DAILY_DOMAINNAME; - - const static NacosString NUL; - - const static NacosString DATAID; - - const static NacosString GROUP; - - const static NacosString LAST_MODIFIED; - - const static NacosString ACCEPT_ENCODING; - - const static NacosString CONTENT_ENCODING; - - const static NacosString PROBE_MODIFY_REQUEST; - - const static NacosString PROBE_MODIFY_RESPONSE; - - const static NacosString PROBE_MODIFY_RESPONSE_NEW; - - const static NacosString USE_ZIP; - - const static NacosString CONTENT_MD5; - - const static NacosString CONFIG_VERSION; - - const static NacosString IF_MODIFIED_SINCE; - - const static NacosString SPACING_INTERVAL; - - const static NacosString BASE_PATH; - - const static NacosString CONFIG_CONTROLLER_PATH; - - /** - * second - */ - const static int ASYNC_UPDATE_ADDRESS_INTERVAL; - - /** - * second - */ - const static int POLLING_INTERVAL_TIME; - - /** - * millisecond - */ - const static int ONCE_TIMEOUT; - - /** - * millisecond - */ - const static int SO_TIMEOUT; - - /** - * millisecond - */ - const static int RECV_WAIT_TIMEOUT; - - const static NacosString ENCODE; - - const static NacosString MAP_FILE; - - const static int FLOW_CONTROL_THRESHOLD; - - const static int FLOW_CONTROL_SLOT; - - const static int FLOW_CONTROL_INTERVAL; - - const static NacosString LINE_SEPARATOR; - - const static NacosString WORD_SEPARATOR; - - const static NacosString LONGPOLLING_LINE_SEPARATOR; - - const static NacosString CLIENT_APPNAME_HEADER; - const static NacosString CLIENT_REQUEST_TS_HEADER; - const static NacosString CLIENT_REQUEST_TOKEN_HEADER; - - const static int ATOMIC_MAX_SIZE; - - const static NacosString NAMING_INSTANCE_ID_SPLITTER; - const static int NAMING_INSTANCE_ID_SEG_COUNT; - const static NacosString NAMING_HTTP_HEADER_SPILIER; - - const static NacosString DEFAULT_CLUSTER_NAME; - - const static NacosString DEFAULT_NAMESPACE_ID; - - const static int WRITE_REDIRECT_CODE; - - const static NacosString SERVICE_INFO_SPLITER; - - const static NacosString NULL_STRING; - - const static NacosString FILE_SEPARATOR; -}; -}//namespace nacos - -#endif diff --git a/include/Debug.h b/include/Debug.h deleted file mode 100644 index be67d0d..0000000 --- a/include/Debug.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef __DEBUG_H_ -#define __DEBUG_H_ - -#include - -#define DETAILED_DEBUG_INFO - -//TODO:Line info -#ifndef DETAILED_DEBUG_INFO -#define log_print(level, format, args...) Debug::debug_print(level, format, ##args) -#define log_debug(format, args...) Debug::debug_debug(format, ##args) -#define log_info(format, args...) Debug::debug_info(format, ##args) -#define log_warn(format, args...) Debug::debug_warn(format, ##args) -#define log_error(format, args...) Debug::debug_error(format, ##args) -#else -#define STR(X) #X -#define log_print(level, format, args...) Debug::debug_print(level, format, ##args) -#define log_debug(format, args...) Debug::debug_debug(format, ##args) -#define log_info(format, args...) Debug::debug_info(format, ##args) -#define log_warn(format, args...) Debug::debug_warn(format, ##args) -#define log_error(format, args...) Debug::debug_error(format, ##args) -#endif - -namespace nacos{ -enum LOG_LEVEL { - DEBUG = 0, - INFO, - WARN, - ERROR, - NONE -}; - -class Debug { -private: - static LOG_LEVEL _CUR_SYS_DEBUG_LEVEL; - - static int debug_helper(LOG_LEVEL level, const char *format, va_list args); - -public: - //Output string in self-defined log_level - static int debug_print(LOG_LEVEL level, const char *format, ...); - - static int debug_debug(const char *format, ...); - - static int debug_info(const char *format, ...); - - static int debug_warn(const char *format, ...); - - static int debug_error(const char *format, ...); - - static void set_debug_level(LOG_LEVEL level) { _CUR_SYS_DEBUG_LEVEL = level; }; -}; -}//namespace nacos - -#endif \ No newline at end of file diff --git a/include/DebugAssertion.h b/include/DebugAssertion.h index 7ec7f61..e8dabf3 100644 --- a/include/DebugAssertion.h +++ b/include/DebugAssertion.h @@ -1,9 +1,10 @@ -#ifndef _ALL_IN_ONE_H_ -#define _ALL_IN_ONE_H_ +#ifndef __DEBUG_ASSERTION_H_ +#define __DEBUG_ASSERTION_H_ #include +#include #include "NacosString.h" -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos{ #define TEST_ITEM_START { @@ -13,7 +14,7 @@ namespace nacos{ #define NACOS_ASSERT(x) \ if (!(x)) \ { \ - log_error("Assertion failed! file:" __FILE__":%d\n", __LINE__); \ + printf("Assertion failed! file:" __FILE__":%d\n", __LINE__); \ abort(); \ } diff --git a/include/NacosExceptions.h b/include/NacosExceptions.h index 1c7c2cf..bfd6191 100644 --- a/include/NacosExceptions.h +++ b/include/NacosExceptions.h @@ -77,6 +77,9 @@ class NacosException : public std::exception { static const int NO_SERVER_AVAILABLE = 1005; static const int INVALID_LOGIN_CREDENTIAL = 1006; static const int UNABLE_TO_OPEN_FILE = 1007; + static const int UNABLE_TO_GET_HOST_IP = 1008; + static const int UNABLE_TO_CREATE_SOCKET = 1009; + static const int INVALID_CONFIG_PARAM = 1010; }; @@ -107,8 +110,8 @@ class IOException : public NacosException { class MalformedConfigException : public NacosException { public: - MalformedConfigException(const NacosString &file) : NacosException(NacosException::MALFORMED_CONFIG_FILE, - "Malformed Config file:" + file) {}; + MalformedConfigException(const NacosString &file, const NacosString &detailedMsg) : NacosException(NacosException::MALFORMED_CONFIG_FILE, + "Malformed Config file:" + file + " reason:" + detailedMsg) {}; }; class InvalidFactoryConfigException : public NacosException { diff --git a/include/ResourceGuard.h b/include/ResourceGuard.h index 1a5b2d4..e2b9119 100644 --- a/include/ResourceGuard.h +++ b/include/ResourceGuard.h @@ -5,7 +5,7 @@ #ifndef NACOS_SDK_CPP_RESOURCEGUARD_H #define NACOS_SDK_CPP_RESOURCEGUARD_H -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos{ template diff --git a/include/constant/ConfigConstant.h b/include/constant/ConfigConstant.h new file mode 100644 index 0000000..7667096 --- /dev/null +++ b/include/constant/ConfigConstant.h @@ -0,0 +1,65 @@ +#ifndef __CONFIG_CONSTANTS_H_ +#define __CONFIG_CONSTANTS_H_ + +#include "NacosString.h" + +/** + * Constant + * + * @author Nacos + */ + +namespace nacos{ + +//Constants for config service +class ConfigConstant { +public: + + const static NacosString DEFAULT_GROUP; + + const static NacosString DEFAULT_CONTEXT_PATH; + + const static NacosString PROTOCOL_VERSION; + + const static NacosString GET_SERVERS_PATH; + + const static NacosString DATAID; + + const static NacosString PROBE_MODIFY_REQUEST; + + const static NacosString PROBE_MODIFY_RESPONSE; + + const static NacosString BASE_PATH; + + const static NacosString CONFIG_CONTROLLER_PATH; + + /** + * second + */ + const static int POLLING_INTERVAL_TIME; + + const static NacosString ENCODE; + + const static int FLOW_CONTROL_THRESHOLD; + + const static NacosString LINE_SEPARATOR; + + const static NacosString WORD_SEPARATOR; + + const static NacosString NAMING_INSTANCE_ID_SPLITTER; + + const static NacosString DEFAULT_CLUSTER_NAME; + + const static NacosString SERVICE_INFO_SPLITER; + + const static NacosString FILE_SEPARATOR; + + const static NacosString CONFIG_NEXT_LINE; + + const static NacosString CONFIG_KV_SEPARATOR; + + const static NacosString DEFAULT_CONFIG_FILE; +}; +}//namespace nacos + +#endif diff --git a/include/naming/NamingCommonParams.h b/include/constant/NamingConstant.h similarity index 68% rename from include/naming/NamingCommonParams.h rename to include/constant/NamingConstant.h index 1082ab2..d916cf5 100644 --- a/include/naming/NamingCommonParams.h +++ b/include/constant/NamingConstant.h @@ -1,14 +1,18 @@ -#ifndef __NAMING_COMM_PARAMS_H_ -#define __NAMING_COMM_PARAMS_H_ +#ifndef __NAMING_CONSTANT_H_ +#define __NAMING_CONSTANT_H_ #include "NacosString.h" namespace nacos{ -class NamingCommonParams { +class NamingConstant { public: static const NacosString SERVICE_NAME; static const NacosString CLUSTER_NAME; + static const NacosString UDP_PORT; + static const NacosString CLUSTERS; + static const NacosString CLIENT_IP; + static const NacosString HEALTHY_ONLY; static const NacosString HEALTHY; diff --git a/include/PropertyKeyConst.h b/include/constant/PropertyKeyConst.h similarity index 85% rename from include/PropertyKeyConst.h rename to include/constant/PropertyKeyConst.h index 39b09c4..83e98be 100644 --- a/include/PropertyKeyConst.h +++ b/include/constant/PropertyKeyConst.h @@ -1,70 +1,72 @@ -#ifndef __PROP_KEY_CONST_H_ -#define __PROP_KEY_CONST_H_ - -#include "NacosString.h" - -namespace nacos{ -class PropertyKeyConst { -public: - static const NacosString CONFIG_FILE_NAME; - - static const NacosString IS_USE_ENDPOINT_PARSING_RULE; - - static const NacosString ENDPOINT; - - static const NacosString ENDPOINT_PORT; - - static const NacosString NAMESPACE; - - static const NacosString ACCESS_KEY; - - static const NacosString SECRET_KEY; - - static const NacosString RAM_ROLE_NAME; - - static const NacosString SERVER_ADDR; - - static const NacosString CONTEXT_PATH; - - static const NacosString CLUSTER_NAME; - - static const NacosString ENCODE; - - static const NacosString NAMING_LOAD_CACHE_AT_START; - - static const NacosString NAMING_CLIENT_BEAT_THREAD_COUNT; - - static const NacosString NAMING_POLLING_THREAD_COUNT; - - static const NacosString SRVLISTMGR_REFRESH_INTERVAL; - - static const NacosString SERVER_REQ_TIMEOUT; - - static const NacosString TCP_NAMING_POLL_INTERVAL; - - static const NacosString CONFIG_LONGPULLLING_TIMEOUT; - - static const NacosString HB_FAIL_WAIT_TIME; - - static const NacosString NACOS_SNAPSHOT_PATH; - - static const NacosString NACOS_LOG_PATH; - - static const NacosString CLIENT_NAME; - static const NacosString AUTH_USERNAME; - static const NacosString AUTH_PASSWORD; - - static const int NACOS_DEFAULT_PORT = 8848; - - /*public static class SystemEnv { - - static const NacosString ALIBABA_ALIWARE_ENDPOINT_PORT = "ALIBABA_ALIWARE_ENDPOINT_PORT"; - - static const NacosString ALIBABA_ALIWARE_NAMESPACE = "ALIBABA_ALIWARE_NAMESPACE"; - - static const NacosString ALIBABA_ALIWARE_ENDPOINT_URL = "ALIBABA_ALIWARE_ENDPOINT_URL"; - }*/ -}; -}//namespace nacos - +#ifndef __PROP_KEY_CONST_H_ +#define __PROP_KEY_CONST_H_ + +#include "NacosString.h" + +namespace nacos{ +class PropertyKeyConst { +public: + static const NacosString IS_USE_ENDPOINT_PARSING_RULE; + + static const NacosString ENDPOINT; + + static const NacosString ENDPOINT_PORT; + + static const NacosString NAMESPACE; + + static const NacosString ACCESS_KEY; + + static const NacosString SECRET_KEY; + + static const NacosString RAM_ROLE_NAME; + + static const NacosString SERVER_ADDR; + + static const NacosString CONTEXT_PATH; + + static const NacosString CLUSTER_NAME; + + static const NacosString ENCODE; + + static const NacosString NAMING_LOAD_CACHE_AT_START; + + static const NacosString NAMING_CLIENT_BEAT_THREAD_COUNT; + + static const NacosString NAMING_POLLING_THREAD_COUNT; + + static const NacosString SRVLISTMGR_REFRESH_INTERVAL; + + static const NacosString SERVER_REQ_TIMEOUT; + + static const NacosString SUBSCRIPTION_POLL_INTERVAL; + + static const NacosString CONFIG_LONGPULLLING_TIMEOUT; + + static const NacosString HB_FAIL_WAIT_TIME; + + static const NacosString NACOS_SNAPSHOT_PATH; + + static const NacosString LOG_PATH; + static const NacosString LOG_ROTATE_TIME; + static const NacosString LOG_LEVEL; + + static const NacosString CLIENT_NAME; + static const NacosString AUTH_USERNAME; + static const NacosString AUTH_PASSWORD; + static const NacosString LOCAL_IP; + static const NacosString UDP_RECEIVER_PORT; + + static const int NACOS_DEFAULT_PORT = 8848; + + /*public static class SystemEnv { + + static const NacosString ALIBABA_ALIWARE_ENDPOINT_PORT = "ALIBABA_ALIWARE_ENDPOINT_PORT"; + + static const NacosString ALIBABA_ALIWARE_NAMESPACE = "ALIBABA_ALIWARE_NAMESPACE"; + + static const NacosString ALIBABA_ALIWARE_ENDPOINT_URL = "ALIBABA_ALIWARE_ENDPOINT_URL"; + }*/ +}; +}//namespace nacos + #endif \ No newline at end of file diff --git a/include/utils/UtilAndComs.h b/include/constant/UtilAndComs.h similarity index 65% rename from include/utils/UtilAndComs.h rename to include/constant/UtilAndComs.h index 1306019..a83f504 100644 --- a/include/utils/UtilAndComs.h +++ b/include/constant/UtilAndComs.h @@ -1,46 +1,31 @@ -#ifndef __UTIL_N_COMS_H_ -#define __UTIL_N_COMS_H_ - -#include "NacosString.h" - -namespace nacos{ -class UtilAndComs { -public: - static NacosString VERSION; - - //for libcurl - static NacosString UA_VERSION; - - static NacosString WEB_CONTEXT; - - static NacosString NACOS_URL_BASE; - - static NacosString NACOS_URL_INSTANCE; - - static NacosString ENCODING; - - static NacosString ENV_LIST_KEY; - - static NacosString ALL_IPS; - - static NacosString FAILOVER_SWITCH; - - static NacosString DEFAULT_NAMESPACE_ID; - - static int REQUEST_DOMAIN_RETRY_COUNT; - - static NacosString NACOS_NAMING_LOG_NAME; - - static NacosString NACOS_NAMING_LOG_LEVEL; - - static NacosString SERVER_ADDR_IP_SPLITER; - - static int DEFAULT_CLIENT_BEAT_THREAD_COUNT;//TODO:Calc this according to nr_processors of the host - - static int DEFAULT_POLLING_THREAD_COUNT;//TODO:Calc this according to nr_processors of the host - - static void Init(); -}; -}//namespace nacos - -#endif +#ifndef __UTIL_N_COMS_H_ +#define __UTIL_N_COMS_H_ + +#include "NacosString.h" + +namespace nacos{ +class UtilAndComs { +public: + static NacosString VERSION; + + static NacosString WEB_CONTEXT; + + static NacosString NACOS_URL_BASE; + + static NacosString NACOS_URL_INSTANCE; + + static NacosString ENCODING; + + static int REQUEST_DOMAIN_RETRY_COUNT; + + static NacosString SERVER_ADDR_IP_SPLITER; + + static int DEFAULT_CLIENT_BEAT_THREAD_COUNT;//TODO:Calc this according to nr_processors of the host + + static int DEFAULT_POLLING_THREAD_COUNT;//TODO:Calc this according to nr_processors of the host + + static void Init(); +}; +}//namespace nacos + +#endif diff --git a/include/factory/NacosServiceFactory.h b/include/factory/NacosServiceFactory.h index 02f5c65..7bf380c 100644 --- a/include/factory/NacosServiceFactory.h +++ b/include/factory/NacosServiceFactory.h @@ -7,6 +7,10 @@ #include "INacosServiceFactory.h" namespace nacos{ + +class AppConfigManager; +class ObjectConfigData; + class NacosServiceFactory : public INacosServiceFactory { private: NacosString configFile; @@ -15,6 +19,7 @@ class NacosServiceFactory : public INacosServiceFactory { bool propsIsSet; void checkConfig() throw(InvalidFactoryConfigException); + AppConfigManager *buildConfigManager(ObjectConfigData *objectConfigData); public: void setConfig(const NacosString &_configFile); diff --git a/include/naming/Cluster.h b/include/naming/Cluster.h index b7ba876..78535f0 100644 --- a/include/naming/Cluster.h +++ b/include/naming/Cluster.h @@ -5,7 +5,7 @@ #include #include #include "NacosString.h" -#include "Constants.h" +#include "constant/ConfigConstant.h" #include "utils/url.h" #include "utils/ParamUtils.h" #include "naming/Instance.h" diff --git a/include/naming/ServiceInfo.h b/include/naming/ServiceInfo.h index ec90ed7..408b6f1 100644 --- a/include/naming/ServiceInfo.h +++ b/include/naming/ServiceInfo.h @@ -5,7 +5,7 @@ #include #include #include "NacosString.h" -#include "Constants.h" +#include "constant/ConfigConstant.h" #include "utils/url.h" #include "utils/ParamUtils.h" #include "naming/Instance.h" @@ -48,7 +48,7 @@ class ServiceInfo { explicit ServiceInfo(const NacosString &key) : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""), _allIPs(false) { std::vector segs; - ParamUtils::Explode(segs, key, Constants::SERVICE_INFO_SPLITER); + ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER); if (segs.size() == 2) { setGroupName(segs[0]); @@ -178,10 +178,9 @@ class ServiceInfo { } //@JSONField(serialize = false) - static ServiceInfo fromKey(const NacosString &key) { - ServiceInfo serviceInfo; + static void fromKey(ServiceInfo &serviceInfo, const NacosString &key) { std::vector segs; - ParamUtils::Explode(segs, key, Constants::SERVICE_INFO_SPLITER); + ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER); if (segs.size() == 2) { serviceInfo.setGroupName(segs[0]); @@ -191,14 +190,12 @@ class ServiceInfo { serviceInfo.setName(segs[1]); serviceInfo.setClusters(segs[2]); } - - return serviceInfo; } //@JSONField(serialize = false) static NacosString getKey(const NacosString &name, const NacosString &clusters) { if (!ParamUtils::isBlank(clusters)) { - return name + Constants::SERVICE_INFO_SPLITER + clusters; + return name + ConfigConstant::SERVICE_INFO_SPLITER + clusters; } return name; diff --git a/include/naming/selectors/HealthInstanceSelector.h b/include/naming/selectors/HealthInstanceSelector.h index cdd1fc7..16258f8 100644 --- a/include/naming/selectors/HealthInstanceSelector.h +++ b/include/naming/selectors/HealthInstanceSelector.h @@ -3,7 +3,7 @@ #include #include "naming/selectors/Selector.h" -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos { namespace naming { namespace selectors { class HealthInstanceSelector : public Selector{ diff --git a/include/naming/selectors/RandomByWeightSelector.h b/include/naming/selectors/RandomByWeightSelector.h index e914756..a3a62b1 100644 --- a/include/naming/selectors/RandomByWeightSelector.h +++ b/include/naming/selectors/RandomByWeightSelector.h @@ -3,7 +3,7 @@ #include #include "naming/selectors/Selector.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "utils/ParamUtils.h" #include "utils/RandomUtils.h" diff --git a/include/naming/selectors/RandomSelector.h b/include/naming/selectors/RandomSelector.h index c1d2299..27edd4d 100644 --- a/include/naming/selectors/RandomSelector.h +++ b/include/naming/selectors/RandomSelector.h @@ -3,7 +3,7 @@ #include #include "naming/selectors/Selector.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "utils/ParamUtils.h" namespace nacos { namespace naming { namespace selectors { diff --git a/include/utils/NamingUtils.h b/include/utils/NamingUtils.h index 3cecf48..233ad23 100644 --- a/include/utils/NamingUtils.h +++ b/include/utils/NamingUtils.h @@ -3,31 +3,31 @@ #include #include "NacosString.h" -#include "Constants.h" +#include "constant/ConfigConstant.h" #include "utils/ParamUtils.h" namespace nacos{ class NamingUtils { public: static NacosString getGroupedName(const NacosString &serviceName, const NacosString &groupName) { - return groupName + Constants::SERVICE_INFO_SPLITER + serviceName; + return groupName + ConfigConstant::SERVICE_INFO_SPLITER + serviceName; } static NacosString getServiceName(const NacosString &serviceNameWithGroup) { - if (!ParamUtils::contains(serviceNameWithGroup, Constants::SERVICE_INFO_SPLITER)) { + if (!ParamUtils::contains(serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER)) { return serviceNameWithGroup; } std::vector splittedNameNGroup; - ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, Constants::SERVICE_INFO_SPLITER); + ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER); return splittedNameNGroup[1]; } static NacosString getGroupName(const NacosString &serviceNameWithGroup) { - if (!ParamUtils::contains(serviceNameWithGroup, Constants::SERVICE_INFO_SPLITER)) { - return Constants::DEFAULT_GROUP; + if (!ParamUtils::contains(serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER)) { + return ConfigConstant::DEFAULT_GROUP; } std::vector splittedNameNGroup; - ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, Constants::SERVICE_INFO_SPLITER); + ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER); return splittedNameNGroup[0]; } }; diff --git a/include/utils/ParamUtils.h b/include/utils/ParamUtils.h index 74b9bd0..d9654ad 100644 --- a/include/utils/ParamUtils.h +++ b/include/utils/ParamUtils.h @@ -7,8 +7,7 @@ #include #include "NacosString.h" #include "NacosExceptions.h" -#include "Constants.h" -#include "Debug.h" +#include "constant/ConfigConstant.h" namespace nacos{ class ParamUtils { @@ -40,13 +39,13 @@ class ParamUtils { } static NacosString null2defaultGroup(const NacosString &group) { - return (isNull(group)) ? Constants::DEFAULT_GROUP : ParamUtils::trim(group); + return (isNull(group)) ? ConfigConstant::DEFAULT_GROUP : ParamUtils::trim(group); } static void parseString2KeyGroupTenant(const NacosString &stringToParse, NacosString &dataId, NacosString &group, NacosString &tenant) { std::vector KGT;//KeyGroupTenant - Explode(KGT, stringToParse, Constants::WORD_SEPARATOR); + Explode(KGT, stringToParse, ConfigConstant::WORD_SEPARATOR); dataId = KGT[0]; group = KGT[1]; if (KGT.size() == 3)//with tenant @@ -97,7 +96,22 @@ class ParamUtils { //A little trick here for NacosString constants static void Explode(std::vector &explodedList, const NacosString &stringToExplode, const NacosString &separator) { - Explode(explodedList, stringToExplode, separator[0]); + size_t start_pos = 0; + size_t separator_len = separator.length(); + size_t cur_pos = 0; + cur_pos = stringToExplode.find(separator, start_pos); + + //break the string with separator + while (cur_pos != std::string::npos) { + NacosString cur_addr = stringToExplode.substr(start_pos, cur_pos - start_pos); + explodedList.push_back(cur_addr); + start_pos = cur_pos + separator_len; + cur_pos = stringToExplode.find(separator, start_pos); + } + + //deal with the last string + NacosString last_addr = stringToExplode.substr(start_pos); + explodedList.push_back(last_addr); } static void Explode(std::vector &explodedList, const NacosString &stringToExplode, char separator) { diff --git a/nacos-cpp-cli.properties b/nacos-cpp-cli.properties index 5007bcf..b91159d 100644 --- a/nacos-cpp-cli.properties +++ b/nacos-cpp-cli.properties @@ -1 +1,31 @@ -serverAddr= \ No newline at end of file +#specify nacos server address here(separated by ,) +#serverAddr= + +#log path, default is ~/nacos/logs/ +#nacos.log.path= + +#rotate time (now we only support hour as unit) +#nacos.log.rotateTime=24h + +#log level, default is ERROR +#nacos.log.level=ERROR + +#client IP, the client will automatically detect NIC and find the best IP +#but if that doesn't work, you can override it here manually +#nacos.client.ip= + +#if the server is secured with password, you may specify it here +#nacos.auth.username= +#nacos.auth.password= + +#specify this if you are using an endpoint +#endpoint= +#endpointPort= + +#advanced settings +#port for udp listener (to receive service change information for subscribed services) +#nacos.udp.port= + +#poller interval (10000 ms by default) to refresh subscribed service information from server +#naming.poller.interval= + diff --git a/src/Constants.cpp b/src/Constants.cpp deleted file mode 100644 index 3a3ba67..0000000 --- a/src/Constants.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "Constants.h" - -/** - * Constant - * - * @author Nacos - */ - -namespace nacos{ -const NacosString Constants::CLIENT_VERSION = "3.0.0"; - -const int Constants::DATA_IN_BODY_VERSION = 204; - -const NacosString Constants::DEFAULT_GROUP = "DEFAULT_GROUP"; -const NacosString Constants::DEFAULT_CONTEXT_PATH = "nacos"; -const NacosString Constants::PROTOCOL_VERSION = "v1"; -const NacosString Constants::GET_SERVERS_PATH = "ns/operator/servers"; - -const NacosString Constants::APPNAME = "AppName"; - -const NacosString Constants::UNKNOWN_APP = "UnknownApp"; - -const NacosString Constants::DEFAULT_DOMAINNAME = "commonconfig.config-host.taobao.com"; - -const NacosString Constants::DAILY_DOMAINNAME = "commonconfig.taobao.net"; - -const NacosString Constants::NUL = ""; - -const NacosString Constants::DATAID = "dataId"; - -const NacosString Constants::GROUP = "group"; - -const NacosString Constants::LAST_MODIFIED = "Last-Modified"; - -const NacosString Constants::ACCEPT_ENCODING = "Accept-Encoding"; - -const NacosString Constants::CONTENT_ENCODING = "Content-Encoding"; - -const NacosString Constants::PROBE_MODIFY_REQUEST = "Listening-Configs"; - -const NacosString Constants::PROBE_MODIFY_RESPONSE = "Probe-Modify-Response"; - -const NacosString Constants::PROBE_MODIFY_RESPONSE_NEW = "Probe-Modify-Response-New"; - -const NacosString Constants::USE_ZIP = "true"; - -const NacosString Constants::CONTENT_MD5 = "Content-MD5"; - -const NacosString Constants::CONFIG_VERSION = "Config-Version"; - -const NacosString Constants::IF_MODIFIED_SINCE = "If-Modified-Since"; - -const NacosString Constants::SPACING_INTERVAL = "client-spacing-interval"; - -const NacosString Constants::BASE_PATH = "/v1/cs"; - -const NacosString Constants::CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs"; - -/** -* second -*/ -const int Constants::ASYNC_UPDATE_ADDRESS_INTERVAL = 300; - -/** -* second -*/ -const int Constants::POLLING_INTERVAL_TIME = 15; - -/** -* millisecond -*/ -const int Constants::ONCE_TIMEOUT = 2000; - -/** -* millisecond -*/ -const int Constants::SO_TIMEOUT = 60000; - -/** -* millisecond -*/ -const int Constants::RECV_WAIT_TIMEOUT = ONCE_TIMEOUT * 5; - -const NacosString Constants::ENCODE = "UTF-8"; - -const NacosString Constants::MAP_FILE = "map-file.js"; - -const int Constants::FLOW_CONTROL_THRESHOLD = 20; - -const int Constants::FLOW_CONTROL_SLOT = 10; - -const int Constants::FLOW_CONTROL_INTERVAL = 1000; - -const NacosString Constants::LINE_SEPARATOR = "\x1"; - -const NacosString Constants::WORD_SEPARATOR = "\x2"; - -const NacosString Constants::LONGPOLLING_LINE_SEPARATOR = "\r\n"; - -const NacosString Constants::CLIENT_APPNAME_HEADER = "Client-AppName"; -const NacosString Constants::CLIENT_REQUEST_TS_HEADER = "Client-RequestTS"; -const NacosString Constants::CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken"; - -const int Constants::ATOMIC_MAX_SIZE = 1000; - -const NacosString Constants::NAMING_INSTANCE_ID_SPLITTER = "#"; -const int Constants::NAMING_INSTANCE_ID_SEG_COUNT = 4; -const NacosString Constants::NAMING_HTTP_HEADER_SPILIER = "\\|"; - -const NacosString Constants::DEFAULT_CLUSTER_NAME = "DEFAULT"; - -const NacosString Constants::DEFAULT_NAMESPACE_ID = "public"; - -const int Constants::WRITE_REDIRECT_CODE = 307; - -const NacosString Constants::SERVICE_INFO_SPLITER = "@@"; - -const NacosString Constants::NULL_STRING = "null"; - -const NacosString Constants::FILE_SEPARATOR = "/"; -}//namespace nacos diff --git a/src/Debug.cpp b/src/Debug.cpp deleted file mode 100644 index 946eacf..0000000 --- a/src/Debug.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include -#include "Debug.h" - -namespace nacos{ -//The current debugging level for the system -LOG_LEVEL Debug::_CUR_SYS_DEBUG_LEVEL = ERROR; - -int Debug::debug_helper(LOG_LEVEL level, const char *format, va_list args) { - //Since the current system debug level is greater than this message - //Supress it - if (Debug::_CUR_SYS_DEBUG_LEVEL > level) { - return 0; - } - //va_list argList; - - //va_start(argList, format); - int retval = vfprintf(stdout, format, args); - //va_end(argList); - return retval; -} - -//Output string in self-defined log_level -int Debug::debug_print(LOG_LEVEL level, const char *format, ...) { - va_list argList; - - va_start(argList, format); - int retval = debug_helper(level, format, argList); - va_end(argList); - return retval; -} - -int Debug::debug_debug(const char *format, ...) { - va_list argList; - - va_start(argList, format); - int retval = debug_helper(DEBUG, format, argList); - va_end(argList); - return retval; -} - -int Debug::debug_info(const char *format, ...) { - va_list argList; - - va_start(argList, format); - int retval = debug_helper(INFO, format, argList); - va_end(argList); - return retval; -} - -int Debug::debug_warn(const char *format, ...) { - va_list argList; - - va_start(argList, format); - int retval = debug_helper(WARN, format, argList); - va_end(argList); - return retval; -} - -int Debug::debug_error(const char *format, ...) { - va_list argList; - - va_start(argList, format); - int retval = debug_helper(ERROR, format, argList); - va_end(argList); - return retval; -} -}//namespace nacos diff --git a/src/config/AppConfigManager.cpp b/src/config/AppConfigManager.cpp index d912366..4f4d8e3 100644 --- a/src/config/AppConfigManager.cpp +++ b/src/config/AppConfigManager.cpp @@ -2,19 +2,18 @@ #include "AppConfigManager.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" -#include "IOUtils.h" +#include "src/utils/NetUtils.h" +#include "constant/PropertyKeyConst.h" #include "NacosExceptions.h" #include "utils/DirUtils.h" #include #include +#include "src/log/Logger.h" +#include "src/utils/ConfigParserUtils.h" using namespace std; namespace nacos{ -NacosString AppConfigManager::LINE_SEPARATOR = "\n"; -NacosString AppConfigManager::KV_SEPARATOR = "="; - bool AppConfigManager::nacosAuthEnabled() { if (contains(PropertyKeyConst::AUTH_USERNAME) && contains(PropertyKeyConst::AUTH_PASSWORD)) { @@ -24,36 +23,6 @@ bool AppConfigManager::nacosAuthEnabled() { } } -Properties AppConfigManager::parseConfigFile(const NacosString &file) { - Properties parsedConfig; - NacosString confContent = IOUtils::readStringFromFile(file, NULLSTR);//TODO: add encoding support - - vector configList; - ParamUtils::Explode(configList, confContent, LINE_SEPARATOR); - - for (vector::iterator it = configList.begin(); - it != configList.end(); it++) { - if (ParamUtils::isBlank(ParamUtils::trim(*it))) { - continue; - } - if (it->find(KV_SEPARATOR) == std::string::npos || - it->at(0) == '=') { - throw MalformedConfigException(file); - } - vector configKV; - ParamUtils::Explode(configKV, *it, KV_SEPARATOR); - //k = v - if (configKV.size() == 1) { - parsedConfig[configKV[0]] = NULLSTR; - } else { - parsedConfig[configKV[0]] = configKV[1]; - } - } - - return parsedConfig; -} - - void AppConfigManager::checkReloadable() throw(NacosException) { if (!reloadable) { throw NacosException(0, "This object is initialized as a non-reloadable one"); @@ -63,7 +32,7 @@ void AppConfigManager::checkReloadable() throw(NacosException) { size_t AppConfigManager::loadConfig() throw(NacosException) { checkReloadable(); initDefaults(); - Properties parsedConfig = parseConfigFile(configFile); + Properties parsedConfig = ConfigParserUtils::parseConfigFile(configFile); applyConfig(parsedConfig); log_debug("loaded config file:%s\n", appConfig.toString().c_str()); return appConfig.size(); @@ -121,21 +90,20 @@ void AppConfigManager::initDefaults() { //appConfig[PropertyKeyConst::NAMESPACE] = "public"; set(PropertyKeyConst::SRVLISTMGR_REFRESH_INTERVAL, "30000"); set(PropertyKeyConst::SERVER_REQ_TIMEOUT, "3000"); - set(PropertyKeyConst::CONTEXT_PATH, Constants::DEFAULT_CONTEXT_PATH); - set(PropertyKeyConst::TCP_NAMING_POLL_INTERVAL, "30000");//30 secs by default + set(PropertyKeyConst::CONTEXT_PATH, ConfigConstant::DEFAULT_CONTEXT_PATH); + set(PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL, "10000");//10 secs by default set(PropertyKeyConst::CONFIG_LONGPULLLING_TIMEOUT, "30000");//ms set(PropertyKeyConst::HB_FAIL_WAIT_TIME, "20000");//ms set(PropertyKeyConst::CLIENT_NAME, "default"); + set(PropertyKeyConst::LOCAL_IP, NetUtils::getHostIp()); + set(PropertyKeyConst::UDP_RECEIVER_PORT, "30620"); NacosString homedir = DirUtils::getHome(); - set(PropertyKeyConst::NACOS_LOG_PATH, homedir + Constants::FILE_SEPARATOR + "nacos" + Constants::FILE_SEPARATOR + "log"); - set(PropertyKeyConst::NACOS_SNAPSHOT_PATH, homedir + Constants::FILE_SEPARATOR + "nacos" + Constants::FILE_SEPARATOR + "snapshot"); - log_info("DEFAULT_LOG_PATH:%s\n", appConfig[PropertyKeyConst::NACOS_LOG_PATH].c_str()); + set(PropertyKeyConst::NACOS_SNAPSHOT_PATH, homedir + ConfigConstant::FILE_SEPARATOR + "nacos" + ConfigConstant::FILE_SEPARATOR + "snapshot"); log_info("DEFAULT_SNAPSHOT_PATH:%s\n", appConfig[PropertyKeyConst::NACOS_SNAPSHOT_PATH].c_str()); } - void AppConfigManager::applyConfig(Properties &rhs) { for (map::iterator it = rhs.begin(); it != rhs.end(); it++) { diff --git a/src/config/AppConfigManager.h b/src/config/AppConfigManager.h index 0e6182f..a846030 100644 --- a/src/config/AppConfigManager.h +++ b/src/config/AppConfigManager.h @@ -6,16 +6,13 @@ #include "Properties.h" namespace nacos{ + class AppConfigManager { private: bool reloadable; Properties appConfig; NacosString configFile; - static Properties parseConfigFile(const NacosString &file); - - static NacosString LINE_SEPARATOR; - static NacosString KV_SEPARATOR; volatile long _serverReqTimeout; AppConfigManager(); diff --git a/src/config/IOUtils.cpp b/src/config/IOUtils.cpp index eefec53..d2326dc 100644 --- a/src/config/IOUtils.cpp +++ b/src/config/IOUtils.cpp @@ -8,7 +8,7 @@ #include #include #include -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos{ size_t IOUtils::getFileSize(const NacosString &file) { diff --git a/src/config/LocalSnapshotManager.cpp b/src/config/LocalSnapshotManager.cpp index 4082017..66704da 100644 --- a/src/config/LocalSnapshotManager.cpp +++ b/src/config/LocalSnapshotManager.cpp @@ -12,8 +12,9 @@ #include "JVMUtil.h" #include "ConcurrentDiskUtil.h" #include "IOUtils.h" -#include "Constants.h" -#include "PropertyKeyConst.h" +#include "constant/ConfigConstant.h" +#include "constant/PropertyKeyConst.h" +#include "src/log/Logger.h" namespace nacos{ @@ -66,9 +67,9 @@ NacosString LocalSnapshotManager::readFile(const NacosString &file) throw(IOExce } if (JVMUtil::isMultiInstance()) { - return ConcurrentDiskUtil::getFileContent(file, Constants::ENCODE); + return ConcurrentDiskUtil::getFileContent(file, ConfigConstant::ENCODE); } else { - return IOUtils::readStringFromFile(file, Constants::ENCODE); + return IOUtils::readStringFromFile(file, ConfigConstant::ENCODE); } }; @@ -96,9 +97,9 @@ LocalSnapshotManager::saveSnapshot(const NacosString &envName, const NacosString } if (JVMUtil::isMultiInstance()) { - ConcurrentDiskUtil::writeFileContent(file, config, Constants::ENCODE); + ConcurrentDiskUtil::writeFileContent(file, config, ConfigConstant::ENCODE); } else { - IOUtils::writeStringToFile(file, config, Constants::ENCODE); + IOUtils::writeStringToFile(file, config, ConfigConstant::ENCODE); } //LOGGER.error("[" + envName + "] save snapshot error, " + file, ioe); @@ -141,7 +142,7 @@ NacosString LocalSnapshotManager::getFailoverFile(const NacosString &serverName, Failoverfile += tenant; } if (NacosStringOps::isNullStr(group)) { - Failoverfile += "/" + Constants::DEFAULT_GROUP + "/" + dataId; + Failoverfile += "/" + ConfigConstant::DEFAULT_GROUP + "/" + dataId; } else { Failoverfile += "/" + group + "/" + dataId; } @@ -158,7 +159,7 @@ NacosString LocalSnapshotManager::getSnapshotFile(const NacosString &envName, co } if (NacosStringOps::isNullStr(group)) { - filename += "/" + Constants::DEFAULT_GROUP + "/" + dataId; + filename += "/" + ConfigConstant::DEFAULT_GROUP + "/" + dataId; } else { filename += "/" + group + "/" + dataId; } diff --git a/src/config/NacosConfigService.cpp b/src/config/NacosConfigService.cpp index 00d59e9..ee51882 100644 --- a/src/config/NacosConfigService.cpp +++ b/src/config/NacosConfigService.cpp @@ -1,7 +1,6 @@ #include "src/config/NacosConfigService.h" #include "src/security/SecurityManager.h" -#include "Constants.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; @@ -92,7 +91,7 @@ bool NacosConfigService::removeConfigInner std::list headers; std::list paramValues; //Get the request url - NacosString path = Constants::DEFAULT_CONTEXT_PATH + Constants::CONFIG_CONTROLLER_PATH; + NacosString path = ConfigConstant::DEFAULT_CONTEXT_PATH + ConfigConstant::CONFIG_CONTROLLER_PATH; HttpResult res; @@ -146,7 +145,7 @@ bool NacosConfigService::publishConfigInner std::list paramValues; NacosString parmGroupid; //Get the request url - NacosString path = Constants::DEFAULT_CONTEXT_PATH + Constants::CONFIG_CONTROLLER_PATH; + NacosString path = ConfigConstant::DEFAULT_CONTEXT_PATH + ConfigConstant::CONFIG_CONTROLLER_PATH; HttpResult res; @@ -202,7 +201,7 @@ void NacosConfigService::addListener const NacosString &group, Listener *listener ) throw(NacosException) { - NacosString parmgroup = Constants::DEFAULT_GROUP; + NacosString parmgroup = ConfigConstant::DEFAULT_GROUP; if (!isNull(group)) { parmgroup = group; } @@ -225,7 +224,7 @@ void NacosConfigService::removeListener const NacosString &group, Listener *listener ) { - NacosString parmgroup = Constants::DEFAULT_GROUP; + NacosString parmgroup = ConfigConstant::DEFAULT_GROUP; if (!isNull(group)) { parmgroup = group; } diff --git a/src/constant/ConfigConstant.cpp b/src/constant/ConfigConstant.cpp new file mode 100644 index 0000000..cc67cf1 --- /dev/null +++ b/src/constant/ConfigConstant.cpp @@ -0,0 +1,51 @@ +#include "constant/ConfigConstant.h" + +/** + * Constant + * + * @author Nacos + */ + +namespace nacos{ +const NacosString ConfigConstant::DEFAULT_GROUP = "DEFAULT_GROUP"; +const NacosString ConfigConstant::DEFAULT_CONTEXT_PATH = "nacos"; +const NacosString ConfigConstant::PROTOCOL_VERSION = "v1"; +const NacosString ConfigConstant::GET_SERVERS_PATH = "ns/operator/servers"; + +const NacosString ConfigConstant::DATAID = "dataId"; + +const NacosString ConfigConstant::PROBE_MODIFY_REQUEST = "Listening-Configs"; + +const NacosString ConfigConstant::PROBE_MODIFY_RESPONSE = "Probe-Modify-Response"; + +const NacosString ConfigConstant::BASE_PATH = "/v1/cs"; + +const NacosString ConfigConstant::CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs"; + +/** +* second +*/ +const int ConfigConstant::POLLING_INTERVAL_TIME = 15; + +const NacosString ConfigConstant::ENCODE = "UTF-8"; + +const int ConfigConstant::FLOW_CONTROL_THRESHOLD = 20; + +const NacosString ConfigConstant::LINE_SEPARATOR = "\x1"; + +const NacosString ConfigConstant::WORD_SEPARATOR = "\x2"; + +const NacosString ConfigConstant::NAMING_INSTANCE_ID_SPLITTER = "#"; + +const NacosString ConfigConstant::DEFAULT_CLUSTER_NAME = "DEFAULT"; + +const NacosString ConfigConstant::SERVICE_INFO_SPLITER = "@@"; + +const NacosString ConfigConstant::FILE_SEPARATOR = "/"; + +const NacosString ConfigConstant::CONFIG_NEXT_LINE = "\n"; + +const NacosString ConfigConstant::CONFIG_KV_SEPARATOR = "="; + +const NacosString ConfigConstant::DEFAULT_CONFIG_FILE = "nacos-cpp-cli.properties"; +}//namespace nacos diff --git a/src/constant/NamingConstant.cpp b/src/constant/NamingConstant.cpp new file mode 100644 index 0000000..29dd38a --- /dev/null +++ b/src/constant/NamingConstant.cpp @@ -0,0 +1,29 @@ +#include "constant/NamingConstant.h" + +namespace nacos{ +const NacosString NamingConstant::SERVICE_NAME = "serviceName"; + +const NacosString NamingConstant::CLUSTER_NAME = "clusterName"; +const NacosString NamingConstant::UDP_PORT = "udpPort"; +const NacosString NamingConstant::CLUSTERS = "clusters"; + +const NacosString NamingConstant::CLIENT_IP = "clientIP"; +const NacosString NamingConstant::HEALTHY_ONLY = "healthyOnly"; + +const NacosString NamingConstant::HEALTHY = "healthy"; + +const NacosString NamingConstant::NAMESPACE_ID = "namespaceId"; + +const NacosString NamingConstant::GROUP_NAME = "groupName"; + +const NacosString NamingConstant::SPLITER = "@@"; + +const NacosString NamingConstant::EMPTY = ""; + +const NacosString NamingConstant::ALL_IPS = "000--00-ALL_IPS--00--000"; + +const NacosString NamingConstant::BEAT = "beat"; + +const NacosString NamingConstant::PAGE_SIZE = "pageSize"; +const NacosString NamingConstant::PAGE_NO = "pageNo"; +}//namespace nacos \ No newline at end of file diff --git a/src/PropertyKeyConst.cpp b/src/constant/PropertyKeyConst.cpp similarity index 78% rename from src/PropertyKeyConst.cpp rename to src/constant/PropertyKeyConst.cpp index e2c6d2d..9ad4cd4 100644 --- a/src/PropertyKeyConst.cpp +++ b/src/constant/PropertyKeyConst.cpp @@ -1,48 +1,53 @@ -#include "PropertyKeyConst.h" - -namespace nacos{ -const NacosString PropertyKeyConst::CONFIG_FILE_NAME = "nacos-cpp-cli.properties"; - -const NacosString PropertyKeyConst::IS_USE_ENDPOINT_PARSING_RULE = "isUseEndpointParsingRule"; - -const NacosString PropertyKeyConst::ENDPOINT = "endpoint"; - -const NacosString PropertyKeyConst::ENDPOINT_PORT = "endpointPort"; - -const NacosString PropertyKeyConst::NAMESPACE = "namespace"; - -const NacosString PropertyKeyConst::ACCESS_KEY = "accessKey"; - -const NacosString PropertyKeyConst::SECRET_KEY = "secretKey"; - -const NacosString PropertyKeyConst::RAM_ROLE_NAME = "ramRoleName"; - -const NacosString PropertyKeyConst::SERVER_ADDR = "serverAddr"; - -const NacosString PropertyKeyConst::CONTEXT_PATH = "contextPath"; - -const NacosString PropertyKeyConst::CLUSTER_NAME = "clusterName"; - -const NacosString PropertyKeyConst::ENCODE = "encode"; - -const NacosString PropertyKeyConst::NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; - -const NacosString PropertyKeyConst::NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; - -const NacosString PropertyKeyConst::NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount"; - -const NacosString PropertyKeyConst::SRVLISTMGR_REFRESH_INTERVAL = "serverListMgr.refreshInterval"; - -const NacosString PropertyKeyConst::SERVER_REQ_TIMEOUT = "nacos.server.reqtimeout"; - -const NacosString PropertyKeyConst::TCP_NAMING_POLL_INTERVAL = "naming.poller.interval"; - -const NacosString PropertyKeyConst::CONFIG_LONGPULLLING_TIMEOUT = "config.longpulling.timeout"; - -const NacosString PropertyKeyConst::HB_FAIL_WAIT_TIME = "naming.heartbeat.failwait"; -const NacosString PropertyKeyConst::NACOS_SNAPSHOT_PATH = "nacos.snapshot.path"; -const NacosString PropertyKeyConst::NACOS_LOG_PATH = "nacos.log.path"; -const NacosString PropertyKeyConst::CLIENT_NAME = "nacos.client.name"; -const NacosString PropertyKeyConst::AUTH_USERNAME = "nacos.auth.username"; -const NacosString PropertyKeyConst::AUTH_PASSWORD = "nacos.auth.password"; -}//namespace nacos +#include "constant/PropertyKeyConst.h" + +namespace nacos{ +const NacosString PropertyKeyConst::IS_USE_ENDPOINT_PARSING_RULE = "isUseEndpointParsingRule"; + +const NacosString PropertyKeyConst::ENDPOINT = "endpoint"; + +const NacosString PropertyKeyConst::ENDPOINT_PORT = "endpointPort"; + +const NacosString PropertyKeyConst::NAMESPACE = "namespace"; + +const NacosString PropertyKeyConst::ACCESS_KEY = "accessKey"; + +const NacosString PropertyKeyConst::SECRET_KEY = "secretKey"; + +const NacosString PropertyKeyConst::RAM_ROLE_NAME = "ramRoleName"; + +const NacosString PropertyKeyConst::SERVER_ADDR = "serverAddr"; + +const NacosString PropertyKeyConst::CONTEXT_PATH = "contextPath"; + +const NacosString PropertyKeyConst::CLUSTER_NAME = "clusterName"; + +const NacosString PropertyKeyConst::ENCODE = "encode"; + +const NacosString PropertyKeyConst::NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; + +const NacosString PropertyKeyConst::NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; + +const NacosString PropertyKeyConst::NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount"; + +const NacosString PropertyKeyConst::SRVLISTMGR_REFRESH_INTERVAL = "serverListMgr.refreshInterval"; + +const NacosString PropertyKeyConst::SERVER_REQ_TIMEOUT = "nacos.server.reqtimeout"; + +const NacosString PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL = "naming.poller.interval"; + +const NacosString PropertyKeyConst::UDP_RECEIVER_PORT = "nacos.udp.port"; + +const NacosString PropertyKeyConst::CONFIG_LONGPULLLING_TIMEOUT = "config.longpulling.timeout"; + +const NacosString PropertyKeyConst::HB_FAIL_WAIT_TIME = "naming.heartbeat.failwait"; +const NacosString PropertyKeyConst::NACOS_SNAPSHOT_PATH = "nacos.snapshot.path"; + +const NacosString PropertyKeyConst::LOG_PATH = "nacos.log.path"; +const NacosString PropertyKeyConst::LOG_ROTATE_TIME = "nacos.log.rotateTime"; +const NacosString PropertyKeyConst::LOG_LEVEL = "nacos.log.level"; + +const NacosString PropertyKeyConst::CLIENT_NAME = "nacos.client.name"; +const NacosString PropertyKeyConst::AUTH_USERNAME = "nacos.auth.username"; +const NacosString PropertyKeyConst::AUTH_PASSWORD = "nacos.auth.password"; +const NacosString PropertyKeyConst::LOCAL_IP = "nacos.client.ip"; +}//namespace nacos diff --git a/src/utils/UtilAndComs.cpp b/src/constant/UtilAndComs.cpp similarity index 59% rename from src/utils/UtilAndComs.cpp rename to src/constant/UtilAndComs.cpp index b41dbd5..c58e1a2 100644 --- a/src/utils/UtilAndComs.cpp +++ b/src/constant/UtilAndComs.cpp @@ -1,49 +1,35 @@ -#include "utils/UtilAndComs.h" - -namespace nacos{ -NacosString UtilAndComs::VERSION = "Nacos-CPP-Client:v1.0.1"; - -NacosString UtilAndComs::UA_VERSION = "Nacos-CPP-Client:v1.0.0"; - -NacosString UtilAndComs::WEB_CONTEXT = "/nacos"; - -NacosString UtilAndComs::NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns"; - -NacosString UtilAndComs::NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance"; - -NacosString UtilAndComs::ENCODING = "UTF-8"; - -NacosString UtilAndComs::ENV_LIST_KEY = "envList"; - -NacosString UtilAndComs::ALL_IPS = "000--00-ALL_IPS--00--000"; - -NacosString UtilAndComs::FAILOVER_SWITCH = "00-00---000-VIPSRV_FAILOVER_SWITCH-000---00-00"; - -NacosString UtilAndComs::DEFAULT_NAMESPACE_ID = "public"; - -int UtilAndComs::REQUEST_DOMAIN_RETRY_COUNT = 3; - -NacosString UtilAndComs::NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename"; - -NacosString UtilAndComs::NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level"; - -NacosString UtilAndComs::SERVER_ADDR_IP_SPLITER = ":"; - -int UtilAndComs::DEFAULT_CLIENT_BEAT_THREAD_COUNT = 1;//TODO:Calc this according to nr_processors of the host - -int UtilAndComs::DEFAULT_POLLING_THREAD_COUNT = 1;//TODO:Calc this according to nr_processors of the host - -//Underlying logic: -/*int UtilAndComs::DEFAULT_CLIENT_BEAT_THREAD_COUNT = Runtime.getRuntime() -.availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 -: 1; - -int UtilAndComs::DEFAULT_POLLING_THREAD_COUNT = Runtime.getRuntime() -.availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 -: 1;*/ - -void UtilAndComs::Init() { - -} - -}//namespace nacos +#include "constant/UtilAndComs.h" + +namespace nacos{ +NacosString UtilAndComs::VERSION = "Nacos-C-Client:v1.0.21";//TODO:fix nacos trunk code for cpp client + +NacosString UtilAndComs::WEB_CONTEXT = "/nacos"; + +NacosString UtilAndComs::NACOS_URL_BASE = WEB_CONTEXT + "/v1/ns"; + +NacosString UtilAndComs::NACOS_URL_INSTANCE = NACOS_URL_BASE + "/instance"; + +NacosString UtilAndComs::ENCODING = "UTF-8"; + +int UtilAndComs::REQUEST_DOMAIN_RETRY_COUNT = 3; + +NacosString UtilAndComs::SERVER_ADDR_IP_SPLITER = ":"; + +int UtilAndComs::DEFAULT_CLIENT_BEAT_THREAD_COUNT = 1;//TODO:Calc this according to nr_processors of the host + +int UtilAndComs::DEFAULT_POLLING_THREAD_COUNT = 1;//TODO:Calc this according to nr_processors of the host + +//Underlying logic: +/*int UtilAndComs::DEFAULT_CLIENT_BEAT_THREAD_COUNT = Runtime.getRuntime() +.availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 +: 1; + +int UtilAndComs::DEFAULT_POLLING_THREAD_COUNT = Runtime.getRuntime() +.availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 +: 1;*/ + +void UtilAndComs::Init() { + +} + +}//namespace nacos diff --git a/src/factory/NacosServiceFactory.cpp b/src/factory/NacosServiceFactory.cpp index a1824ba..7f39553 100644 --- a/src/factory/NacosServiceFactory.cpp +++ b/src/factory/NacosServiceFactory.cpp @@ -8,13 +8,18 @@ #include "src/naming/NacosNamingMaintainService.h" #include "ObjectConfigData.h" #include "src/config/NacosConfigService.h" +#include "src/config/AppConfigManager.h" #include "src/http/HttpDelegate.h" #include "src/http/delegate/NoOpHttpDelegate.h" #include "src/http/delegate/NacosAuthHttpDelegate.h" #include "src/http/HTTPCli.h" #include "src/naming/subscribe/EventDispatcher.h" -#include "src/naming/subscribe/TcpNamingServicePoller.h" +#include "src/naming/subscribe/SubscriptionPoller.h" +#include "src/naming/subscribe/UdpNamingServiceListener.h" +#include "src/naming/subscribe/HostReactor.h" #include "src/security/SecurityManager.h" +#include "src/utils/ConfigParserUtils.h" +#include "utils/DirUtils.h" //Unlike Java, in cpp, there's no container, no spring to do the ORM job, so I have to handle it myself namespace nacos{ @@ -33,17 +38,10 @@ void buildSecurityManagerAndHttpDelegate(ObjectConfigData *objectConfigData) { } } -//FIXME:Memory leak at initializing stage, e.g.: -//when a HttpDelegate is allocated in CreateConfigService, after that an EXCEPTION is thrown during the initialization of ServerListManager -//the resource for HttpDelegate is never released -NamingService *NacosServiceFactory::CreateNamingService() throw(NacosException) { - checkConfig(); - ObjectConfigData *objectConfigData = new ObjectConfigData(NAMING); - objectConfigData->name = "config"; - NacosString encoding = "UTF-8"; - +AppConfigManager *NacosServiceFactory::buildConfigManager(ObjectConfigData *objectConfigData) { //Create configuration data and load configs AppConfigManager *appConfigManager = NULL; + if (configIsSet) { appConfigManager = new AppConfigManager(configFile); appConfigManager->loadConfig(configFile); @@ -52,6 +50,21 @@ NamingService *NacosServiceFactory::CreateNamingService() throw(NacosException) } objectConfigData->_appConfigManager = appConfigManager; + return appConfigManager; +} + +//FIXME:Memory leak at initializing stage, e.g.: +//when a HttpDelegate is allocated in CreateConfigService, after that an EXCEPTION is thrown during the initialization of ServerListManager +//the resource for HttpDelegate is never released +NamingService *NacosServiceFactory::CreateNamingService() throw(NacosException) { + Init::doInit(); + checkConfig(); + ObjectConfigData *objectConfigData = new ObjectConfigData(NAMING); + objectConfigData->name = "config"; + NacosString encoding = "UTF-8"; + + buildConfigManager(objectConfigData); + //Create http client IHttpCli *httpCli= new HTTPCli(); objectConfigData->_httpCli = httpCli; @@ -71,8 +84,14 @@ NamingService *NacosServiceFactory::CreateNamingService() throw(NacosException) EventDispatcher *eventDispatcher = new EventDispatcher(); objectConfigData->_eventDispatcher = eventDispatcher; - TcpNamingServicePoller *tcpNamingServicePoller = new TcpNamingServicePoller(objectConfigData); - objectConfigData->_tcpNamingServicePoller = tcpNamingServicePoller; + SubscriptionPoller *subscriptionPoller = new SubscriptionPoller(objectConfigData); + objectConfigData->_subscriptionPoller = subscriptionPoller; + + UdpNamingServiceListener *udpNamingServiceListener = new UdpNamingServiceListener(objectConfigData); + objectConfigData->_udpNamingServiceListener = udpNamingServiceListener; + + HostReactor *hostReactor = new HostReactor(objectConfigData); + objectConfigData->_hostReactor = hostReactor; objectConfigData->checkAssembledObject(); NamingService *instance = new NacosNamingService(objectConfigData); @@ -82,19 +101,12 @@ NamingService *NacosServiceFactory::CreateNamingService() throw(NacosException) } ConfigService *NacosServiceFactory::CreateConfigService() throw(NacosException) { + Init::doInit(); checkConfig(); ObjectConfigData *objectConfigData = new ObjectConfigData(CONFIG); objectConfigData->name = "name"; - //Create configuration data and load configs - AppConfigManager *appConfigManager = NULL; - if (configIsSet) { - appConfigManager = new AppConfigManager(configFile); - appConfigManager->loadConfig(configFile); - } else { - appConfigManager = new AppConfigManager(props); - } - objectConfigData->_appConfigManager = appConfigManager; + AppConfigManager *appConfigManager = buildConfigManager(objectConfigData); //Create http client IHttpCli *httpCli = NULL; @@ -121,20 +133,13 @@ ConfigService *NacosServiceFactory::CreateConfigService() throw(NacosException) } NamingMaintainService *NacosServiceFactory::CreateNamingMaintainService() throw(NacosException){ + Init::doInit(); checkConfig(); ObjectConfigData *objectConfigData = new ObjectConfigData(MAINTAIN); objectConfigData->name = "config"; NacosString encoding = "UTF-8"; - //Create configuration data and load configs - AppConfigManager *appConfigManager = NULL; - if (configIsSet) { - appConfigManager = new AppConfigManager(configFile); - appConfigManager->loadConfig(configFile); - } else { - appConfigManager = new AppConfigManager(props); - } - objectConfigData->_appConfigManager = appConfigManager; + buildConfigManager(objectConfigData); //Create http client IHttpCli *httpCli= new HTTPCli(); @@ -160,7 +165,6 @@ NacosServiceFactory::~NacosServiceFactory() { } - void NacosServiceFactory::checkConfig() throw(InvalidFactoryConfigException) { if (!configIsSet && !propsIsSet) { throw InvalidFactoryConfigException(); @@ -180,6 +184,8 @@ void NacosServiceFactory::setProps(Properties &_props) { NacosServiceFactory::NacosServiceFactory() { configIsSet = false; propsIsSet = false; + + setConfig(DirUtils::getCwd() + "/" + ConfigConstant::DEFAULT_CONFIG_FILE); } NacosServiceFactory::NacosServiceFactory(const NacosString &_configFile) { @@ -193,4 +199,5 @@ NacosServiceFactory::NacosServiceFactory(Properties &_props) { propsIsSet = false; setProps(_props); } + }//namespace nacos \ No newline at end of file diff --git a/src/factory/ObjectConfigData.cpp b/src/factory/ObjectConfigData.cpp index 1c0f921..9d41244 100644 --- a/src/factory/ObjectConfigData.cpp +++ b/src/factory/ObjectConfigData.cpp @@ -1,25 +1,26 @@ #include "ObjectConfigData.h" #include "src/http/HttpDelegate.h" -#include "src/http/IHttpCli.h" #include "src/naming/NamingProxy.h" #include "src/naming/beat/BeatReactor.h" #include "src/naming/subscribe/EventDispatcher.h" -#include "src/naming/subscribe/TcpNamingServicePoller.h" -#include "src/config/AppConfigManager.h" -#include "src/server/ServerListManager.h" +#include "src/naming/subscribe/SubscriptionPoller.h" +#include "src/naming/subscribe/UdpNamingServiceListener.h" +#include "src/naming/subscribe/HostReactor.h" #include "src/listen/ClientWorker.h" -#include "src/config/LocalSnapshotManager.h" #include "src/security/SecurityManager.h" +#include "utils/UuidUtils.h" + namespace nacos{ ObjectConfigData::ObjectConfigData(FactoryType theFactoryType) { + objectId = UuidUtils::generateUuid(); factoryType = theFactoryType; _httpDelegate = NULL; _httpCli = NULL; _serverProxy = NULL; _beatReactor = NULL; _eventDispatcher = NULL; - _tcpNamingServicePoller = NULL; + _subscriptionPoller = NULL; _appConfigManager = NULL; _serverListManager = NULL; _clientWorker = NULL; @@ -31,20 +32,25 @@ void ObjectConfigData::checkNamingService() throw(NacosException) { if (factoryType != NAMING) { throw NacosException(NacosException::INVALID_PARAM, "Invalid configuration for naming service, please check"); } + NACOS_ASSERT(_httpDelegate != NULL); NACOS_ASSERT(_httpCli != NULL); NACOS_ASSERT(_serverProxy != NULL); NACOS_ASSERT(_beatReactor != NULL); NACOS_ASSERT(_eventDispatcher != NULL); - NACOS_ASSERT(_tcpNamingServicePoller != NULL); + NACOS_ASSERT(_subscriptionPoller != NULL); + NACOS_ASSERT(_hostReactor != NULL); NACOS_ASSERT(_appConfigManager != NULL); NACOS_ASSERT(_serverListManager != NULL); + NACOS_ASSERT(_udpNamingServiceListener != NULL); + NACOS_ASSERT(_udpNamingServiceListener != NULL); } void ObjectConfigData::checkConfigService() throw(NacosException) { if (factoryType != CONFIG) { throw NacosException(NacosException::INVALID_PARAM, "Invalid configuration for config service, please check"); } + NACOS_ASSERT(_appConfigManager != NULL); NACOS_ASSERT(_httpCli != NULL); NACOS_ASSERT(_httpDelegate != NULL); @@ -117,8 +123,12 @@ void ObjectConfigData::destroyNamingService() { _beatReactor->stop(); } - if (_tcpNamingServicePoller != NULL) { - _tcpNamingServicePoller->stop(); + if (_subscriptionPoller != NULL) { + _subscriptionPoller->stop(); + } + + if (_udpNamingServiceListener != NULL) { + _udpNamingServiceListener->stop(); } if (_eventDispatcher != NULL) { @@ -133,10 +143,6 @@ void ObjectConfigData::destroyNamingService() { _serverListManager->stop(); } - if (_securityManager != NULL) { - _securityManager->stop(); - } - if (_httpDelegate != NULL) { delete _httpDelegate; _httpDelegate = NULL; @@ -147,10 +153,16 @@ void ObjectConfigData::destroyNamingService() { _beatReactor = NULL; } - if (_tcpNamingServicePoller != NULL) + if (_subscriptionPoller != NULL) { - delete _tcpNamingServicePoller; - _tcpNamingServicePoller = NULL; + delete _subscriptionPoller; + _subscriptionPoller = NULL; + } + + if (_udpNamingServiceListener != NULL) + { + delete _udpNamingServiceListener; + _udpNamingServiceListener = NULL; } if (_eventDispatcher != NULL) @@ -159,6 +171,11 @@ void ObjectConfigData::destroyNamingService() { _eventDispatcher = NULL; } + if (_hostReactor != NULL) { + delete _hostReactor; + _hostReactor = NULL; + } + if (_serverProxy != NULL) { delete _serverProxy; _serverProxy = NULL; diff --git a/src/factory/ObjectConfigData.h b/src/factory/ObjectConfigData.h index 32ad432..41be637 100644 --- a/src/factory/ObjectConfigData.h +++ b/src/factory/ObjectConfigData.h @@ -11,12 +11,14 @@ class IHttpCli; class NamingProxy; class BeatReactor; class EventDispatcher; -class TcpNamingServicePoller; +class SubscriptionPoller; class AppConfigManager; class ServerListManager; class ClientWorker; class LocalSnapshotManager; class SecurityManager; +class UdpNamingServiceListener; +class HostReactor; enum FactoryType { CONFIG = 0, @@ -35,7 +37,9 @@ class ObjectConfigData { void checkConfigService() throw(NacosException); void checkNamingService() throw(NacosException); void checkMaintainService() throw(NacosException); + NacosString objectId; public: + const NacosString &getObjectId() const { return objectId; }; ObjectConfigData(FactoryType theFactoryType); void checkAssembledObject() throw(NacosException); ~ObjectConfigData(); @@ -45,12 +49,14 @@ class ObjectConfigData { NamingProxy *_serverProxy; BeatReactor *_beatReactor; EventDispatcher *_eventDispatcher; - TcpNamingServicePoller *_tcpNamingServicePoller; + SubscriptionPoller *_subscriptionPoller; AppConfigManager *_appConfigManager; ServerListManager *_serverListManager; ClientWorker *_clientWorker; LocalSnapshotManager *_localSnapshotManager; SecurityManager *_securityManager; + UdpNamingServiceListener *_udpNamingServiceListener; + HostReactor *_hostReactor; }; }//namespace nacos diff --git a/src/http/HTTPCli.cpp b/src/http/HTTPCli.cpp index 2a66896..8aaf4d4 100644 --- a/src/http/HTTPCli.cpp +++ b/src/http/HTTPCli.cpp @@ -1,7 +1,8 @@ #include #include "HTTPCli.h" #include "utils/url.h" -#include "Debug.h" +#include "constant/UtilAndComs.h" +#include "src/log/Logger.h" using namespace std; @@ -74,7 +75,7 @@ void HTTPCli::destroyCurlHandle(void *arg) { } void HTTPCli::HTTPBasicSettings(CURL *curlHandle) { - curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); + curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, UtilAndComs::VERSION.c_str()); curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, receiveResponseCallback); curl_easy_setopt(curlHandle, CURLOPT_HEADERFUNCTION, receiveHeaderCallback); } diff --git a/src/init/Init.cpp b/src/init/Init.cpp index 142c976..e06a6c4 100644 --- a/src/init/Init.cpp +++ b/src/init/Init.cpp @@ -3,12 +3,14 @@ #include "src/config/SnapShotSwitch.h" #include "src/config/JVMUtil.h" #include "naming/ServiceInfo2.h" -#include "utils/UtilAndComs.h" +#include "constant/UtilAndComs.h" #include "utils/UuidUtils.h" #include "utils/RandomUtils.h" +#include "src/thread/Thread.h" static nacos::Init initobj;//Implicitly call the constructors namespace nacos{ +Mutex Init::initflagMutex; bool Init::inited = false; bool SnapShotSwitch::isSnapShot = true; bool JVMUtil::_isMultiInstance = false; @@ -18,24 +20,41 @@ void Init::doInit() { if (inited) { return; } + { + LockGuard _initGuard(initflagMutex); + if (inited) { + return; + } - inited = true; - Debug::set_debug_level(ERROR); - HTTPCli::HTTP_GLOBAL_INIT(); - UtilAndComs::Init(); - RandomUtils::Init(); - UuidUtils::Init(); - ServiceInfo2::nullServiceInfo2.setNull(true); + Logger::Init(); + HTTPCli::HTTP_GLOBAL_INIT(); + UtilAndComs::Init(); + RandomUtils::Init(); + UuidUtils::Init(); + Thread::Init(); + ServiceInfo2::nullServiceInfo2.setNull(true); + inited = true; + } } void Init::doDeinit() { if (!inited) { return; } - inited = false; - UuidUtils::DeInit(); - RandomUtils::DeInit(); - HTTPCli::HTTP_GLOBAL_DEINIT(); + + { + LockGuard _initGuard(initflagMutex); + if (!inited) { + return; + } + + Thread::DeInit(); + UuidUtils::DeInit(); + RandomUtils::DeInit(); + HTTPCli::HTTP_GLOBAL_DEINIT(); + Logger::deInit(); + inited = false; + } } }//namespace nacos diff --git a/src/init/Init.h b/src/init/Init.h index 4182ce6..44731a7 100644 --- a/src/init/Init.h +++ b/src/init/Init.h @@ -1,12 +1,15 @@ #ifndef __INIT_H_ #define __INIT_H_ +#include "src/thread/Mutex.h" + namespace nacos{ class Init { private: static bool inited; + static Mutex initflagMutex; public: - Init() { doInit(); }; + Init() {}; ~Init() { doDeinit(); }; diff --git a/src/json/JSON.cpp b/src/json/JSON.cpp index d857adf..b10e445 100644 --- a/src/json/JSON.cpp +++ b/src/json/JSON.cpp @@ -141,6 +141,11 @@ Instance JSON::Json2Instance(const Value &host) throw(NacosException) { theinstance.metadata = mtdata; + if (host.HasMember("clusterName")) { + const Value &clusterName = host["clusterName"]; + theinstance.clusterName = clusterName.GetString(); + } + return theinstance; } @@ -255,6 +260,10 @@ ServiceInfo JSON::JsonStr2ServiceInfo(const NacosString &jsonString) throw(Nacos const Value &clusters = d["clusters"]; si.setClusters(clusters.GetString()); + markRequired(d, "name"); + const Value &name = d["name"]; + ServiceInfo::fromKey(si, name.GetString()); + return si; } @@ -414,4 +423,25 @@ AccessToken JSON::Json2AccessToken(const NacosString &nacosString) throw(NacosEx return accessTokenRes; } +PushPacket JSON::Json2PushPacket(const char *jsonString) throw(NacosException) +{ + cout << jsonString << endl; + PushPacket pushPacket; + Document d; + d.Parse(jsonString); + markRequired(d, "data"); + const Value &data = d["data"]; + pushPacket.data = data.GetString(); + + markRequired(d, "type"); + const Value &type = d["type"]; + pushPacket.type = type.GetString(); + + markRequired(d, "lastRefTime"); + const Value &lastRefTime = d["lastRefTime"]; + pushPacket.lastRefTime = lastRefTime.GetInt64(); + + return pushPacket; +} + }//namespace nacos \ No newline at end of file diff --git a/src/json/JSON.h b/src/json/JSON.h index c616b6a..608fce1 100644 --- a/src/json/JSON.h +++ b/src/json/JSON.h @@ -13,6 +13,7 @@ #include "naming/ListView.h" #include "naming/ServiceInfo2.h" #include "src/security/SecurityManager.h" +#include "src/naming/subscribe/UdpNamingServiceListener.h" /** * JSON @@ -50,6 +51,8 @@ class JSON { static ListView Json2ServiceList(const NacosString &nacosString) throw(NacosException); static AccessToken Json2AccessToken(const NacosString &nacosString) throw(NacosException); + + static PushPacket Json2PushPacket(const char *jsonString) throw(NacosException); }; }//namespace nacos diff --git a/src/listen/ClientWorker.cpp b/src/listen/ClientWorker.cpp index 868f074..14eac2b 100644 --- a/src/listen/ClientWorker.cpp +++ b/src/listen/ClientWorker.cpp @@ -6,10 +6,10 @@ #include "src/md5/md5.h" #include "utils/ParamUtils.h" #include "src/utils/TimeUtils.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "DebugAssertion.h" -#include "Constants.h" -#include "PropertyKeyConst.h" +#include "constant/ConfigConstant.h" +#include "constant/PropertyKeyConst.h" #include "src/http/HttpStatus.h" using namespace std; @@ -77,7 +77,7 @@ HttpResult ClientWorker::getServerConfigHelper if (!isNull(group)) { ParamUtils::addKV(paramValues, "group", group); } else { - ParamUtils::addKV(paramValues, "group", Constants::DEFAULT_GROUP); + ParamUtils::addKV(paramValues, "group", ConfigConstant::DEFAULT_GROUP); } if (!isNull(tenant)) { @@ -85,7 +85,7 @@ HttpResult ClientWorker::getServerConfigHelper } //Get the request url - NacosString path = Constants::DEFAULT_CONTEXT_PATH + Constants::CONFIG_CONTROLLER_PATH; + NacosString path = ConfigConstant::DEFAULT_CONTEXT_PATH + ConfigConstant::CONFIG_CONTROLLER_PATH; NacosString serverAddr = _objectConfigData->_serverListManager->getCurrentServerAddr(); NacosString url = serverAddr + "/" + path; log_debug("httpGet Assembled URL:%s\n", url.c_str()); @@ -122,7 +122,7 @@ vector ClientWorker::parseListenedKeys(const NacosString &Returned NacosString changedKeyList = urldecode(ReturnedKeys); vector explodedList; - ParamUtils::Explode(explodedList, changedKeyList, Constants::LINE_SEPARATOR); + ParamUtils::Explode(explodedList, changedKeyList, ConfigConstant::LINE_SEPARATOR); //If the server returns a string with a trailing \x01, actually there is no data after that //but ParamUtils::Explode will return an extra item with empty string, we need to remove that @@ -290,18 +290,18 @@ NacosString ClientWorker::checkListenedKeys() { ListeningData *curListenedKey = it->second; postData += curListenedKey->getDataId(); - postData += Constants::WORD_SEPARATOR; + postData += ConfigConstant::WORD_SEPARATOR; postData += curListenedKey->getGroup(); - postData += Constants::WORD_SEPARATOR; + postData += ConfigConstant::WORD_SEPARATOR; if (!isNull(curListenedKey->getTenant())) { postData += curListenedKey->getMD5(); - postData += Constants::WORD_SEPARATOR; + postData += ConfigConstant::WORD_SEPARATOR; postData += curListenedKey->getTenant(); - postData += Constants::LINE_SEPARATOR; + postData += ConfigConstant::LINE_SEPARATOR; } else { postData += curListenedKey->getMD5(); - postData += Constants::LINE_SEPARATOR; + postData += ConfigConstant::LINE_SEPARATOR; } } pthread_mutex_unlock(&watchListMutex); @@ -312,13 +312,13 @@ NacosString ClientWorker::checkListenedKeys() { headers.push_back("Long-Pulling-Timeout"); headers.push_back(_longPullingTimeoutStr); - paramValues.push_back(Constants::PROBE_MODIFY_REQUEST); + paramValues.push_back(ConfigConstant::PROBE_MODIFY_REQUEST); paramValues.push_back(postData); log_debug("Assembled postData:%s\n", postData.c_str()); //Get the request url //TODO:move /listener to constant - NacosString path = Constants::DEFAULT_CONTEXT_PATH + Constants::CONFIG_CONTROLLER_PATH + "/listener"; + NacosString path = ConfigConstant::DEFAULT_CONTEXT_PATH + ConfigConstant::CONFIG_CONTROLLER_PATH + "/listener"; HttpResult res; NacosString serverAddr = _objectConfigData->_serverListManager->getCurrentServerAddr(); @@ -366,7 +366,7 @@ void ClientWorker::performWatch() { updatedcontent = res.content; } catch (NacosException &e) { - //Same design as TcpNamingServicePoller + //Same design as SubscriptionPoller log_warn("Encountered exception when getting config from server:%s:%s:%s\n", listenedList->getTenant().c_str(), listenedList->getGroup().c_str(), diff --git a/src/listen/ListeningData.h b/src/listen/ListeningData.h index 5d910a7..4443b98 100644 --- a/src/listen/ListeningData.h +++ b/src/listen/ListeningData.h @@ -6,7 +6,7 @@ #include "NacosString.h" #include "listen/Listener.h" #include "src/md5/md5.h" -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos{ class ListeningData { diff --git a/src/log/Logger.cpp b/src/log/Logger.cpp new file mode 100644 index 0000000..e4bd1b3 --- /dev/null +++ b/src/log/Logger.cpp @@ -0,0 +1,201 @@ +#include +#include +#include +#include +#include "Logger.h" +#include "src/utils/TimeUtils.h" +#include "NacosExceptions.h" +#include "src/utils/ConfigParserUtils.h" +#include "Properties.h" +#include "utils/DirUtils.h" +#include "utils/ParamUtils.h" +#include "src/config/IOUtils.h" +#include "constant/ConfigConstant.h" +#include "constant/PropertyKeyConst.h" + +namespace nacos{ + +LOG_LEVEL Logger::_CUR_SYS_LOG_LEVEL = ERROR; +NacosString Logger::_log_base_dir = ""; +NacosString Logger::_log_file = ""; +int64_t Logger::_rotate_time; +int64_t Logger::_last_rotate_time; +FILE *Logger::_output_file; +Mutex Logger::setFileLock; + +//rotate time (in Ms) +void Logger::setRotateTime(int64_t rotateTime) { + _rotate_time = rotateTime; +} + +void Logger::setBaseDir(const NacosString &baseDir) { + LockGuard _setFile(setFileLock); + _log_base_dir = baseDir; + if (_output_file != NULL) { + fclose(_output_file); + _output_file = NULL; + } + + IOUtils::recursivelyCreate(_log_base_dir.c_str()); + _log_file = _log_base_dir + ConfigConstant::FILE_SEPARATOR + "nacos-sdk-cpp.log"; + _output_file = fopen(_log_file.c_str(), "a"); + if (_output_file == NULL) { + NacosString errMsg = "Unable to open file "; + errMsg += _log_file; + throw NacosException(NacosException::UNABLE_TO_OPEN_FILE, errMsg); + } +} + +void Logger::setLogLevel(LOG_LEVEL level) { + _CUR_SYS_LOG_LEVEL = level; +}; + +int64_t Logger::getRotateTime() { + return _rotate_time; +} + +const NacosString &Logger::getBaseDir() { + return _log_base_dir; +} + +LOG_LEVEL Logger::getLogLevel() { + return _CUR_SYS_LOG_LEVEL; +} + +int Logger::debug_helper(LOG_LEVEL level, const char *format, va_list args) { + //Since the current system debug level is greater than this message + //Supress it + if (Logger::_CUR_SYS_LOG_LEVEL > level) { + return 0; + } + //va_list argList; + + //va_start(argList, format); + int64_t now = TimeUtils::getCurrentTimeInMs(); + if (now - _last_rotate_time >= _rotate_time) { + truncate(_log_file.c_str(), 0); + _last_rotate_time = now; + } + + int retval = vfprintf(_output_file, format, args); + fflush(_output_file); + //va_end(argList); + return retval; +} + +//Output string in self-defined log_level +int Logger::debug_print(LOG_LEVEL level, const char *format, ...) { + va_list argList; + + va_start(argList, format); + int retval = debug_helper(level, format, argList); + va_end(argList); + return retval; +} + +int Logger::debug_debug(const char *format, ...) { + va_list argList; + + va_start(argList, format); + int retval = debug_helper(DEBUG, format, argList); + va_end(argList); + return retval; +} + +int Logger::debug_info(const char *format, ...) { + va_list argList; + + va_start(argList, format); + int retval = debug_helper(INFO, format, argList); + va_end(argList); + return retval; +} + +int Logger::debug_warn(const char *format, ...) { + va_list argList; + + va_start(argList, format); + int retval = debug_helper(WARN, format, argList); + va_end(argList); + return retval; +} + +int Logger::debug_error(const char *format, ...) { + va_list argList; + + va_start(argList, format); + int retval = debug_helper(ERROR, format, argList); + va_end(argList); + return retval; +} + +void Logger::deInit() { + if (_output_file != NULL) { + fclose(_output_file); + _output_file = NULL; + } +} + +void Logger::initializeLogSystem() { + Properties props; + + //if we failed to read log settings + props = ConfigParserUtils::parseConfigFile(DirUtils::getCwd() + ConfigConstant::FILE_SEPARATOR + ConfigConstant::DEFAULT_CONFIG_FILE); + + if (!props.contains(PropertyKeyConst::LOG_PATH)) { + NacosString homedir = DirUtils::getHome(); + Logger::setBaseDir(homedir + ConfigConstant::FILE_SEPARATOR + "nacos" + ConfigConstant::FILE_SEPARATOR + "logs"); + } else { + Logger::setBaseDir(props[PropertyKeyConst::LOG_PATH]); + } + + if (props.contains(PropertyKeyConst::LOG_LEVEL)) { + //default log level is error, if user specifies it within configuration file, update it + NacosString &logLevelStr = props[PropertyKeyConst::LOG_LEVEL]; + + if (logLevelStr == "DEBUG") { + Logger::setLogLevel(DEBUG); + } else if (logLevelStr == "INFO") { + Logger::setLogLevel(INFO); + } else if (logLevelStr == "WARN") { + Logger::setLogLevel(WARN); + } else if (logLevelStr == "ERROR") { + Logger::setLogLevel(ERROR); + } else if (logLevelStr == "NONE") { + Logger::setLogLevel(NONE); + } else { + throw NacosException(NacosException::INVALID_CONFIG_PARAM, "Invalid option " + logLevelStr + " for " + PropertyKeyConst::LOG_LEVEL); + } + } + + if (!props.contains(PropertyKeyConst::LOG_ROTATE_TIME)) { + Logger::setRotateTime(24 * 60 * 60 * 1000); + } else { + const NacosString &logRotateTimeStr = props[PropertyKeyConst::LOG_ROTATE_TIME]; + if (ParamUtils::isBlank(logRotateTimeStr)) { + throw NacosException(NacosException::INVALID_CONFIG_PARAM, + "Invalid option " + logRotateTimeStr + " for " + PropertyKeyConst::LOG_ROTATE_TIME); + } + + if (logRotateTimeStr[logRotateTimeStr.length() - 1] != 'h' && + logRotateTimeStr[logRotateTimeStr.length() - 1] != 'H') { + throw NacosException(NacosException::INVALID_CONFIG_PARAM, + "Invalid option " + logRotateTimeStr + " for " + PropertyKeyConst::LOG_ROTATE_TIME + ", we only support hour currently"); + } + + int logRotateTime = atol(logRotateTimeStr.substr(0, logRotateTimeStr.length() - 2).c_str()); + if (logRotateTime <= 0) { + throw NacosException(NacosException::INVALID_CONFIG_PARAM, + PropertyKeyConst::LOG_ROTATE_TIME + " should be greater than 0"); + } + Logger::setRotateTime(logRotateTime); + } + + log_info("DEFAULT_LOG_PATH:%s\n", Logger::getBaseDir().c_str()); +} + +void Logger::Init() { + initializeLogSystem(); +} + +}//namespace nacos diff --git a/src/log/Logger.h b/src/log/Logger.h new file mode 100644 index 0000000..184193c --- /dev/null +++ b/src/log/Logger.h @@ -0,0 +1,78 @@ +#ifndef __LOGGER_H_ +#define __LOGGER_H_ + +#include +#include +#include "NacosString.h" +#include "src/thread/Mutex.h" + +#define DETAILED_DEBUG_INFO + +//TODO:Line info +#ifndef DETAILED_DEBUG_INFO +#define log_print(level, format, args...) Logger::debug_print(level, format, ##args) +#define log_debug(format, args...) Logger::debug_debug(format, ##args) +#define log_info(format, args...) Logger::debug_info(format, ##args) +#define log_warn(format, args...) Logger::debug_warn(format, ##args) +#define log_error(format, args...) Logger::debug_error(format, ##args) +#else +#define STR(X) #X +#define log_print(level, format, args...) Logger::debug_print(level, format, ##args) +#define log_debug(format, args...) Logger::debug_debug(format, ##args) +#define log_info(format, args...) Logger::debug_info(format, ##args) +#define log_warn(format, args...) Logger::debug_warn(format, ##args) +#define log_error(format, args...) Logger::debug_error(format, ##args) +#endif + +namespace nacos{ + +enum LOG_LEVEL { + DEBUG = 0, + INFO, + WARN, + ERROR, + NONE +}; + +class Logger { +private: + static LOG_LEVEL _CUR_SYS_LOG_LEVEL; + static NacosString _log_base_dir; + static NacosString _log_file; + static int64_t _rotate_time; + static int64_t _last_rotate_time; + static FILE *_output_file; + + static Mutex setFileLock; + + static int debug_helper(LOG_LEVEL level, const char *format, va_list args); + + static void initializeLogSystem(); + +public: + + static void setRotateTime(int64_t rotateTime); + static void setBaseDir(const NacosString &baseDir); + static void setLogLevel(LOG_LEVEL level); + + static int64_t getRotateTime(); + static const NacosString &getBaseDir(); + static LOG_LEVEL getLogLevel(); + + //Output string in self-defined log_level + static int debug_print(LOG_LEVEL level, const char *format, ...); + + static int debug_debug(const char *format, ...); + + static int debug_info(const char *format, ...); + + static int debug_warn(const char *format, ...); + + static int debug_error(const char *format, ...); + + static void Init(); + static void deInit(); +}; +}//namespace nacos + +#endif \ No newline at end of file diff --git a/src/naming/Instance.cpp b/src/naming/Instance.cpp index 69c4a1a..e8babbb 100644 --- a/src/naming/Instance.cpp +++ b/src/naming/Instance.cpp @@ -1,6 +1,6 @@ #include "naming/Instance.h" #include "utils/ParamUtils.h" -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos{ Instance::Instance() { diff --git a/src/naming/NacosNamingMaintainService.cpp b/src/naming/NacosNamingMaintainService.cpp index e32f819..f92f720 100644 --- a/src/naming/NacosNamingMaintainService.cpp +++ b/src/naming/NacosNamingMaintainService.cpp @@ -36,7 +36,7 @@ ServiceInfo2 NacosNamingMaintainService::queryService bool NacosNamingMaintainService::createService(const ServiceInfo2 &service, naming::Selector *selector) throw(NacosException) { ServiceInfo2 parmServiceInfo = service; if (!parmServiceInfo.isGroupNameSet()) { - parmServiceInfo.setGroupName(Constants::DEFAULT_GROUP); + parmServiceInfo.setGroupName(ConfigConstant::DEFAULT_GROUP); } return _objectConfigData->_serverProxy->createServiceInfo(parmServiceInfo, selector); } diff --git a/src/naming/NacosNamingService.cpp b/src/naming/NacosNamingService.cpp index c3f0dfa..fc22ddc 100644 --- a/src/naming/NacosNamingService.cpp +++ b/src/naming/NacosNamingService.cpp @@ -1,9 +1,11 @@ #include "src/naming/NacosNamingService.h" +#include "src/naming/subscribe/SubscriptionPoller.h" +#include "src/naming/subscribe/UdpNamingServiceListener.h" #include "src/naming/beat/BeatReactor.h" #include "utils/NamingUtils.h" -#include "utils/UtilAndComs.h" +#include "constant/UtilAndComs.h" #include "utils/ParamUtils.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "src/json/JSON.h" using namespace std; @@ -13,7 +15,8 @@ namespace nacos{ NacosNamingService::NacosNamingService(ObjectConfigData *objectConfigData) { _objectConfigData = objectConfigData; _objectConfigData->_beatReactor->start(); - _objectConfigData->_tcpNamingServicePoller->start(); + _objectConfigData->_subscriptionPoller->start(); + _objectConfigData->_udpNamingServiceListener->start(); if (_objectConfigData->_appConfigManager->nacosAuthEnabled()) { _objectConfigData->_securityManager->login(); @@ -31,7 +34,7 @@ void NacosNamingService::registerInstance const NacosString &ip, int port ) throw(NacosException) { - registerInstance(serviceName, ip, port, Constants::DEFAULT_CLUSTER_NAME); + registerInstance(serviceName, ip, port, ConfigConstant::DEFAULT_CLUSTER_NAME); } void NacosNamingService::registerInstance @@ -41,7 +44,7 @@ void NacosNamingService::registerInstance const NacosString &ip, int port ) throw(NacosException) { - registerInstance(serviceName, groupName, ip, port, Constants::DEFAULT_CLUSTER_NAME); + registerInstance(serviceName, groupName, ip, port, ConfigConstant::DEFAULT_CLUSTER_NAME); } void NacosNamingService::registerInstance @@ -51,7 +54,7 @@ void NacosNamingService::registerInstance int port, const NacosString &clusterName ) throw(NacosException) { - registerInstance(serviceName, Constants::DEFAULT_GROUP, ip, port, clusterName); + registerInstance(serviceName, ConfigConstant::DEFAULT_GROUP, ip, port, clusterName); } void NacosNamingService::registerInstance @@ -76,7 +79,7 @@ void NacosNamingService::registerInstance const NacosString &serviceName, Instance &instance ) throw(NacosException) { - registerInstance(serviceName, Constants::DEFAULT_GROUP, instance); + registerInstance(serviceName, ConfigConstant::DEFAULT_GROUP, instance); } void NacosNamingService::registerInstance @@ -108,7 +111,7 @@ void NacosNamingService::deregisterInstance const NacosString &ip, int port ) throw(NacosException) { - deregisterInstance(serviceName, ip, port, Constants::DEFAULT_CLUSTER_NAME); + deregisterInstance(serviceName, ip, port, ConfigConstant::DEFAULT_CLUSTER_NAME); } void NacosNamingService::deregisterInstance @@ -118,7 +121,7 @@ void NacosNamingService::deregisterInstance const NacosString &ip, int port ) throw(NacosException) { - deregisterInstance(serviceName, groupName, ip, port, Constants::DEFAULT_CLUSTER_NAME); + deregisterInstance(serviceName, groupName, ip, port, ConfigConstant::DEFAULT_CLUSTER_NAME); } void NacosNamingService::deregisterInstance @@ -128,7 +131,7 @@ void NacosNamingService::deregisterInstance int port, const NacosString &clusterName ) throw(NacosException) { - deregisterInstance(serviceName, Constants::DEFAULT_GROUP, ip, port, clusterName); + deregisterInstance(serviceName, ConfigConstant::DEFAULT_GROUP, ip, port, clusterName); } void NacosNamingService::deregisterInstance @@ -179,7 +182,7 @@ list NacosNamingService::getAllInstances const NacosString &serviceName, const list &clusters ) throw(NacosException) { - return getAllInstances(serviceName, Constants::DEFAULT_GROUP, clusters); + return getAllInstances(serviceName, ConfigConstant::DEFAULT_GROUP, clusters); } list NacosNamingService::getAllInstances @@ -191,8 +194,10 @@ list NacosNamingService::getAllInstances ServiceInfo serviceInfo; //TODO:cache and failover NacosString clusterString = ParamUtils::Implode(clusters); - NacosString result = _objectConfigData->_serverProxy->queryList(serviceName, clusterString, 0/*What should be filled in UDPPort??*/, - false); + NacosString result = _objectConfigData->_serverProxy->queryList( + serviceName, groupName, clusterString, + 0/*non-zero value to receive subscription push from the server, set to 0 since we don't need it here*/, + false); serviceInfo = JSON::JsonStr2ServiceInfo(result); list hostlist = serviceInfo.getHosts(); return hostlist; @@ -201,7 +206,7 @@ list NacosNamingService::getAllInstances void NacosNamingService::subscribe(const NacosString &serviceName, EventListener *listener) throw (NacosException) { list clusters;//empty cluster - subscribe(serviceName, Constants::DEFAULT_GROUP, clusters, listener); + subscribe(serviceName, ConfigConstant::DEFAULT_GROUP, clusters, listener); } @@ -222,7 +227,7 @@ void NacosNamingService::subscribe( EventListener *listener ) throw (NacosException) { - subscribe(serviceName, Constants::DEFAULT_GROUP, clusters, listener); + subscribe(serviceName, ConfigConstant::DEFAULT_GROUP, clusters, listener); } void NacosNamingService::subscribe @@ -238,7 +243,7 @@ void NacosNamingService::subscribe if (!_objectConfigData->_eventDispatcher->addListener(groupedName, clusterName, listener)){ return;//The listener is already listening to the service specified, no need to add to the polling list } - _objectConfigData->_tcpNamingServicePoller->addPollItem(serviceName, groupName, clusterName); + _objectConfigData->_subscriptionPoller->addPollItem(serviceName, groupName, clusterName); } @@ -257,7 +262,7 @@ void NacosNamingService::unsubscribe( } if (remainingListener == 0) { //Since there's no more listeners listening to this service, remove it from the polling list - _objectConfigData->_tcpNamingServicePoller->removePollItem(serviceName, groupName, clusterName); + _objectConfigData->_subscriptionPoller->removePollItem(serviceName, groupName, clusterName); } } @@ -268,7 +273,7 @@ void NacosNamingService::unsubscribe EventListener *listener ) throw (NacosException) { - unsubscribe(serviceName, Constants::DEFAULT_GROUP, clusters, listener); + unsubscribe(serviceName, ConfigConstant::DEFAULT_GROUP, clusters, listener); } void NacosNamingService::unsubscribe @@ -285,11 +290,11 @@ void NacosNamingService::unsubscribe void NacosNamingService::unsubscribe(const NacosString &serviceName, EventListener *listener) throw (NacosException) { list clusters; - unsubscribe(serviceName, Constants::DEFAULT_GROUP, clusters, listener); + unsubscribe(serviceName, ConfigConstant::DEFAULT_GROUP, clusters, listener); } ListView NacosNamingService::getServiceList(int pageNo, int pageSize) throw (NacosException) { - return _objectConfigData->_serverProxy->getServiceList(pageNo, pageSize, Constants::DEFAULT_GROUP); + return _objectConfigData->_serverProxy->getServiceList(pageNo, pageSize, ConfigConstant::DEFAULT_GROUP); } ListView NacosNamingService::getServiceList(int pageNo, int pageSize, const NacosString &groupName) throw (NacosException){ @@ -319,7 +324,7 @@ list NacosNamingService::getInstanceWithPredicate Selector *predicate ) throw(NacosException) { - list allInstances = getAllInstances(serviceName, Constants::DEFAULT_GROUP, clusters); + list allInstances = getAllInstances(serviceName, ConfigConstant::DEFAULT_GROUP, clusters); if (predicate) { return predicate->select(allInstances); } else { @@ -350,7 +355,7 @@ list NacosNamingService::getInstanceWithPredicate ) throw(NacosException) { list clusters; - list allInstances = getAllInstances(serviceName, Constants::DEFAULT_GROUP, clusters); + list allInstances = getAllInstances(serviceName, ConfigConstant::DEFAULT_GROUP, clusters); if (predicate) { return predicate->select(allInstances); } else { diff --git a/src/naming/NacosNamingService.h b/src/naming/NacosNamingService.h index 49e866a..4581b90 100644 --- a/src/naming/NacosNamingService.h +++ b/src/naming/NacosNamingService.h @@ -5,7 +5,6 @@ #include "naming/Instance.h" #include "src/naming/NamingProxy.h" #include "src/naming/subscribe/EventDispatcher.h" -#include "src/naming/subscribe/TcpNamingServicePoller.h" #include "src/naming/beat/BeatReactor.h" #include "src/http/IHttpCli.h" #include "NacosString.h" diff --git a/src/naming/NamingCommonParams.cpp b/src/naming/NamingCommonParams.cpp deleted file mode 100644 index cc4fdf4..0000000 --- a/src/naming/NamingCommonParams.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "naming/NamingCommonParams.h" - -namespace nacos{ -const NacosString NamingCommonParams::SERVICE_NAME = "serviceName"; - -const NacosString NamingCommonParams::CLUSTER_NAME = "clusterName"; - -const NacosString NamingCommonParams::HEALTHY = "healthy"; - -const NacosString NamingCommonParams::NAMESPACE_ID = "namespaceId"; - -const NacosString NamingCommonParams::GROUP_NAME = "groupName"; - -const NacosString NamingCommonParams::SPLITER = "@@"; - -const NacosString NamingCommonParams::EMPTY = ""; - -const NacosString NamingCommonParams::ALL_IPS = "000--00-ALL_IPS--00--000"; - -const NacosString NamingCommonParams::BEAT = "beat"; - -const NacosString NamingCommonParams::PAGE_SIZE = "pageSize"; -const NacosString NamingCommonParams::PAGE_NO = "pageNo"; -}//namespace nacos \ No newline at end of file diff --git a/src/naming/NamingProxy.cpp b/src/naming/NamingProxy.cpp index fb7265b..6970172 100644 --- a/src/naming/NamingProxy.cpp +++ b/src/naming/NamingProxy.cpp @@ -1,13 +1,13 @@ #include #include "NamingProxy.h" -#include "naming/NamingCommonParams.h" -#include "utils/UtilAndComs.h" +#include "constant/NamingConstant.h" +#include "constant/UtilAndComs.h" #include "utils/UuidUtils.h" #include "src/utils/NetUtils.h" #include "utils/RandomUtils.h" #include "src/json/JSON.h" #include "src/http/HttpStatus.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosExceptions.h" using namespace std; @@ -42,15 +42,15 @@ void NamingProxy::registerService(const NacosString &serviceName, const NacosStr getNamespaceId().c_str(), serviceName.c_str(), instance.toString().c_str()); list params; - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, serviceName); - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, groupName); - ParamUtils::addKV(params, NamingCommonParams::CLUSTER_NAME, instance.clusterName); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, serviceName); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, groupName); + ParamUtils::addKV(params, NamingConstant::CLUSTER_NAME, instance.clusterName); ParamUtils::addKV(params, "ip", instance.ip); ParamUtils::addKV(params, "port", NacosStringOps::valueOf(instance.port)); ParamUtils::addKV(params, "weight", NacosStringOps::valueOf(instance.weight)); ParamUtils::addKV(params, "enable", NacosStringOps::valueOf(instance.enabled)); - ParamUtils::addKV(params, "healthy", NacosStringOps::valueOf(instance.healthy)); + ParamUtils::addKV(params, NamingConstant::HEALTHY, NacosStringOps::valueOf(instance.healthy)); ParamUtils::addKV(params, "ephemeral", NacosStringOps::valueOf(instance.ephemeral)); ParamUtils::addKV(params, "metadata", JSON::toJSONString(instance.metadata)); @@ -62,9 +62,9 @@ void NamingProxy::deregisterService(const NacosString &serviceName, Instance &in getNamespaceId().c_str(), serviceName.c_str(), instance.toString().c_str()); list params; - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, serviceName); - ParamUtils::addKV(params, NamingCommonParams::CLUSTER_NAME, instance.clusterName); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, serviceName); + ParamUtils::addKV(params, NamingConstant::CLUSTER_NAME, instance.clusterName); ParamUtils::addKV(params, "ip", instance.ip); ParamUtils::addKV(params, "port", NacosStringOps::valueOf(instance.port)); ParamUtils::addKV(params, "ephemeral", NacosStringOps::valueOf(instance.ephemeral)); @@ -72,15 +72,17 @@ void NamingProxy::deregisterService(const NacosString &serviceName, Instance &in reqAPI(UtilAndComs::NACOS_URL_INSTANCE, params, IHttpCli::DELETE); } -NacosString NamingProxy::queryList(const NacosString &serviceName, const NacosString &clusters, int udpPort, - bool healthyOnly) throw(NacosException) { +NacosString NamingProxy::queryList(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters, + int udpPort, bool healthyOnly) throw(NacosException) { list params; - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, serviceName); - ParamUtils::addKV(params, "clusters", clusters); - ParamUtils::addKV(params, "udpPort", NacosStringOps::valueOf(udpPort)); - ParamUtils::addKV(params, "clientIP", NetUtils::localIP()); - ParamUtils::addKV(params, "healthyOnly", NacosStringOps::valueOf(healthyOnly)); + const NacosString &localIp = _objectConfigData->_appConfigManager->get(PropertyKeyConst::LOCAL_IP); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, serviceName); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, groupName); + ParamUtils::addKV(params, NamingConstant::CLUSTERS, clusters); + ParamUtils::addKV(params, NamingConstant::UDP_PORT, NacosStringOps::valueOf(udpPort)); + ParamUtils::addKV(params, NamingConstant::CLIENT_IP, localIp); + ParamUtils::addKV(params, NamingConstant::HEALTHY_ONLY, NacosStringOps::valueOf(healthyOnly)); return reqAPI(UtilAndComs::NACOS_URL_BASE + "/instance/list", params, IHttpCli::GET); } @@ -220,9 +222,6 @@ list NamingProxy::builderHeaders() { headers.push_back("Client-Version"); headers.push_back(UtilAndComs::VERSION); - headers.push_back("User-Agent"); - headers.push_back(UtilAndComs::UA_VERSION); - headers.push_back("Accept-Encoding"); headers.push_back("gzip,deflate,sdch"); @@ -242,9 +241,9 @@ long NamingProxy::sendBeat(BeatInfo &beatInfo) { NacosString beatInfoStr = beatInfo.toString(); log_info("[BEAT] %s sending beat to server: %s\n", getNamespaceId().c_str(), beatInfoStr.c_str()); list params; - ParamUtils::addKV(params, NamingCommonParams::BEAT, JSON::toJSONString(beatInfo)); - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, beatInfo.serviceName); + ParamUtils::addKV(params, NamingConstant::BEAT, JSON::toJSONString(beatInfo)); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, beatInfo.serviceName); NacosString result = reqAPI(UtilAndComs::NACOS_URL_BASE + "/instance/beat", params, IHttpCli::PUT); //JSONObject jsonObject = JSON.parseObject(result); @@ -264,10 +263,10 @@ ListView NamingProxy::getServiceList(int page, int pageSize, const { log_debug("[NAMEPRXY] request:group=%s page=%d pageSize=%d\n", groupName.c_str(), page, pageSize); list params; - ParamUtils::addKV(params, NamingCommonParams::PAGE_NO, NacosStringOps::valueOf(page)); - ParamUtils::addKV(params, NamingCommonParams::PAGE_SIZE, NacosStringOps::valueOf(pageSize)); - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, groupName); - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::PAGE_NO, NacosStringOps::valueOf(page)); + ParamUtils::addKV(params, NamingConstant::PAGE_SIZE, NacosStringOps::valueOf(pageSize)); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, groupName); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); NacosString result = reqAPI(UtilAndComs::NACOS_URL_BASE + "/service/list", params, IHttpCli::GET); if (!isNull(result)) { @@ -282,13 +281,13 @@ ServiceInfo2 NamingProxy::getServiceInfo(const NacosString &serviceName, const N log_debug("[NAMEPRXY] getServiceInfo request:serviceName=%s groupName=%s\n", serviceName.c_str(), groupName.c_str()); list params; - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, serviceName); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, serviceName); if (!NacosStringOps::isNullStr(groupName)) { - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, groupName); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, groupName); } else { - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, Constants::DEFAULT_GROUP); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, ConfigConstant::DEFAULT_GROUP); } - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); NacosString result = reqAPI(UtilAndComs::NACOS_URL_BASE + "/service", params, IHttpCli::GET); log_debug("NamingProxy::getServiceInfo: service info from server:%s\n", result.c_str()); @@ -319,9 +318,9 @@ bool areYouOk(const NacosString &imVeryOk) { */ bool NamingProxy::deleteServiceInfo(const NacosString &serviceName, const NacosString &groupName) throw(NacosException) { list params; - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, serviceName); - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, groupName); - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, serviceName); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, groupName); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); NacosString result = reqAPI(UtilAndComs::NACOS_URL_BASE + "/service", params, IHttpCli::DELETE); return areYouOk(result); @@ -329,13 +328,13 @@ bool NamingProxy::deleteServiceInfo(const NacosString &serviceName, const NacosS void assembleServiceInfoRequest(list &target, const ServiceInfo2 &serviceInfo2) { if (serviceInfo2.isNameSet()) { - ParamUtils::addKV(target, NamingCommonParams::SERVICE_NAME, serviceInfo2.getName()); + ParamUtils::addKV(target, NamingConstant::SERVICE_NAME, serviceInfo2.getName()); } if (serviceInfo2.isGroupNameSet()) { - ParamUtils::addKV(target, NamingCommonParams::GROUP_NAME, serviceInfo2.getGroupName()); + ParamUtils::addKV(target, NamingConstant::GROUP_NAME, serviceInfo2.getGroupName()); } if (serviceInfo2.isNamespaceIdSet()) { - ParamUtils::addKV(target, NamingCommonParams::NAMESPACE_ID, serviceInfo2.getNamespaceId()); + ParamUtils::addKV(target, NamingConstant::NAMESPACE_ID, serviceInfo2.getNamespaceId()); } if (serviceInfo2.isProtectThresholdSet()) { ParamUtils::addKV(target, "protectThreshold", NacosStringOps::valueOf(serviceInfo2.getProtectThreshold())); @@ -404,7 +403,7 @@ Instance NamingProxy::getServiceInstance ) throw(NacosException) { list paramsList; - ParamUtils::addKV(paramsList, NamingCommonParams::SERVICE_NAME, serviceName); + ParamUtils::addKV(paramsList, NamingConstant::SERVICE_NAME, serviceName); ParamUtils::addKV(paramsList, "ip", ip); ParamUtils::addKV(paramsList, "port", NacosStringOps::valueOf(port)); @@ -413,12 +412,12 @@ throw(NacosException) { ParamUtils::addKV(paramsList, it->first, it->second); } - if (params.count(NamingCommonParams::NAMESPACE_ID) == 0) { - ParamUtils::addKV(paramsList, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); + if (params.count(NamingConstant::NAMESPACE_ID) == 0) { + ParamUtils::addKV(paramsList, NamingConstant::NAMESPACE_ID, getNamespaceId()); } - if (params.count(NamingCommonParams::GROUP_NAME) == 0) { - ParamUtils::addKV(paramsList, NamingCommonParams::GROUP_NAME, Constants::DEFAULT_GROUP); + if (params.count(NamingConstant::GROUP_NAME) == 0) { + ParamUtils::addKV(paramsList, NamingConstant::GROUP_NAME, ConfigConstant::DEFAULT_GROUP); } NacosString result = reqAPI(UtilAndComs::NACOS_URL_BASE + "/instance", paramsList, IHttpCli::GET); @@ -428,24 +427,24 @@ throw(NacosException) { bool NamingProxy::updateServiceInstance(const Instance &instance) throw(NacosException) { list params; - ParamUtils::addKV(params, NamingCommonParams::SERVICE_NAME, instance.serviceName); + ParamUtils::addKV(params, NamingConstant::SERVICE_NAME, instance.serviceName); ParamUtils::addKV(params, "ip", instance.ip); ParamUtils::addKV(params, "port", NacosStringOps::valueOf(instance.port)); if (NacosStringOps::isNullStr(instance.groupName)) { - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, Constants::DEFAULT_GROUP); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, ConfigConstant::DEFAULT_GROUP); } else { - ParamUtils::addKV(params, NamingCommonParams::GROUP_NAME, instance.groupName); + ParamUtils::addKV(params, NamingConstant::GROUP_NAME, instance.groupName); } if (NacosStringOps::isNullStr(instance.namespaceId)) { - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, getNamespaceId()); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, getNamespaceId()); } else { - ParamUtils::addKV(params, NamingCommonParams::NAMESPACE_ID, instance.namespaceId); + ParamUtils::addKV(params, NamingConstant::NAMESPACE_ID, instance.namespaceId); } if (!NacosStringOps::isNullStr(instance.clusterName)) { - ParamUtils::addKV(params, NamingCommonParams::CLUSTER_NAME, instance.clusterName); + ParamUtils::addKV(params, NamingConstant::CLUSTER_NAME, instance.clusterName); } if (instance.metadata.size() > 0) { diff --git a/src/naming/NamingProxy.h b/src/naming/NamingProxy.h index cae621a..123b67b 100644 --- a/src/naming/NamingProxy.h +++ b/src/naming/NamingProxy.h @@ -55,8 +55,8 @@ class NamingProxy { void deregisterService(const NacosString &serviceName, Instance &instance) throw(NacosException); - NacosString queryList(const NacosString &serviceName, const NacosString &clusters, int udpPort, - bool healthyOnly) throw(NacosException); + NacosString queryList(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters, + int udpPort, bool healthyOnly) throw(NacosException); //service CRUD ListView getServiceList(int page, int pageSize, const NacosString &groupName) throw(NacosException); diff --git a/src/naming/beat/BeatInfo.h b/src/naming/beat/BeatInfo.h index 96e91f3..23bd80d 100644 --- a/src/naming/beat/BeatInfo.h +++ b/src/naming/beat/BeatInfo.h @@ -33,6 +33,7 @@ class BeatInfo { NacosString cluster; std::map metadata; volatile bool scheduled; + volatile long nextHbTime; NacosString toString(); }; diff --git a/src/naming/beat/BeatReactor.cpp b/src/naming/beat/BeatReactor.cpp index 53169cf..b0d5018 100644 --- a/src/naming/beat/BeatReactor.cpp +++ b/src/naming/beat/BeatReactor.cpp @@ -19,6 +19,7 @@ void BeatReactor::stop() { return; } _stop = true; + _beatMaster->kill(); _beatMaster->join(); _threadPool->stop(); } @@ -48,7 +49,7 @@ void *BeatReactor::beatMaster(void *param) { void BeatReactor::addBeatInfo(const NacosString &serviceName, BeatInfo &beatInfo) { NacosString beatInfoStr = beatInfo.toString(); - log_info("[BEAT] adding beat: %s to beat map.", beatInfoStr.c_str()); + log_info("[BEAT] adding beat: %s to beat map.\n", beatInfoStr.c_str()); BeatTask *beattask = new BeatTask(beatInfo, _objectConfigData); NacosString beatKey = buildKey(serviceName, beatInfo.ip, beatInfo.port); beattask->setTaskName(beatKey); @@ -96,7 +97,7 @@ bool BeatReactor::getBeatInfo(const NacosString &serviceName, const NacosString */ bool BeatReactor::modifyBeatInfo(const NacosString &serviceName, BeatInfo &beatInfo) { NacosString beatInfoStr = beatInfo.toString(); - log_info("[BEAT] modify beat: %s to beat map.", beatInfoStr.c_str()); + log_info("[BEAT] modify beat: %s to beat map.\n", beatInfoStr.c_str()); NacosString beatKey = buildKey(serviceName, beatInfo.ip, beatInfo.port); { LockGuard _lockguard(_beatInfoLock); @@ -161,7 +162,7 @@ void BeatReactor::removeAllBeatInfo() { } NacosString BeatReactor::buildKey(const NacosString &serviceName, const NacosString &ip, int port) { - return serviceName + Constants::NAMING_INSTANCE_ID_SPLITTER - + ip + Constants::NAMING_INSTANCE_ID_SPLITTER + NacosStringOps::valueOf(port); + return serviceName + ConfigConstant::NAMING_INSTANCE_ID_SPLITTER + + ip + ConfigConstant::NAMING_INSTANCE_ID_SPLITTER + NacosStringOps::valueOf(port); } }//namespace nacos diff --git a/src/naming/beat/BeatReactor.h b/src/naming/beat/BeatReactor.h index 0015fea..9848762 100644 --- a/src/naming/beat/BeatReactor.h +++ b/src/naming/beat/BeatReactor.h @@ -10,8 +10,8 @@ #include "src/thread/Thread.h" #include "src/thread/Mutex.h" #include "BeatTask.h" -#include "Constants.h" -#include "utils/UtilAndComs.h" +#include "constant/ConfigConstant.h" +#include "constant/UtilAndComs.h" #include "src/factory/ObjectConfigData.h" namespace nacos{ diff --git a/src/naming/beat/BeatTask.cpp b/src/naming/beat/BeatTask.cpp index c8f8c4e..6472a59 100644 --- a/src/naming/beat/BeatTask.cpp +++ b/src/naming/beat/BeatTask.cpp @@ -2,7 +2,7 @@ #include "BeatReactor.h" #include "BeatTask.h" #include "NacosString.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; diff --git a/src/naming/beat/BeatTask.h b/src/naming/beat/BeatTask.h index 167e020..4b63fbb 100644 --- a/src/naming/beat/BeatTask.h +++ b/src/naming/beat/BeatTask.h @@ -6,7 +6,7 @@ #include "BeatReactor.h" #include "src/thread/ThreadPool.h" #include "thread/AtomicInt.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "src/factory/ObjectConfigData.h" namespace nacos{ diff --git a/src/naming/subscribe/HostReactor.cpp b/src/naming/subscribe/HostReactor.cpp new file mode 100644 index 0000000..ce62bda --- /dev/null +++ b/src/naming/subscribe/HostReactor.cpp @@ -0,0 +1,55 @@ +// +// Created by liuhanyu on 2021/1/7. +// + +#include "HostReactor.h" +#include "src/json/JSON.h" +#include "utils/NamingUtils.h" +#include "src/naming/subscribe/EventDispatcher.h" + +namespace nacos { + +HostReactor::HostReactor(ObjectConfigData *objectConfigData) { + _objectConfigData = objectConfigData; +} + +void HostReactor::processServiceJson(const NacosString &json) { + ServiceInfo serviceInfo = JSON::JsonStr2ServiceInfo(json); + + NacosString name = NamingUtils::getGroupedName(serviceInfo.getName(), serviceInfo.getGroupName()); + NacosString key = ServiceInfo::getKey(name, serviceInfo.getClusters()); + ServiceInfo oldServiceInfo; + bool newServiceInfo = false; + { + WriteGuard _writeGuard(rwLock); + if (serviceInfoMap.count(key) == 0) { + serviceInfoMap[key] = serviceInfo; + newServiceInfo = true; + } else { + oldServiceInfo = serviceInfoMap[key]; + if (oldServiceInfo.getLastRefTime() >= serviceInfo.getLastRefTime()) { + log_warn("ServiceInfo got from server is older than the one in client.\n"); + return; + } + serviceInfoMap[key] = serviceInfo;//update local service info to the new one + } + } + ChangeAdvice changeAdvice; + changeAdvice.key = key; + if (newServiceInfo) { + changeAdvice.added = true; + changeAdvice.newServiceInfo = serviceInfo; + _objectConfigData->_eventDispatcher->notifyDirectly(changeAdvice); + } else {//service info is updated + ChangeAdvice::compareChange(oldServiceInfo, serviceInfo, changeAdvice); + log_debug("Change status:modified:%d added:%d removed:%d\n", changeAdvice.modified, changeAdvice.added, + changeAdvice.removed); + if (changeAdvice.modified || changeAdvice.added || changeAdvice.removed) { + //asm volatile("int $3"); + changeAdvice.newServiceInfo = serviceInfo; + _objectConfigData->_eventDispatcher->notifyDirectly(changeAdvice); + } + } +} + +} \ No newline at end of file diff --git a/src/naming/subscribe/HostReactor.h b/src/naming/subscribe/HostReactor.h new file mode 100644 index 0000000..cf76ab9 --- /dev/null +++ b/src/naming/subscribe/HostReactor.h @@ -0,0 +1,29 @@ +// +// Created by liuhanyu on 2021/1/7. +// + +#ifndef NACOS_SDK_CPP_HOSTREACTOR_H +#define NACOS_SDK_CPP_HOSTREACTOR_H +#include +#include "NacosString.h" +#include "naming/ServiceInfo.h" +#include "src/factory/ObjectConfigData.h" +#include "src/thread/RWLock.h" + +namespace nacos { + +class HostReactor { +private: + ObjectConfigData *_objectConfigData; + //memory cache + std::map serviceInfoMap; + //rw lock for serviceInfoMap + RWLock rwLock; +public: + HostReactor(ObjectConfigData *objectConfigData); + void processServiceJson(const NacosString &json); +}; + +} + +#endif //NACOS_SDK_CPP_HOSTREACTOR_H diff --git a/src/naming/subscribe/TcpNamingServicePoller.cpp b/src/naming/subscribe/SubscriptionPoller.cpp similarity index 63% rename from src/naming/subscribe/TcpNamingServicePoller.cpp rename to src/naming/subscribe/SubscriptionPoller.cpp index 1c6b1d1..061db49 100644 --- a/src/naming/subscribe/TcpNamingServicePoller.cpp +++ b/src/naming/subscribe/SubscriptionPoller.cpp @@ -1,20 +1,22 @@ -#include "TcpNamingServicePoller.h" -#include "Constants.h" +#include "SubscriptionPoller.h" +#include "constant/ConfigConstant.h" #include "utils/NamingUtils.h" #include "src/json/JSON.h" +#include "HostReactor.h" using namespace std; namespace nacos{ -TcpNamingServicePoller::TcpNamingServicePoller(ObjectConfigData *objectConfigData) +SubscriptionPoller::SubscriptionPoller(ObjectConfigData *objectConfigData) { _objectConfigData = objectConfigData; _pollingThread = new Thread("NamingServicePoller", pollingThreadFunc, (void*)this); - _pollingInterval = atoi(_objectConfigData->_appConfigManager->get(PropertyKeyConst::TCP_NAMING_POLL_INTERVAL).c_str()); + _pollingInterval = atoi(_objectConfigData->_appConfigManager->get(PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL).c_str()); + _udpPort = atoi(_objectConfigData->_appConfigManager->get(PropertyKeyConst::UDP_RECEIVER_PORT).c_str()); _started = false; } -TcpNamingServicePoller::~TcpNamingServicePoller() +SubscriptionPoller::~SubscriptionPoller() { if (_started) { stop(); @@ -26,7 +28,7 @@ TcpNamingServicePoller::~TcpNamingServicePoller() } } -bool TcpNamingServicePoller::addPollItem(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters) +bool SubscriptionPoller::addPollItem(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters) { struct PollingData pd; pd.clusters = clusters; @@ -45,7 +47,7 @@ bool TcpNamingServicePoller::addPollItem(const NacosString &serviceName, const N } } -bool TcpNamingServicePoller::removePollItem(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters) +bool SubscriptionPoller::removePollItem(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters) { NacosString name = NamingUtils::getGroupedName(serviceName, groupName); NacosString key = ServiceInfo::getKey(name, clusters); @@ -59,32 +61,33 @@ bool TcpNamingServicePoller::removePollItem(const NacosString &serviceName, cons return true; } -void TcpNamingServicePoller::start() +void SubscriptionPoller::start() { if (_started) { - log_warn("Calling start on already-started TcpNamingServicePoller\n"); + log_warn("Calling start on already-started SubscriptionPoller\n"); return; } _started = true; _pollingThread->start(); } -void TcpNamingServicePoller::stop() +void SubscriptionPoller::stop() { if (!_started) { - log_warn("Calling stop on already-stopped TcpNamingServicePoller\n"); + log_warn("Calling stop on already-stopped SubscriptionPoller\n"); return; } _started = false; + _pollingThread->kill(); _pollingThread->join(); } -void *TcpNamingServicePoller::pollingThreadFunc(void *parm) +void *SubscriptionPoller::pollingThreadFunc(void *parm) { - TcpNamingServicePoller *thisObj = (TcpNamingServicePoller*)parm; + SubscriptionPoller *thisObj = (SubscriptionPoller*)parm; while (thisObj->_started) { - log_debug("TcpNamingServicePoller::pollingThreadFunc start polling, interval = %d\n", thisObj->_pollingInterval); + log_debug("SubscriptionPoller::pollingThreadFunc start polling, interval = %d\n", thisObj->_pollingInterval); map copiedList; { ReadGuard __readGuard(thisObj->rwLock); @@ -106,7 +109,7 @@ void *TcpNamingServicePoller::pollingThreadFunc(void *parm) NacosString result; try { result = thisObj->_objectConfigData->_serverProxy->queryList( - it->second.serviceName, it->second.clusters, 0,false); + it->second.serviceName, it->second.groupName, it->second.clusters, thisObj->_udpPort,false); } catch (NacosException &e) { //no server available or all servers tried but failed @@ -122,23 +125,8 @@ void *TcpNamingServicePoller::pollingThreadFunc(void *parm) } log_debug("Server info got from server:%s\n=======>\n", result.c_str()); - ServiceInfo serviceInfo = JSON::JsonStr2ServiceInfo(result); - if (thisObj->serviceInfoList.count(key) == 0) { - //The first time, don't notify - thisObj->serviceInfoList[key] = serviceInfo; - } else { - ServiceInfo oldServiceInfo = thisObj->serviceInfoList[key]; - ChangeAdvice changeAdvice; - changeAdvice.key = key; - ChangeAdvice::compareChange(oldServiceInfo, serviceInfo, changeAdvice); - log_debug("Change status:modified:%d added:%d removed:%d\n", changeAdvice.modified, changeAdvice.added, changeAdvice.removed); - if (changeAdvice.modified || changeAdvice.added || changeAdvice.removed) { - //asm volatile("int $3"); - changeAdvice.newServiceInfo = serviceInfo; - thisObj->_objectConfigData->_eventDispatcher->notifyDirectly(changeAdvice); - } - thisObj->serviceInfoList[key] = serviceInfo;//update local service info to the new one - } + + thisObj->_objectConfigData->_hostReactor->processServiceJson(result); } log_debug("Polling process finished, hibernating...\n"); diff --git a/src/naming/subscribe/TcpNamingServicePoller.h b/src/naming/subscribe/SubscriptionPoller.h similarity index 68% rename from src/naming/subscribe/TcpNamingServicePoller.h rename to src/naming/subscribe/SubscriptionPoller.h index 1a4cc73..09b68d3 100644 --- a/src/naming/subscribe/TcpNamingServicePoller.h +++ b/src/naming/subscribe/SubscriptionPoller.h @@ -2,8 +2,8 @@ // Created by liuhanyu on 2020/9/26. // -#ifndef NACOS_SDK_CPP_TCPNAMINGSERVICEPOLLER_H -#define NACOS_SDK_CPP_TCPNAMINGSERVICEPOLLER_H +#ifndef NACOS_SDK_CPP_SUBSCRIPTIONPOLLER_H +#define NACOS_SDK_CPP_SUBSCRIPTIONPOLLER_H #include #include "src/thread/Thread.h" @@ -17,32 +17,34 @@ struct PollingData NacosString serviceName; NacosString groupName; NacosString clusters; + volatile long nextPollTime; }; -class TcpNamingServicePoller +class SubscriptionPoller { private: Thread *_pollingThread = NULL; int _pollingInterval;//In ms - bool _started; + int _udpPort;//udp receiver port + volatile bool _started; ObjectConfigData *_objectConfigData; - TcpNamingServicePoller(); + SubscriptionPoller(); static void *pollingThreadFunc(void *parm); + //for polling list RWLock rwLock; std::map pollingList; - std::map serviceInfoList; public: - TcpNamingServicePoller(ObjectConfigData *objectConfigData); + SubscriptionPoller(ObjectConfigData *objectConfigData); bool addPollItem(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters); bool removePollItem(const NacosString &serviceName, const NacosString &groupName, const NacosString &clusters); void start(); void stop(); - ~TcpNamingServicePoller(); + ~SubscriptionPoller(); }; }//namespace nacos -#endif //NACOS_SDK_CPP_TCPNAMINGSERVICEPOLLER_H +#endif //NACOS_SDK_CPP_SUBSCRIPTIONPOLLER_H diff --git a/src/naming/subscribe/UdpNamingServiceListener.cpp b/src/naming/subscribe/UdpNamingServiceListener.cpp new file mode 100644 index 0000000..891f614 --- /dev/null +++ b/src/naming/subscribe/UdpNamingServiceListener.cpp @@ -0,0 +1,137 @@ +#include +#include +#include + +#include "UdpNamingServiceListener.h" +#include "src/config/AppConfigManager.h" +#include "constant/PropertyKeyConst.h" +#include "src/json/JSON.h" +#include "HostReactor.h" + +#include +using namespace std; + +namespace nacos { + +void UdpNamingServiceListener::initializeUdpListener() throw(NacosException) { + log_debug("in thread UdpNamingServiceListener::initializeUdpListener()\n"); + // Creating socket file descriptor + if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { + throw NacosException(NacosException::UNABLE_TO_CREATE_SOCKET, "Unable to create socket"); + } + + memset(&cliaddr, 0, sizeof(cliaddr)); + + // Filling client information + cliaddr.sin_family = AF_INET; // IPv4 + cliaddr.sin_addr.s_addr = INADDR_ANY; + cliaddr.sin_port = htons(udpReceiverPort); + log_debug("udp receiver port = %d\n", cliaddr.sin_port); + + // Bind the socket with the server address + if ( bind(sockfd, (const struct sockaddr *)&cliaddr, + sizeof(cliaddr)) < 0 ) + { + throw NacosException(NacosException::UNABLE_TO_CREATE_SOCKET, "Unable to bind"); + } + + log_debug("socket bound\n"); +} + +void *UdpNamingServiceListener::listenerThreadFunc(void *param) { + UdpNamingServiceListener *thisObj = (UdpNamingServiceListener*)param; + log_debug("in thread UdpNamingServiceListener::listenerThreadFunc()\n"); + thisObj->initializeUdpListener(); + while (thisObj->_started) { + int ret;//also data_len + + log_debug("before recvfrom() socketfd:%d\n", thisObj->sockfd); + struct sockaddr src_addr; + socklen_t src_addr_len; + ret = recvfrom(thisObj->sockfd, (char *)thisObj->receiveBuffer, UDP_MSS, MSG_WAITALL, &src_addr, &src_addr_len); + log_debug("ret got from recvfrom():%d\n", ret); + + if (ret == -1) { + if (errno == EINTR) { + log_debug("got sigint from main thread, exiting...\n"); + //got kill() signal from main thread, free resources & exit + } + //other kinds of error + break; + } + //parse the package + thisObj->receiveBuffer[ret] = 0; + log_debug("content got from UDP server is %s\n", thisObj->receiveBuffer); + PushPacket pushPacket; + + try { + pushPacket = JSON::Json2PushPacket(thisObj->receiveBuffer); + } catch (NacosException &e) { + log_error("Invalid json string got from server:%s\n", thisObj->receiveBuffer); + continue; + } + + NacosString ack; + + if (pushPacket.type == "dom" || pushPacket.type == "service") { + thisObj->_objectConfigData->_hostReactor->processServiceJson(pushPacket.data); + + // send ack to server + ack = "{\"type\": \"push-ack\", \"lastRefTime\":\"" + NacosStringOps::valueOf(pushPacket.lastRefTime) + "\", \"data\":\"\"}"; + } else if (pushPacket.type == "dump") { + // dump data to server + //TODO:Unimplemented + ack = "{\"type\": \"dump-ack\", \"lastRefTime\": \"" + NacosStringOps::valueOf(pushPacket.lastRefTime) + "\", \"data\":\"\"}"; + } else { + // do nothing & send ack only + ack = "{\"type\": \"unknown-ack\", \"lastRefTime\":\"" + NacosStringOps::valueOf(pushPacket.lastRefTime) + + "\", \"data\":\"\"}"; + } + + ssize_t recv_ret = sendto(thisObj->sockfd, ack.c_str(), ack.length(), 0, &src_addr, src_addr_len); + if (recv_ret < 0) { + log_error("error while sending data...%d", errno); + } + } + + close(thisObj->sockfd); + return NULL; +} + +UdpNamingServiceListener::UdpNamingServiceListener(ObjectConfigData *objectConfigData) { + _started = false; + _objectConfigData = objectConfigData; + udpReceiverPort = atoi(_objectConfigData->_appConfigManager->get(PropertyKeyConst::UDP_RECEIVER_PORT).c_str()); + log_debug("udpReceiverPort is %d\n", udpReceiverPort); + _listenerThread = new Thread(objectConfigData->name + "UDPListener", listenerThreadFunc, (void*)this); +} + +void UdpNamingServiceListener::start() { + if (_started) { + return; + } + + _started = true; + _listenerThread->start(); +} + +void UdpNamingServiceListener::stop() { + if (!_started) { + return; + } + + _started = false; + _listenerThread->kill(); + _listenerThread->join(); +} + +UdpNamingServiceListener::~UdpNamingServiceListener() { + if (_started) { + stop(); + } + if (_listenerThread != NULL) { + delete _listenerThread; + } +} + +} diff --git a/src/naming/subscribe/UdpNamingServiceListener.h b/src/naming/subscribe/UdpNamingServiceListener.h index 9c18302..f1fbbf2 100644 --- a/src/naming/subscribe/UdpNamingServiceListener.h +++ b/src/naming/subscribe/UdpNamingServiceListener.h @@ -5,6 +5,41 @@ #ifndef NACOS_SDK_CPP_UDPLSNR_H_ #define NACOS_SDK_CPP_UDPLSNR_H_ +#include +#include +#include +#include +#include "src/factory/ObjectConfigData.h" +#include "src/thread/Thread.h" + +#define UDP_MSS 64 * 1024 + namespace nacos{ + +typedef struct { + NacosString type; + long lastRefTime; + NacosString data; +} PushPacket; + +class UdpNamingServiceListener { +private: + ObjectConfigData *_objectConfigData; + volatile bool _started; + int sockfd; + int udpReceiverPort; + struct sockaddr_in cliaddr; + char receiveBuffer[UDP_MSS]; + Thread *_listenerThread = NULL; + + void initializeUdpListener() throw(NacosException); + static void *listenerThreadFunc(void *param); +public: + UdpNamingServiceListener(ObjectConfigData *objectConfigData); + ~UdpNamingServiceListener(); + void start(); + void stop(); +}; + }//namespace nacos #endif //NACOS_SDK_CPP_UDPLSNR_H_ diff --git a/src/security/SecurityManager.cpp b/src/security/SecurityManager.cpp index a30dd78..50bfd59 100644 --- a/src/security/SecurityManager.cpp +++ b/src/security/SecurityManager.cpp @@ -16,7 +16,7 @@ SecurityManager::SecurityManager(ObjectConfigData *objectConfigData) { } void SecurityManager::doLogin(const NacosString &serverAddr) throw(NacosException, NetworkException) { //TODO:refactor string constants - NacosString url = serverAddr + "/" + Constants::DEFAULT_CONTEXT_PATH + "/v1/auth/users/login"; + NacosString url = serverAddr + "/" + ConfigConstant::DEFAULT_CONTEXT_PATH + "/v1/auth/users/login"; list headers; list paramValues; @@ -138,6 +138,7 @@ void SecurityManager::stop() { return; } _started = false; + _tokenRefreshThread->kill(); _tokenRefreshThread->join(); } }//nacos \ No newline at end of file diff --git a/src/server/ServerListManager.cpp b/src/server/ServerListManager.cpp index 7854587..639ca39 100644 --- a/src/server/ServerListManager.cpp +++ b/src/server/ServerListManager.cpp @@ -1,9 +1,9 @@ #include #include #include "ServerListManager.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "utils/ParamUtils.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "src/json/JSON.h" using namespace std; @@ -99,7 +99,7 @@ void ServerListManager::initAll() throw(NacosException) { serverList.sort(); } else {//use endpoint mode to pull nacos server info from server if (!props.contains(PropertyKeyConst::ENDPOINT)) { - throw NacosException(NacosException::CLIENT_INVALID_PARAM, "endpoint is blank"); + throw NacosException(NacosException::CLIENT_INVALID_PARAM, "no server address specified and the endpoint is blank"); } isFixed = false; @@ -150,8 +150,8 @@ list ServerListManager::tryPullServerListFromNacosServer() thr log_debug("Trying to access server:%s\n", server.getCompleteAddress().c_str()); try { HttpResult serverRes = _objectConfigData->_httpDelegate->httpGet( - server.getCompleteAddress() + "/" + Constants::DEFAULT_CONTEXT_PATH + "/" - + Constants::PROTOCOL_VERSION + "/" + Constants::GET_SERVERS_PATH, + server.getCompleteAddress() + "/" + ConfigConstant::DEFAULT_CONTEXT_PATH + "/" + + ConfigConstant::PROTOCOL_VERSION + "/" + ConfigConstant::GET_SERVERS_PATH, headers, paramValues, NULLSTR, _read_timeout); return JSON::Json2NacosServerInfo(serverRes.content); } diff --git a/src/server/ServerListManager.h b/src/server/ServerListManager.h index 93f928c..f22d9e0 100644 --- a/src/server/ServerListManager.h +++ b/src/server/ServerListManager.h @@ -9,7 +9,7 @@ #include "src/http/HttpDelegate.h" #include "src/thread/Thread.h" #include "src/config/AppConfigManager.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "src/thread/RWLock.h" #include "src/factory/ObjectConfigData.h" diff --git a/src/thread/Thread.cpp b/src/thread/Thread.cpp new file mode 100644 index 0000000..fea1112 --- /dev/null +++ b/src/thread/Thread.cpp @@ -0,0 +1,60 @@ +#include "Thread.h" + +using namespace nacos; + +struct sigaction Thread::old_action; + +void Thread::Init() { + struct sigaction action; + + action.sa_flags = 0; + action.sa_handler = empty_signal_handler; + sigemptyset(&action.sa_mask); + + sigaction(THREAD_STOP_SIGNAL, &action, &Thread::old_action); +}; + +void Thread::DeInit() { + sigaction(THREAD_STOP_SIGNAL, &Thread::old_action, NULL); +}; + +void *Thread::threadFunc(void *param) { + Thread *currentThread = (Thread *) param; + //currentThread->_tid = gettidv1(); + + try { + return currentThread->_function(currentThread->_threadData); + } + catch (std::exception &e) { + currentThread->_function = NULL; + log_error("Exception happens when executing:\n"); + log_error("Thread Name:%s Thread Id:%d\n", currentThread->_threadName.c_str(), currentThread->_tid); + log_error("Raison:%s", e.what()); + abort(); + } + catch (...) { + currentThread->_function = NULL; + log_error("Unknown exception happens when executing:\n"); + log_error("Thread Name:%s Thread Id:%d\n", currentThread->_threadName.c_str(), currentThread->_tid); + throw; + } +} + +void Thread::start() { + _start = true; + pthread_create(&_thread, NULL, threadFunc, (void *) this); +} + +void Thread::join() { + log_debug("Calling Thread::join() on %s\n", _threadName.c_str()); + if (!_start) { + log_debug("Thread::join() called on stopped thread for %s\n", _threadName.c_str()); + return; + } + + pthread_join(_thread, NULL); +} + +void Thread::kill() { + pthread_kill(_thread, THREAD_STOP_SIGNAL); +} \ No newline at end of file diff --git a/src/thread/Thread.h b/src/thread/Thread.h index d67a67a..aedb21c 100644 --- a/src/thread/Thread.h +++ b/src/thread/Thread.h @@ -3,12 +3,14 @@ #include #include +#include #include //#include #include "NacosString.h" -#include "Debug.h" +#include "src/log/Logger.h" #define gettidv1() ::syscall(__NR_gettid) +#define THREAD_STOP_SIGNAL SIGUSR1 namespace nacos{ typedef void *(*ThreadFn)(void *); @@ -32,32 +34,18 @@ class Thread { void *_threadData; Thread() {}; + + static void empty_signal_handler(int signum) {}; + static struct sigaction old_action; public: + static void Init(); + static void DeInit(); + void setThreadName(const NacosString &threadName) { _threadName = threadName; }; NacosString getThreadName() { return _threadName; }; - static void *threadFunc(void *param) { - Thread *currentThread = (Thread *) param; - //currentThread->_tid = gettidv1(); - - try { - return currentThread->_function(currentThread->_threadData); - } - catch (std::exception &e) { - currentThread->_function = NULL; - log_error("Exception happens when executing:\n"); - log_error("Thread Name:%s Thread Id:%d\n", currentThread->_threadName.c_str(), currentThread->_tid); - log_error("Raison:%s", e.what()); - abort(); - } - catch (...) { - currentThread->_function = NULL; - log_error("Unknown exception happens when executing:\n"); - log_error("Thread Name:%s Thread Id:%d\n", currentThread->_threadName.c_str(), currentThread->_tid); - throw; - } - } + static void *threadFunc(void *param); Thread(const NacosString &threadName, ThreadFn fn) : _threadName(threadName), _function(fn), _threadData(NULL) { @@ -73,20 +61,11 @@ class Thread { _start = false; } - void start() { - _start = true; - pthread_create(&_thread, NULL, threadFunc, (void *) this); - } + void start(); - void join() { - log_debug("Calling Thread::join() on %s\n", _threadName.c_str()); - if (!_start) { - log_debug("Thread::join() called on stopped thread for %s\n", _threadName.c_str()); - return; - } + void join(); - pthread_join(_thread, NULL); - } + void kill(); }; }//namespace nacos diff --git a/src/thread/ThreadLocal.h b/src/thread/ThreadLocal.h index e08ba24..500cb01 100644 --- a/src/thread/ThreadLocal.h +++ b/src/thread/ThreadLocal.h @@ -2,7 +2,7 @@ #define __THREAD_LOCAL_H_ #include -#include "Debug.h" +#include "src/log/Logger.h" namespace nacos{ template diff --git a/src/thread/ThreadPool.cpp b/src/thread/ThreadPool.cpp index 27056d7..008bb31 100644 --- a/src/thread/ThreadPool.cpp +++ b/src/thread/ThreadPool.cpp @@ -1,6 +1,5 @@ #include #include "ThreadPool.h" -#include "Thread.h" using namespace std; diff --git a/src/utils/ConfigParserUtils.cpp b/src/utils/ConfigParserUtils.cpp new file mode 100644 index 0000000..78d4c09 --- /dev/null +++ b/src/utils/ConfigParserUtils.cpp @@ -0,0 +1,57 @@ +// +// Created by liuhanyu on 2021/1/9. +// + +#include +#include "ConfigParserUtils.h" +#include "src/config/IOUtils.h" +#include "utils/ParamUtils.h" +#include "constant/ConfigConstant.h" +using namespace std; + +namespace nacos { + +Properties ConfigParserUtils::parseConfigFile(const NacosString &file) throw(NacosException) { + Properties parsedConfig; + NacosString confContent = IOUtils::readStringFromFile(file, NULLSTR);//TODO: add encoding support + + vector configList; + ParamUtils::Explode(configList, confContent, ConfigConstant::CONFIG_NEXT_LINE); + + int line = 0; + for (vector::iterator it = configList.begin(); + it != configList.end(); it++) { + line++; + NacosString trimmedLine = ParamUtils::trim(*it); + if (ParamUtils::isBlank(trimmedLine)) { + continue; + } + + if (trimmedLine[0] == '#') { + //skip comment + continue; + } + + if (it->find(ConfigConstant::CONFIG_KV_SEPARATOR) == std::string::npos) { + throw MalformedConfigException(file, " no '=' found at line " + NacosStringOps::valueOf(line)); + } + + vector configKV; + ParamUtils::Explode(configKV, *it, ConfigConstant::CONFIG_KV_SEPARATOR); + //k = v + NacosString key = ParamUtils::trim(configKV[0]); + if (ParamUtils::isBlank(key)) { + throw MalformedConfigException(file, " key is blank at " + NacosStringOps::valueOf(line)); + } + + if (configKV.size() == 1) { + parsedConfig[key] = NULLSTR; + } else { + parsedConfig[key] = configKV[1]; + } + } + + return parsedConfig; +} + +} \ No newline at end of file diff --git a/src/utils/ConfigParserUtils.h b/src/utils/ConfigParserUtils.h new file mode 100644 index 0000000..92a6e3a --- /dev/null +++ b/src/utils/ConfigParserUtils.h @@ -0,0 +1,20 @@ +// +// Created by liuhanyu on 2021/1/9. +// + +#ifndef NACOS_SDK_CPP_CONFIGPARSERUTILS_H +#define NACOS_SDK_CPP_CONFIGPARSERUTILS_H +#include "Properties.h" +#include "NacosExceptions.h" + +namespace nacos { + +class ConfigParserUtils { +public: + static Properties parseConfigFile(const NacosString &file) throw(NacosException); + +}; + +} + +#endif //NACOS_SDK_CPP_CONFIGPARSERUTILS_H diff --git a/src/utils/NetUtils.cpp b/src/utils/NetUtils.cpp index 5237df7..15507c9 100644 --- a/src/utils/NetUtils.cpp +++ b/src/utils/NetUtils.cpp @@ -1,8 +1,47 @@ #include "NetUtils.h" +#include +#include +#include +#include +#include +#include namespace nacos{ -NacosString NetUtils::localIP() { - return "127.0.0.1";//TODO:read local ip; +NacosString NetUtils::getHostIp() throw(NacosException){ + + struct ifaddrs *ifaddr, *ifa; + int s; + char host[NI_MAXHOST]; + + if (getifaddrs(&ifaddr) == -1) + { + throw NacosException(NacosException::UNABLE_TO_GET_HOST_IP, "Failed to get IF address"); + } + + + for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { + log_debug("iterating on iface=%s\n", ifa->ifa_name); + if (ifa->ifa_addr == NULL || !(ifa->ifa_addr->sa_family==AF_INET)) { + continue; + } + + if((strcmp(ifa->ifa_name,"lo")==0)) { + continue; + } + + s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); + if (s != 0) { + freeifaddrs(ifaddr); + throw NacosException(NacosException::UNABLE_TO_GET_HOST_IP, "Failed to get IF address"); + } + + log_debug("selected iface=%s ip=%s\n", ifa->ifa_name, host); + freeifaddrs(ifaddr); + return host; + } + //Usually the program will not run to here + throw NacosException(NacosException::UNABLE_TO_GET_HOST_IP, "Failed to get IF address"); } }//namespace nacos diff --git a/src/utils/NetUtils.h b/src/utils/NetUtils.h index 38bbdd5..e761646 100644 --- a/src/utils/NetUtils.h +++ b/src/utils/NetUtils.h @@ -2,11 +2,13 @@ #define __NET_UTILS_H_ #include "NacosString.h" +#include "NacosExceptions.h" namespace nacos{ class NetUtils { public: - static NacosString localIP(); + //Get IP address (best guess) + static NacosString getHostIp() throw(NacosException); }; }//namespace nacos diff --git a/test/allinone.cpp b/test/allinone.cpp index 837eaf3..d764643 100644 --- a/test/allinone.cpp +++ b/test/allinone.cpp @@ -1,6 +1,8 @@ #include #include #include "DebugAssertion.h" +#include "src/init/Init.h" +#include using namespace std; using namespace nacos; @@ -53,6 +55,8 @@ bool testURLEncodeAndDecode(); bool testStringExplode(); +bool testStringExplode2(); + bool testNamingProxySmokeTest(); bool testNamingServiceRegister(); @@ -115,9 +119,10 @@ bool testPublishConfigWithHttpPrefix(); bool testRemoveKeyBeingWatched(); -TestData testList1[] = -TEST_ITEM_START +bool testGetHostIp(); +TestData disabledTestList[] = +TEST_ITEM_START TEST_ITEM_END TestData @@ -147,7 +152,7 @@ TEST_ITEM_START TEST_ITEM("Test MD5", testMD5) TEST_ITEM("Endpoint function test, get available nacos server from endpoint", testEndpointWithNamingProxy) TEST_ITEM("Test urlencode/urldecode of libcurl", testURLEncodeAndDecode) - TEST_ITEM("Test Listener function for nacos", testAddListener) + TEST_ITEM("Test Config Listener function for nacos", testAddListener) TEST_ITEM("Test basic function of NamingProxy's registerService", testNamingProxySmokeTest) TEST_ITEM("Check whether rapidjson is introduced into the project successfully", testRapidJsonIntroduce) TEST_ITEM("Check if the serialization succeeds", testSerialize) @@ -161,6 +166,7 @@ TEST_ITEM_START TEST_ITEM("Register many services and get one", testGetAllInstances) TEST_ITEM("Listen to key and remove it from listening list", testListeningKeys) TEST_ITEM("Test explode function", testStringExplode) + TEST_ITEM("Test explode function version 2 enhanced", testStringExplode2) TEST_ITEM("AppConfigManager smoke test", testAppConfigManager) TEST_ITEM("ServerListManager smoke test", testServerListManager) TEST_ITEM("Test UUID generation", testUUID) @@ -179,14 +185,17 @@ TEST_ITEM_START TEST_ITEM("MaintainService: testMaintainUpdateInstance", testMaintainUpdateInstance) TEST_ITEM("Test with address config containing http prefix", testPublishConfigWithHttpPrefix) TEST_ITEM("Test with address config containing http prefix", testRemoveKeyBeingWatched) + TEST_ITEM("Get local machine's IP", testGetHostIp) TEST_ITEM_END int main() { + Init::doInit(); + list failed_list; cout << "Please start a nacos server listening on port 8848 in this machine first." << endl; cout << "And when the server is ready, press any key to start the test." << endl; getchar(); int nr_succ = 0, nr_fail = 0; - //Debug::set_debug_level(DEBUG); + Logger::setLogLevel(DEBUG); cout << "BEGIN OF TESTS" << endl; cout << "===========================" << endl; for (size_t i = 0; i < sizeof(testList) / sizeof(TestData); i++) { @@ -196,6 +205,7 @@ int main() { bool pass = testfunction(); if (!pass) { cout << "FAILED" << endl; + failed_list.push_back(curtest); nr_fail++; } else { cout << "PASSED!" << endl; @@ -203,6 +213,15 @@ int main() { } cout << "===========================" << endl; } + + if (!failed_list.empty()) { + cout << "List of failed cases:" << endl; + for (list::iterator it = failed_list.begin(); it != failed_list.end(); it++) { + cout << (*it)->testName << endl; + } + cout << "===========================" << endl; + } + cout << "SUMMARY" << endl; cout << "Total:" << nr_succ + nr_fail << endl; cout << "Succ:" << nr_succ << endl; diff --git a/test/testcase/DebugTest.cpp b/test/testcase/DebugTest.cpp index 19eef06..73639f1 100644 --- a/test/testcase/DebugTest.cpp +++ b/test/testcase/DebugTest.cpp @@ -1,4 +1,4 @@ -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; diff --git a/test/testcase/testAppConfigManager.cpp b/test/testcase/testAppConfigManager.cpp index 456f623..f4ce13f 100644 --- a/test/testcase/testAppConfigManager.cpp +++ b/test/testcase/testAppConfigManager.cpp @@ -1,8 +1,7 @@ #include #include "src/config/AppConfigManager.h" -#include "PropertyKeyConst.h" #include "utils/DirUtils.h" -#include "Constants.h" +#include "constant/ConfigConstant.h" using namespace std; using namespace nacos; @@ -10,7 +9,7 @@ using namespace nacos; bool testAppConfigManager() { cout << "in function testAppConfigManager" << endl; - NacosString configFile = DirUtils::getCwd() + Constants::FILE_SEPARATOR + PropertyKeyConst::CONFIG_FILE_NAME; + NacosString configFile = DirUtils::getCwd() + ConfigConstant::FILE_SEPARATOR + ConfigConstant::DEFAULT_CONFIG_FILE; AppConfigManager appConfigManager(configFile); appConfigManager.loadConfig(configFile); Properties configs = appConfigManager.getAllConfig(); diff --git a/test/testcase/testDeleteConfig.cpp b/test/testcase/testDeleteConfig.cpp index e6550c9..c998cfb 100644 --- a/test/testcase/testDeleteConfig.cpp +++ b/test/testcase/testDeleteConfig.cpp @@ -1,7 +1,7 @@ #include #include #include "factory/NacosServiceFactory.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" #include "ResourceGuard.h" diff --git a/test/testcase/testDeleteListenedKeys.cpp b/test/testcase/testDeleteListenedKeys.cpp index 0fc34bc..25cdd46 100644 --- a/test/testcase/testDeleteListenedKeys.cpp +++ b/test/testcase/testDeleteListenedKeys.cpp @@ -5,9 +5,9 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "listen/Listener.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; @@ -29,7 +29,7 @@ class MyListener : public Listener { }; bool testRemoveKeyBeingWatched() { - cout << "in function testListeningKeys" << endl; + cout << "in function testRemoveKeyBeingWatched" << endl; Properties props; props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848"; ADD_AUTH_INFO(props); diff --git a/test/testcase/testEndpointWithNamingSvc.cpp b/test/testcase/testEndpointWithNamingSvc.cpp index f64045f..3ccf2ec 100644 --- a/test/testcase/testEndpointWithNamingSvc.cpp +++ b/test/testcase/testEndpointWithNamingSvc.cpp @@ -6,20 +6,20 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "naming/Instance.h" -#include "Constants.h" -#include "utils/UtilAndComs.h" +#include "constant/ConfigConstant.h" +#include "constant/UtilAndComs.h" #include "src/http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" using namespace std; using namespace nacos; bool testEndpointWithNamingProxy() { - cout << "in function testNamingServiceRegister" << endl; + cout << "in function testEndpointWithNamingProxy" << endl; cout << "For this test, please create an endpoint on your 80 port with a file in the following path:" << endl; cout << "yourip:80/endpoints/endpoint0" << endl; cout << "And the content should be a list of ip:port separated with \\n the ip:port group points at a nacos server" << endl; diff --git a/test/testcase/testGetAllInstances.cpp b/test/testcase/testGetAllInstances.cpp index 9e6bc17..7f895d1 100644 --- a/test/testcase/testGetAllInstances.cpp +++ b/test/testcase/testGetAllInstances.cpp @@ -5,14 +5,14 @@ #include "src/naming/NamingProxy.h" #include "factory/NacosServiceFactory.h" #include "naming/Instance.h" -#include "Constants.h" -#include "utils/UtilAndComs.h" +#include "constant/ConfigConstant.h" +#include "constant/UtilAndComs.h" #include "src/http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "ResourceGuard.h" using namespace std; diff --git a/test/testcase/testGetConfig.cpp b/test/testcase/testGetConfig.cpp index 9b384d7..8e0bb4d 100644 --- a/test/testcase/testGetConfig.cpp +++ b/test/testcase/testGetConfig.cpp @@ -1,9 +1,9 @@ #include #include "factory/NacosServiceFactory.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" #include "ResourceGuard.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; @@ -61,7 +61,7 @@ bool testInvalidConfig() { ss = n->getConfig("k", NULLSTR, 1000); } catch (NacosException &e) { - NacosString errmsgShouldBe = "endpoint is blank"; + NacosString errmsgShouldBe = "no server address specified and the endpoint is blank"; if (errmsgShouldBe == e.what()) { return true; } else { diff --git a/test/testcase/testGetServiceNames.cpp b/test/testcase/testGetServiceNames.cpp index 4836f13..a1608e5 100644 --- a/test/testcase/testGetServiceNames.cpp +++ b/test/testcase/testGetServiceNames.cpp @@ -5,14 +5,14 @@ #include "src/naming/NamingProxy.h" #include "factory/NacosServiceFactory.h" #include "naming/Instance.h" -#include "Constants.h" -#include "utils/UtilAndComs.h" +#include "constant/ConfigConstant.h" +#include "constant/UtilAndComs.h" #include "src/http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "ResourceGuard.h" using namespace std; diff --git a/test/testcase/testHttpRequest.cpp b/test/testcase/testHttpRequest.cpp index c69f4d4..8f43bdd 100644 --- a/test/testcase/testHttpRequest.cpp +++ b/test/testcase/testHttpRequest.cpp @@ -1,5 +1,5 @@ #include "src/http/HTTPCli.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "DebugAssertion.h" #include diff --git a/test/testcase/testIOUtils.cpp b/test/testcase/testIOUtils.cpp index ef7c452..9e2098b 100644 --- a/test/testcase/testIOUtils.cpp +++ b/test/testcase/testIOUtils.cpp @@ -2,7 +2,7 @@ #include "DebugAssertion.h" #include "src/config/IOUtils.h" #include "utils/DirUtils.h" -#include "Debug.h" +#include "src/log/Logger.h" #define ENCODING "UTF-8" diff --git a/test/testcase/testInstanceSelector.cpp b/test/testcase/testInstanceSelector.cpp index 8029d62..7284824 100644 --- a/test/testcase/testInstanceSelector.cpp +++ b/test/testcase/testInstanceSelector.cpp @@ -7,14 +7,14 @@ #include "naming/selectors/RandomByWeightSelector.h" #include "naming/selectors/HealthInstanceSelector.h" #include "naming/selectors/RandomSelector.h" -#include "Constants.h" -#include "utils/UtilAndComs.h" +#include "constant/ConfigConstant.h" +#include "constant/UtilAndComs.h" #include "src/http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "ResourceGuard.h" using namespace std; @@ -26,7 +26,7 @@ bool testInstanceSelectors() { Properties configProps; ADD_AUTH_INFO(configProps); configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1"; - configProps[PropertyKeyConst::TCP_NAMING_POLL_INTERVAL] = "3000"; + configProps[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "3000"; NacosServiceFactory *factory = new NacosServiceFactory(configProps); ResourceGuard _guardFactory(factory); @@ -73,7 +73,7 @@ bool testRandomByWeightSelector() Properties configProps; ADD_AUTH_INFO(configProps); configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1"; - configProps[PropertyKeyConst::TCP_NAMING_POLL_INTERVAL] = "3000"; + configProps[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "3000"; NacosServiceFactory *factory = new NacosServiceFactory(configProps); ResourceGuard _guardFactory(factory); diff --git a/test/testcase/testJson2BizObjects.cpp b/test/testcase/testJson2BizObjects.cpp index 3e95ebd..017096b 100644 --- a/test/testcase/testJson2BizObjects.cpp +++ b/test/testcase/testJson2BizObjects.cpp @@ -28,7 +28,8 @@ bool testString2ServiceInfo() { " \"checksum\": \"3bbcf6dd1175203a8afdade0e77a27cd1528787794594\"," " \"lastRefTime\": 1528787794594," " \"env\": \"\"," - " \"clusters\": \"\"" + " \"clusters\": \"\"," + " \"name\": \"test\"" "}"; cout << "Deserializing the following string into an object:" << endl << json << endl; @@ -61,7 +62,8 @@ bool testMalformedJson2ServiceInfo() { " \"checksum\": \"3bbcf6dd1175203a8afdade0e77a27cd1528787794594\"," " \"lastRefTime\": 152878779459499999999999999999999999999999999999999," " \"env\": \"\"," - " \"clusters\": \"\"" + " \"clusters\": \"\"," + " \"name\": \"test\"" "}"; cout << "Deserializing the following string into an object:" << endl << json << endl; @@ -99,7 +101,8 @@ bool testMalformedDouble2ServiceInfo() { " \"checksum\": \"3bbcf6dd1175203a8afdade0e77a27cd1528787794594\"," " \"lastRefTime\": 1528787794594," " \"env\": \"\"," - " \"clusters\": \"\"" + " \"clusters\": \"\"," + " \"name\": \"test\"" "}"; cout << "Deserializing the following string into an object:" << endl << json << endl; @@ -139,7 +142,8 @@ bool testLackcacheMillisServiceInfo() { " \"checksum\": \"3bbcf6dd1175203a8afdade0e77a27cd1528787794594\"," " \"lastRefTime\": 1528787794594," " \"env\": \"\"," - " \"clusters\": \"\"" + " \"clusters\": \"\"," + " \"name\": \"test\"" "}"; cout << "Deserializing the following string into an object:" << endl << json << endl; diff --git a/test/testcase/testListenWorker.cpp b/test/testcase/testListenWorker.cpp index ae007e9..4363783 100644 --- a/test/testcase/testListenWorker.cpp +++ b/test/testcase/testListenWorker.cpp @@ -1,17 +1,20 @@ #include #include #include -#include "Debug.h" +#include +#include "src/log/Logger.h" #include "DebugAssertion.h" #include "listen/Listener.h" #include "src/http/HttpDelegate.h" #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" using namespace std; using namespace nacos; +bool key_change_called = false; + class KeyChangeListener : public Listener { private: NacosString key; @@ -21,6 +24,7 @@ class KeyChangeListener : public Listener { NacosString getKey() const { return key; }; void receiveConfigInfo(const NacosString &configInfo) { + key_change_called = true; cout << "in receiveConfigInfo: " << key << " changed to " << configInfo << endl; } }; @@ -38,10 +42,16 @@ bool testAddListener() { ResourceGuard _guardFactory(factory); ConfigService *n = factory->CreateConfigService(); ResourceGuard _serviceFactory(n); + n->removeConfig("k4", NULLSTR); + n->removeConfig("k2", NULLSTR);//Known issue: this key will be monitored in next cycle(LONG_PULLING_TIME) + n->removeConfig("k", NULLSTR);//so will this + sleep(1); n->addListener("k4", NULLSTR, thelistener); n->addListener("k2", NULLSTR, thelistener); n->addListener("k", NULLSTR, thelistener); - bSucc = n->publishConfig("k", NULLSTR, "hahaha"); + sleep(1); + cout << "publish k" << endl; + bSucc = n->publishConfig("k4", NULLSTR, "hahaha"); } catch (NacosException &e) { cout << @@ -50,6 +60,7 @@ bool testAddListener() { return false; } + SHOULD_BE_TRUE(key_change_called, "Notification function should be called"); SHOULD_BE_TRUE(bSucc, "Publish should succeed"); cout << "test successful" << endl; return true; diff --git a/test/testcase/testListeningKeys.cpp b/test/testcase/testListeningKeys.cpp index 2d6e2e6..42dee5e 100644 --- a/test/testcase/testListeningKeys.cpp +++ b/test/testcase/testListeningKeys.cpp @@ -5,9 +5,9 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "listen/Listener.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; @@ -53,16 +53,28 @@ bool testListeningKeys() { n->addListener(strKey, NULLSTR, theListener3); } - cout << "Hold for 2 mins" << endl; - sleep(120); + cout << "Change key and hold for 15 secs" << endl; + n->publishConfig("dqid", NULLSTR, "Hello"); + n->publishConfig("dqid", NULLSTR, "World"); + sleep(15); cout << "remove listener" << endl; n->removeListener("dqid", NULLSTR, theListener); - cout << "Hold for 2 mins" << endl; - sleep(120); + cout << "Hold for 15 secs" << endl; + n->publishConfig("dqid3", NULLSTR, "Hello-3"); + n->publishConfig("dqid3", NULLSTR, "World-3"); + n->publishConfig("dqid1", NULLSTR, "World-3"); + n->publishConfig("dqid2", NULLSTR, "World-3"); + n->publishConfig("dqid3", NULLSTR, "World-3"); + n->publishConfig("dqid1", NULLSTR, "World-3"); + n->publishConfig("dqid2", NULLSTR, "World-3"); + n->publishConfig("dqid3", NULLSTR, "World-3"); + sleep(15); cout << "remove listener2" << endl; + n->publishConfig("dqid", NULLSTR, "Data change before remove"); n->removeListener("dqid", NULLSTR, theListener2); n->removeListener("dqid", NULLSTR, theListener3); + n->publishConfig("dqid", NULLSTR, "Data change after remove"); cout << "test successful" << endl; return true; diff --git a/test/testcase/testListeningKeysWithHttpPrefix.cpp b/test/testcase/testListeningKeysWithHttpPrefix.cpp index 368de18..dfd25f1 100644 --- a/test/testcase/testListeningKeysWithHttpPrefix.cpp +++ b/test/testcase/testListeningKeysWithHttpPrefix.cpp @@ -5,9 +5,9 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "listen/Listener.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; diff --git a/test/testcase/testMaintainInstances.cpp b/test/testcase/testMaintainInstances.cpp index d25a8f3..0f305aa 100644 --- a/test/testcase/testMaintainInstances.cpp +++ b/test/testcase/testMaintainInstances.cpp @@ -5,10 +5,10 @@ #include "factory/NacosServiceFactory.h" #include "naming/NamingMaintainService.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "ResourceGuard.h" using namespace std; @@ -34,7 +34,7 @@ bool testMaintainUpdateInstance() { instance.port = 2333; instance.ephemeral = false; try { - maintainService->deleteService("MaintainTestUpdateInstance", Constants::DEFAULT_GROUP); + maintainService->deleteService("MaintainTestUpdateInstance", ConfigConstant::DEFAULT_GROUP); } catch (exception &ignore) { /*We may come across service not exist exception, just ignore*/ } namingService->registerInstance("MaintainTestUpdateInstance", instance); map metadata; @@ -50,7 +50,7 @@ bool testMaintainUpdateInstance() { SHOULD_BE_TRUE(metadataGet["hello"].compare("world") == 0, "metadata should be {hello: world}"); try { //restore to the initial status - maintainService->deleteService("MaintainTestUpdateInstance", Constants::DEFAULT_GROUP); + maintainService->deleteService("MaintainTestUpdateInstance", ConfigConstant::DEFAULT_GROUP); } catch (exception &ignore) { /*We may come across service not exist exception, just ignore*/ } return true; } diff --git a/test/testcase/testMaintainServices.cpp b/test/testcase/testMaintainServices.cpp index fdd0cef..d4bc5d0 100644 --- a/test/testcase/testMaintainServices.cpp +++ b/test/testcase/testMaintainServices.cpp @@ -5,10 +5,10 @@ #include "factory/NacosServiceFactory.h" #include "naming/NamingMaintainService.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "ResourceGuard.h" using namespace std; diff --git a/test/testcase/testNamingService.cpp b/test/testcase/testNamingService.cpp index 92da4fd..15e0a40 100644 --- a/test/testcase/testNamingService.cpp +++ b/test/testcase/testNamingService.cpp @@ -6,14 +6,14 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "naming/Instance.h" -#include "Constants.h" -#include "utils/UtilAndComs.h" +#include "constant/ConfigConstant.h" +#include "constant/UtilAndComs.h" #include "src/http/HTTPCli.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "NacosString.h" #include "Properties.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" using namespace std; using namespace nacos; @@ -55,7 +55,7 @@ bool testNamingProxySmokeTest() { for (int i = 0; i < 10; i++) { NacosString serviceName = "TestServiceName" + NacosStringOps::valueOf(i); theinstance.serviceName = serviceName; - namingProxy->registerService(serviceName, Constants::DEFAULT_GROUP, theinstance); + namingProxy->registerService(serviceName, ConfigConstant::DEFAULT_GROUP, theinstance); sleep(1); } } @@ -68,7 +68,7 @@ bool testNamingProxySmokeTest() { //check whether the data are correct for (int i = 0; i < 10; i++) { NacosString serviceName = "TestServiceName" + NacosStringOps::valueOf(i); - NacosString serverlist = namingProxy->queryList(serviceName, "TestCluster", 0, false); + NacosString serverlist = namingProxy->queryList(serviceName, ConfigConstant::DEFAULT_GROUP, "TestCluster", 0, false); if (serverlist.find("\"serviceName\":\"" + serviceName + "\"") == string::npos) { cout << "Failed to get data for:" << serviceName << endl; @@ -133,6 +133,24 @@ bool testNamingProxyFailOver() { return true; } +class NamingServiceSelector : public naming::selectors::Selector { +private: + int _port; +public: + void setSelectPort(int port) { _port = port; }; + list select(const std::list &itemsToSelect) { + list res; + for (list::const_iterator it = itemsToSelect.begin(); + it != itemsToSelect.end(); it++) { + if ((*it).port == _port) { + res.push_back(*it); + } + } + + return res; + } +}; + bool testNamingServiceRegister() { cout << "in function testNamingServiceRegister" << endl; Properties configProps; @@ -167,6 +185,25 @@ bool testNamingServiceRegister() { return false; } + try { + for (int i = 0; i < 2; i++) { + NacosString serviceName = "TestNamingService" + NacosStringOps::valueOf(i); + for (int j = 0; j < 3; j++) { + NamingServiceSelector selector; + selector.setSelectPort(20000 + i*10+j); + list instanceList = namingSvc->getInstanceWithPredicate(serviceName, &selector); + cout << "Instance info got from server:" << instanceList.begin()->toString() << endl; + SHOULD_BE_TRUE(instanceList.size() == 1, "There should be only 1 instance for each port"); + SHOULD_BE_TRUE(instanceList.begin()->clusterName == "DefaultCluster", "Cluster name should be DefaultCluster"); + SHOULD_BE_TRUE(instanceList.begin()->ephemeral == true, "Should be ephemeral node"); + } + } + } + catch (NacosException &e) { + cout << "encounter exception while getting service instance, raison:" << e.what() << endl; + return false; + } + cout << "testNamingServiceRegister successful" << endl; return true; diff --git a/test/testcase/testNamingSubscribe.cpp b/test/testcase/testNamingSubscribe.cpp index 459878f..8b0918d 100644 --- a/test/testcase/testNamingSubscribe.cpp +++ b/test/testcase/testNamingSubscribe.cpp @@ -5,9 +5,9 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "naming/subscribe/EventListener.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; @@ -33,6 +33,7 @@ bool testListenService() { cout << "in function testListenService" << endl; Properties props; props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848"; + props[PropertyKeyConst::LOCAL_IP] = "127.0.0.1"; ADD_AUTH_INFO(props); NacosServiceFactory *factory = new NacosServiceFactory(props); ResourceGuard _guardFactory(factory); @@ -43,11 +44,16 @@ bool testListenService() { n->registerInstance("ss", "127.0.0.1", 33); n->registerInstance("ss", "127.0.0.1", 34); - cout << "Hold for 1 min" << endl; - sleep(60); n->deregisterInstance("ss", "127.0.0.1", 33); n->deregisterInstance("ss", "127.0.0.1", 34); + + n->registerInstance("ss", "127.0.0.1", 33); + n->registerInstance("ss", "127.0.0.1", 34); + + n->deregisterInstance("ss", "127.0.0.1", 33); + n->deregisterInstance("ss", "127.0.0.1", 34); + cout << "All instances Unregistered" << endl; return true; diff --git a/test/testcase/testNetUtils.cpp b/test/testcase/testNetUtils.cpp new file mode 100644 index 0000000..c6f45e3 --- /dev/null +++ b/test/testcase/testNetUtils.cpp @@ -0,0 +1,17 @@ +#include +#include "src/utils//NetUtils.h" +#include "DebugAssertion.h" + +using namespace std; +using namespace nacos; + +bool testGetHostIp() { + cout << "in function testGetHostIp" << endl; + + NacosString ip = NetUtils::getHostIp(); + cout << "ip:" << ip << endl; + SHOULD_BE_TRUE(!ip.empty(), "Ip got for local machine should not be empty"); + cout << "test end..." << endl; + + return true; +} \ No newline at end of file diff --git a/test/testcase/testPublishConfig.cpp b/test/testcase/testPublishConfig.cpp index 8d9e09b..41f7117 100644 --- a/test/testcase/testPublishConfig.cpp +++ b/test/testcase/testPublishConfig.cpp @@ -4,9 +4,9 @@ #include #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; diff --git a/test/testcase/testPublishConfigWithHttpPrefix.cpp b/test/testcase/testPublishConfigWithHttpPrefix.cpp index dc0be84..65ec3f9 100644 --- a/test/testcase/testPublishConfigWithHttpPrefix.cpp +++ b/test/testcase/testPublishConfigWithHttpPrefix.cpp @@ -4,9 +4,9 @@ #include #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; diff --git a/test/testcase/testServerListManager.cpp b/test/testcase/testServerListManager.cpp index 11a98e8..7fb5ee4 100644 --- a/test/testcase/testServerListManager.cpp +++ b/test/testcase/testServerListManager.cpp @@ -5,7 +5,7 @@ #include "factory/NacosServiceFactory.h" #include "ResourceGuard.h" #include "src/http/HTTPCli.h" -#include "PropertyKeyConst.h" +#include "constant/PropertyKeyConst.h" #include "src/json/JSON.h" using namespace std; diff --git a/test/testcase/testStringExplode.cpp b/test/testcase/testStringExplode.cpp index 149ed71..5418340 100644 --- a/test/testcase/testStringExplode.cpp +++ b/test/testcase/testStringExplode.cpp @@ -3,7 +3,7 @@ #include #include "utils/ParamUtils.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos; @@ -42,3 +42,38 @@ bool testStringExplode() { return true; } + +bool testStringExplode2() { + cout << "in function testStringExplode2 - enhanced one which can handle string separator" << endl; + + vector explodedList; + NacosString originalContent = "Hello||World||My||Name||Is"; + ParamUtils::Explode(explodedList, originalContent, "||"); + SHOULD_BE_TRUE(explodedList.size() == 5, + "Exploding Hello||World||My||Name||Is with separator || should get a list with size 5."); + SHOULD_BE_TRUE(explodedList[0] == "Hello", "explodedList[0] should be Hello"); + SHOULD_BE_TRUE(explodedList[1] == "World", "explodedList[1] should be World"); + SHOULD_BE_TRUE(explodedList[2] == "My", "explodedList[2] should be My"); + SHOULD_BE_TRUE(explodedList[3] == "Name", "explodedList[3] should be Name"); + SHOULD_BE_TRUE(explodedList[4] == "Is", "explodedList[4] should be Is"); + + vector specialExplode; + NacosString specialoriginalContent = "Hello\x1\x1World\x1\x1My\x1\x1Name\x1\x1Is\x1\x1"; + ParamUtils::Explode(specialExplode, specialoriginalContent, "\x1\x1"); + SHOULD_BE_TRUE(specialExplode.size() == 6, + "Exploding Hello\x1\x1World\x1\x1My\x1\x1Name\x1\x1Is\x1\x1 with separator \x1\x1 should get a list with size 5."); + SHOULD_BE_TRUE(specialExplode[0] == "Hello", "specialExplode[0] should be Hello"); + SHOULD_BE_TRUE(specialExplode[1] == "World", "specialExplode[1] should be World"); + SHOULD_BE_TRUE(specialExplode[2] == "My", "specialExplode[2] should be My"); + SHOULD_BE_TRUE(specialExplode[3] == "Name", "specialExplode[3] should be Name"); + SHOULD_BE_TRUE(specialExplode[4] == "Is", "specialExplode[4] should be Is"); + + vector nullEnd; + NacosString nullEndStr = "k=="; + ParamUtils::Explode(nullEnd, nullEndStr, "=="); + SHOULD_BE_TRUE(nullEnd.size() == 2, "exploding k== should get 2 items"); + SHOULD_BE_TRUE(nullEnd[0] == "k", "nullEnd[0] should be k"); + SHOULD_BE_TRUE(nullEnd[1] == "", "nullEnd[0] should be empty"); + + return true; +} \ No newline at end of file diff --git a/test/testcase/testThreadSmoke.cpp b/test/testcase/testThreadSmoke.cpp index 475bea6..e5c9400 100644 --- a/test/testcase/testThreadSmoke.cpp +++ b/test/testcase/testThreadSmoke.cpp @@ -1,6 +1,6 @@ #include #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" #include "src/thread/Thread.h" #include "src/thread/ThreadPool.h" #include "NacosString.h" diff --git a/test/testcase/testURL.cpp b/test/testcase/testURL.cpp index 3280aa3..bbb8227 100644 --- a/test/testcase/testURL.cpp +++ b/test/testcase/testURL.cpp @@ -2,7 +2,7 @@ #include #include "utils/url.h" #include "DebugAssertion.h" -#include "Debug.h" +#include "src/log/Logger.h" using namespace std; using namespace nacos;