Compare commits

...

69 Commits

Author SHA1 Message Date
brother-戎 2b4104d252
[BUG FIX] fix up naming signData && url encoding (#139)
* 1. fix naming signData
2. fix url encoding

* rollback CURLOPT_POSTFIELDS

* fix up
2024-01-16 17:05:17 +08:00
brother-戎 f58d97ab21
fix (#138) 2024-01-16 11:39:31 +08:00
Visual Ten 21ee34dbf1
feature 支持指定endpoint时携带参数,去除编译警告 (#135)
* feature 支持指定endpoint时携带参数,去除编译警告

* fix 编码风格统一

* Update PropertyKeyConst.cpp

* feature 支持查询endpoint和查询配置时的contextPath差异,支持传入AppName

* fix 新增endpointQueryParam,支持与namespace同步设置
2023-11-23 11:39:10 +08:00
HakureiGenei 60dc0fb86c
Merge pull request #111 from nacos-group/develop
issue #85 and NacosConfigService::getConfig behavior change
2022-04-10 23:40:19 +08:00
TTTTTAAAAAKKKKEEEENNNN 707be611f0 issue #85 fix, getConfig behavior polish
issue #85 fix:
If the client fails to login to nacos server at initialization stage, it will crash
If the server's password is changed when the client is running, the client will try to login the server every 30 seconds and put this issue to log

NacosConfigService::getConfig behavior change:
When the server returns 403(no permission), the client will try to get local snapshot, if there is no snapshot, the getConfig() will throw an exception with errorcode = 403 and the user is to decide failback strategy
2022-04-10 23:38:00 +08:00
TTTTTAAAAAKKKKEEEENNNN e145b91061 compatible for linux 2022-01-26 16:48:58 +08:00
HakureiGenei 72d0cd276c
Merge pull request #108 from nacos-group/develop
Version 1.0.9
2022-01-25 16:50:38 +08:00
HakureiGenei be55f904ce
Merge pull request #107 from nacos-group/project_dir_refactor
project dir refactor
2022-01-25 16:26:07 +08:00
Liu, Hanyu 8a6a201f64 header integration 2022-01-25 13:11:26 +08:00
Liu, Hanyu 028b8a6eb3 project directory structure optimization
move .h files that are not used by users to the project's src directory
polish readme.md
2022-01-25 08:54:54 +08:00
TTTTTAAAAAKKKKEEEENNNN 75d93f034a refactor directory,more precise, more concise 2022-01-22 23:50:38 +08:00
TTTTTAAAAAKKKKEEEENNNN 923fa46c5b add static lib 2022-01-22 22:24:43 +08:00
HakureiGenei cee3851bf3
Merge pull request #104 from nacos-group/merge_back
merge back
2022-01-15 15:02:58 +08:00
HakureiGenei 09c0cc0211
Merge branch 'develop' into merge_back 2022-01-15 15:02:37 +08:00
TTTTTAAAAAKKKKEEEENNNN aede871b87 testcase 2022-01-15 14:36:28 +08:00
TTTTTAAAAAKKKKEEEENNNN 4299758ac6 add testcase 2022-01-15 14:11:17 +08:00
TTTTTAAAAAKKKKEEEENNNN c234cb97fb bugfix #101 2022-01-15 12:36:35 +08:00
HakureiGenei 85fca1dcab
Merge pull request #100 from nacos-group/develop
#99 fix and cmake guidance
2021-12-26 18:19:14 +08:00
TTTTTAAAAAKKKKEEEENNNN de9629d15f fix #99 and add guidance on building the project with cmake 2021-12-26 18:18:28 +08:00
TTTTTAAAAAKKKKEEEENNNN beb310f318 issue #99 fix 2021-12-26 18:11:54 +08:00
HakureiGenei 240a44b86d
Merge pull request #98 from nacos-group/develop
adjust include dir
2021-12-18 20:40:01 +08:00
TTTTTAAAAAKKKKEEEENNNN 39a361d686 fix header file 2021-12-18 20:36:54 +08:00
TTTTTAAAAAKKKKEEEENNNN 77e17abf0f ff=unix to remove \r 2021-12-18 18:48:43 +08:00
TTTTTAAAAAKKKKEEEENNNN 5e85a6d49f header file install 2021-12-18 18:46:25 +08:00
HakureiGenei 330d781edd
Merge pull request #97 from nacos-group/develop
#96 fix, log rotate mechanism and log level prompt
2021-12-18 10:56:26 +08:00
TTTTTAAAAAKKKKEEEENNNN eb38bfab15 fix size parse and file size issue, add loglevel prompt 2021-12-18 10:43:20 +08:00
Liu, Hanyu 780b0b4037 fix info 2021-12-18 09:19:28 +08:00
Liu, Hanyu 65f58110dd Merge branch 'develop' of https://github.com/nacos-group/nacos-sdk-cpp into develop 2021-12-18 09:11:08 +08:00
Liu, Hanyu 06b777edbf log size and #96 , thanks to @cool-colo 2021-12-18 09:10:53 +08:00
TTTTTAAAAAKKKKEEEENNNN 1e9e728e3f add auth testcase 2021-12-15 23:08:06 +08:00
TTTTTAAAAAKKKKEEEENNNN 102978dd9d add auth testcases 2021-12-15 23:06:59 +08:00
TTTTTAAAAAKKKKEEEENNNN 13bb4e20f2 ignore list 2021-12-15 00:33:13 +08:00
TTTTTAAAAAKKKKEEEENNNN d9db6431ea cmakelist 2021-12-15 00:33:00 +08:00
Liu, Hanyu f589e883b8 use cmake 2021-12-14 20:04:54 +08:00
Liu, Hanyu 2ee9988af5 use cmake instead of makefile 2021-12-14 20:03:58 +08:00
HakureiGenei ae12b5850e
Merge pull request #95 from nacos-group/develop
empty server info fix and SPAS
2021-12-13 20:15:22 +08:00
HakureiGenei ef44913519
Merge pull request #92 from labman000/master
fix sending ack error
2021-11-20 18:49:56 +08:00
labman000 82a9aa14c9 fix sending ack error 2021-11-12 18:39:40 +08:00
Liu, Hanyu 29ee036c5d Fix crash
use non-static map to avoid crashing when the program exits.
2021-07-21 21:13:41 +08:00
HakureiGenei ffec1205ab
Merge pull request #83 from RONGDZ/develop
fix get instance return empty
2021-07-21 17:59:20 +08:00
RONGDZ 2d9a73fba4 fix get instance return empty 2021-07-20 15:02:20 +08:00
HakureiGenei af815fc75f
not needed 2021-07-10 22:28:00 +08:00
HakureiGenei ea1492ace8
not needed 2021-07-10 22:27:40 +08:00
Liu, Hanyu cced37a499 fix crash and code polish
don't clear map when call Deinit of IMACProvider to prevent crash
add accesskey/secretkey config
2021-07-10 21:49:44 +08:00
Liu, Hanyu 13e836f09f signature algorithm 2021-07-10 17:59:20 +08:00
Liu, Hanyu 77f54bd0cc SPAS testcase add credential info 2021-07-10 11:56:58 +08:00
TTTTTAAAAAKKKKEEEENNNN 16b448fddf SPAS(tentative) 2021-07-10 10:24:58 +08:00
Liu, Hanyu e1d775f624 HMAC algorithm & testcases 2021-07-09 19:51:31 +08:00
TTTTTAAAAAKKKKEEEENNNN 665046a365 refactor & add algorithm 2021-07-09 08:41:00 +08:00
HakureiGenei a055952cc4
Update README.md
client should be singular and a s should be added to the verb
2021-07-01 11:01:13 +08:00
TTTTTAAAAAKKKKEEEENNNN f78af10ef0 pass testcase 2021-06-27 23:35:17 +08:00
TTTTTAAAAAKKKKEEEENNNN 4524def3e1 fix #75 2021-06-27 22:40:11 +08:00
HakureiGenei 140e3c4edf
Merge pull request #77 from LiarMaiq/master
Fix get the "healthy" and "enabled" attribute
2021-06-27 11:08:34 +08:00
TTTTTAAAAAKKKKEEEENNNN 5f584b5204 compilation error fix 2021-06-27 10:54:26 +08:00
LiarMaiq 1559034643 Fix get the "healthy" and "enabled" attribute 2021-06-25 11:33:25 +08:00
HakureiGenei c3f4668c83
Merge pull request #73 from nacos-group/develop
Bugfix #70 , to comply with Nacos 2.x, the client won't check instanceId got from the server and will automatically create an instanceId when registering a new service
Testcase order adjust to avoid test failures
2021-06-18 22:30:49 +08:00
TTTTTAAAAAKKKKEEEENNNN cdbf474d72 refactor. only refer to include directory's file 2021-06-18 22:25:50 +08:00
TTTTTAAAAAKKKKEEEENNNN 1d16d4a0c6 refactor, only refer to include directory's file 2021-06-18 22:25:28 +08:00
TTTTTAAAAAKKKKEEEENNNN f6ed702929 remove extra / 2021-06-18 22:24:53 +08:00
TTTTTAAAAAKKKKEEEENNNN 6fb9f49ca4 errno fix 2021-06-13 00:24:48 +08:00
TTTTTAAAAAKKKKEEEENNNN 66e286bc0d Fix compilation issue #71 (tentative) 2021-06-09 22:35:15 +08:00
Liu, Hanyu 9fc57def60 adjust testcase order 2021-06-07 23:12:06 +08:00
Liu, Hanyu f91852dc6c register service with auto-generated instanceid to avoid instance being null 2021-06-07 22:42:59 +08:00
Liu, Hanyu 4ff85e481f Client-side generated instanceId when registering a service 2021-06-06 21:56:25 +08:00
Liu, Hanyu b94a7bb946 code polish 2021-06-06 13:03:56 +08:00
Liu, Hanyu 6e50b29175 SequenceProvider with test case 2021-06-06 10:45:44 +08:00
TTTTTAAAAAKKKKEEEENNNN 5f27f0bc8d sequence provider 2021-06-06 08:27:38 +08:00
Liu, Hanyu 4b8431bd5a sequence provider 2021-06-05 22:28:11 +08:00
TTTTTAAAAAKKKKEEEENNNN 5fb1773a0e fix document 2021-05-27 23:29:52 +08:00
175 changed files with 3112 additions and 1567 deletions

14
.gitignore vendored
View File

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

65
CMakeLists.txt Normal file
View File

@ -0,0 +1,65 @@
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*")

View File

@ -1,68 +0,0 @@
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,24 +4,28 @@
# Nacos-sdk-cpp # Nacos-sdk-cpp
Nacos-sdk-cpp for c++ clients allow users to access Nacos service, it supports service discovery and dynamic configuration. Nacos-sdk-cpp for c++ client allows 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://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 # Quick Examples
## Setup project ## Setup project
Download the source and run the following command in bash: Download the source and run the following command in bash:
`cd nacos-sdk-cpp` ```
cd nacos-sdk-cpp
`make` cmake .
make
```
a libnacos-cli.so and a nacos-cli.out will be generated a libnacos-cli.so and a nacos-cli.out will be generated
run `./nacos-cli.out` to perform test on the library 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 **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: 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:
@ -38,11 +42,7 @@ Here is an example showing how to integrate the library(.so) into your project:
IntegratingIntoYourProject.cpp: IntegratingIntoYourProject.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "ResourceGuard.h"
#include "NacosString.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -71,7 +71,7 @@ int main() {
``` ```
`g++ IntegratingIntoYourProject.cpp -L. -lnacos-cli -Iinclude -o integrated.out` `g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o integrated.out`
Start a nacos on your localmachine listening on port 8848, and run `./integrated.out` Start a nacos on your localmachine listening on port 8848, and run `./integrated.out`
@ -79,16 +79,14 @@ Then you'll see:
`SuccessfullyIntegrated` `SuccessfullyIntegrated`
You may come across the following problem: ## 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:
`error while loading shared libraries: libnacos-cli.so: cannot open shared object file: No such file or directory` `g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lcurl -lz -L. -lnacos-cli-static -o integrated.out`
**solution:** -lcurl -lz Specifies the curl and lz library used by libnacos
assume that your libnacos-cli.so resides in /usr/local/libnacos/ -L. -lnacos-cli-static links the static libnacos library resides in the same directory as IntegratingIntoYourProject.cpp
`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 ## Configuration
@ -97,9 +95,7 @@ or you can use ldconfig to add libnacos-cli.so to your lib path.
getConfig.cpp: getConfig.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -132,9 +128,7 @@ int main() {
setConfig.cpp: setConfig.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "ResourceGuard.h"
#include "constant/PropertyKeyConst.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -179,10 +173,7 @@ int main() {
listenToKeys.cpp: listenToKeys.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "ResourceGuard.h"
#include "listen/Listener.h"
#include "constant/PropertyKeyConst.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -232,12 +223,7 @@ registerInstances.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <unistd.h> #include <unistd.h>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "ResourceGuard.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -292,10 +278,7 @@ int main() {
subscribeServices.cpp: subscribeServices.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "ResourceGuard.h"
#include "naming/subscribe/EventListener.h"
#include "constant/PropertyKeyConst.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -352,12 +335,7 @@ getAllInstances.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <list> #include <list>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -396,6 +374,21 @@ using namespace nacos;
NamingService *namingSvc = factory->CreateNamingService(); 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 # Supported System/Compilers
| OS/Environment | Compilers | Tested version | | OS/Environment | Compilers | Tested version |

View File

@ -5,20 +5,24 @@
Nacos-sdk-cpp是nacos客戶端的C++版本,它支持服务发现和动态配置 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://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` ```
cd nacos-sdk-cpp
`make` cmake .
make
```
将会产生一个libnacos-cli.so 和一个 nacos-cli.out 将会产生一个libnacos-cli.so 和一个 nacos-cli.out
运行 `./nacos-cli.out` 以执行客户端的所有testcase 运行 `./nacos-cli.out` 以执行客户端的所有testcase
运行 `make install` 将libnacos-cli安装到lib目录
**注意:** 你需要在本机运行一个nacos server监听8848端口以完成所有测试 **注意:** 你需要在本机运行一个nacos server监听8848端口以完成所有测试
其中有个测试将会测试端点endpoint功能**所以你还需要**在本机运行一个http服务器在路径/endpoints/endpoint0提供下述内容 其中有个测试将会测试端点endpoint功能**所以你还需要**在本机运行一个http服务器在路径/endpoints/endpoint0提供下述内容
@ -33,12 +37,7 @@ Nacos-sdk-cpp是nacos客戶端的C++版本,它支持服务发现和动态配
IntegratingIntoYourProject.cpp: IntegratingIntoYourProject.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "ResourceGuard.h"
#include "Logger.h"
#include "NacosString.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -67,7 +66,7 @@ int main() {
``` ```
`g++ IntegratingIntoYourProject.cpp -L. -lnacos-cli -Iinclude -o integrated.out` `g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o integrated.out`
在本机的8848端口启动一个nacos server, 并且运行 `./integrated.out` 在本机的8848端口启动一个nacos server, 并且运行 `./integrated.out`
@ -75,16 +74,14 @@ int main() {
`SuccessfullyIntegrated` `SuccessfullyIntegrated`
你可能会遇到下述问题: ## 如果你使用静态库(.a)链接
假设.a文件和待编译文件在同一目录, 请执行下述命令:
`error while loading shared libraries: libnacos-cli.so: cannot open shared object file: No such file or directory` `g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lcurl -lz -L. -lnacos-cli-static -o integrated.out`
**解决方法:** 使用-lcurl -lz指定nacos客户端使用的curl和lz库
假设你的 libnacos-cli.so 在如下目录 /usr/local/libnacos/ 使用-L. -lnacos-cli-static引用当前目录下的libnacos-cli-static.a
`export LD_LIBRARY_PATH=/usr/local/libnacos/` (请勿包含lib文件的名字)
你也可以通过ldconfig将库配置到libpath当中
## 配置 ## 配置
@ -93,11 +90,7 @@ int main() {
getConfig.cpp: getConfig.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "PropertyKeyConst.h"
#include "DebugAssertion.h"
#include "ResourceGuard.h"
#include "Logger.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -130,13 +123,7 @@ int main() {
setConfig.cpp: setConfig.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <stdlib.h> #include "Nacos.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 std;
using namespace nacos; using namespace nacos;
@ -181,14 +168,7 @@ int main() {
listenToKeys.cpp: listenToKeys.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <stdlib.h> #include "Nacos.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 std;
using namespace nacos; using namespace nacos;
@ -237,21 +217,8 @@ int main() {
registerInstances.cpp: registerInstances.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include "naming/NamingProxy.h" #include "Nacos.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 std;
using namespace nacos; using namespace nacos;
@ -306,14 +273,7 @@ int main() {
subscribeServices.cpp: subscribeServices.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <stdlib.h> #include "Nacos.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 std;
using namespace nacos; using namespace nacos;
@ -369,21 +329,8 @@ int main() {
getAllInstances.cpp: getAllInstances.cpp:
```C++ ```C++
#include <iostream> #include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <list> #include <list>
#include "naming/NamingProxy.h" #include "Nacos.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 std;
using namespace nacos; using namespace nacos;
@ -423,6 +370,20 @@ 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,8 +1,5 @@
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
#include "NacosString.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -10,8 +7,8 @@ using namespace nacos;
int main() { int main() {
Properties props; Properties props;
props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//Server address props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//Server address
NacosServiceFactory *factory = new NacosServiceFactory(props); INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory); ResourceGuard <INacosServiceFactory> _guardFactory(factory);
ConfigService *n = factory->CreateConfigService(); ConfigService *n = factory->CreateConfigService();
ResourceGuard <ConfigService> _serviceFactory(n); ResourceGuard <ConfigService> _serviceFactory(n);
NacosString ss = ""; NacosString ss = "";

View File

@ -1,16 +1,9 @@
#!/bin/bash #!/bin/bash
if [ ! -f ../libnacos-cli.so ]; then g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o IntegratingIntoYourProject.out
echo "Please create the libnacos-cli.so by running make on the project's root directory first."; g++ -I/usr/local/include/nacos/ getAllInstances.cpp -lnacos-cli -o getAllInstances.out
exit; g++ -I/usr/local/include/nacos/ getConfig.cpp -lnacos-cli -o getConfig.out
fi 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
cp ../libnacos-cli.so . 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
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,11 +1,6 @@
#include <iostream> #include <iostream>
#include <list> #include <list>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "naming/Instance.h"
#include "NacosString.h"
#include "Properties.h"
#include "constant/PropertyKeyConst.h"
#include "ResourceGuard.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -13,8 +8,8 @@ using namespace nacos;
int main() { int main() {
Properties configProps; Properties configProps;
configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1"; configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
NacosServiceFactory *factory = new NacosServiceFactory(configProps); INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(configProps);
ResourceGuard <NacosServiceFactory> _guardFactory(factory); ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NamingService *namingSvc = factory->CreateNamingService(); NamingService *namingSvc = factory->CreateNamingService();
ResourceGuard <NamingService> _guardService(namingSvc); ResourceGuard <NamingService> _guardService(namingSvc);

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,6 @@
#include <iostream> #include <iostream>
#include "factory/NacosServiceFactory.h" #include "Nacos.h"
#include "ResourceGuard.h" #include <stdio.h>
#include "naming/subscribe/EventListener.h"
#include "constant/PropertyKeyConst.h"
using namespace std; using namespace std;
using namespace nacos; using namespace nacos;
@ -30,8 +28,8 @@ int main() {
//Interval for poller to check the status of subscribed services(unit:Ms), 30000 by default //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 //Here we set it to 5000 to see the output more quick
props[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "5000"; props[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "5000";
NacosServiceFactory *factory = new NacosServiceFactory(props); INacosServiceFactory *factory = NacosFactoryFactory::getNacosFactory(props);
ResourceGuard <NacosServiceFactory> _guardFactory(factory); ResourceGuard <INacosServiceFactory> _guardFactory(factory);
NamingService *n = factory->CreateNamingService(); NamingService *n = factory->CreateNamingService();
ResourceGuard <NamingService> _serviceFactory(n); ResourceGuard <NamingService> _serviceFactory(n);

24
include/Nacos.h Normal file
View File

@ -0,0 +1,24 @@
/*
* 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,6 +81,7 @@ public:
static const int UNABLE_TO_GET_HOST_IP = 1008; static const int UNABLE_TO_GET_HOST_IP = 1008;
static const int UNABLE_TO_CREATE_SOCKET = 1009; static const int UNABLE_TO_CREATE_SOCKET = 1009;
static const int INVALID_CONFIG_PARAM = 1010; static const int INVALID_CONFIG_PARAM = 1010;
static const int UNABLE_TO_GET_HOST_NAME = 1011;
}; };

View File

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

View File

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

View File

@ -0,0 +1,11 @@
#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

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

View File

@ -1,14 +1,8 @@
#ifndef __CLUSTER_H_ #ifndef __CLUSTER_H_
#define __CLUSTER_H_ #define __CLUSTER_H_
#include <vector> #include <map>
#include <list>
#include <sys/time.h>
#include "NacosString.h" #include "NacosString.h"
#include "constant/ConfigConstant.h"
#include "utils/url.h"
#include "utils/ParamUtils.h"
#include "naming/Instance.h"
namespace nacos{ namespace nacos{
class HealthChecker { class HealthChecker {
@ -24,29 +18,17 @@ private:
HealthChecker healthChecker; HealthChecker healthChecker;
std::map<NacosString, NacosString> metadata; std::map<NacosString, NacosString> metadata;
public: 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 }//namespace nacos

View File

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

View File

@ -1,13 +1,8 @@
#ifndef __SVC_INFO_H_ #ifndef __SVC_INFO_H_
#define __SVC_INFO_H_ #define __SVC_INFO_H_
#include <vector>
#include <list> #include <list>
#include <sys/time.h>
#include "NacosString.h" #include "NacosString.h"
#include "constant/ConfigConstant.h"
#include "utils/url.h"
#include "utils/ParamUtils.h"
#include "naming/Instance.h" #include "naming/Instance.h"
namespace nacos{ namespace nacos{
@ -34,200 +29,77 @@ private:
volatile bool _allIPs; volatile bool _allIPs;
public: public:
ServiceInfo() : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""), _allIPs(false) { ServiceInfo();
}
bool isAllIPs() const{ bool isAllIPs() const;
return _allIPs;
}
void setAllIPs(bool allIPs) { void setAllIPs(bool allIPs);
_allIPs = allIPs;
}
explicit ServiceInfo(const NacosString &key) : _jsonFromServer(""), _cacheMillis(1000L), _lastRefTime(0L), _checksum(""), explicit ServiceInfo(const NacosString &key);
_allIPs(false) {
std::vector <NacosString> segs;
ParamUtils::Explode(segs, key, ConfigConstant::SERVICE_INFO_SPLITER);
if (segs.size() == 2) { ServiceInfo(const NacosString &name, const NacosString &clusters);
setGroupName(segs[0]);
setName(segs[1]);
} else if (segs.size() == 3) {
setGroupName(segs[0]);
setName(segs[1]);
setClusters(segs[2]);
}
}
ServiceInfo(const NacosString &name, const NacosString &clusters) { int ipCount();
_name = name;
_clusters = clusters;
}
int ipCount() { bool expired() const;
return _hosts.size();
}
bool expired() const{ void setHosts(std::list <Instance> &hosts);
//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; bool isValid();
}
void setHosts(std::list <Instance> &hosts) { NacosString getName();
_hosts = hosts;
}
bool isValid() { void setName(const NacosString &name);
return _hosts.size() > 0;
}
NacosString getName() { NacosString getGroupName();
return _name;
}
void setName(const NacosString &name) { void setGroupName(const NacosString &groupName);
_name = name;
}
NacosString getGroupName() { void setLastRefTime(long lastRefTime);
return _groupName;
}
void setGroupName(const NacosString &groupName) { long getLastRefTime();
_groupName = groupName;
}
void setLastRefTime(long lastRefTime) { NacosString getClusters();
_lastRefTime = lastRefTime;
}
long getLastRefTime() { void setClusters(const NacosString &clusters);
return _lastRefTime;
}
NacosString getClusters() { long getCacheMillis();
return _clusters;
}
void setClusters(const NacosString &clusters) { void setCacheMillis(long cacheMillis);
_clusters = clusters;
}
long getCacheMillis() { std::list <Instance> getHosts();
return _cacheMillis;
}
void setCacheMillis(long cacheMillis) { std::list <Instance> *getHostsNocopy();
_cacheMillis = cacheMillis;
}
std::list <Instance> getHosts() { bool validate() const;
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) //@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) //@JSONField(serialize = false)
NacosString getKey() const{ NacosString getKey() const;
return getKey(_name, _clusters);
}
//@JSONField(serialize = false) //@JSONField(serialize = false)
NacosString getKeyEncoded() const{ NacosString getKeyEncoded() const;
return getKey(urlencode(_name), _clusters);
}
//@JSONField(serialize = false) //@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) //@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 //@Override
NacosString toString() const{ NacosString toString() const;
return getKey();
}
//!!BE CAREFUL!! //!!BE CAREFUL!!
//This function is very expensive!! call it with care! //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";
}
res += "\n]"; NacosString getChecksum() const;
return res; void setChecksum(const NacosString &checksum);
}
NacosString getChecksum() const{
return _checksum;
}
void setChecksum(const NacosString &checksum) {
_checksum = checksum;
}
}; };
}//namespace nacos }//namespace nacos

View File

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

View File

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

View File

@ -1,11 +1,12 @@
#!!please NOTE that the file format for this properties should be UNIX!!
#specify nacos server address here(separated by ,) #specify nacos server address here(separated by ,)
#serverAddr= #serverAddr=
#log path, default is ~/nacos/logs/ #log path, default is ~/nacos/logs/
#nacos.log.path= #nacos.log.path=
#rotate time (now we only support hour as unit) #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.rotateTime=24h #nacos.log.rotateSize=100m
#log level, default is ERROR #log level, default is ERROR
#nacos.log.level=ERROR #nacos.log.level=ERROR
@ -32,3 +33,6 @@
#poller interval (10000 ms by default) to refresh subscribed service information from server #poller interval (10000 ms by default) to refresh subscribed service information from server
#naming.poller.interval= #naming.poller.interval=
#accessKey/secretKey for SPAS
#accessKey=
#secretKey=

View File

@ -1,15 +1,16 @@
#include "utils/ParamUtils.h" #include "src/utils/ParamUtils.h"
#include "AppConfigManager.h" #include "AppConfigManager.h"
#include "NacosString.h" #include "NacosString.h"
#include "Properties.h" #include "Properties.h"
#include "src/utils/NetUtils.h" #include "src/utils/NetUtils.h"
#include "constant/PropertyKeyConst.h" #include "constant/PropertyKeyConst.h"
#include "NacosExceptions.h" #include "NacosExceptions.h"
#include "utils/DirUtils.h" #include "src/utils/DirUtils.h"
#include <vector> #include <vector>
#include <stdlib.h> #include <stdlib.h>
#include "src/log/Logger.h" #include "src/log/Logger.h"
#include "src/utils/ConfigParserUtils.h" #include "src/utils/ConfigParserUtils.h"
#include "src/utils/Env.h"
using namespace std; using namespace std;
@ -49,7 +50,7 @@ void AppConfigManager::clearConfig() {
appConfig.clear(); appConfig.clear();
} }
const NacosString &AppConfigManager::get(const NacosString &key) { const NacosString& AppConfigManager::get(const NacosString &key) {
if (appConfig.count(key) == 0) { if (appConfig.count(key) == 0) {
return NULLSTR; return NULLSTR;
} }
@ -59,7 +60,13 @@ const NacosString &AppConfigManager::get(const NacosString &key) {
{ {
return NULLSTR; return NULLSTR;
} }
return appConfig[key];
Properties::iterator iter = appConfig.find(key);
if (iter == appConfig.end()) {
return NULLSTR;
}
return iter->second;
} }
void AppConfigManager::set(const NacosString &key, const NacosString &value) { void AppConfigManager::set(const NacosString &key, const NacosString &value) {
@ -87,6 +94,15 @@ AppConfigManager::AppConfigManager(const NacosString &_configFile) {
configFile = _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() { void AppConfigManager::initDefaults() {
appConfig.clear(); appConfig.clear();
//appConfig[PropertyKeyConst::NAMESPACE] = "public"; //appConfig[PropertyKeyConst::NAMESPACE] = "public";
@ -100,8 +116,15 @@ void AppConfigManager::initDefaults() {
set(PropertyKeyConst::LOCAL_IP, NetUtils::getHostIp()); set(PropertyKeyConst::LOCAL_IP, NetUtils::getHostIp());
set(PropertyKeyConst::UDP_RECEIVER_PORT, "30620"); set(PropertyKeyConst::UDP_RECEIVER_PORT, "30620");
NacosString appName = getAppNameFromEnv();
if (!NacosStringOps::isNullStr(appName)) {
set(PropertyKeyConst::APP_NAME, appName);
}
NacosString homedir = DirUtils::getHome(); 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"); 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()); 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; bool contains(const NacosString &key) const;
Properties getAllConfig() const { return appConfig; }; const Properties& getAllConfig() { return appConfig; };
const NacosString & getContextPath() const { return _contextPath; }; 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"); FILE *fp = fopen(file.c_str(), "rb");
if (fp == NULL) { if (fp == NULL) {
char errbuf[100]; char errbuf[100];
sprintf(errbuf, "Failed to open file for read, errno: %d", errno); snprintf(errbuf, sizeof(errbuf), "Failed to open file for read, errno: %d", errno);
//TODO:add errorcode //TODO:add errorcode
throw IOException(NacosException::UNABLE_TO_OPEN_FILE, errbuf); throw IOException(NacosException::UNABLE_TO_OPEN_FILE, errbuf);
} }
@ -57,7 +57,7 @@ bool ConcurrentDiskUtil::writeFileContent
FILE *fp = fopen(path.c_str(), "wb"); FILE *fp = fopen(path.c_str(), "wb");
if (fp == NULL) { if (fp == NULL) {
char errbuf[100]; char errbuf[100];
sprintf(errbuf, "Failed to open file for write, errno: %d", errno); snprintf(errbuf, sizeof(errbuf), "Failed to open file for write, errno: %d", errno);
//TODO:add errorcode //TODO:add errorcode
throw IOException(NacosException::UNABLE_TO_OPEN_FILE, errbuf); throw IOException(NacosException::UNABLE_TO_OPEN_FILE, errbuf);
} }

View File

@ -0,0 +1,79 @@
//
// 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();
}
}
}

25
src/config/ConfigProxy.h Normal file
View File

@ -0,0 +1,25 @@
//
// 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 <errno.h>
#include "NacosExceptions.h" #include "NacosExceptions.h"
#include "NacosString.h" #include "NacosString.h"
#include "utils/ParamUtils.h" #include "src/utils/ParamUtils.h"
#include "utils/DirUtils.h" #include "src/utils/DirUtils.h"
#include "SnapShotSwitch.h" #include "SnapShotSwitch.h"
#include "JVMUtil.h" #include "JVMUtil.h"
#include "ConcurrentDiskUtil.h" #include "ConcurrentDiskUtil.h"

View File

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

View File

@ -9,16 +9,22 @@ const NacosString PropertyKeyConst::ENDPOINT_PORT = "endpointPort";
const NacosString PropertyKeyConst::NAMESPACE = "namespace"; const NacosString PropertyKeyConst::NAMESPACE = "namespace";
const NacosString PropertyKeyConst::ENDPOINT_QUERY_PARAMS = "endpointQueryParams";
const NacosString PropertyKeyConst::ACCESS_KEY = "accessKey"; const NacosString PropertyKeyConst::ACCESS_KEY = "accessKey";
const NacosString PropertyKeyConst::SECRET_KEY = "secretKey"; const NacosString PropertyKeyConst::SECRET_KEY = "secretKey";
const NacosString PropertyKeyConst::APP_NAME = "appName";
const NacosString PropertyKeyConst::RAM_ROLE_NAME = "ramRoleName"; const NacosString PropertyKeyConst::RAM_ROLE_NAME = "ramRoleName";
const NacosString PropertyKeyConst::SERVER_ADDR = "serverAddr"; const NacosString PropertyKeyConst::SERVER_ADDR = "serverAddr";
const NacosString PropertyKeyConst::CONTEXT_PATH = "nacos.server.contextpath"; const NacosString PropertyKeyConst::CONTEXT_PATH = "nacos.server.contextpath";
const NacosString PropertyKeyConst::ENDPOINT_CONTEXT_PATH = "endpointContextPath";
const NacosString PropertyKeyConst::CLUSTER_NAME = "clusterName"; const NacosString PropertyKeyConst::CLUSTER_NAME = "clusterName";
const NacosString PropertyKeyConst::ENCODE = "encode"; const NacosString PropertyKeyConst::ENCODE = "encode";
@ -43,11 +49,13 @@ const NacosString PropertyKeyConst::HB_FAIL_WAIT_TIME = "naming.heartbeat.failwa
const NacosString PropertyKeyConst::NACOS_SNAPSHOT_PATH = "nacos.snapshot.path"; const NacosString PropertyKeyConst::NACOS_SNAPSHOT_PATH = "nacos.snapshot.path";
const NacosString PropertyKeyConst::LOG_PATH = "nacos.log.path"; const NacosString PropertyKeyConst::LOG_PATH = "nacos.log.path";
const NacosString PropertyKeyConst::LOG_ROTATE_TIME = "nacos.log.rotateTime"; const NacosString PropertyKeyConst::LOG_ROTATE_SIZE = "nacos.log.rotateSize";
const NacosString PropertyKeyConst::LOG_LEVEL = "nacos.log.level"; const NacosString PropertyKeyConst::LOG_LEVEL = "nacos.log.level";
const NacosString PropertyKeyConst::CLIENT_NAME = "nacos.client.name"; const NacosString PropertyKeyConst::CLIENT_NAME = "nacos.client.name";
const NacosString PropertyKeyConst::AUTH_USERNAME = "nacos.auth.username"; const NacosString PropertyKeyConst::AUTH_USERNAME = "nacos.auth.username";
const NacosString PropertyKeyConst::AUTH_PASSWORD = "nacos.auth.password"; const NacosString PropertyKeyConst::AUTH_PASSWORD = "nacos.auth.password";
const NacosString PropertyKeyConst::LOCAL_IP = "nacos.client.ip"; 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 }//namespace nacos

View File

@ -0,0 +1,54 @@
//
// 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;
}
}

35
src/crypto/MACProvider.h Normal file
View File

@ -0,0 +1,35 @@
//
// 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

@ -0,0 +1,36 @@
//
// 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

@ -0,0 +1,72 @@
/*
* 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

@ -0,0 +1,22 @@
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

@ -0,0 +1,19 @@
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

@ -0,0 +1,19 @@
/**
* @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

@ -0,0 +1,106 @@
/**
* @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

@ -0,0 +1,42 @@
/**
* @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

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

View File

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

View File

@ -0,0 +1,15 @@
#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. // Created by liuhanyu on 2020/8/30.
// //
#include "factory/NacosServiceFactory.h" #include "src/factory/NacosServiceFactory.h"
#include "src/init/Init.h" #include "src/init/Init.h"
#include "src/naming/NacosNamingService.h" #include "src/naming/NacosNamingService.h"
#include "src/naming/NacosNamingMaintainService.h" #include "src/naming/NacosNamingMaintainService.h"
@ -19,7 +19,9 @@
#include "src/naming/subscribe/HostReactor.h" #include "src/naming/subscribe/HostReactor.h"
#include "src/security/SecurityManager.h" #include "src/security/SecurityManager.h"
#include "src/utils/ConfigParserUtils.h" #include "src/utils/ConfigParserUtils.h"
#include "utils/DirUtils.h" #include "src/utils/SequenceProvider.h"
#include "src/config/ConfigProxy.h"
#include "src/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 //Unlike Java, in cpp, there's no container, no spring to do the ORM job, so I have to handle it myself
namespace nacos{ namespace nacos{
@ -81,7 +83,7 @@ NamingService *NacosServiceFactory::CreateNamingService() NACOS_THROW(NacosExcep
checkConfig(); checkConfig();
ObjectConfigData *objectConfigData = new ObjectConfigData(NAMING); ObjectConfigData *objectConfigData = new ObjectConfigData(NAMING);
objectConfigData->name = "config"; objectConfigData->name = "config";
NacosString encoding = "UTF-8"; objectConfigData->encoding = "UTF-8";
AppConfigManager *appConfigManager = buildConfigManager(objectConfigData); AppConfigManager *appConfigManager = buildConfigManager(objectConfigData);
initializeRuntimeLogSettings(appConfigManager); initializeRuntimeLogSettings(appConfigManager);
@ -114,6 +116,10 @@ NamingService *NacosServiceFactory::CreateNamingService() NACOS_THROW(NacosExcep
HostReactor *hostReactor = new HostReactor(objectConfigData); HostReactor *hostReactor = new HostReactor(objectConfigData);
objectConfigData->_hostReactor = hostReactor; 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(); objectConfigData->checkAssembledObject();
NamingService *instance = new NacosNamingService(objectConfigData); NamingService *instance = new NacosNamingService(objectConfigData);
@ -126,6 +132,7 @@ ConfigService *NacosServiceFactory::CreateConfigService() NACOS_THROW(NacosExcep
checkConfig(); checkConfig();
ObjectConfigData *objectConfigData = new ObjectConfigData(CONFIG); ObjectConfigData *objectConfigData = new ObjectConfigData(CONFIG);
objectConfigData->name = "name"; objectConfigData->name = "name";
objectConfigData->encoding = "UTF-8";
AppConfigManager *appConfigManager = buildConfigManager(objectConfigData); AppConfigManager *appConfigManager = buildConfigManager(objectConfigData);
initializeRuntimeLogSettings(appConfigManager); initializeRuntimeLogSettings(appConfigManager);
@ -133,7 +140,6 @@ ConfigService *NacosServiceFactory::CreateConfigService() NACOS_THROW(NacosExcep
//Create http client //Create http client
IHttpCli *httpCli = NULL; IHttpCli *httpCli = NULL;
httpCli = new HTTPCli(); httpCli = new HTTPCli();
NacosString encoding = "UTF-8";
objectConfigData->_httpCli = httpCli; objectConfigData->_httpCli = httpCli;
buildSecurityManagerAndHttpDelegate(objectConfigData); buildSecurityManagerAndHttpDelegate(objectConfigData);
@ -142,6 +148,9 @@ ConfigService *NacosServiceFactory::CreateConfigService() NACOS_THROW(NacosExcep
ServerListManager *serverListManager = new ServerListManager(objectConfigData); ServerListManager *serverListManager = new ServerListManager(objectConfigData);
objectConfigData->_serverListManager = serverListManager; objectConfigData->_serverListManager = serverListManager;
ConfigProxy *configProxy = new ConfigProxy(objectConfigData);
objectConfigData->_configProxy = configProxy;
LocalSnapshotManager *localSnapshotManager = new LocalSnapshotManager(appConfigManager); LocalSnapshotManager *localSnapshotManager = new LocalSnapshotManager(appConfigManager);
objectConfigData->_localSnapshotManager = localSnapshotManager; objectConfigData->_localSnapshotManager = localSnapshotManager;
ClientWorker *clientWorker = new ClientWorker(objectConfigData); ClientWorker *clientWorker = new ClientWorker(objectConfigData);
@ -159,7 +168,7 @@ NamingMaintainService *NacosServiceFactory::CreateNamingMaintainService() NACOS_
checkConfig(); checkConfig();
ObjectConfigData *objectConfigData = new ObjectConfigData(MAINTAIN); ObjectConfigData *objectConfigData = new ObjectConfigData(MAINTAIN);
objectConfigData->name = "config"; objectConfigData->name = "config";
NacosString encoding = "UTF-8"; objectConfigData->encoding = "UTF-8";
AppConfigManager *appConfigManager = buildConfigManager(objectConfigData); AppConfigManager *appConfigManager = buildConfigManager(objectConfigData);
initializeRuntimeLogSettings(appConfigManager); initializeRuntimeLogSettings(appConfigManager);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -110,9 +110,10 @@ long JSON::getLong(const NacosString &jsonString, const NacosString &fieldname)
Instance JSON::Json2Instance(const Value &host) NACOS_THROW(NacosException) { Instance JSON::Json2Instance(const Value &host) NACOS_THROW(NacosException) {
Instance theinstance; Instance theinstance;
markRequired(host, "instanceId"); if (host.HasMember("instanceId")) {
const Value &instanceId = host["instanceId"]; const Value &instanceId = host["instanceId"];
theinstance.instanceId = instanceId.GetString(); theinstance.instanceId = instanceId.GetString();
}
markRequired(host, "port"); markRequired(host, "port");
const Value &port = host["port"]; const Value &port = host["port"];
@ -140,6 +141,20 @@ Instance JSON::Json2Instance(const Value &host) NACOS_THROW(NacosException) {
theinstance.metadata = mtdata; 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")) { if (host.HasMember("clusterName")) {
const Value &clusterName = host["clusterName"]; const Value &clusterName = host["clusterName"];
theinstance.clusterName = clusterName.GetString(); theinstance.clusterName = clusterName.GetString();
@ -223,11 +238,36 @@ ServiceInfo JSON::JsonStr2ServiceInfo(const NacosString &jsonString) NACOS_THROW
"Error while parsing the JSON String for ServiceInfo!"); "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"); markRequired(d, "hosts");
const Value &hosts = d["hosts"]; const Value &hosts = d["hosts"];
if (hosts.Size() == 0) { if (hosts.Size() == 0) {
return si; return si;
} }
std::list <Instance> hostlist; std::list <Instance> hostlist;
for (SizeType i = 0; i < hosts.Size(); i++) { for (SizeType i = 0; i < hosts.Size(); i++) {
const Value &curhost = hosts[i]; const Value &curhost = hosts[i];
@ -237,32 +277,10 @@ ServiceInfo JSON::JsonStr2ServiceInfo(const NacosString &jsonString) NACOS_THROW
si.setHosts(hostlist); 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"); markRequired(d, "checksum");
const Value &checkSum = d["checksum"]; const Value &checkSum = d["checksum"];
si.setChecksum(checkSum.GetString()); 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; return si;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,8 +15,8 @@
#ifndef RAPIDJSON_INTERNAL_REGEX_H_ #ifndef RAPIDJSON_INTERNAL_REGEX_H_
#define RAPIDJSON_INTERNAL_REGEX_H_ #define RAPIDJSON_INTERNAL_REGEX_H_
#include "../allocators.h" #include "src/json/rapidjson/allocators.h"
#include "../stream.h" #include "src/json/rapidjson/stream.h"
#include "stack.h" #include "stack.h"
#ifdef __clang__ #ifdef __clang__

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_INTERNAL_STACK_H_ #ifndef RAPIDJSON_INTERNAL_STACK_H_
#define RAPIDJSON_INTERNAL_STACK_H_ #define RAPIDJSON_INTERNAL_STACK_H_
#include "../allocators.h" #include "src/json/rapidjson/allocators.h"
#include "swap.h" #include "swap.h"
#include <cstddef> #include <cstddef>

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_ #ifndef RAPIDJSON_INTERNAL_STRFUNC_H_
#define RAPIDJSON_INTERNAL_STRFUNC_H_ #define RAPIDJSON_INTERNAL_STRFUNC_H_
#include "../stream.h" #include "src/json/rapidjson/stream.h"
#include <cwchar> #include <cwchar>
RAPIDJSON_NAMESPACE_BEGIN RAPIDJSON_NAMESPACE_BEGIN

View File

@ -15,7 +15,7 @@
#ifndef RAPIDJSON_INTERNAL_SWAP_H_ #ifndef RAPIDJSON_INTERNAL_SWAP_H_
#define RAPIDJSON_INTERNAL_SWAP_H_ #define RAPIDJSON_INTERNAL_SWAP_H_
#include "../rapidjson.h" #include "src/json/rapidjson/rapidjson.h"
#if defined(__clang__) #if defined(__clang__)
RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PUSH

View File

@ -16,7 +16,7 @@
#define RAPIDJSON_MEMORYBUFFER_H_ #define RAPIDJSON_MEMORYBUFFER_H_
#include "stream.h" #include "stream.h"
#include "internal/stack.h" #include "src/json/rapidjson/internal/stack.h"
RAPIDJSON_NAMESPACE_BEGIN RAPIDJSON_NAMESPACE_BEGIN

View File

@ -16,7 +16,7 @@
#define RAPIDJSON_POINTER_H_ #define RAPIDJSON_POINTER_H_
#include "document.h" #include "document.h"
#include "internal/itoa.h" #include "src/json/rapidjson/internal/itoa.h"
#ifdef __clang__ #ifdef __clang__
RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PUSH

View File

@ -20,9 +20,9 @@
#include "allocators.h" #include "allocators.h"
#include "stream.h" #include "stream.h"
#include "encodedstream.h" #include "encodedstream.h"
#include "internal/meta.h" #include "src/json/rapidjson/internal/meta.h"
#include "internal/stack.h" #include "src/json/rapidjson/internal/stack.h"
#include "internal/strtod.h" #include "src/json/rapidjson/internal/strtod.h"
#include <limits> #include <limits>
#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
@ -122,7 +122,7 @@ RAPIDJSON_DIAG_OFF(effc++)
RAPIDJSON_MULTILINEMACRO_END RAPIDJSON_MULTILINEMACRO_END
#endif #endif
#include "error/error.h" // ParseErrorCode, ParseResult #include "src/json/rapidjson/error/error.h" // ParseErrorCode, ParseResult
RAPIDJSON_NAMESPACE_BEGIN RAPIDJSON_NAMESPACE_BEGIN

View File

@ -33,7 +33,7 @@
#endif #endif
#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX #if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
#include "internal/regex.h" #include "src/json/rapidjson/internal/regex.h"
#elif RAPIDJSON_SCHEMA_USE_STDREGEX #elif RAPIDJSON_SCHEMA_USE_STDREGEX
#include <regex> #include <regex>
#endif #endif

View File

@ -16,13 +16,13 @@
#define RAPIDJSON_STRINGBUFFER_H_ #define RAPIDJSON_STRINGBUFFER_H_
#include "stream.h" #include "stream.h"
#include "internal/stack.h" #include "src/json/rapidjson/internal/stack.h"
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS #if RAPIDJSON_HAS_CXX11_RVALUE_REFS
#include <utility> // std::move #include <utility> // std::move
#endif #endif
#include "internal/stack.h" #include "src/json/rapidjson/internal/stack.h"
#if defined(__clang__) #if defined(__clang__)
RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PUSH

View File

@ -16,11 +16,11 @@
#define RAPIDJSON_WRITER_H_ #define RAPIDJSON_WRITER_H_
#include "stream.h" #include "stream.h"
#include "internal/meta.h" #include "src/json/rapidjson/internal/meta.h"
#include "internal/stack.h" #include "src/json/rapidjson/internal/stack.h"
#include "internal/strfunc.h" #include "src/json/rapidjson/internal/strfunc.h"
#include "internal/dtoa.h" #include "src/json/rapidjson/internal/dtoa.h"
#include "internal/itoa.h" #include "src/json/rapidjson/internal/itoa.h"
#include "stringbuffer.h" #include "stringbuffer.h"
#include <new> // placement new #include <new> // placement new

View File

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

View File

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

View File

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

View File

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

View File

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

29
src/naming/Cluster.cpp Normal file
View File

@ -0,0 +1,29 @@
#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 "naming/Instance.h"
#include "utils/ParamUtils.h" #include "src/utils/ParamUtils.h"
#include "src/log/Logger.h" #include "src/log/Logger.h"
namespace nacos{ namespace nacos{

View File

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

View File

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

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