Compare commits

..

No commits in common. "master" and "v1.0.7" have entirely different histories.

175 changed files with 1570 additions and 3115 deletions

14
.gitignore vendored
View File

@ -34,19 +34,7 @@
# temp
tmp/
# CMakeFiles
CMakeFiles/
CMakeLists.txt
CMakeCache.txt
cmake_install.cmake
install_manifest.txt
Makefile
# idea project
.idea
CMakeLists.txt
cmake-build-debug
*.dat
.vscode/

View File

@ -1,65 +0,0 @@
cmake_minimum_required(VERSION 3.4.1)
project(nacos-sdk-cpp)
#add_definitions(-DNACOS_AUTH)
#add_definitions(-DNACOS_SPAS)
include_directories (
.
include
)
aux_source_directory( src SRCS_DIRS)
aux_source_directory( src/config SRCS_DIRS)
aux_source_directory( src/constant SRCS_DIRS)
aux_source_directory( src/crypto SRCS_DIRS)
aux_source_directory( src/crypto/base64 SRCS_DIRS)
aux_source_directory( src/crypto/hmac_sha1 SRCS_DIRS)
aux_source_directory( src/crypto/hmac_sha1/hmac SRCS_DIRS)
aux_source_directory( src/crypto/hmac_sha1/sha SRCS_DIRS)
aux_source_directory( src/crypto/md5 SRCS_DIRS)
aux_source_directory( src/factory SRCS_DIRS)
aux_source_directory( src/http SRCS_DIRS)
aux_source_directory( src/http/delegate SRCS_DIRS)
aux_source_directory( src/init SRCS_DIRS)
aux_source_directory( src/json SRCS_DIRS)
aux_source_directory( src/json/rapidjson SRCS_DIRS)
aux_source_directory( src/json/rapidjson/error SRCS_DIRS)
aux_source_directory( src/json/rapidjson/internal SRCS_DIRS)
aux_source_directory( src/json/rapidjson/msinttypes SRCS_DIRS)
aux_source_directory( src/listen SRCS_DIRS)
aux_source_directory( src/log SRCS_DIRS)
aux_source_directory( src/naming SRCS_DIRS)
aux_source_directory( src/naming/beat SRCS_DIRS)
aux_source_directory( src/naming/cache SRCS_DIRS)
aux_source_directory( src/naming/selectors SRCS_DIRS)
aux_source_directory( src/naming/subscribe SRCS_DIRS)
aux_source_directory( src/security SRCS_DIRS)
aux_source_directory( src/server SRCS_DIRS)
aux_source_directory( src/thread SRCS_DIRS)
aux_source_directory( src/utils SRCS_DIRS)
aux_source_directory( test SRCS_DIRS)
aux_source_directory( test/testcase SRCS_DIRS)
aux_source_directory(test TEST_SRCS_DIRS)
aux_source_directory(test/testcase TEST_SRCS_DIRS)
add_executable(nacos-cli.out ${TEST_SRCS_DIRS} ${SRCS_DIRS})
add_library(nacos-cli SHARED ${SRCS_DIRS})
add_library(nacos-cli-static STATIC ${SRCS_DIRS})
set(THREADS_PREFER_PTHREAD_FLAG ON)
target_link_libraries(nacos-cli PRIVATE Threads::Threads curl z)
target_link_libraries(nacos-cli-static PRIVATE Threads::Threads curl z)
target_link_libraries(nacos-cli.out PRIVATE Threads::Threads curl z)
find_package(Threads REQUIRED)
find_package(CURL REQUIRED)
find_package(ZLIB REQUIRED)
install(TARGETS nacos-cli
LIBRARY DESTINATION lib)
install(DIRECTORY ${CMAKE_SOURCE_DIR}/include/
DESTINATION include/nacos
FILES_MATCHING PATTERN "*.h*")

68
Makefile Normal file
View File

@ -0,0 +1,68 @@
SRCS_DIRS := $(shell find ./src/ -maxdepth 3 -type d)
TEST_SRCS_DIRS := $(shell find ./test/ -maxdepth 3 -type d)
ALL_SRCS_DIRS := $(shell find ./src/ -maxdepth 3 -type d)
ALL_SRCS_DIRS += $(shell find ./test/ -maxdepth 3 -type d)
SRCS := $(foreach dir,$(SRCS_DIRS),$(wildcard $(dir)/*.cpp))
TEST_SRCS := $(foreach dir,$(SRCS_DIRS),$(wildcard $(dir)/*.cpp))
ALL_SRCS := $(foreach dir,$(ALL_SRCS_DIRS),$(wildcard $(dir)/*.cpp))
MAKEROOT = $(shell pwd)
OBJ_DIR = $(MAKEROOT)/obj
DEP_DIR = $(MAKEROOT)/dep
OBJS = $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(notdir $(SRCS)))
TEST_OBJS = $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(notdir $(TEST_SRCS)))
ALL_OBJS = $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(notdir $(ALL_SRCS)))
DEPS = $(patsubst %.o, $(DEP_DIR)/%.d, $(notdir $(ALL_OBJS)))
CC = g++
INCLUDES = -Iinclude \
-Itest \
-I.
LIBS = -lcurl -lpthread
CCFLAGS = -g -Wall -O0 -fPIC
OUTPUT = nacos-cli.out
OUTLIB1 = libnacos-cli.so
OUTLIB2 = libnacos-cli.a
vpath %.cpp $(ALL_SRCS_DIRS)
all :$(DEPS) $(OUTPUT) $(OUTLIB1) $(OUTLIB2)
$(OUTPUT) : $(ALL_OBJS)
$(info Linking $@ ...)
@$(CC) $^ -o $@ $(INCLUDES) $(LIBS) $(CCFLAGS)
$(OUTLIB1) : $(OBJS)
$(info Linking Dynamic $@ ...)
@$(CC) $^ -o $@ $(INCLUDES) $(LIBS) $(CCFLAGS) -shared
$(OUTLIB2) : $(OBJS)
$(info Linking Static $@ ...)
ar cru $(OUTLIB2) $(OBJS)
ranlib $(OUTLIB2)
$(ALL_OBJS) : $(OBJ_DIR)/%.o : %.cpp
$(info Building $@ ...)
@mkdir -p "$(OBJ_DIR)"
@$(CC) -c $< -o $@ $(CCFLAGS) $(INCLUDES)
-include $(DEPS)
$(DEPS) : $(DEP_DIR)/%.d : %.cpp
$(info Creating $< Dependencies file ...)
@mkdir -p "$(DEP_DIR)"
@$(CC) $(CCFLAGS) $(INCLUDES) -MM -MT $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(notdir $<)) -MF $@ $<
testcase : all
SRCS = $(SRCS:testcase/*.cpp)
clean:
rm -rf *.out
rm -rf *.so
rm -rf $(OBJ_DIR)
rm -rf $(DEP_DIR)
.PHONY:clean

View File

@ -4,28 +4,24 @@
# Nacos-sdk-cpp
Nacos-sdk-cpp for c++ client allows users to access Nacos service, it supports service discovery and dynamic configuration.
Nacos-sdk-cpp for c++ clients allow users to access Nacos service, it supports service discovery and dynamic configuration.
[![Gitter](https://badges.gitter.im/alibaba/nacos.svg)](https://gitter.im/alibaba/nacos?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)
[![Gitter](https://travis-ci.org/alibaba/nacos.svg?branch=master)](https://travis-ci.org/alibaba/nacos)
# Quick Examples
## Setup project
Download the source and run the following command in bash:
```
cd nacos-sdk-cpp
cmake .
make
```
`cd nacos-sdk-cpp`
`make`
a libnacos-cli.so and a nacos-cli.out will be generated
run `./nacos-cli.out` to perform test on the library
run `make install` to install the libnacos-cli to your system library path
**Note:** You need to run a nacos server on your local machine listening on port 8848 to go through the whole test
One of the testcases will test endpoint functionality, so **you also need** to run a simple http server on port 80 which provides the following content:
@ -42,7 +38,11 @@ Here is an example showing how to integrate the library(.so) into your project:
IntegratingIntoYourProject.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "ResourceGuard.h"
#include "NacosString.h"
using namespace std;
using namespace nacos;
@ -71,7 +71,7 @@ int main() {
```
`g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o integrated.out`
`g++ IntegratingIntoYourProject.cpp -L. -lnacos-cli -Iinclude -o integrated.out`
Start a nacos on your localmachine listening on port 8848, and run `./integrated.out`
@ -79,14 +79,16 @@ Then you'll see:
`SuccessfullyIntegrated`
## If you are using a static lib(.a):
Assume that the file you are compiling resides in the same directory as the .a library, please use the following command:
You may come across the following problem:
`g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lcurl -lz -L. -lnacos-cli-static -o integrated.out`
`error while loading shared libraries: libnacos-cli.so: cannot open shared object file: No such file or directory`
-lcurl -lz Specifies the curl and lz library used by libnacos
**solution:**
-L. -lnacos-cli-static links the static libnacos library resides in the same directory as IntegratingIntoYourProject.cpp
assume that your libnacos-cli.so resides in /usr/local/libnacos/
`export LD_LIBRARY_PATH=/usr/local/libnacos/` (DON'T include the so file's name)
or you can use ldconfig to add libnacos-cli.so to your lib path.
## Configuration
@ -95,7 +97,9 @@ Assume that the file you are compiling resides in the same directory as the .a l
getConfig.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std;
using namespace nacos;
@ -128,7 +132,9 @@ int main() {
setConfig.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -173,7 +179,10 @@ int main() {
listenToKeys.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "listen/Listener.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -223,7 +232,12 @@ registerInstances.cpp:
```C++
#include <iostream>
#include <unistd.h>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -278,7 +292,10 @@ int main() {
subscribeServices.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "naming/subscribe/EventListener.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -335,7 +352,12 @@ getAllInstances.cpp:
```C++
#include <iostream>
#include <list>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std;
using namespace nacos;
@ -374,21 +396,6 @@ using namespace nacos;
NamingService *namingSvc = factory->CreateNamingService();
......
```
### Enabling SPAS Authentication
```C++
using namespace nacos;
......
configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
configProps[PropertyKeyConst::ACCESS_KEY] = "accessKey";
configProps[PropertyKeyConst::SECRET_KEY] = "secretKey";
NacosServiceFactory *factory = new NacosServiceFactory(configProps);
ConfigService *n = factory->CreateConfigService();
NamingService *namingSvc = factory->CreateNamingService();
......
```
# Supported System/Compilers
| OS/Environment | Compilers | Tested version |

View File

@ -5,24 +5,20 @@
Nacos-sdk-cpp是nacos客戶端的C++版本,它支持服务发现和动态配置
[![Gitter](https://badges.gitter.im/alibaba/nacos.svg)](https://gitter.im/alibaba/nacos?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)
[![Gitter](https://travis-ci.org/alibaba/nacos.svg?branch=master)](https://travis-ci.org/alibaba/nacos)
# 快速开始
## 设置工程
下载工程源代码并且执行下述命令:
```
cd nacos-sdk-cpp
cmake .
make
```
`cd nacos-sdk-cpp`
`make`
将会产生一个libnacos-cli.so 和一个 nacos-cli.out
运行 `./nacos-cli.out` 以执行客户端的所有testcase
运行 `make install` 将libnacos-cli安装到lib目录
**注意:** 你需要在本机运行一个nacos server监听8848端口以完成所有测试
其中有个测试将会测试端点endpoint功能**所以你还需要**在本机运行一个http服务器在路径/endpoints/endpoint0提供下述内容
@ -37,7 +33,12 @@ make
IntegratingIntoYourProject.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "ResourceGuard.h"
#include "Logger.h"
#include "NacosString.h"
using namespace std;
using namespace nacos;
@ -66,7 +67,7 @@ int main() {
```
`g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o integrated.out`
`g++ IntegratingIntoYourProject.cpp -L. -lnacos-cli -Iinclude -o integrated.out`
在本机的8848端口启动一个nacos server, 并且运行 `./integrated.out`
@ -74,14 +75,16 @@ int main() {
`SuccessfullyIntegrated`
## 如果你使用静态库(.a)链接
假设.a文件和待编译文件在同一目录, 请执行下述命令:
你可能会遇到下述问题:
`g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lcurl -lz -L. -lnacos-cli-static -o integrated.out`
`error while loading shared libraries: libnacos-cli.so: cannot open shared object file: No such file or directory`
使用-lcurl -lz指定nacos客户端使用的curl和lz库
**解决方法:**
使用-L. -lnacos-cli-static引用当前目录下的libnacos-cli-static.a
假设你的 libnacos-cli.so 在如下目录 /usr/local/libnacos/
`export LD_LIBRARY_PATH=/usr/local/libnacos/` (请勿包含lib文件的名字)
你也可以通过ldconfig将库配置到libpath当中
## 配置
@ -90,7 +93,11 @@ int main() {
getConfig.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "ResourceGuard.h"
#include "Logger.h"
using namespace std;
using namespace nacos;
@ -123,7 +130,13 @@ int main() {
setConfig.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include <stdlib.h>
#include <unistd.h>
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "Logger.h"
using namespace std;
using namespace nacos;
@ -168,7 +181,14 @@ int main() {
listenToKeys.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include <stdlib.h>
#include <unistd.h>
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "listen/Listener.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "Logger.h"
using namespace std;
using namespace nacos;
@ -217,8 +237,21 @@ int main() {
registerInstances.cpp:
```C++
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include "Nacos.h"
#include "naming/NamingProxy.h"
#include "naming/NacosNamingService.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "naming/Instance.h"
#include "Constants.h"
#include "utils/UtilAndComs.h"
#include "http/HTTPCli.h"
#include "DebugAssertion.h"
#include "Logger.h"
#include "NacosString.h"
#include "Properties.h"
#include "PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -273,7 +306,14 @@ int main() {
subscribeServices.cpp:
```C++
#include <iostream>
#include "Nacos.h"
#include <stdlib.h>
#include <unistd.h>
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "naming/subscribe/EventListener.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "Logger.h"
using namespace std;
using namespace nacos;
@ -329,8 +369,21 @@ int main() {
getAllInstances.cpp:
```C++
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <list>
#include "Nacos.h"
#include "naming/NamingProxy.h"
#include "factory/NacosServiceFactory.h"
#include "naming/Instance.h"
#include "Constants.h"
#include "utils/UtilAndComs.h"
#include "http/HTTPCli.h"
#include "DebugAssertion.h"
#include "Logger.h"
#include "NacosString.h"
#include "Properties.h"
#include "PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std;
using namespace nacos;
@ -370,20 +423,6 @@ using namespace nacos;
......
```
### 启动SPAS鉴权
```C++
using namespace nacos;
......
configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
configProps[PropertyKeyConst::ACCESS_KEY] = "accessKey";
configProps[PropertyKeyConst::SECRET_KEY] = "secretKey";
NacosServiceFactory *factory = new NacosServiceFactory(configProps);
ConfigService *n = factory->CreateConfigService();
NamingService *namingSvc = factory->CreateNamingService();
......
```
# 支持的系统/编译器
| 操作系统/环境 | 编译器 | 测试版本 |

View File

@ -1,5 +1,8 @@
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
#include "NacosString.h"
using namespace std;
using namespace nacos;
@ -7,8 +10,8 @@ using namespace nacos;
int main() {
Properties props;
props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//Server address
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
ConfigService *n = factory->CreateConfigService();
ResourceGuard <ConfigService> _serviceFactory(n);
NacosString ss = "";

View File

@ -1,9 +1,16 @@
#!/bin/bash
g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o IntegratingIntoYourProject.out
g++ -I/usr/local/include/nacos/ getAllInstances.cpp -lnacos-cli -o getAllInstances.out
g++ -I/usr/local/include/nacos/ getConfig.cpp -lnacos-cli -o getConfig.out
g++ -I/usr/local/include/nacos/ listenToKeys.cpp -lnacos-cli -o listenToKeys.out
g++ -I/usr/local/include/nacos/ registerInstances.cpp -lnacos-cli -o registerInstances.out
g++ -I/usr/local/include/nacos/ setConfig.cpp -lnacos-cli -o setConfig.out
g++ -I/usr/local/include/nacos/ subscribeServices.cpp -lnacos-cli -o subscribeServices.out
if [ ! -f ../libnacos-cli.so ]; then
echo "Please create the libnacos-cli.so by running make on the project's root directory first.";
exit;
fi
cp ../libnacos-cli.so .
g++ IntegratingIntoYourProject.cpp -L. -lnacos-cli -I../include -o IntegratingIntoYourProject.out
g++ getAllInstances.cpp -L. -lnacos-cli -I../include -o getAllInstances.out
g++ getConfig.cpp -L. -lnacos-cli -I../include -o getConfig.out
g++ listenToKeys.cpp -L. -lnacos-cli -I../include -o listenToKeys.out
g++ registerInstances.cpp -L. -lnacos-cli -I../include -o registerInstances.out
g++ setConfig.cpp -L. -lnacos-cli -I../include -o setConfig.out
g++ subscribeServices.cpp -L. -lnacos-cli -I../include -o subscribeServices.out

View File

@ -1,6 +1,11 @@
#include <iostream>
#include <list>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std;
using namespace nacos;
@ -8,8 +13,8 @@ using namespace nacos;
int main() {
Properties configProps;
configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(configProps);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(configProps);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
NamingService *namingSvc = factory->CreateNamingService();
ResourceGuard <NamingService> _guardService(namingSvc);

View File

@ -1,5 +1,7 @@
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std;
using namespace nacos;
@ -7,8 +9,8 @@ using namespace nacos;
int main() {
Properties props;
props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//Server address
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
ConfigService *n = factory->CreateConfigService();
ResourceGuard <ConfigService> _serviceFactory(n);
NacosString ss = "";

View File

@ -1,6 +1,8 @@
#include <iostream>
#include "Nacos.h"
#include <stdio.h>
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "listen/Listener.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -24,8 +26,8 @@ public:
int main() {
Properties props;
props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
ConfigService *n = factory->CreateConfigService();
ResourceGuard <ConfigService> _serviceFactory(n);

View File

@ -1,6 +1,11 @@
#include <iostream>
#include <unistd.h>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -8,8 +13,8 @@ using namespace nacos;
int main() {
Properties configProps;
configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(configProps);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(configProps);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
NamingService *namingSvc = factory->CreateNamingService();
ResourceGuard <NamingService> _serviceFactory(namingSvc);
Instance instance;

View File

@ -1,5 +1,7 @@
#include <iostream>
#include "Nacos.h"
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -7,8 +9,8 @@ using namespace nacos;
int main() {
Properties props;
props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//server address
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
ConfigService *n = factory->CreateConfigService();
ResourceGuard <ConfigService> _serviceFactory(n);
bool bSucc = false;

View File

@ -1,6 +1,8 @@
#include <iostream>
#include "Nacos.h"
#include <stdio.h>
#include "factory/NacosServiceFactory.h"
#include "ResourceGuard.h"
#include "naming/subscribe/EventListener.h"
#include "constant/PropertyKeyConst.h"
using namespace std;
using namespace nacos;
@ -28,8 +30,8 @@ int main() {
//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::SUBSCRIPTION_POLL_INTERVAL] = "5000";
INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NacosServiceFactory *factory = new NacosServiceFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory);
NamingService *n = factory->CreateNamingService();
ResourceGuard <NamingService> _serviceFactory(n);

View File

@ -1,61 +1,50 @@
#ifndef __DEBUG_ASSERTION_H_
#define __DEBUG_ASSERTION_H_
#include <stdlib.h>
#include <stdio.h>
#include "NacosString.h"
namespace nacos{
#define TEST_ITEM_START {
#define TEST_ITEM(testName, testfn) {(testName), (testfn)},
#define TEST_ITEM_END };
#define NACOS_ASSERT(x) \
if (!(x)) \
{ \
printf("Assertion failed! file:" __FILE__":%d\n", __LINE__); \
abort(); \
}
typedef bool (*TESTFN)();
typedef struct tagTestData {
NacosString testName;
TESTFN testFn;
} TestData;
#define SHOULD_BE_TRUE(assertion, message) \
do \
{ \
if (!(assertion)) \
{ \
cout << (message) << "...:failed" << endl; \
return false; \
} \
cout << (message) << "...:passed" << endl; \
} while(0);
#define SHOULD_BE_FALSE(assertion, message) SHOULD_BE_TRUE(!(assertion), (message))
#ifdef NACOS_AUTH
#define ADD_AUTH_INFO(x) \
do { \
(x)["nacos.auth.username"] = "nacos"; \
(x)["nacos.auth.password"] = "nacos"; \
} while (0)
#else
#define ADD_AUTH_INFO(x)
#endif
#ifdef NACOS_SPAS
#define ADD_SPAS_INFO(x) \
do { \
(x)["secretKey"] = "nacos"; \
(x)["accessKey"] = "nacos"; \
} while (0)
#else
#define ADD_SPAS_INFO(x)
#endif
}//namespace nacos
#ifndef __DEBUG_ASSERTION_H_
#define __DEBUG_ASSERTION_H_
#include <stdlib.h>
#include <stdio.h>
#include "NacosString.h"
namespace nacos{
#define TEST_ITEM_START {
#define TEST_ITEM(testName, testfn) {(testName), (testfn)},
#define TEST_ITEM_END };
#define NACOS_ASSERT(x) \
if (!(x)) \
{ \
printf("Assertion failed! file:" __FILE__":%d\n", __LINE__); \
abort(); \
}
typedef bool (*TESTFN)();
typedef struct tagTestData {
NacosString testName;
TESTFN testFn;
} TestData;
#define SHOULD_BE_TRUE(assertion, message) \
do \
{ \
if (!(assertion)) \
{ \
cout << (message) << "...:failed" << endl; \
return false; \
} \
cout << (message) << "...:passed" << endl; \
} while(0);
#define SHOULD_BE_FALSE(assertion, message) SHOULD_BE_TRUE(!(assertion), (message))
#ifdef NACOS_AUTH
#define ADD_AUTH_INFO(x) \
do { \
(x)["nacos.auth.username"] = "nacos"; \
(x)["nacos.auth.password"] = "nacos"; \
} while (0)
#else
#define ADD_AUTH_INFO(x)
#endif
}//namespace nacos
#endif

View File

@ -1,24 +0,0 @@
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _NACOS_H_
#define _NACOS_H_
#include "factory/INacosServiceFactory.h"
#include "factory/NacosFactoryFactory.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
#endif

View File

@ -81,7 +81,6 @@ public:
static const int UNABLE_TO_GET_HOST_IP = 1008;
static const int UNABLE_TO_CREATE_SOCKET = 1009;
static const int INVALID_CONFIG_PARAM = 1010;
static const int UNABLE_TO_GET_HOST_NAME = 1011;
};

View File

@ -14,22 +14,16 @@ public:
static const NacosString NAMESPACE;
static const NacosString ENDPOINT_QUERY_PARAMS;
static const NacosString ACCESS_KEY;
static const NacosString SECRET_KEY;
static const NacosString APP_NAME;
static const NacosString RAM_ROLE_NAME;
static const NacosString SERVER_ADDR;
static const NacosString CONTEXT_PATH;
static const NacosString ENDPOINT_CONTEXT_PATH;
static const NacosString CLUSTER_NAME;
static const NacosString ENCODE;
@ -53,7 +47,7 @@ public:
static const NacosString NACOS_SNAPSHOT_PATH;
static const NacosString LOG_PATH;
static const NacosString LOG_ROTATE_SIZE;
static const NacosString LOG_ROTATE_TIME;
static const NacosString LOG_LEVEL;
static const NacosString CLIENT_NAME;
@ -64,10 +58,6 @@ public:
static const int NACOS_DEFAULT_PORT = 8848;
static const NacosString INSTANCE_ID_SEQ_FILE;
static const NacosString INSTANCE_ID_PREFIX;
/*public static class SystemEnv {
static const NacosString ALIBABA_ALIWARE_ENDPOINT_PORT = "ALIBABA_ALIWARE_ENDPOINT_PORT";

View File

@ -23,7 +23,7 @@ public:
virtual NamingMaintainService *CreateNamingMaintainService() = 0;
virtual ~INacosServiceFactory() {};
~INacosServiceFactory() {};
};
}//namespace nacos

View File

@ -1,11 +0,0 @@
#ifndef NACOS_FACTORY_FACTORY_H
#define NACOS_FACTORY_FACTORY_H
#include "factory/INacosServiceFactory.h"
namespace nacos {
class NacosFactoryFactory {
public:
static INacosServiceFactory *getNacosFactory(const NacosString &_configFile);
static INacosServiceFactory *getNacosFactory(Properties &_props);
};
}
#endif

View File

@ -5,10 +5,9 @@
#ifndef NACOS_SDK_CPP_NACOSSERVICEFACTORY_H
#define NACOS_SDK_CPP_NACOSSERVICEFACTORY_H
#include "factory/INacosServiceFactory.h"
#include "Compatibility.h"
#include "INacosServiceFactory.h"
#include "src/thread/Mutex.h"
#include "Compatibility.h"
namespace nacos{
class AppConfigManager;

View File

@ -8,7 +8,7 @@ namespace nacos{
class Listener {
private:
NacosString listenerName;
AtomicInt<int> refCount;
AtomicInt refCount;
public:
Listener() {
this->listenerName = "theListener";

View File

@ -1,8 +1,14 @@
#ifndef __CLUSTER_H_
#define __CLUSTER_H_
#include <map>
#include <vector>
#include <list>
#include <sys/time.h>
#include "NacosString.h"
#include "constant/ConfigConstant.h"
#include "utils/url.h"
#include "utils/ParamUtils.h"
#include "naming/Instance.h"
namespace nacos{
class HealthChecker {
@ -18,17 +24,29 @@ private:
HealthChecker healthChecker;
std::map<NacosString, NacosString> metadata;
public:
NacosString getName() const;
NacosString getName() const {
return name;
}
void setName(const NacosString &name);
void setName(const NacosString &name) {
Cluster::name = name;
}
HealthChecker getHealthChecker() const;
HealthChecker getHealthChecker() const {
return healthChecker;
}
void setHealthChecker(const HealthChecker &healthChecker);
void setHealthChecker(const HealthChecker &healthChecker) {
Cluster::healthChecker = healthChecker;
}
std::map<NacosString, NacosString> getMetadata() const;
std::map<NacosString, NacosString> getMetadata() const {
return metadata;
}
void setMetadata(const std::map<NacosString, NacosString> &metadata);
void setMetadata(const std::map<NacosString, NacosString> &metadata) {
Cluster::metadata = metadata;
}
};
}//namespace nacos

View File

@ -4,7 +4,7 @@
#include <list>
#include "naming/Instance.h"
#include "naming/selectors/Selector.h"
#include "naming/subscribe/EventListener.h"
#include "naming/subscribe//EventListener.h"
#include "NacosString.h"
#include "NacosExceptions.h"
#include "ListView.h"

View File

@ -1,8 +1,13 @@
#ifndef __SVC_INFO_H_
#define __SVC_INFO_H_
#include <vector>
#include <list>
#include <sys/time.h>
#include "NacosString.h"
#include "constant/ConfigConstant.h"
#include "utils/url.h"
#include "utils/ParamUtils.h"
#include "naming/Instance.h"
namespace nacos{
@ -29,77 +34,200 @@ private:
volatile bool _allIPs;
public:
ServiceInfo();
ServiceInfo() : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""), _allIPs(false) {
}
bool isAllIPs() const;
bool isAllIPs() const{
return _allIPs;
}
void setAllIPs(bool allIPs);
void setAllIPs(bool allIPs) {
_allIPs = allIPs;
}
explicit ServiceInfo(const NacosString &key);
explicit ServiceInfo(const NacosString &key) : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""),
_allIPs(false) {
std::vector <NacosString> segs;
ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER);
ServiceInfo(const NacosString &name, const NacosString &clusters);
if (segs.size() == 2) {
setGroupName(segs[0]);
setName(segs[1]);
} else if (segs.size() == 3) {
setGroupName(segs[0]);
setName(segs[1]);
setClusters(segs[2]);
}
}
int ipCount();
ServiceInfo(const NacosString &name, const NacosString &clusters) {
_name = name;
_clusters = clusters;
}
bool expired() const;
int ipCount() {
return _hosts.size();
}
void setHosts(std::list <Instance> &hosts);
bool expired() const{
//TODO:extract this snippet to a common util
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
bool isValid();
return ms - _lastRefTime > _cacheMillis;
}
NacosString getName();
void setHosts(std::list <Instance> &hosts) {
_hosts = hosts;
}
void setName(const NacosString &name);
bool isValid() {
return _hosts.size() > 0;
}
NacosString getGroupName();
NacosString getName() {
return _name;
}
void setGroupName(const NacosString &groupName);
void setName(const NacosString &name) {
_name = name;
}
void setLastRefTime(long lastRefTime);
NacosString getGroupName() {
return _groupName;
}
long getLastRefTime();
void setGroupName(const NacosString &groupName) {
_groupName = groupName;
}
NacosString getClusters();
void setLastRefTime(long lastRefTime) {
_lastRefTime = lastRefTime;
}
void setClusters(const NacosString &clusters);
long getLastRefTime() {
return _lastRefTime;
}
long getCacheMillis();
NacosString getClusters() {
return _clusters;
}
void setCacheMillis(long cacheMillis);
void setClusters(const NacosString &clusters) {
_clusters = clusters;
}
std::list <Instance> getHosts();
long getCacheMillis() {
return _cacheMillis;
}
std::list <Instance> *getHostsNocopy();
void setCacheMillis(long cacheMillis) {
_cacheMillis = cacheMillis;
}
bool validate() const;
std::list <Instance> getHosts() {
return _hosts;
}
std::list <Instance> *getHostsNocopy() {
return &_hosts;
}
bool validate() const{
if (isAllIPs()) {
return true;
}
//TODO: Idk what does this mean in Java, ignore in C++
/*std::list<Instance> validHosts;
for (std::list<Instance>::iterator it = _hosts.begin()
it != _hosts.end(); it++)
{
if (it->isHealthy())
{
continue;
}
for (int i = 0; i < it->getWeight(); i++)
{
validHosts.push_back(*it);
}
}*/
return true;
}
//@JSONField(serialize = false)
NacosString getJsonFromServer() const;
NacosString getJsonFromServer() const{
return _jsonFromServer;
}
void setJsonFromServer(const NacosString &jsonFromServer);
void setJsonFromServer(const NacosString &jsonFromServer) {
_jsonFromServer = jsonFromServer;
}
//@JSONField(serialize = false)
NacosString getKey() const;
NacosString getKey() const{
return getKey(_name, _clusters);
}
//@JSONField(serialize = false)
NacosString getKeyEncoded() const;
NacosString getKeyEncoded() const{
return getKey(urlencode(_name), _clusters);
}
//@JSONField(serialize = false)
static void fromKey(ServiceInfo &serviceInfo, const NacosString &key);
static void fromKey(ServiceInfo &serviceInfo, const NacosString &key) {
std::vector <NacosString> segs;
ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER);
if (segs.size() == 2) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
} else if (segs.size() == 3) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
serviceInfo.setClusters(segs[2]);
}
}
//@JSONField(serialize = false)
static NacosString getKey(const NacosString &name, const NacosString &clusters);
static NacosString getKey(const NacosString &name, const NacosString &clusters) {
if (!ParamUtils::isBlank(clusters)) {
return name + ConfigConstant::SERVICE_INFO_SPLITER + clusters;
}
return name;
}
//@Override
NacosString toString() const;
NacosString toString() const{
return getKey();
}
//!!BE CAREFUL!!
//This function is very expensive!! call it with care!
NacosString toInstanceString() const;
NacosString toInstanceString() const{
NacosString res = "[\n";
for (std::list<Instance>::const_iterator it = _hosts.begin();
it != _hosts.end(); it++)
{
res += it->toString() + "\n";
}
NacosString getChecksum() const;
res += "\n]";
void setChecksum(const NacosString &checksum);
return res;
}
NacosString getChecksum() const{
return _checksum;
}
void setChecksum(const NacosString &checksum) {
_checksum = checksum;
}
};
}//namespace nacos

View File

@ -8,12 +8,13 @@
#include "NacosString.h"
#include "thread/AtomicInt.h"
#include "naming/ChangeAdvice.h"
#include "DebugAssertion.h"
namespace nacos{
class EventListener {
private:
NacosString listenerName;
AtomicInt<int> refCount;
AtomicInt refCount;
public:
EventListener() {
this->listenerName = "theListener";
@ -31,7 +32,7 @@ public:
virtual void receiveNamingInfo(const ServiceInfo &changeAdvice) = 0;
virtual ~EventListener();
virtual ~EventListener() { NACOS_ASSERT(refCnt() == 0) };
};
}//namespace nacos

View File

@ -2,30 +2,22 @@
#define __ATOMIC_INT_H_
namespace nacos{
template<typename T>
class AtomicInt {
private:
volatile T _curval;
volatile int _intval;
public:
AtomicInt(T curval = 0) : _curval(curval) {};
AtomicInt(int initval = 0) : _intval(initval) {};
void set(T val) { _curval = val; };
T inc(T incval = 1) {
T oldValue = getAndInc(incval);
int inc(int incval = 1) {
int oldValue = __sync_fetch_and_add(&_intval, incval);
return incval + oldValue;
};
T getAndInc(T incval = 1) {
T oldValue = __sync_fetch_and_add(&_curval, incval);
return oldValue;
}
T dec(int decval = 1) {
int dec(int decval = 1) {
return inc(-decval);
};
T get() const { return _curval; };
int get() const { return _intval; };
};
}//namespace nacos

View File

@ -1,119 +1,119 @@
#ifndef __GROUP_KEY_H_
#define __GROUP_KEY_H_
#include "NacosString.h"
#include "src/utils/url.h"
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Synthesize the form of dataId+groupId. Escapes reserved characters in dataId and groupId.
*
* @author Nacos
*/
namespace nacos{
class GroupKey {
public:
static NacosString getKey(const NacosString &dataId, const NacosString &group) {
//DataID+GroupId
return urlencode(dataId) + "+" + urlencode(group);
}
static NacosString getKeyTenant(const NacosString &dataId, const NacosString &group, const NacosString &tenant) {
//DataID+GroupId
NacosString key = getKey(dataId, group);
if (!isNull(tenant)) {
key = key + "+" + urlencode(tenant);
}
return key;
}
/*static NacosString getKey(const NacosString &dataId, const NacosString &group, const NacosString &datumStr)
{
//DataID+GroupId+datumStr
return urlencode(dataId) + "+" + urlencode(group) + "+" + urlencode(datumStr);
}*/
/*static public NacosString[] parseKey(NacosString groupKey) {
StringBuilder sb = new StringBuilder();
NacosString dataId = null;
NacosString group = null;
NacosString tenant = null;
for (int i = 0; i < groupKey.length(); ++i) {
char c = groupKey.charAt(i);
if ('+' == c) {
if (null == dataId) {
dataId = sb.toString();
sb.setLength(0);
} else if (null == group) {
group = sb.toString();
sb.setLength(0);
} else {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
} else if ('%' == c) {
char next = groupKey.charAt(++i);
char nextnext = groupKey.charAt(++i);
if ('2' == next && 'B' == nextnext) {
sb.append('+');
} else if ('2' == next && '5' == nextnext) {
sb.append('%');
} else {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
} else {
sb.append(c);
}
}
if (StringUtils.isBlank(group)) {
group = sb.toString();
if (group.length() == 0) {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
} else {
tenant = sb.toString();
if (group.length() == 0) {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
}
return new NacosString[] {dataId, group, tenant};
}*/
/**
* + -> %2B % -> %25
*/
/*static void urlEncode(NacosString str, StringBuilder sb) {
for (int idx = 0; idx < str.length(); ++idx) {
char c = str.charAt(idx);
if ('+' == c) {
sb.append("%2B");
} else if ('%' == c) {
sb.append("%25");
} else {
sb.append(c);
}
}
}*/
};
}//namespace nacos
#ifndef __GROUP_KEY_H_
#define __GROUP_KEY_H_
#include "NacosString.h"
#include "utils/url.h"
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Synthesize the form of dataId+groupId. Escapes reserved characters in dataId and groupId.
*
* @author Nacos
*/
namespace nacos{
class GroupKey {
public:
static NacosString getKey(const NacosString &dataId, const NacosString &group) {
//DataID+GroupId
return urlencode(dataId) + "+" + urlencode(group);
}
static NacosString getKeyTenant(const NacosString &dataId, const NacosString &group, const NacosString &tenant) {
//DataID+GroupId
NacosString key = getKey(dataId, group);
if (!isNull(tenant)) {
key = key + "+" + urlencode(tenant);
}
return key;
}
/*static NacosString getKey(const NacosString &dataId, const NacosString &group, const NacosString &datumStr)
{
//DataID+GroupId+datumStr
return urlencode(dataId) + "+" + urlencode(group) + "+" + urlencode(datumStr);
}*/
/*static public NacosString[] parseKey(NacosString groupKey) {
StringBuilder sb = new StringBuilder();
NacosString dataId = null;
NacosString group = null;
NacosString tenant = null;
for (int i = 0; i < groupKey.length(); ++i) {
char c = groupKey.charAt(i);
if ('+' == c) {
if (null == dataId) {
dataId = sb.toString();
sb.setLength(0);
} else if (null == group) {
group = sb.toString();
sb.setLength(0);
} else {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
} else if ('%' == c) {
char next = groupKey.charAt(++i);
char nextnext = groupKey.charAt(++i);
if ('2' == next && 'B' == nextnext) {
sb.append('+');
} else if ('2' == next && '5' == nextnext) {
sb.append('%');
} else {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
} else {
sb.append(c);
}
}
if (StringUtils.isBlank(group)) {
group = sb.toString();
if (group.length() == 0) {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
} else {
tenant = sb.toString();
if (group.length() == 0) {
throw new IllegalArgumentException("invalid groupkey:" + groupKey);
}
}
return new NacosString[] {dataId, group, tenant};
}*/
/**
* + -> %2B % -> %25
*/
/*static void urlEncode(NacosString str, StringBuilder sb) {
for (int idx = 0; idx < str.length(); ++idx) {
char c = str.charAt(idx);
if ('+' == c) {
sb.append("%2B");
} else if ('%' == c) {
sb.append("%25");
} else {
sb.append(c);
}
}
}*/
};
}//namespace nacos
#endif

View File

@ -1,36 +1,36 @@
#ifndef __NAMING_UTILS_H_
#define __NAMING_UTILS_H_
#include <vector>
#include "NacosString.h"
#include "constant/ConfigConstant.h"
#include "src/utils/ParamUtils.h"
namespace nacos{
class NamingUtils {
public:
static NacosString getGroupedName(const NacosString &serviceName, const NacosString &groupName) {
return groupName + ConfigConstant::SERVICE_INFO_SPLITER + serviceName;
}
static NacosString getServiceName(const NacosString &serviceNameWithGroup) {
if (!ParamUtils::contains(serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER)) {
return serviceNameWithGroup;
}
std::vector <NacosString> splittedNameNGroup;
ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER);
return splittedNameNGroup[1];
}
static NacosString getGroupName(const NacosString &serviceNameWithGroup) {
if (!ParamUtils::contains(serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER)) {
return ConfigConstant::DEFAULT_GROUP;
}
std::vector <NacosString> splittedNameNGroup;
ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER);
return splittedNameNGroup[0];
}
};
}//namespace nacos
#endif
#ifndef __NAMING_UTILS_H_
#define __NAMING_UTILS_H_
#include <vector>
#include "NacosString.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 + ConfigConstant::SERVICE_INFO_SPLITER + serviceName;
}
static NacosString getServiceName(const NacosString &serviceNameWithGroup) {
if (!ParamUtils::contains(serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER)) {
return serviceNameWithGroup;
}
std::vector <NacosString> splittedNameNGroup;
ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER);
return splittedNameNGroup[1];
}
static NacosString getGroupName(const NacosString &serviceNameWithGroup) {
if (!ParamUtils::contains(serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER)) {
return ConfigConstant::DEFAULT_GROUP;
}
std::vector <NacosString> splittedNameNGroup;
ParamUtils::Explode(splittedNameNGroup, serviceNameWithGroup, ConfigConstant::SERVICE_INFO_SPLITER);
return splittedNameNGroup[0];
}
};
}//namespace nacos
#endif

View File

@ -1,240 +1,229 @@
#ifndef __PARMUTILS_H_
#define __PARMUTILS_H_
#include <map>
#include <list>
#include <vector>
#include <assert.h>
#include "NacosString.h"
#include "NacosExceptions.h"
#include "constant/ConfigConstant.h"
namespace nacos{
class ParamUtils {
public:
template<typename T>
static const T &getNthElem(const std::list <T> &parm, size_t i) {
assert(parm.size() > i);
typename std::list<T>::const_iterator it = parm.begin();
for (size_t skipper = 0; skipper < i; skipper++) {
it++;
}
return *it;
}
static NacosString trim(const NacosString &content) {
int start = 0;
int end = content.size() - 1;
while (start < end && isBlank(content[start])) {
start++;
}
while (start < end && isBlank(content[end])) {
end--;
}
return NacosString(content.substr(start, end - start + 1));
}
static NacosString null2defaultGroup(const NacosString &group) {
return (isNull(group)) ? ConfigConstant::DEFAULT_GROUP : ParamUtils::trim(group);
}
static void parseString2KeyGroupTenant(const NacosString &stringToParse, NacosString &dataId, NacosString &group,
NacosString &tenant) {
std::vector <NacosString> KGT;//KeyGroupTenant
Explode(KGT, stringToParse, ConfigConstant::WORD_SEPARATOR);
dataId = KGT[0];
group = KGT[1];
if (KGT.size() == 3)//with tenant
{
tenant = KGT[2];
} else {
tenant = NULLSTR;
}
}
static bool isBlank(char character) {
switch (character) {
case ' ':
case '\t':
case '\r':
case '\n':
return true;
default:
return false;
}
}
static bool isBlank(const NacosString &content) {
//TODO:Apply ParamUtils.Java's logic to here, support whitespaces in other countries/zones
if (content.size() == 0) {
return true;
}
for (size_t i = 0; i < content.size(); i++) {
if (!isBlank(content[i]))
return false;
}
return true;
};
static bool isValid(const NacosString &content) {
return false;
};
static void
checkParam(const NacosString &dataId, const NacosString &group, const NacosString &content) NACOS_THROW(NacosException) {
if (isBlank(content)) {
throw NacosException(NacosException::CLIENT_INVALID_PARAM, "content invalid");
}
};
//A little trick here for NacosString constants
static void
Explode(std::vector <NacosString> &explodedList, const NacosString &stringToExplode, const NacosString &separator) {
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 <NacosString> &explodedList, const NacosString &stringToExplode, char separator) {
size_t start_pos = 0;
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 + 1;
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::list <NacosString> &explodedList, const NacosString &stringToExplode, char separator) {
size_t start_pos = 0;
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 + 1;
cur_pos = stringToExplode.find(separator, start_pos);
}
//deal with the last string
NacosString last_addr = stringToExplode.substr(start_pos);
explodedList.push_back(last_addr);
}
//use ',' as separator by default
static NacosString Implode(const std::list <NacosString> &toImplode) {
return Implode(toImplode, ',');
}
static NacosString Implode(const std::list <NacosString> &toImplode, char separator) {
NacosString implodedString;
for (std::list<NacosString>::const_iterator it = toImplode.begin();
it != toImplode.end(); /*it++ is within the for ... loop*/) {
implodedString += *it;
it++;
if (it != toImplode.end()) {
implodedString += ",";
}
}
return implodedString;
}
//use ',' as default separator to serialize a map
static NacosString Implode(const std::map <NacosString, NacosString> &toImplode) {
return Implode(toImplode, ',');
}
static NacosString Implode(const std::map <NacosString, NacosString> &toImplode, char separator) {
NacosString implodedString;
for (std::map<NacosString, NacosString>::const_iterator it = toImplode.begin(); it != toImplode.end(); it++) {
implodedString += it->first + "=" + it->second;
if (it != toImplode.end()) {
implodedString += ",";
}
}
return implodedString;
}
static bool contains(const NacosString &haystack, char needle) {
if (haystack.find(needle) != std::string::npos) {
return true;
}
return false;
}
static bool contains(const NacosString &haystack, const NacosString &needle) {
if (haystack.find(needle) != std::string::npos) {
return true;
}
return false;
}
static void addKV(std::list<NacosString> &list, const NacosString &key, const NacosString &value) {
list.push_back(key);
list.push_back(value);
}
static NacosString toLower(const NacosString &str) {
NacosString lowerCaseString;
for (NacosString::const_iterator it = str.begin(); it != str.end(); it++) {
lowerCaseString.push_back(tolower(*it));
}
return lowerCaseString;
}
static bool equals_ic(const NacosString &str1, const NacosString &str2) {
NacosString lcase_str1 = toLower(str1);
NacosString lcase_str2 = toLower(str2);
return lcase_str1 == lcase_str2;
}
static const NacosString &findByKey(const std::list <NacosString> &hayStack, const NacosString &needleKey) {
for (std::list<NacosString>::const_iterator it = hayStack.begin(); it != hayStack.end(); it++) {
if (*it == needleKey) {
it++;
return *it;
}
}
return NacosStringOps::nullstr;
}
};
}//namespace nacos
#endif
#ifndef __PARMUTILS_H_
#define __PARMUTILS_H_
#include <map>
#include <list>
#include <vector>
#include <assert.h>
#include "NacosString.h"
#include "NacosExceptions.h"
#include "constant/ConfigConstant.h"
namespace nacos{
class ParamUtils {
public:
template<typename T>
static const T &getNthElem(const std::list <T> &parm, size_t i) {
assert(parm.size() > i);
typename std::list<T>::const_iterator it = parm.begin();
for (size_t skipper = 0; skipper < i; skipper++) {
it++;
}
return *it;
}
static NacosString trim(const NacosString &content) {
int start = 0;
int end = content.size() - 1;
while (start < end && isBlank(content[start])) {
start++;
}
while (start < end && isBlank(content[end])) {
end--;
}
return NacosString(content.substr(start, end - start + 1));
}
static NacosString null2defaultGroup(const NacosString &group) {
return (isNull(group)) ? ConfigConstant::DEFAULT_GROUP : ParamUtils::trim(group);
}
static void parseString2KeyGroupTenant(const NacosString &stringToParse, NacosString &dataId, NacosString &group,
NacosString &tenant) {
std::vector <NacosString> KGT;//KeyGroupTenant
Explode(KGT, stringToParse, ConfigConstant::WORD_SEPARATOR);
dataId = KGT[0];
group = KGT[1];
if (KGT.size() == 3)//with tenant
{
tenant = KGT[2];
} else {
tenant = NULLSTR;
}
}
static bool isBlank(char character) {
switch (character) {
case ' ':
case '\t':
case '\r':
case '\n':
return true;
default:
return false;
}
}
static bool isBlank(const NacosString &content) {
//TODO:Apply ParamUtils.Java's logic to here, support whitespaces in other countries/zones
if (content.size() == 0) {
return true;
}
for (size_t i = 0; i < content.size(); i++) {
if (!isBlank(content[i]))
return false;
}
return true;
};
static bool isValid(const NacosString &content) {
return false;
};
static void
checkParam(const NacosString &dataId, const NacosString &group, const NacosString &content) NACOS_THROW(NacosException) {
if (isBlank(content)) {
throw NacosException(NacosException::CLIENT_INVALID_PARAM, "content invalid");
}
};
//A little trick here for NacosString constants
static void
Explode(std::vector <NacosString> &explodedList, const NacosString &stringToExplode, const NacosString &separator) {
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 <NacosString> &explodedList, const NacosString &stringToExplode, char separator) {
size_t start_pos = 0;
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 + 1;
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::list <NacosString> &explodedList, const NacosString &stringToExplode, char separator) {
size_t start_pos = 0;
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 + 1;
cur_pos = stringToExplode.find(separator, start_pos);
}
//deal with the last string
NacosString last_addr = stringToExplode.substr(start_pos);
explodedList.push_back(last_addr);
}
//use ',' as separator by default
static NacosString Implode(const std::list <NacosString> &toImplode) {
return Implode(toImplode, ',');
}
static NacosString Implode(const std::list <NacosString> &toImplode, char separator) {
NacosString implodedString;
for (std::list<NacosString>::const_iterator it = toImplode.begin();
it != toImplode.end(); /*it++ is within the for ... loop*/) {
implodedString += *it;
it++;
if (it != toImplode.end()) {
implodedString += ",";
}
}
return implodedString;
}
//use ',' as default separator to serialize a map
static NacosString Implode(const std::map <NacosString, NacosString> &toImplode) {
return Implode(toImplode, ',');
}
static NacosString Implode(const std::map <NacosString, NacosString> &toImplode, char separator) {
NacosString implodedString;
for (std::map<NacosString, NacosString>::const_iterator it = toImplode.begin(); it != toImplode.end(); it++) {
implodedString += it->first + "=" + it->second;
if (it != toImplode.end()) {
implodedString += ",";
}
}
return implodedString;
}
static bool contains(const NacosString &haystack, char needle) {
if (haystack.find(needle) != std::string::npos) {
return true;
}
return false;
}
static bool contains(const NacosString &haystack, const NacosString &needle) {
if (haystack.find(needle) != std::string::npos) {
return true;
}
return false;
}
static void addKV(std::list<NacosString> &list, const NacosString &key, const NacosString &value) {
list.push_back(key);
list.push_back(value);
}
static NacosString toLower(const NacosString &str) {
NacosString lowerCaseString;
for (NacosString::const_iterator it = str.begin(); it != str.end(); it++) {
lowerCaseString.push_back(tolower(*it));
}
return lowerCaseString;
}
static bool equals_ic(const NacosString &str1, const NacosString &str2) {
NacosString lcase_str1 = toLower(str1);
NacosString lcase_str2 = toLower(str2);
return lcase_str1 == lcase_str2;
}
};
}//namespace nacos
#endif

View File

@ -1,27 +1,27 @@
#ifndef __UUID_UTILS_H_
#define __UUID_UTILS_H_
#include "NacosString.h"
#define UUID_LEN_BYTES 16
/**
* UuidUtils
*
* @author yzz-ihep
* Generates UUID from /dev/urandom
*/
namespace nacos{
class UuidUtils {
private:
public:
static NacosString generateUuid();
static void Init();
static void DeInit();
};
}//namespace nacos
#endif
#ifndef __UUID_UTILS_H_
#define __UUID_UTILS_H_
#include "NacosString.h"
#define UUID_LEN_BYTES 16
/**
* UuidUtils
*
* @author yzz-ihep
* Generates UUID from /dev/urandom
*/
namespace nacos{
class UuidUtils {
private:
public:
static NacosString generateUuid();
static void Init();
static void DeInit();
};
}//namespace nacos
#endif

View File

@ -1,12 +1,12 @@
#ifndef __URL_H_
#define __URL_H_
#include "NacosString.h"
namespace nacos{
NacosString urlencode(const NacosString &content);
NacosString urldecode(const NacosString &content);
}//namespace nacos
#ifndef __URL_H_
#define __URL_H_
#include "NacosString.h"
namespace nacos{
NacosString urlencode(const NacosString &content);
NacosString urldecode(const NacosString &content);
}//namespace nacos
#endif

View File

@ -1,12 +1,11 @@
#!!please NOTE that the file format for this properties should be UNIX!!
#specify nacos server address here(separated by ,)
#serverAddr=
#log path, default is ~/nacos/logs/
#nacos.log.path=
#rotate size (number [+ unit], unit can be k/K m/M g/G. the size is regarded as byte if there is no unit)
#nacos.log.rotateSize=100m
#rotate time (now we only support hour as unit)
#nacos.log.rotateTime=24h
#log level, default is ERROR
#nacos.log.level=ERROR
@ -33,6 +32,3 @@
#poller interval (10000 ms by default) to refresh subscribed service information from server
#naming.poller.interval=
#accessKey/secretKey for SPAS
#accessKey=
#secretKey=

View File

@ -1,16 +1,15 @@
#include "src/utils/ParamUtils.h"
#include "utils/ParamUtils.h"
#include "AppConfigManager.h"
#include "NacosString.h"
#include "Properties.h"
#include "src/utils/NetUtils.h"
#include "constant/PropertyKeyConst.h"
#include "NacosExceptions.h"
#include "src/utils/DirUtils.h"
#include "utils/DirUtils.h"
#include <vector>
#include <stdlib.h>
#include "src/log/Logger.h"
#include "src/utils/ConfigParserUtils.h"
#include "src/utils/Env.h"
using namespace std;
@ -50,7 +49,7 @@ void AppConfigManager::clearConfig() {
appConfig.clear();
}
const NacosString& AppConfigManager::get(const NacosString &key) {
const NacosString &AppConfigManager::get(const NacosString &key) {
if (appConfig.count(key) == 0) {
return NULLSTR;
}
@ -60,13 +59,7 @@ const NacosString& AppConfigManager::get(const NacosString &key) {
{
return NULLSTR;
}
Properties::iterator iter = appConfig.find(key);
if (iter == appConfig.end()) {
return NULLSTR;
}
return iter->second;
return appConfig[key];
}
void AppConfigManager::set(const NacosString &key, const NacosString &value) {
@ -94,15 +87,6 @@ AppConfigManager::AppConfigManager(const NacosString &_configFile) {
configFile = _configFile;
}
NacosString getAppNameFromEnv() {
const char* env = getEnv("APP_NAME");
if (env != NULL && std::char_traits<char>::length(env) > 0) {
return NacosString(env);
}
return NacosStringOps::nullstr;
}
void AppConfigManager::initDefaults() {
appConfig.clear();
//appConfig[PropertyKeyConst::NAMESPACE] = "public";
@ -116,15 +100,8 @@ void AppConfigManager::initDefaults() {
set(PropertyKeyConst::LOCAL_IP, NetUtils::getHostIp());
set(PropertyKeyConst::UDP_RECEIVER_PORT, "30620");
NacosString appName = getAppNameFromEnv();
if (!NacosStringOps::isNullStr(appName)) {
set(PropertyKeyConst::APP_NAME, appName);
}
NacosString homedir = DirUtils::getHome();
set(PropertyKeyConst::INSTANCE_ID_PREFIX, NetUtils::getHostName());
set(PropertyKeyConst::INSTANCE_ID_SEQ_FILE, homedir + ConfigConstant::FILE_SEPARATOR + "nacos" + ConfigConstant::FILE_SEPARATOR + "instance_seq.dat");
set(PropertyKeyConst::NACOS_SNAPSHOT_PATH, homedir + ConfigConstant::FILE_SEPARATOR + "nacos" + ConfigConstant::FILE_SEPARATOR + "snapshot");
log_info("[AppConfigManager]-initDefaults:DEFAULT_SNAPSHOT_PATH:%s\n", appConfig[PropertyKeyConst::NACOS_SNAPSHOT_PATH].c_str());
}

View File

@ -47,7 +47,7 @@ public:
bool contains(const NacosString &key) const;
const Properties& getAllConfig() { return appConfig; };
Properties getAllConfig() const { return appConfig; };
const NacosString & getContextPath() const { return _contextPath; };

View File

@ -26,7 +26,7 @@ ConcurrentDiskUtil::getFileContent(const NacosString &file, const NacosString &c
FILE *fp = fopen(file.c_str(), "rb");
if (fp == NULL) {
char errbuf[100];
snprintf(errbuf, sizeof(errbuf), "Failed to open file for read, errno: %d", errno);
sprintf(errbuf, "Failed to open file for read, errno: %d", errno);
//TODO:add errorcode
throw IOException(NacosException::UNABLE_TO_OPEN_FILE, errbuf);
}
@ -57,7 +57,7 @@ bool ConcurrentDiskUtil::writeFileContent
FILE *fp = fopen(path.c_str(), "wb");
if (fp == NULL) {
char errbuf[100];
snprintf(errbuf, sizeof(errbuf), "Failed to open file for write, errno: %d", errno);
sprintf(errbuf, "Failed to open file for write, errno: %d", errno);
//TODO:add errorcode
throw IOException(NacosException::UNABLE_TO_OPEN_FILE, errbuf);
}

View File

@ -1,79 +0,0 @@
//
// Created by liuhanyu on 2021/7/6.
//
#include "ConfigProxy.h"
#include "src/http/HttpDelegate.h"
#include "src/utils/ParamUtils.h"
#include "src/utils/TimeUtils.h"
#include "src/config/AppConfigManager.h"
#include "constant/PropertyKeyConst.h"
#include "src/crypto/SignatureTool.h"
namespace nacos {
NacosString ConfigProxy::getDataToSign(const std::list <NacosString> &paramValues, const NacosString &nowTimeMs) {
const NacosString & group = ParamUtils::findByKey(paramValues, "group");
const NacosString & tenant = ParamUtils::findByKey(paramValues, "tenant");
NacosString dataToSign = "";
if (!NacosStringOps::isNullStr(tenant)) {
dataToSign = tenant + "+";
}
if (!NacosStringOps::isNullStr(group)) {
dataToSign += group;
}
if (!NacosStringOps::isNullStr(dataToSign)) {
dataToSign += "+" + nowTimeMs;
} else {
dataToSign = nowTimeMs;
}
return dataToSign;
}
HttpResult ConfigProxy::reqAPI
(
int method,
const NacosString &path,
std::list <NacosString> &headers,
std::list <NacosString> &paramValues,
const NacosString &encoding,
long readTimeoutMs
) NACOS_THROW(NetworkException) {
HttpDelegate *_httpDelegate = _objectConfigData->_httpDelegate;
//TODO: refactor to a common procedure
const NacosString& secretKey = _objectConfigData->_appConfigManager->get(PropertyKeyConst::SECRET_KEY);
const NacosString& accessKey = _objectConfigData->_appConfigManager->get(PropertyKeyConst::ACCESS_KEY);
const NacosString& appName = _objectConfigData->_appConfigManager->get(PropertyKeyConst::APP_NAME);
//If SPAS security credentials are set, SPAS is enabled
if (!ParamUtils::isBlank(secretKey) && !ParamUtils::isBlank(accessKey)) {
NacosString nowTimeMs = NacosStringOps::valueOf(TimeUtils::getCurrentTimeInMs());
NacosString dataToSign = getDataToSign(paramValues, nowTimeMs);
NacosString signature = SignatureTool::SignWithHMAC_SHA1(dataToSign, secretKey);
ParamUtils::addKV(headers, "Spas-Signature", signature);
ParamUtils::addKV(headers, "Timestamp", nowTimeMs);
ParamUtils::addKV(headers, "Spas-AccessKey", accessKey);
}
if (!NacosStringOps::isNullStr(appName)) {
ParamUtils::addKV(headers, "Client-AppName", appName);
}
switch (method) {
case IHttpCli::GET:
return _httpDelegate->httpGet(path, headers, paramValues, encoding, readTimeoutMs);
case IHttpCli::POST:
return _httpDelegate->httpPost(path, headers, paramValues, encoding, readTimeoutMs);
case IHttpCli::PUT:
return _httpDelegate->httpPut(path, headers, paramValues, encoding, readTimeoutMs);
case IHttpCli::DELETE:
return _httpDelegate->httpDelete(path, headers, paramValues, encoding, readTimeoutMs);
default://should never happen
abort();
}
}
}

View File

@ -1,25 +0,0 @@
//
// Created by liuhanyu on 2021/7/6.
//
#ifndef NACOS_SDK_CPP_CONFIGPROXY_H
#define NACOS_SDK_CPP_CONFIGPROXY_H
#include "src/factory/ObjectConfigData.h"
#include "src/http/IHttpCli.h"
namespace nacos {
class ConfigProxy {
private:
ObjectConfigData *_objectConfigData;
NacosString getDataToSign(const std::list <NacosString> &paramValues, const NacosString &nowTimeMs);
public:
ConfigProxy(ObjectConfigData *objectConfigData) : _objectConfigData(objectConfigData) {};
HttpResult reqAPI(int method, const NacosString &path, std::list <NacosString> &headers, std::list <NacosString> &paramValues,
const NacosString &encoding, long readTimeoutMs) NACOS_THROW(NetworkException);
};
}
#endif //NACOS_SDK_CPP_CONFIGPROXY_H

View File

@ -6,8 +6,8 @@
#include <errno.h>
#include "NacosExceptions.h"
#include "NacosString.h"
#include "src/utils/ParamUtils.h"
#include "src/utils/DirUtils.h"
#include "utils/ParamUtils.h"
#include "utils/DirUtils.h"
#include "SnapShotSwitch.h"
#include "JVMUtil.h"
#include "ConcurrentDiskUtil.h"

View File

@ -1,8 +1,6 @@
#include "NacosConfigService.h"
#include "src/config/NacosConfigService.h"
#include "src/security/SecurityManager.h"
#include "src/log/Logger.h"
#include "ConfigProxy.h"
#include "src/utils/ParamUtils.h"
using namespace std;
@ -74,14 +72,11 @@ NacosString NacosConfigService::getConfigInner
result = _objectConfigData->_clientWorker->getServerConfig(tenant, dataId, group, timeoutMs);
} catch (NacosException &e) {
if (e.errorcode() == NacosException::NO_RIGHT) {
log_error("Invalid credential, e: %d = %s\n", e.errorcode(), e.what());
}
const NacosString &clientName = _appConfigManager->get(PropertyKeyConst::CLIENT_NAME);
result = _localSnapshotManager->getSnapshot(clientName, dataId, group, tenant);
if (e.errorcode() == NacosException::NO_RIGHT && NacosStringOps::isNullStr(result)) {
//permission denied and no failback, let user decide what to do
throw e;
}
const NacosString &clientName = _appConfigManager->get(PropertyKeyConst::CLIENT_NAME);
result = _localSnapshotManager->getSnapshot(clientName, dataId, group, tenant);
}
return result;
}
@ -116,9 +111,9 @@ bool NacosConfigService::removeConfigInner
NacosString url = serverAddr + "/" + path;
log_debug("[NacosConfigService]-removeConfigInner: Assembled URL:%s\n", url.c_str());
ConfigProxy *_configProxy = _objectConfigData->_configProxy;
HttpDelegate *_httpDelegate = _objectConfigData->_httpDelegate;
try {
res = _configProxy->reqAPI(IHttpCli::DELETE, url, headers, paramValues, _objectConfigData->encoding, POST_TIMEOUT);
res = _httpDelegate->httpDelete(url, headers, paramValues, _httpDelegate->getEncode(), POST_TIMEOUT);
}
catch (NetworkException &e) {
log_warn("[NacosConfigService]-removeConfigInner: error, %s, %s, %s, msg: %s\n", dataId.c_str(), group.c_str(), tenant.c_str(), e.what());
@ -181,9 +176,9 @@ bool NacosConfigService::publishConfigInner
NacosString url = serverAddr + "/" + path;
log_debug("[NacosConfigService]-publishConfigInner:httpPost Assembled URL:%s\n", url.c_str());
ConfigProxy *_configProxy = _objectConfigData->_configProxy;
HttpDelegate *_httpDelegate = _objectConfigData->_httpDelegate;
try {
res = _configProxy->reqAPI(IHttpCli::POST, url, headers, paramValues, _objectConfigData->encoding, POST_TIMEOUT);
res = _httpDelegate->httpPost(url, headers, paramValues, _httpDelegate->getEncode(), POST_TIMEOUT);
}
catch (NetworkException &e) {
//

View File

@ -9,22 +9,16 @@ const NacosString PropertyKeyConst::ENDPOINT_PORT = "endpointPort";
const NacosString PropertyKeyConst::NAMESPACE = "namespace";
const NacosString PropertyKeyConst::ENDPOINT_QUERY_PARAMS = "endpointQueryParams";
const NacosString PropertyKeyConst::ACCESS_KEY = "accessKey";
const NacosString PropertyKeyConst::SECRET_KEY = "secretKey";
const NacosString PropertyKeyConst::APP_NAME = "appName";
const NacosString PropertyKeyConst::RAM_ROLE_NAME = "ramRoleName";
const NacosString PropertyKeyConst::SERVER_ADDR = "serverAddr";
const NacosString PropertyKeyConst::CONTEXT_PATH = "nacos.server.contextpath";
const NacosString PropertyKeyConst::ENDPOINT_CONTEXT_PATH = "endpointContextPath";
const NacosString PropertyKeyConst::CLUSTER_NAME = "clusterName";
const NacosString PropertyKeyConst::ENCODE = "encode";
@ -49,13 +43,11 @@ const NacosString PropertyKeyConst::HB_FAIL_WAIT_TIME = "naming.heartbeat.failwa
const NacosString PropertyKeyConst::NACOS_SNAPSHOT_PATH = "nacos.snapshot.path";
const NacosString PropertyKeyConst::LOG_PATH = "nacos.log.path";
const NacosString PropertyKeyConst::LOG_ROTATE_SIZE = "nacos.log.rotateSize";
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";
const NacosString PropertyKeyConst::INSTANCE_ID_SEQ_FILE = "nacos.instId.seq.file";
const NacosString PropertyKeyConst::INSTANCE_ID_PREFIX = "nacos.instId.prefix";
}//namespace nacos

View File

@ -1,54 +0,0 @@
//
// Created by liuhanyu on 2021/7/8.
//
#include "MACProvider.h"
#include "src/crypto/hmac_sha1/hmac/hmac.h"
namespace nacos {
std::map<int, IMAC*> *MACProvider::MACRegistry;
const int MACProvider::HMAC_SHA1;
class HMACSha1 : public IMAC {
public:
void getMac(const void *k, /* secret key */
size_t lk, /* length of the key in bytes */
const void *d, /* data */
size_t ld, /* length of data in bytes */
void *out, /* output buffer, at least "t" bytes */
size_t *t);
};
void HMACSha1::getMac(const void *k, /* secret key */
size_t lk, /* length of the key in bytes */
const void *d, /* data */
size_t ld, /* length of data in bytes */
void *out, /* output buffer, at least "t" bytes */
size_t *t) {
hmac_sha1((const uint8_t*)k, lk, (const uint8_t*)d, ld, (uint8_t*)out, t);
}
void MACProvider::Init() {
MACRegistry = new std::map<int, IMAC*>();
(*MACRegistry)[MACProvider::HMAC_SHA1] = new HMACSha1();
}
void MACProvider::DeInit() {
for (std::map<int, IMAC*>::iterator it = MACRegistry->begin(); it != MACRegistry->end(); it++) {
IMAC * curMACProvider = it->second;
delete curMACProvider;
}
delete MACRegistry;
}
IMAC *MACProvider::getMAC(int algorithm) {
if (MACRegistry->count(algorithm) > 0) {
return (*MACRegistry)[algorithm];
}
return NULL;
}
}

View File

@ -1,35 +0,0 @@
//
// Created by liuhanyu on 2021/7/8.
//
#ifndef NACOS_SDK_CPP_MACPROVIDER_H
#define NACOS_SDK_CPP_MACPROVIDER_H
#include "NacosString.h"
#include <map>
namespace nacos {
class IMAC {
public:
virtual void getMac(const void *k, /* secret key */
size_t lk, /* length of the key in bytes */
const void *d, /* data */
size_t ld, /* length of data in bytes */
void *out, /* output buffer, at least "t" bytes */
size_t *t) = 0;
virtual ~IMAC() {};
};
class MACProvider {
private:
static std::map<int, IMAC*> *MACRegistry;
public:
static void Init();
static void DeInit();
static IMAC *getMAC(int algorithm);
static const int HMAC_SHA1 = 930620;
};
}
#endif //NACOS_SDK_CPP_MACPROVIDER_H

View File

@ -1,36 +0,0 @@
//
// Created by liuhanyu on 2021/7/8.
//
#ifndef SIGNATURE_TOOL
#define SIGNATURE_TOOL
#include "NacosString.h"
#include "MACProvider.h"
#include "base64/base64.h"
#include "src/debug/DebugAssertion.h"
namespace nacos {
/**
* SignatureTool
*
* @author Liu, Hanyu
* Signature tool
*/
class SignatureTool {
public:
//Returns a base64-encoded signature string
static NacosString SignWithHMAC_SHA1(const NacosString &dataToSign, const NacosString &secretKey) {
IMAC *digester = MACProvider::getMAC(MACProvider::HMAC_SHA1);
unsigned char signature[20];
size_t outlen = sizeof(signature);
digester->getMac(secretKey.c_str(), secretKey.length(), dataToSign.c_str(), dataToSign.length(), (void*)signature, &outlen);
NACOS_ASSERT(outlen == 20);//must be 20 since we're using HMAC_SHA1
NacosString encoded_signature = base64_encode(signature, sizeof(signature));
return encoded_signature;
}
};
}
#endif //NACOS_SDK_CPP_MACPROVIDER_H

View File

@ -1,72 +0,0 @@
/*
* Base64 encoding/decoding (RFC1341)
* Copyright (c) 2005-2011, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
// 2016-12-12 - Gaspard Petit : Slightly modified to return a std::string
// instead of a buffer allocated with malloc.
#include <string>
namespace nacos {
static const unsigned char base64_table[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* base64_encode - Base64 encode
* @src: Data to be encoded
* @len: Length of the data to be encoded
* @out_len: Pointer to output length variable, or %NULL if not used
* Returns: Allocated buffer of out_len bytes of encoded data,
* or empty string on failure
*/
static std::string base64_encode(const unsigned char *src, size_t len)
{
unsigned char *out, *pos;
const unsigned char *end, *in;
size_t olen;
olen = 4*((len + 2) / 3); /* 3-byte blocks to 4-byte */
if (olen < len)
return std::string(); /* integer overflow */
std::string outStr;
outStr.resize(olen);
out = (unsigned char*)&outStr[0];
end = src + len;
in = src;
pos = out;
while (end - in >= 3) {
*pos++ = base64_table[in[0] >> 2];
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
*pos++ = base64_table[in[2] & 0x3f];
in += 3;
}
if (end - in) {
*pos++ = base64_table[in[0] >> 2];
if (end - in == 1) {
*pos++ = base64_table[(in[0] & 0x03) << 4];
*pos++ = '=';
}
else {
*pos++ = base64_table[((in[0] & 0x03) << 4) |
(in[1] >> 4)];
*pos++ = base64_table[(in[1] & 0x0f) << 2];
}
*pos++ = '=';
}
return outStr;
}
}

View File

@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Bob Liu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,19 +0,0 @@
hmac-sha1
=========
[![Build Status](https://travis-ci.org/Akagi201/hmac-sha1.svg)](https://travis-ci.org/Akagi201/hmac-sha1)
Standalone implementation of `HMAC()` + `EVP_sha1()` in `OpenSSL`
## API
```
#include "hmac/hmac.h"
void hmac_sha1(const uint8_t *k, /* secret key */
size_t lk, /* length of the key in bytes */
const uint8_t *d, /* data */
size_t ld, /* length of data in bytes */
uint8_t *out, /* output buffer, at least "t" bytes */
size_t *t);
```

View File

@ -1,19 +0,0 @@
/**
* @file re_hmac.h Interface to HMAC functions
*
* Copyright (C) 2010 Creytiv.com
*/
#ifndef HMAC_H_
#define HMAC_H_ (1)
#include <stdint.h>
void hmac_sha1(const uint8_t *k, /* secret key */
size_t lk, /* length of the key in bytes */
const uint8_t *d, /* data */
size_t ld, /* length of data in bytes */
uint8_t *out, /* output buffer, at least "t" bytes */
size_t *t);
#endif // HMAC_H_

View File

@ -1,106 +0,0 @@
/**
* @file hmac_sha1.c Implements HMAC-SHA1 as of RFC 2202
*
* Copyright (C) 2010 Creytiv.com
*/
#include <string.h>
#include <stdint.h>
#ifdef USE_OPENSSL
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/err.h>
#else
#include "../sha/sha.h"
#endif
#include "hmac.h"
/** SHA-1 Block size */
#ifndef SHA_BLOCKSIZE
#define SHA_BLOCKSIZE (64)
#endif
/**
* Function to compute the digest
*
* @param k Secret key
* @param lk Length of the key in bytes
* @param d Data
* @param ld Length of data in bytes
* @param out Digest output
* @param t Size of digest output
*/
void hmac_sha1(const uint8_t *k, /* secret key */
size_t lk, /* length of the key in bytes */
const uint8_t *d, /* data */
size_t ld, /* length of data in bytes */
uint8_t *out, /* output buffer, at least "t" bytes */
size_t *t) {
#ifdef USE_OPENSSL
if (!HMAC(EVP_sha1(), k, (int)lk, d, ld, out, t)) {
ERR_clear_error();
}
#else
SHA_CTX ictx, octx;
uint8_t isha[SHA_DIGEST_LENGTH], osha[SHA_DIGEST_LENGTH];
uint8_t key[SHA_DIGEST_LENGTH];
uint8_t buf[SHA_BLOCKSIZE];
size_t i;
if (lk > SHA_BLOCKSIZE) {
SHA_CTX tctx;
SHA1_Init(&tctx);
SHA1_Update(&tctx, k, lk);
SHA1_Final(key, &tctx);
k = key;
lk = SHA_DIGEST_LENGTH;
}
/**** Inner Digest ****/
SHA1_Init(&ictx);
/* Pad the key for inner digest */
for (i = 0; i < lk; ++i) {
buf[i] = k[i] ^ 0x36;
}
for (i = lk; i < SHA_BLOCKSIZE; ++i) {
buf[i] = 0x36;
}
SHA1_Update(&ictx, buf, SHA_BLOCKSIZE);
SHA1_Update(&ictx, d, ld);
SHA1_Final(isha, &ictx);
/**** Outer Digest ****/
SHA1_Init(&octx);
/* Pad the key for outter digest */
for (i = 0; i < lk; ++i) {
buf[i] = k[i] ^ 0x5c;
}
for (i = lk; i < SHA_BLOCKSIZE; ++i) {
buf[i] = 0x5c;
}
SHA1_Update(&octx, buf, SHA_BLOCKSIZE);
SHA1_Update(&octx, isha, SHA_DIGEST_LENGTH);
SHA1_Final(osha, &octx);
/* truncate and print the results */
*t = *t > SHA_DIGEST_LENGTH ? SHA_DIGEST_LENGTH : *t;
memcpy(out, osha, *t);
#endif
}

View File

@ -1,42 +0,0 @@
/**
* @file re_sha.h Interface to SHA (Secure Hash Standard) functions
*
* Copyright (C) 2010 Creytiv.com
*/
#ifndef SHA_H_
#define SHA_H_ (1)
#ifdef USE_OPENSSL
#include <openssl/sha.h>
#else
/* public api for steve reid's public domain SHA-1 implementation */
/* this file is in the public domain */
/** SHA-1 Context */
typedef struct {
uint32_t state[5];
/**< Context state */
uint32_t count[2];
/**< Counter */
uint8_t buffer[64]; /**< SHA-1 buffer */
} SHA1_CTX;
/** SHA-1 Context (OpenSSL compat) */
typedef SHA1_CTX SHA_CTX;
/** SHA-1 Digest size in bytes */
#define SHA1_DIGEST_SIZE 20
/** SHA-1 Digest size in bytes (OpenSSL compat) */
#define SHA_DIGEST_LENGTH SHA1_DIGEST_SIZE
void SHA1_Init(SHA1_CTX *context);
void SHA1_Update(SHA1_CTX *context, const void *p, size_t len);
void SHA1_Final(uint8_t digest[SHA1_DIGEST_SIZE], SHA1_CTX *context);
#endif
#endif // SHA_H_

View File

@ -1,328 +0,0 @@
/**
* @file sha1.c SHA-1 in C
*/
/*
By Steve Reid <sreid@sea-to-sky.net>
100% Public Domain
-----------------
Modified 7/98
By James H. Brown <jbrown@burgoyne.com>
Still 100% Public Domain
Corrected a problem which generated improper hash values on 16 bit machines
Routine SHA1Update changed from
void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int
len)
to
void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned
long len)
The 'len' parameter was declared an int which works fine on 32 bit machines.
However, on 16 bit machines an int is too small for the shifts being done
against
it. This caused the hash function to generate incorrect values if len was
greater than 8191 (8K - 1) due to the 'len << 3' on line 3 of SHA1Update().
Since the file IO in main() reads 16K at a time, any file 8K or larger would
be guaranteed to generate the wrong hash (e.g. Test Vector #3, a million
"a"s).
I also changed the declaration of variables i & j in SHA1Update to
unsigned long from unsigned int for the same reason.
These changes should make no difference to any 32 bit implementations since
an
int and a long are the same size in those environments.
--
I also corrected a few compiler warnings generated by Borland C.
1. Added #include <process.h> for exit() prototype
2. Removed unused variable 'j' in SHA1Final
3. Changed exit(0) to return(0) at end of main.
ALL changes I made can be located by searching for comments containing 'JHB'
-----------------
Modified 8/98
By Steve Reid <sreid@sea-to-sky.net>
Still 100% public domain
1- Removed #include <process.h> and used return() instead of exit()
2- Fixed overwriting of finalcount in SHA1Final() (discovered by Chris Hall)
3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net
-----------------
Modified 4/01
By Saul Kravitz <Saul.Kravitz@celera.com>
Still 100% PD
Modified to run on Compaq Alpha hardware.
-----------------
Modified 07/2002
By Ralph Giles <giles@artofcode.com>
Still 100% public domain
modified for use with stdint types, autoconf
code cleanup, removed attribution comments
switched SHA1Final() argument order for consistency
use SHA1_ prefix for public api
move public api to sha1.h
*/
/*
Test Vectors (from FIPS PUB 180-1)
"abc"
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
A million repetitions of "a"
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/
#define SHA1HANDSOFF (1)
#include <stdint.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#include "sha.h"
void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]);
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
#if defined (BYTE_ORDER) && defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN)
#define WORDS_BIGENDIAN 1
#endif
#ifdef _BIG_ENDIAN
#define WORDS_BIGENDIAN 1
#endif
/* blk0() and blk() perform the initial expand. */
/* I got the idea of expanding during the round function from SSLeay */
/* FIXME: can we do this in an endian-proof way? */
#ifdef WORDS_BIGENDIAN
#define blk0(i) block->l[i]
#else
#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xff00ff00) \
|(rol(block->l[i],8)&0x00ff00ff))
#endif
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
^block->l[(i+2)&15]^block->l[i&15],1))
/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v, w, x, y, z, i) \
z+=((w&(x^y))^y)+blk0(i)+0x5a827999+rol(v,5);w=rol(w,30);
#define R1(v, w, x, y, z, i) \
z+=((w&(x^y))^y)+blk(i)+0x5a827999+rol(v,5);w=rol(w,30);
#define R2(v, w, x, y, z, i) \
z+=(w^x^y)+blk(i)+0x6ed9eba1+rol(v,5);w=rol(w,30);
#define R3(v, w, x, y, z, i) \
z+=(((w|x)&y)|(w&x))+blk(i)+0x8f1bbcdc+rol(v,5);w=rol(w,30);
#define R4(v, w, x, y, z, i) \
z+=(w^x^y)+blk(i)+0xca62c1d6+rol(v,5);w=rol(w,30);
/* Hash a single 512-bit block. This is the core of the algorithm. */
void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]) {
uint32_t a, b, c, d, e;
typedef union {
uint8_t c[64];
uint32_t l[16];
} CHAR64LONG16;
CHAR64LONG16 *block;
#ifdef SHA1HANDSOFF
CHAR64LONG16 workspace;
block = &workspace;
memcpy(block, buffer, 64);
#else
block = (CHAR64LONG16*)buffer;
#endif
/* Copy context->state[] to working vars */
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* 4 rounds of 20 operations each. Loop unrolled. */
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
/* Add the working vars back into context.state[] */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Wipe variables */
a = b = c = d = e = 0;
}
/**
* Initialize new context
*
* @param context SHA1-Context
*/
void SHA1_Init(SHA1_CTX *context) {
/* SHA1 initialization constants */
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
context->state[4] = 0xc3d2e1f0;
context->count[0] = context->count[1] = 0;
}
/**
* Run your data through this
*
* @param context SHA1-Context
* @param p Buffer to run SHA1 on
* @param len Number of bytes
*/
void SHA1_Update(SHA1_CTX *context, const void *p, size_t len) {
const uint8_t *data = (const uint8_t *)p;
size_t i, j;
j = (context->count[0] >> 3) & 63;
if ((context->count[0] += (uint32_t) (len << 3)) < (len << 3)) {
context->count[1]++;
}
context->count[1] += (uint32_t) (len >> 29);
if ((j + len) > 63) {
memcpy(&context->buffer[j], data, (i = 64 - j));
SHA1_Transform(context->state, context->buffer);
for (; i + 63 < len; i += 64) {
SHA1_Transform(context->state, data + i);
}
j = 0;
}
else i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
/**
* Add padding and return the message digest
*
* @param digest Generated message digest
* @param context SHA1-Context
*/
void SHA1_Final(uint8_t digest[SHA1_DIGEST_SIZE], SHA1_CTX *context) {
uint32_t i;
uint8_t finalcount[8];
for (i = 0; i < 8; i++) {
finalcount[i] = (uint8_t) ((context->count[(i >= 4 ? 0 : 1)]
>> ((3 - (i & 3)) * 8)) & 255);
}
SHA1_Update(context, (uint8_t *) "\200", 1);
while ((context->count[0] & 504) != 448) {
SHA1_Update(context, (uint8_t *) "\0", 1);
}
SHA1_Update(context, finalcount, 8); /* Should cause SHA1_Transform */
for (i = 0; i < SHA1_DIGEST_SIZE; i++) {
digest[i] = (uint8_t)
((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
/* Wipe variables */
i = 0;
memset(context->buffer, 0, 64);
memset(context->state, 0, 20);
memset(context->count, 0, 8);
memset(finalcount, 0, 8); /* SWR */
#ifdef SHA1HANDSOFF /* make SHA1Transform overwrite its own static vars */
SHA1_Transform(context->state, context->buffer);
#endif
}

View File

@ -1,15 +0,0 @@
#include "factory/NacosFactoryFactory.h"
#include "src/factory/NacosServiceFactory.h"
namespace nacos {
INacosServiceFactory *NacosFactoryFactory::getNacosFactory(const NacosString &_configFile) {
NacosServiceFactory *factory = new NacosServiceFactory(_configFile);
return factory;
}
INacosServiceFactory *NacosFactoryFactory::getNacosFactory(Properties &_props) {
NacosServiceFactory *factory = new NacosServiceFactory(_props);
return factory;
}
}

View File

@ -2,7 +2,7 @@
// Created by liuhanyu on 2020/8/30.
//
#include "src/factory/NacosServiceFactory.h"
#include "factory/NacosServiceFactory.h"
#include "src/init/Init.h"
#include "src/naming/NacosNamingService.h"
#include "src/naming/NacosNamingMaintainService.h"
@ -19,9 +19,7 @@
#include "src/naming/subscribe/HostReactor.h"
#include "src/security/SecurityManager.h"
#include "src/utils/ConfigParserUtils.h"
#include "src/utils/SequenceProvider.h"
#include "src/config/ConfigProxy.h"
#include "src/utils/DirUtils.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{
@ -83,7 +81,7 @@ NamingService *NacosServiceFactory::CreateNamingService() NACOS_THROW(NacosExcep
checkConfig();
ObjectConfigData *objectConfigData = new ObjectConfigData(NAMING);
objectConfigData->name = "config";
objectConfigData->encoding = "UTF-8";
NacosString encoding = "UTF-8";
AppConfigManager *appConfigManager = buildConfigManager(objectConfigData);
initializeRuntimeLogSettings(appConfigManager);
@ -116,10 +114,6 @@ NamingService *NacosServiceFactory::CreateNamingService() NACOS_THROW(NacosExcep
HostReactor *hostReactor = new HostReactor(objectConfigData);
objectConfigData->_hostReactor = hostReactor;
const NacosString &seqConfile = appConfigManager->get(PropertyKeyConst::INSTANCE_ID_SEQ_FILE);
SequenceProvider<int64_t> *sequenceProvider = new SequenceProvider<int64_t>(seqConfile, 1, 10);
objectConfigData->_sequenceProvider = sequenceProvider;
objectConfigData->checkAssembledObject();
NamingService *instance = new NacosNamingService(objectConfigData);
@ -132,7 +126,6 @@ ConfigService *NacosServiceFactory::CreateConfigService() NACOS_THROW(NacosExcep
checkConfig();
ObjectConfigData *objectConfigData = new ObjectConfigData(CONFIG);
objectConfigData->name = "name";
objectConfigData->encoding = "UTF-8";
AppConfigManager *appConfigManager = buildConfigManager(objectConfigData);
initializeRuntimeLogSettings(appConfigManager);
@ -140,6 +133,7 @@ ConfigService *NacosServiceFactory::CreateConfigService() NACOS_THROW(NacosExcep
//Create http client
IHttpCli *httpCli = NULL;
httpCli = new HTTPCli();
NacosString encoding = "UTF-8";
objectConfigData->_httpCli = httpCli;
buildSecurityManagerAndHttpDelegate(objectConfigData);
@ -148,9 +142,6 @@ ConfigService *NacosServiceFactory::CreateConfigService() NACOS_THROW(NacosExcep
ServerListManager *serverListManager = new ServerListManager(objectConfigData);
objectConfigData->_serverListManager = serverListManager;
ConfigProxy *configProxy = new ConfigProxy(objectConfigData);
objectConfigData->_configProxy = configProxy;
LocalSnapshotManager *localSnapshotManager = new LocalSnapshotManager(appConfigManager);
objectConfigData->_localSnapshotManager = localSnapshotManager;
ClientWorker *clientWorker = new ClientWorker(objectConfigData);
@ -168,7 +159,7 @@ NamingMaintainService *NacosServiceFactory::CreateNamingMaintainService() NACOS_
checkConfig();
ObjectConfigData *objectConfigData = new ObjectConfigData(MAINTAIN);
objectConfigData->name = "config";
objectConfigData->encoding = "UTF-8";
NacosString encoding = "UTF-8";
AppConfigManager *appConfigManager = buildConfigManager(objectConfigData);
initializeRuntimeLogSettings(appConfigManager);

View File

@ -8,10 +8,7 @@
#include "src/naming/subscribe/HostReactor.h"
#include "src/listen/ClientWorker.h"
#include "src/security/SecurityManager.h"
#include "src/utils/UuidUtils.h"
#include "src/utils/SequenceProvider.h"
#include "src/config/ConfigProxy.h"
#include "src/debug/DebugAssertion.h"
#include "utils/UuidUtils.h"
namespace nacos{
@ -29,7 +26,6 @@ ObjectConfigData::ObjectConfigData(FactoryType theFactoryType) {
_clientWorker = NULL;
_localSnapshotManager = NULL;
_securityManager = NULL;
_configProxy = NULL;
}
void ObjectConfigData::checkNamingService() NACOS_THROW(NacosException) {
@ -48,7 +44,6 @@ void ObjectConfigData::checkNamingService() NACOS_THROW(NacosException) {
NACOS_ASSERT(_serverListManager != NULL);
NACOS_ASSERT(_udpNamingServiceListener != NULL);
NACOS_ASSERT(_udpNamingServiceListener != NULL);
NACOS_ASSERT(_sequenceProvider != NULL);
}
void ObjectConfigData::checkConfigService() NACOS_THROW(NacosException) {
@ -62,7 +57,6 @@ void ObjectConfigData::checkConfigService() NACOS_THROW(NacosException) {
NACOS_ASSERT(_serverListManager != NULL);
NACOS_ASSERT(_clientWorker != NULL);
NACOS_ASSERT(_localSnapshotManager != NULL);
NACOS_ASSERT(_configProxy != NULL);
}
void ObjectConfigData::checkMaintainService() NACOS_THROW(NacosException) {
@ -121,11 +115,6 @@ void ObjectConfigData::destroyConfigService() {
delete _appConfigManager;
_appConfigManager = NULL;
}
if (_configProxy != NULL) {
delete _configProxy;
_configProxy = NULL;
}
}
void ObjectConfigData::destroyNamingService() {
@ -217,12 +206,6 @@ void ObjectConfigData::destroyNamingService() {
delete _appConfigManager;
_appConfigManager = NULL;
}
if (_sequenceProvider != NULL)
{
delete _sequenceProvider;
_sequenceProvider = NULL;
}
}
void ObjectConfigData::destroyMaintainService() {

View File

@ -5,7 +5,6 @@
#include "config/ConfigService.h"
#include "NacosExceptions.h"
#include "Compatibility.h"
#include <stdint.h>
namespace nacos{
class HttpDelegate;
@ -21,8 +20,6 @@ class LocalSnapshotManager;
class SecurityManager;
class UdpNamingServiceListener;
class HostReactor;
class ConfigProxy;
template <typename T>class SequenceProvider;
enum FactoryType {
CONFIG = 0,
@ -48,7 +45,6 @@ public:
void checkAssembledObject() NACOS_THROW(NacosException);
~ObjectConfigData();
NacosString name;
NacosString encoding;
HttpDelegate *_httpDelegate;
IHttpCli *_httpCli;
NamingProxy *_serverProxy;
@ -62,8 +58,6 @@ public:
SecurityManager *_securityManager;
UdpNamingServiceListener *_udpNamingServiceListener;
HostReactor *_hostReactor;
SequenceProvider<int64_t> *_sequenceProvider;
ConfigProxy *_configProxy;
};
}//namespace nacos

View File

@ -1,6 +1,6 @@
#include <string.h>
#include "HTTPCli.h"
#include "src/utils/url.h"
#include "utils/url.h"
#include "constant/UtilAndComs.h"
#include "src/log/Logger.h"

View File

@ -4,10 +4,9 @@
#include "src/config/JVMUtil.h"
#include "naming/ServiceInfo2.h"
#include "constant/UtilAndComs.h"
#include "src/utils/UuidUtils.h"
#include "src/utils/RandomUtils.h"
#include "utils/UuidUtils.h"
#include "utils/RandomUtils.h"
#include "src/thread/Thread.h"
#include "src/crypto/MACProvider.h"
static nacos::Init initobj;//Implicitly call the constructors
namespace nacos{
@ -28,7 +27,6 @@ void Init::doInit() {
}
Logger::Init();
MACProvider::Init();
HTTPCli::HTTP_GLOBAL_INIT();
UtilAndComs::Init();
RandomUtils::Init();
@ -50,7 +48,6 @@ void Init::doDeinit() {
return;
}
MACProvider::DeInit();
Thread::DeInit();
UuidUtils::DeInit();
RandomUtils::DeInit();

View File

@ -110,10 +110,9 @@ long JSON::getLong(const NacosString &jsonString, const NacosString &fieldname)
Instance JSON::Json2Instance(const Value &host) NACOS_THROW(NacosException) {
Instance theinstance;
if (host.HasMember("instanceId")) {
const Value &instanceId = host["instanceId"];
theinstance.instanceId = instanceId.GetString();
}
markRequired(host, "instanceId");
const Value &instanceId = host["instanceId"];
theinstance.instanceId = instanceId.GetString();
markRequired(host, "port");
const Value &port = host["port"];
@ -141,20 +140,6 @@ Instance JSON::Json2Instance(const Value &host) NACOS_THROW(NacosException) {
theinstance.metadata = mtdata;
markRequired(host, "healthy");
const Value &healthy = host["healthy"];
if (!healthy.IsBool()) {
throw NacosException(NacosException::INVALID_JSON_FORMAT, "Error while parsing healthy for Instance!");
}
theinstance.healthy = healthy.GetBool();
markRequired(host, "enabled");
const Value &enabled = host["enabled"];
if (!enabled.IsBool()) {
throw NacosException(NacosException::INVALID_JSON_FORMAT, "Error while parsing enabled for Instance!");
}
theinstance.enabled = enabled.GetBool();
if (host.HasMember("clusterName")) {
const Value &clusterName = host["clusterName"];
theinstance.clusterName = clusterName.GetString();
@ -238,36 +223,11 @@ ServiceInfo JSON::JsonStr2ServiceInfo(const NacosString &jsonString) NACOS_THROW
"Error while parsing the JSON String for ServiceInfo!");
}
//bugfix #75, need to refresh the lastRefTime if it is present in the json
if (d.HasMember("lastRefTime")) {
const Value &lastRefTime = d["lastRefTime"];
if (!lastRefTime.IsInt64()) {
throw NacosException(NacosException::INVALID_JSON_FORMAT, "Error while parsing lastRefTime for ServiceInfo!");
}
si.setLastRefTime(lastRefTime.GetInt64());
}
markRequired(d, "name");
const Value &name = d["name"];
ServiceInfo::fromKey(si, name.GetString());
markRequired(d, "clusters");
const Value &clusters = d["clusters"];
si.setClusters(clusters.GetString());
markRequired(d, "cacheMillis");
const Value &cacheMillis = d["cacheMillis"];
if (!cacheMillis.IsInt64()) {
throw NacosException(NacosException::INVALID_JSON_FORMAT, "Error while parsing cacheMillis for ServiceInfo!");
}
si.setCacheMillis(cacheMillis.GetInt64());
markRequired(d, "hosts");
const Value &hosts = d["hosts"];
if (hosts.Size() == 0) {
return si;
}
std::list <Instance> hostlist;
for (SizeType i = 0; i < hosts.Size(); i++) {
const Value &curhost = hosts[i];
@ -277,10 +237,32 @@ ServiceInfo JSON::JsonStr2ServiceInfo(const NacosString &jsonString) NACOS_THROW
si.setHosts(hostlist);
markRequired(d, "cacheMillis");
const Value &cacheMillis = d["cacheMillis"];
if (!cacheMillis.IsInt64()) {
throw NacosException(NacosException::INVALID_JSON_FORMAT, "Error while parsing cacheMillis for ServiceInfo!");
}
si.setCacheMillis(cacheMillis.GetInt64());
markRequired(d, "checksum");
const Value &checkSum = d["checksum"];
si.setChecksum(checkSum.GetString());
markRequired(d, "lastRefTime");
const Value &lastRefTime = d["lastRefTime"];
if (!lastRefTime.IsInt64()) {
throw NacosException(NacosException::INVALID_JSON_FORMAT, "Error while parsing lastRefTime for ServiceInfo!");
}
si.setLastRefTime(lastRefTime.GetInt64());
markRequired(d, "clusters");
const Value &clusters = d["clusters"];
si.setClusters(clusters.GetString());
markRequired(d, "name");
const Value &name = d["name"];
ServiceInfo::fromKey(si, name.GetString());
return si;
}

View File

@ -5,9 +5,9 @@
#include "NacosString.h"
#include "src/naming/beat/BeatInfo.h"
#include "naming/ServiceInfo.h"
#include "src/json/rapidjson/document.h"
#include "src/json/rapidjson/writer.h"
#include "src/json/rapidjson/stringbuffer.h"
#include "src/rapidjson/document.h"
#include "src/rapidjson/writer.h"
#include "src/rapidjson/stringbuffer.h"
#include "naming/Instance.h"
#include "src/server/NacosServerInfo.h"
#include "naming/ListView.h"

View File

@ -1,17 +1,16 @@
#include <vector>
#include "ClientWorker.h"
#include "listen/Listener.h"
#include "src/utils/url.h"
#include "src/utils/GroupKey.h"
#include "src/crypto/md5/md5.h"
#include "src/utils/ParamUtils.h"
#include "utils/url.h"
#include "utils/GroupKey.h"
#include "src/md5/md5.h"
#include "utils/ParamUtils.h"
#include "src/utils/TimeUtils.h"
#include "src/log/Logger.h"
#include "src/debug/DebugAssertion.h"
#include "DebugAssertion.h"
#include "constant/ConfigConstant.h"
#include "constant/PropertyKeyConst.h"
#include "src/http/HttpStatus.h"
#include "src/config/ConfigProxy.h"
#define MAX(a,b) ((a) > (b) ? (a) : (b))
@ -94,9 +93,9 @@ HttpResult ClientWorker::getServerConfigHelper
log_debug("[ClientWorker]-getServerConfigHelper:httpGet Assembled URL:%s\n", url.c_str());
HttpResult res;
ConfigProxy *_configProxy = _objectConfigData->_configProxy;
HttpDelegate *_httpDelegate = _objectConfigData->_httpDelegate;
try {
res = _configProxy->reqAPI(IHttpCli::GET, url, headers, paramValues, _objectConfigData->encoding, timeoutMs);
res = _httpDelegate->httpGet(url, headers, paramValues, _httpDelegate->getEncode(), timeoutMs);
}
catch (NetworkException &e) {
throw NacosException(NacosException::SERVER_ERROR, e.what());
@ -329,8 +328,8 @@ NacosString ClientWorker::checkListenedKeys() NACOS_THROW(NetworkException,Nacos
NacosString url = serverAddr + "/" + path;
log_debug("[ClientWorker]-checkListenedKeys:httpPost Assembled URL:%s\n", url.c_str());
ConfigProxy *_configProxy = _objectConfigData->_configProxy;
res = _configProxy->reqAPI(IHttpCli::POST, url, headers, paramValues, _objectConfigData->encoding, _longPullingTimeout);
HttpDelegate *_httpDelegate = _objectConfigData->_httpDelegate;
res = _httpDelegate->httpPost(url, headers, paramValues, _httpDelegate->getEncode(), _longPullingTimeout);
log_debug("[ClientWorker]-checkListenedKeys:Received the message below from server:\n%s\n", res.content.c_str());
log_debug("[ClientWorker]-checkListenedKeys:return status:httpcode=%d curlcode=%d\n", res.code, res.curlcode);

View File

@ -5,6 +5,7 @@
#include <vector>
#include <pthread.h>
#include "NacosString.h"
#include "src/http/HttpDelegate.h"
#include "listen/Listener.h"
#include "ListeningData.h"
#include "OperateItem.h"

View File

@ -5,7 +5,7 @@
#include <list>
#include "NacosString.h"
#include "listen/Listener.h"
#include "src/crypto//md5/md5.h"
#include "src/md5/md5.h"
#include "src/log/Logger.h"
namespace nacos{

View File

@ -7,27 +7,26 @@
#include "NacosExceptions.h"
#include "src/utils/ConfigParserUtils.h"
#include "Properties.h"
#include "src/utils/DirUtils.h"
#include "src/utils/ParamUtils.h"
#include "utils/DirUtils.h"
#include "utils/ParamUtils.h"
#include "src/config/IOUtils.h"
#include "constant/ConfigConstant.h"
#include "constant/PropertyKeyConst.h"
#include <ctime>
#include <sys/stat.h>
namespace nacos{
LOG_LEVEL Logger::_CUR_SYS_LOG_LEVEL = ERROR;
NacosString Logger::_log_base_dir = "";
NacosString Logger::_log_file = "";
int64_t Logger::_rotate_size;
int64_t Logger::_rotate_time;
int64_t Logger::_last_rotate_time;
FILE *Logger::_output_file;
Mutex Logger::setFileLock;
//rotate time (in Ms)
void Logger::setRotateSize(int64_t rotateSize) {
_rotate_size = rotateSize;
void Logger::setRotateTime(int64_t rotateTime) {
_rotate_time = rotateTime;
}
void Logger::setBaseDir(const NacosString &baseDir) {
@ -38,8 +37,8 @@ void Logger::setBaseDir(const NacosString &baseDir) {
_output_file = NULL;
}
_log_file = _log_base_dir + ConfigConstant::FILE_SEPARATOR + "nacos-sdk-cpp.log";
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 ";
@ -52,8 +51,8 @@ void Logger::setLogLevel(LOG_LEVEL level) {
_CUR_SYS_LOG_LEVEL = level;
};
int64_t Logger::getRotateSize() {
return _rotate_size;
int64_t Logger::getRotateTime() {
return _rotate_time;
}
const NacosString &Logger::getBaseDir() {
@ -74,36 +73,11 @@ int Logger::debug_helper(LOG_LEVEL level, const char *format, va_list args) {
//va_start(argList, format);
int64_t now = TimeUtils::getCurrentTimeInMs();
struct stat stat_buf;
stat(_log_file.c_str(), &stat_buf);
if (stat_buf.st_size >= _rotate_size) {
if (now - _last_rotate_time >= _rotate_time) {
truncate(_log_file.c_str(), 0);
_last_rotate_time = now;
}
const char *log_level;
switch (level) {
case DEBUG:
log_level = "[DEBUG]";
break;
case INFO:
log_level = "[INFO]";
break;
case WARN:
log_level = "[WARN]";
break;
case ERROR:
log_level = "[ERROR]";
break;
case NONE:
log_level = "[NONE]";
break;
default:
log_level = "[UNKNOWN]";
break;
}
time_t t = time(0);
struct tm current_time;
localtime_r(&t, &current_time);
@ -111,7 +85,7 @@ int Logger::debug_helper(LOG_LEVEL level, const char *format, va_list args) {
char time_buf[22];
strftime(time_buf, sizeof(time_buf), "[%Y-%m-%d %H:%M:%S]", &current_time);
int retval = fprintf(_output_file, "%s%s", time_buf, log_level);
int retval = fprintf(_output_file, "%s", time_buf);
retval += vfprintf(_output_file, format, args);
fflush(_output_file);
//va_end(argList);
@ -212,51 +186,30 @@ void Logger::applyLogSettings(Properties &props) {
}
}
if (!props.contains(PropertyKeyConst::LOG_ROTATE_SIZE)) {
Logger::setRotateSize(10 * 1024 *1024);//10M by default
if (!props.contains(PropertyKeyConst::LOG_ROTATE_TIME)) {
Logger::setRotateTime(24 * 60 * 60 * 1000);
} else {
const NacosString &logRotateSizeStr = props[PropertyKeyConst::LOG_ROTATE_SIZE];
if (ParamUtils::isBlank(logRotateSizeStr)) {
const NacosString &logRotateTimeStr = props[PropertyKeyConst::LOG_ROTATE_TIME];
if (ParamUtils::isBlank(logRotateTimeStr)) {
throw NacosException(NacosException::INVALID_CONFIG_PARAM,
"Invalid option '" + logRotateSizeStr + "' for " + PropertyKeyConst::LOG_ROTATE_SIZE);
"Invalid option " + logRotateTimeStr + " for " + PropertyKeyConst::LOG_ROTATE_TIME);
}
size_t logrotate_lastch = logRotateSizeStr.length() - 1;
int mulplier = 1;
unsigned long logRotateSize = 0;
switch (logRotateSizeStr[logrotate_lastch])
{
case 'g':
case 'G':
mulplier *= 1024;
case 'm':
case 'M':
mulplier *= 1024;
case 'k':
case 'K':
mulplier *= 1024;
logRotateSize = atol(logRotateSizeStr.substr(0, logrotate_lastch).c_str());//logrotate_lastch = exclude the unit
logRotateSize *= mulplier;
break;
default:
if (!isdigit(logRotateSizeStr[logrotate_lastch])) {
throw NacosException(NacosException::INVALID_CONFIG_PARAM,
"Invalid option '" + logRotateSizeStr + "' for " + PropertyKeyConst::LOG_ROTATE_SIZE + ", the unit of size must be G/g M/m K/k or decimal numbers.");
}
mulplier = 1;
logRotateSize = atol(logRotateSizeStr.substr(0, logRotateSizeStr.length()).c_str());
break;
}
if (logRotateSize <= 0) {
if (logRotateTimeStr[logRotateTimeStr.length() - 1] != 'h' &&
logRotateTimeStr[logRotateTimeStr.length() - 1] != 'H') {
throw NacosException(NacosException::INVALID_CONFIG_PARAM,
PropertyKeyConst::LOG_ROTATE_SIZE + " should be greater than 0");
"Invalid option " + logRotateTimeStr + " for " + PropertyKeyConst::LOG_ROTATE_TIME + ", we only support hour currently");
}
Logger::setRotateSize(logRotateSize);
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("Current log path:%s\n", Logger::getBaseDir().c_str());
log_info("DEFAULT_LOG_PATH:%s\n", Logger::getBaseDir().c_str());
}
void Logger::Init() {

View File

@ -57,7 +57,7 @@ private:
static LOG_LEVEL _CUR_SYS_LOG_LEVEL;
static NacosString _log_base_dir;
static NacosString _log_file;
static int64_t _rotate_size;
static int64_t _rotate_time;
static int64_t _last_rotate_time;
static FILE *_output_file;
@ -70,11 +70,11 @@ private:
public:
static void applyLogSettings(Properties &props);
static void setRotateSize(int64_t rotateSize);
static void setRotateTime(int64_t rotateTime);
static void setBaseDir(const NacosString &baseDir);
static void setLogLevel(LOG_LEVEL level);
static int64_t getRotateSize();
static int64_t getRotateTime();
static const NacosString &getBaseDir();
static LOG_LEVEL getLogLevel();

View File

@ -1,341 +1,341 @@
#include "md5.h"
using namespace std;
/* Constants for MD5Transform routine. */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
namespace nacos{
const byte MD5::PADDING[64] = {0x80};
const char MD5::HEX[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
/* Default construct. */
MD5::MD5() {
reset();
}
/* Construct a MD5 object with a input buffer. */
MD5::MD5(const void *input, size_t length) {
reset();
update(input, length);
}
/* Construct a MD5 object with a string. */
MD5::MD5(const NacosString &str) {
reset();
update(str);
}
/* Construct a MD5 object with a file. */
MD5::MD5(ifstream &in) {
reset();
update(in);
}
/* Return the message-digest */
const byte *MD5::digest() {
if (!_finished) {
_finished = true;
final();
}
return _digest;
}
/* Reset the calculate state */
void MD5::reset() {
_finished = false;
/* reset number of bits. */
_count[0] = _count[1] = 0;
/* Load magic initialization constants. */
_state[0] = 0x67452301;
_state[1] = 0xefcdab89;
_state[2] = 0x98badcfe;
_state[3] = 0x10325476;
}
/* Updating the context with a input buffer. */
void MD5::update(const void *input, size_t length) {
update((const byte *) input, length);
}
/* Updating the context with a string. */
void MD5::update(const NacosString &str) {
update((const byte *) str.c_str(), str.length());
}
/* Updating the context with a file. */
void MD5::update(ifstream &in) {
if (!in) {
return;
}
std::streamsize length;
char buffer[BUFFER_SIZE];
while (!in.eof()) {
in.read(buffer, BUFFER_SIZE);
length = in.gcount();
if (length > 0) {
update(buffer, length);
}
}
in.close();
}
/* MD5 block update operation. Continues an MD5 message-digest
operation, processing another message block, and updating the
context.
*/
void MD5::update(const byte *input, size_t length) {
uint32 i, index, partLen;
_finished = false;
/* Compute number of bytes mod 64 */
index = (uint32)((_count[0] >> 3) & 0x3f);
/* update number of bits */
if ((_count[0] += ((uint32) length << 3)) < ((uint32) length << 3)) {
++_count[1];
}
_count[1] += ((uint32) length >> 29);
partLen = 64 - index;
/* transform as many times as possible. */
if (length >= partLen) {
memcpy(&_buffer[index], input, partLen);
transform(_buffer);
for (i = partLen; i + 63 < length; i += 64) {
transform(&input[i]);
}
index = 0;
} else {
i = 0;
}
/* Buffer remaining input */
memcpy(&_buffer[index], &input[i], length - i);
}
/* MD5 finalization. Ends an MD5 message-_digest operation, writing the
the message _digest and zeroizing the context.
*/
void MD5::final() {
byte bits[8];
uint32 oldState[4];
uint32 oldCount[2];
uint32 index, padLen;
/* Save current state and count. */
memcpy(oldState, _state, 16);
memcpy(oldCount, _count, 8);
/* Save number of bits */
encode(_count, bits, 8);
/* Pad out to 56 mod 64. */
index = (uint32)((_count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
update(PADDING, padLen);
/* Append length (before padding) */
update(bits, 8);
/* Store state in digest */
encode(_state, _digest, 16);
/* Restore current state and count. */
memcpy(_state, oldState, 16);
memcpy(_count, oldCount, 8);
}
/* MD5 basic transformation. Transforms _state based on block. */
void MD5::transform(const byte block[64]) {
uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16];
decode(block, x, 64);
/* Round 1 */
FF (a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
_state[0] += a;
_state[1] += b;
_state[2] += c;
_state[3] += d;
}
/* Encodes input (ulong) into output (byte). Assumes length is
a multiple of 4.
*/
void MD5::encode(const uint32 *input, byte *output, size_t length) {
for (size_t i = 0, j = 0; j < length; ++i, j += 4) {
output[j] = (byte)(input[i] & 0xff);
output[j + 1] = (byte)((input[i] >> 8) & 0xff);
output[j + 2] = (byte)((input[i] >> 16) & 0xff);
output[j + 3] = (byte)((input[i] >> 24) & 0xff);
}
}
/* Decodes input (byte) into output (ulong). Assumes length is
a multiple of 4.
*/
void MD5::decode(const byte *input, uint32 *output, size_t length) {
for (size_t i = 0, j = 0; j < length; ++i, j += 4) {
output[i] = ((uint32) input[j]) | (((uint32) input[j + 1]) << 8) |
(((uint32) input[j + 2]) << 16) | (((uint32) input[j + 3]) << 24);
}
}
/* Convert byte array to hex string. */
NacosString MD5::bytesToHexString(const byte *input, size_t length) {
NacosString str;
str.reserve(length << 1);
for (size_t i = 0; i < length; ++i) {
int t = input[i];
int a = t / 16;
int b = t % 16;
str.append(1, HEX[a]);
str.append(1, HEX[b]);
}
return str;
}
/* Convert digest to string value */
NacosString MD5::toString() {
return bytesToHexString(digest(), 16);
}
#include "md5.h"
using namespace std;
/* Constants for MD5Transform routine. */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + ac; \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
namespace nacos{
const byte MD5::PADDING[64] = {0x80};
const char MD5::HEX[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
/* Default construct. */
MD5::MD5() {
reset();
}
/* Construct a MD5 object with a input buffer. */
MD5::MD5(const void *input, size_t length) {
reset();
update(input, length);
}
/* Construct a MD5 object with a string. */
MD5::MD5(const NacosString &str) {
reset();
update(str);
}
/* Construct a MD5 object with a file. */
MD5::MD5(ifstream &in) {
reset();
update(in);
}
/* Return the message-digest */
const byte *MD5::digest() {
if (!_finished) {
_finished = true;
final();
}
return _digest;
}
/* Reset the calculate state */
void MD5::reset() {
_finished = false;
/* reset number of bits. */
_count[0] = _count[1] = 0;
/* Load magic initialization constants. */
_state[0] = 0x67452301;
_state[1] = 0xefcdab89;
_state[2] = 0x98badcfe;
_state[3] = 0x10325476;
}
/* Updating the context with a input buffer. */
void MD5::update(const void *input, size_t length) {
update((const byte *) input, length);
}
/* Updating the context with a string. */
void MD5::update(const NacosString &str) {
update((const byte *) str.c_str(), str.length());
}
/* Updating the context with a file. */
void MD5::update(ifstream &in) {
if (!in) {
return;
}
std::streamsize length;
char buffer[BUFFER_SIZE];
while (!in.eof()) {
in.read(buffer, BUFFER_SIZE);
length = in.gcount();
if (length > 0) {
update(buffer, length);
}
}
in.close();
}
/* MD5 block update operation. Continues an MD5 message-digest
operation, processing another message block, and updating the
context.
*/
void MD5::update(const byte *input, size_t length) {
uint32 i, index, partLen;
_finished = false;
/* Compute number of bytes mod 64 */
index = (uint32)((_count[0] >> 3) & 0x3f);
/* update number of bits */
if ((_count[0] += ((uint32) length << 3)) < ((uint32) length << 3)) {
++_count[1];
}
_count[1] += ((uint32) length >> 29);
partLen = 64 - index;
/* transform as many times as possible. */
if (length >= partLen) {
memcpy(&_buffer[index], input, partLen);
transform(_buffer);
for (i = partLen; i + 63 < length; i += 64) {
transform(&input[i]);
}
index = 0;
} else {
i = 0;
}
/* Buffer remaining input */
memcpy(&_buffer[index], &input[i], length - i);
}
/* MD5 finalization. Ends an MD5 message-_digest operation, writing the
the message _digest and zeroizing the context.
*/
void MD5::final() {
byte bits[8];
uint32 oldState[4];
uint32 oldCount[2];
uint32 index, padLen;
/* Save current state and count. */
memcpy(oldState, _state, 16);
memcpy(oldCount, _count, 8);
/* Save number of bits */
encode(_count, bits, 8);
/* Pad out to 56 mod 64. */
index = (uint32)((_count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
update(PADDING, padLen);
/* Append length (before padding) */
update(bits, 8);
/* Store state in digest */
encode(_state, _digest, 16);
/* Restore current state and count. */
memcpy(_state, oldState, 16);
memcpy(_count, oldCount, 8);
}
/* MD5 basic transformation. Transforms _state based on block. */
void MD5::transform(const byte block[64]) {
uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16];
decode(block, x, 64);
/* Round 1 */
FF (a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
_state[0] += a;
_state[1] += b;
_state[2] += c;
_state[3] += d;
}
/* Encodes input (ulong) into output (byte). Assumes length is
a multiple of 4.
*/
void MD5::encode(const uint32 *input, byte *output, size_t length) {
for (size_t i = 0, j = 0; j < length; ++i, j += 4) {
output[j] = (byte)(input[i] & 0xff);
output[j + 1] = (byte)((input[i] >> 8) & 0xff);
output[j + 2] = (byte)((input[i] >> 16) & 0xff);
output[j + 3] = (byte)((input[i] >> 24) & 0xff);
}
}
/* Decodes input (byte) into output (ulong). Assumes length is
a multiple of 4.
*/
void MD5::decode(const byte *input, uint32 *output, size_t length) {
for (size_t i = 0, j = 0; j < length; ++i, j += 4) {
output[i] = ((uint32) input[j]) | (((uint32) input[j + 1]) << 8) |
(((uint32) input[j + 2]) << 16) | (((uint32) input[j + 3]) << 24);
}
}
/* Convert byte array to hex string. */
NacosString MD5::bytesToHexString(const byte *input, size_t length) {
NacosString str;
str.reserve(length << 1);
for (size_t i = 0; i < length; ++i) {
int t = input[i];
int a = t / 16;
int b = t % 16;
str.append(1, HEX[a]);
str.append(1, HEX[b]);
}
return str;
}
/* Convert digest to string value */
NacosString MD5::toString() {
return bytesToHexString(digest(), 16);
}
}//namespace nacos

View File

@ -1,29 +0,0 @@
#include "naming/Cluster.h"
namespace nacos{
NacosString Cluster::getName() const {
return name;
}
void Cluster::setName(const NacosString &name) {
Cluster::name = name;
}
HealthChecker Cluster::getHealthChecker() const {
return healthChecker;
}
void Cluster::setHealthChecker(const HealthChecker &healthChecker) {
Cluster::healthChecker = healthChecker;
}
std::map<NacosString, NacosString> Cluster::getMetadata() const {
return metadata;
}
void Cluster::setMetadata(const std::map<NacosString, NacosString> &metadata) {
Cluster::metadata = metadata;
}
}//namespace nacos

View File

@ -1,5 +1,5 @@
#include "naming/Instance.h"
#include "src/utils/ParamUtils.h"
#include "utils/ParamUtils.h"
#include "src/log/Logger.h"
namespace nacos{

View File

@ -1,6 +1,5 @@
#include "src/naming/NacosNamingMaintainService.h"
#include "src/security/SecurityManager.h"
#include "constant/ConfigConstant.h"
using namespace std;

View File

@ -2,10 +2,9 @@
#include "src/naming/subscribe/SubscriptionPoller.h"
#include "src/naming/subscribe/UdpNamingServiceListener.h"
#include "src/naming/beat/BeatReactor.h"
#include "src/utils/SequenceProvider.h"
#include "src/utils/NamingUtils.h"
#include "utils/NamingUtils.h"
#include "constant/UtilAndComs.h"
#include "src/utils/ParamUtils.h"
#include "utils/ParamUtils.h"
#include "constant/PropertyKeyConst.h"
#include "src/json/JSON.h"
@ -89,8 +88,7 @@ void NacosNamingService::registerInstance
const NacosString &groupName,
Instance &instance
) NACOS_THROW(NacosException) {
const NacosString &instanceIdPrefix = _objectConfigData->_appConfigManager->get(PropertyKeyConst::INSTANCE_ID_PREFIX);
instance.instanceId = instanceIdPrefix + NacosStringOps::valueOf(_objectConfigData->_sequenceProvider->next());
if (instance.ephemeral) {
BeatInfo beatInfo;
beatInfo.serviceName = NamingUtils::getGroupedName(serviceName, groupName);

View File

@ -2,14 +2,13 @@
#include "NamingProxy.h"
#include "constant/NamingConstant.h"
#include "constant/UtilAndComs.h"
#include "src/utils/UuidUtils.h"
#include "src/utils/ParamUtils.h"
#include "src/utils/url.h"
#include "src/utils/RandomUtils.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 "src/log/Logger.h"
#include "NacosExceptions.h"
#include "src/crypto/SignatureTool.h"
using namespace std;
@ -150,19 +149,6 @@ NacosString NamingProxy::callServer
return callServer(api, params, nacosDomain, IHttpCli::GET);
}
NacosString NamingProxy::getDataToSign(const std::list <NacosString> &paramValues, NacosString &nowTimeMs) {
const NacosString &serviceName = ParamUtils::findByKey(paramValues, NamingConstant::SERVICE_NAME);
const NacosString &groupName = ParamUtils::findByKey(paramValues, NamingConstant::GROUP_NAME);
NacosString dataToSign = "";
if ((!ParamUtils::isBlank(serviceName) && serviceName.find(NamingConstant::SPLITER) != std::string::npos) || ParamUtils::isBlank(groupName)) {
dataToSign = nowTimeMs + NamingConstant::SPLITER + serviceName;
} else {
dataToSign = nowTimeMs + NamingConstant::SPLITER + groupName + NamingConstant::SPLITER + serviceName;
}
return dataToSign;
}
NacosString NamingProxy::callServer
(
const NacosString &api,
@ -185,27 +171,7 @@ NacosString NamingProxy::callServer
list <NacosString> headers;
headers = builderHeaders();
//SPAS security
NacosString secretKey = _objectConfigData->_appConfigManager->get(PropertyKeyConst::SECRET_KEY);
NacosString accessKey = _objectConfigData->_appConfigManager->get(PropertyKeyConst::ACCESS_KEY);
//If SPAS security credentials are set, SPAS is enabled
if (!ParamUtils::isBlank(secretKey) && !ParamUtils::isBlank(accessKey)) {
NacosString nowTimeMs = NacosStringOps::valueOf(TimeUtils::getCurrentTimeInMs());
NacosString dataToSign = getDataToSign(params, nowTimeMs);
NacosString signature = SignatureTool::SignWithHMAC_SHA1(dataToSign, secretKey);
//inject security credentials
if (method == IHttpCli::GET || method == IHttpCli::DELETE) {
ParamUtils::addKV(params, "signature", signature);
ParamUtils::addKV(params, "data", dataToSign);
ParamUtils::addKV(params, "ak", accessKey);
} else {
requestUrl = requestUrl + "?signature=" + urlencode(signature) + "&data=" + dataToSign + "&ak=" + accessKey;
}
}
HttpDelegate *_httpDelegate = _objectConfigData->_httpDelegate;
try {
long _http_req_timeout = _objectConfigData->_appConfigManager->getServeReqTimeout();
switch (method) {

View File

@ -39,9 +39,6 @@ private:
long _hb_fail_wait;//Time to wait when a heartbeat request fails (in ms)
static ListView<NacosString> nullResult;
NacosString getDataToSign(const std::list <NacosString> &paramValues, NacosString &nowTimeMs);
public:
NamingProxy(ObjectConfigData *objectConfigData);

View File

@ -1,206 +0,0 @@
#include "naming/ServiceInfo.h"
#include <vector>
#include <list>
#include <sys/time.h>
#include "NacosString.h"
#include "constant/ConfigConstant.h"
#include "src/utils/url.h"
#include "src/utils/ParamUtils.h"
#include "naming/Instance.h"
namespace nacos{
ServiceInfo::ServiceInfo() : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""), _allIPs(false) {
}
bool ServiceInfo::isAllIPs() const{
return _allIPs;
}
void ServiceInfo::setAllIPs(bool allIPs) {
_allIPs = allIPs;
}
ServiceInfo::ServiceInfo(const NacosString &key) : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""),
_allIPs(false) {
std::vector <NacosString> segs;
ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER);
if (segs.size() == 2) {
setGroupName(segs[0]);
setName(segs[1]);
} else if (segs.size() == 3) {
setGroupName(segs[0]);
setName(segs[1]);
setClusters(segs[2]);
}
}
ServiceInfo::ServiceInfo(const NacosString &name, const NacosString &clusters) {
_name = name;
_clusters = clusters;
}
int ServiceInfo::ipCount() {
return _hosts.size();
}
bool ServiceInfo::expired() const{
//TODO:extract this snippet to a common util
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
return ms - _lastRefTime > _cacheMillis;
}
void ServiceInfo::setHosts(std::list <Instance> &hosts) {
_hosts = hosts;
}
bool ServiceInfo::isValid() {
return _hosts.size() > 0;
}
NacosString ServiceInfo::getName() {
return _name;
}
void ServiceInfo::setName(const NacosString &name) {
_name = name;
}
NacosString ServiceInfo::getGroupName() {
return _groupName;
}
void ServiceInfo::setGroupName(const NacosString &groupName) {
_groupName = groupName;
}
void ServiceInfo::setLastRefTime(long lastRefTime) {
_lastRefTime = lastRefTime;
}
long ServiceInfo::getLastRefTime() {
return _lastRefTime;
}
NacosString ServiceInfo::getClusters() {
return _clusters;
}
void ServiceInfo::setClusters(const NacosString &clusters) {
_clusters = clusters;
}
long ServiceInfo::getCacheMillis() {
return _cacheMillis;
}
void ServiceInfo::setCacheMillis(long cacheMillis) {
_cacheMillis = cacheMillis;
}
std::list <Instance> ServiceInfo::getHosts() {
return _hosts;
}
std::list <Instance> *ServiceInfo::getHostsNocopy() {
return &_hosts;
}
bool ServiceInfo::validate() const{
if (isAllIPs()) {
return true;
}
//TODO: Idk what does this mean in Java, ignore in C++
/*std::list<Instance> validHosts;
for (std::list<Instance>::iterator it = _hosts.begin()
it != _hosts.end(); it++)
{
if (it->isHealthy())
{
continue;
}
for (int i = 0; i < it->getWeight(); i++)
{
validHosts.push_back(*it);
}
}*/
return true;
}
//@JSONField(serialize = false)
NacosString ServiceInfo::getJsonFromServer() const{
return _jsonFromServer;
}
void ServiceInfo::setJsonFromServer(const NacosString &jsonFromServer) {
_jsonFromServer = jsonFromServer;
}
//@JSONField(serialize = false)
NacosString ServiceInfo::getKey() const{
return getKey(_name, _clusters);
}
//@JSONField(serialize = false)
NacosString ServiceInfo::getKeyEncoded() const{
return getKey(urlencode(_name), _clusters);
}
//@JSONField(serialize = false)
void ServiceInfo::fromKey(ServiceInfo &serviceInfo, const NacosString &key) {
std::vector <NacosString> segs;
ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER);
if (segs.size() == 2) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
} else if (segs.size() == 3) {
serviceInfo.setGroupName(segs[0]);
serviceInfo.setName(segs[1]);
serviceInfo.setClusters(segs[2]);
}
}
//@JSONField(serialize = false)
NacosString ServiceInfo::getKey(const NacosString &name, const NacosString &clusters) {
if (!ParamUtils::isBlank(clusters)) {
return name + ConfigConstant::SERVICE_INFO_SPLITER + clusters;
}
return name;
}
//@Override
NacosString ServiceInfo::toString() const{
return getKey();
}
//!!BE CAREFUL!!
//This function is very expensive!! call it with care!
NacosString ServiceInfo::toInstanceString() const{
NacosString res = "{\"lastRefTime\":" + NacosStringOps::valueOf(_lastRefTime) + " [\n";
for (std::list<Instance>::const_iterator it = _hosts.begin();
it != _hosts.end(); it++)
{
res += it->toString() + "\n";
}
res += "\n]}";
return res;
}
NacosString ServiceInfo::getChecksum() const{
return _checksum;
}
void ServiceInfo::setChecksum(const NacosString &checksum) {
_checksum = checksum;
}
}

View File

@ -2,7 +2,7 @@
#include "BeatReactor.h"
#include "BeatTask.h"
#include "NacosString.h"
#include "src/debug/DebugAssertion.h"
#include "DebugAssertion.h"
using namespace std;

View File

@ -1,6 +1,9 @@
#include <map>
#include "BeatReactor.h"
#include "BeatTask.h"
#include "NacosString.h"
#include "src/log/Logger.h"
#include "src/utils/TimeUtils.h"
using namespace std;

View File

@ -8,7 +8,6 @@
#include "src/thread/RWLock.h"
#include "naming/ChangeAdvice.h"
#include "Compatibility.h"
#include "NacosExceptions.h"
namespace nacos{
class NamingCache {

View File

@ -2,8 +2,8 @@
#include <vector>
#include "naming/selectors/RandomByWeightSelector.h"
#include "src/log/Logger.h"
#include "src/utils/ParamUtils.h"
#include "src/utils/RandomUtils.h"
#include "utils/ParamUtils.h"
#include "utils/RandomUtils.h"
#define BASIC_WEIGHT 65536

View File

@ -1,7 +1,7 @@
#include "naming/selectors/RandomSelector.h"
#include "src/log/Logger.h"
#include "src/utils/RandomUtils.h"
#include "src/utils/ParamUtils.h"
#include "utils/RandomUtils.h"
#include "utils/ParamUtils.h"
namespace nacos { namespace naming { namespace selectors {

View File

@ -3,7 +3,7 @@
//
#include "EventDispatcher.h"
#include "src/debug/DebugAssertion.h"
#include "DebugAssertion.h"
using namespace std;

View File

@ -1,10 +0,0 @@
#include "naming/subscribe/EventListener.h"
#include "src/debug/DebugAssertion.h"
namespace nacos {
EventListener::~EventListener() {
NACOS_ASSERT(refCnt() == 0)
}
}//namespace nacos

View File

@ -4,7 +4,7 @@
#include "HostReactor.h"
#include "src/json/JSON.h"
#include "src/utils/NamingUtils.h"
#include "utils/NamingUtils.h"
#include "src/naming/subscribe/EventDispatcher.h"
namespace nacos {
@ -23,10 +23,6 @@ void HostReactor::processServiceJson(const NacosString &json) {
{
WriteGuard _writeGuard(rwLock);
if (serviceInfoMap.count(key) == 0) {
if (serviceInfo.ipCount()==0) {
log_warn("hosts got from server is empty.\n");
return;
}
serviceInfoMap[key] = serviceInfo;
newServiceInfo = true;
} else {

View File

@ -1,6 +1,6 @@
#include "SubscriptionPoller.h"
#include "constant/ConfigConstant.h"
#include "src/utils/NamingUtils.h"
#include "utils/NamingUtils.h"
#include "src/json/JSON.h"
#include "HostReactor.h"

View File

@ -7,8 +7,6 @@
#include "constant/PropertyKeyConst.h"
#include "src/json/JSON.h"
#include "HostReactor.h"
#include "zlib.h"
#include "src/debug/DebugAssertion.h"
#include <iostream>
using namespace std;
@ -40,48 +38,6 @@ void UdpNamingServiceListener::initializeUdpListener() NACOS_THROW(NacosExceptio
log_debug("socket bound\n");
}
bool UdpNamingServiceListener::unGzip(char *inBuffer, size_t inSize) {
//reference:https://zlib.net/zlib_how.html
/* allocate inflate state */
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
int ret = inflateInit2(&strm, MAX_WBITS + 16);
if (ret != Z_OK) {
log_error("failed to perform inflateInit()\n");
return false;
}
strm.avail_in = inSize;
strm.next_in = (unsigned char*)inBuffer;
strm.avail_out = sizeof(this->uncompressedData);
strm.next_out = (unsigned char*)this->uncompressedData;
ret = inflate(&strm, Z_NO_FLUSH);
NACOS_ASSERT(ret != Z_STREAM_ERROR);
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
log_error("in switch block, inflate failed with code = %d\n", ret);
return false;
}
if (strm.avail_out == 0) {
log_error("uncompressed data exceeds the size limit, please consider a larger uncompressedData\n");
return false;
}
(void)inflateEnd(&strm);
this->uncompressedData[sizeof(this->uncompressedData) - strm.avail_out] = '\0';
return true;
}
void *UdpNamingServiceListener::listenerThreadFunc(void *param) {
UdpNamingServiceListener *thisObj = (UdpNamingServiceListener*)param;
log_debug("in thread UdpNamingServiceListener::listenerThreadFunc()\n");
@ -91,7 +47,7 @@ void *UdpNamingServiceListener::listenerThreadFunc(void *param) {
log_debug("before recvfrom() socketfd:%d\n", thisObj->sockfd);
struct sockaddr src_addr = {0};
socklen_t src_addr_len = sizeof(struct sockaddr_in);
socklen_t src_addr_len = {0};
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);
@ -109,19 +65,7 @@ void *UdpNamingServiceListener::listenerThreadFunc(void *param) {
PushPacket pushPacket;
try {
if (ret <= 2) {
//the server returns a packet shorter than 2 bytes, which could not be parsed by the listener
log_warn("got an invalid packet, len = %d, content = %s", ret, thisObj->receiveBuffer);
continue;
}
char *packetToParse = thisObj->receiveBuffer;
if ((unsigned char)thisObj->receiveBuffer[0] == 0x1f && (unsigned char)thisObj->receiveBuffer[1] == 0x8b) {
if (!thisObj->unGzip(thisObj->receiveBuffer, ret)) {
continue;
}
packetToParse = thisObj->uncompressedData;
}
pushPacket = JSON::Json2PushPacket(packetToParse);
pushPacket = JSON::Json2PushPacket(thisObj->receiveBuffer);
} catch (NacosException &e) {
log_error("Invalid json string got from server:%s\n", thisObj->receiveBuffer);
continue;
@ -146,7 +90,7 @@ void *UdpNamingServiceListener::listenerThreadFunc(void *param) {
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\n", errno);
log_error("error while sending data...%d", errno);
}
}

View File

@ -31,13 +31,10 @@ private:
int udpReceiverPort;
struct sockaddr_in cliaddr;
char receiveBuffer[UDP_MSS];
//assume the max compress ratio = 90%
char uncompressedData[UDP_MSS * 10];
Thread *_listenerThread;
void initializeUdpListener() NACOS_THROW(NacosException);
static void *listenerThreadFunc(void *param);
bool unGzip(char *inBuffer, size_t inSize);
public:
UdpNamingServiceListener(ObjectConfigData *objectConfigData);
~UdpNamingServiceListener();

View File

@ -18,8 +18,8 @@
/*! \file document.h */
#include "reader.h"
#include "src/json/rapidjson/internal/meta.h"
#include "src/json/rapidjson/internal/strfunc.h"
#include "internal/meta.h"
#include "internal/strfunc.h"
#include "memorystream.h"
#include "encodedstream.h"
#include <new> // placement new

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_ERROR_ERROR_H_
#define RAPIDJSON_ERROR_ERROR_H_
#include "src/json/rapidjson/rapidjson.h"
#include "../rapidjson.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_BIGINTEGER_H_
#define RAPIDJSON_BIGINTEGER_H_
#include "src/json/rapidjson/rapidjson.h"
#include "../rapidjson.h"
#if defined(_MSC_VER) && !__INTEL_COMPILER && defined(_M_AMD64)
#include <intrin.h> // for _umul128

View File

@ -19,7 +19,7 @@
#ifndef RAPIDJSON_DIYFP_H_
#define RAPIDJSON_DIYFP_H_
#include "src/json/rapidjson/rapidjson.h"
#include "../rapidjson.h"
#include <limits>
#if defined(_MSC_VER) && defined(_M_AMD64) && !defined(__INTEL_COMPILER)

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_IEEE754_
#define RAPIDJSON_IEEE754_
#include "src/json/rapidjson/rapidjson.h"
#include "../rapidjson.h"
RAPIDJSON_NAMESPACE_BEGIN
namespace internal {

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_ITOA_
#define RAPIDJSON_ITOA_
#include "src/json/rapidjson/rapidjson.h"
#include "../rapidjson.h"
RAPIDJSON_NAMESPACE_BEGIN
namespace internal {

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