├── .gitignore ├── doc ├── Mooon基础类库编程手册.doc ├── Mooon基础类库编程手册.pdf ├── 开源mooon开发规范说明书.doc ├── 开源mooon开发规范说明书.pdf └── Linux远程批量工具mooon_ssh和mooon_upload使用示例.pdf ├── tools ├── test.thrift ├── README.txt ├── hbase_constants.cpp ├── random_string.cpp ├── hbase_constants.h ├── test_types.h ├── charset_conv.cpp ├── base64.cpp ├── rsa256_sign.cpp ├── rsa_pub_encrypt.cpp ├── rsa_priv_decrypt.cpp ├── thrift_client.cpp ├── pidof.cpp ├── sha.cpp ├── rsa_decrypt.cpp ├── rsa_encrypt.cpp ├── curl_download.cpp ├── md5.cpp ├── killall.cpp ├── zk_download.cpp └── USAGE.txt ├── test ├── Makefile ├── CMakeLists.txt ├── utils │ ├── run.sh │ ├── Makefile │ ├── CMakeLists.txt │ ├── test_args_parser.cpp │ ├── ut_tokener.cpp │ └── ut_string_utils.cpp ├── net │ ├── run.sh │ ├── CMakeLists.txt │ ├── Makefile │ ├── udp_client_test.cpp │ ├── udp_server_test.cpp │ ├── ut_tcp_client.cpp │ ├── ut_net_utils.cpp │ └── ut_libssh2.cpp ├── sys │ ├── run.sh │ ├── CMakeLists.txt │ ├── Makefile │ ├── ut_thread.cpp │ ├── ut_object_pool.cpp │ ├── ut_thread_pool.cpp │ ├── ut_fs_utils.cpp │ └── ut_datetime_utils.cpp └── plugin │ └── plugin_mysql │ ├── run.sh │ └── Makefile ├── src ├── helper │ └── CMakeLists.txt ├── README ├── CMakeLists.txt ├── utils │ ├── file_format_exception.cpp │ ├── CMakeLists.txt │ ├── md5.h │ ├── bit_utils.cpp │ ├── crypto.cpp │ ├── integer_utils.cpp │ ├── exception.cpp │ └── object.cpp ├── net │ ├── CMakeLists.txt │ ├── sensor.cpp │ └── ip_address.cpp └── sys │ ├── shared_library.cpp │ ├── CMakeLists.txt │ ├── syscall_exception.cpp │ ├── signal_handler.cpp │ ├── shared_memory.cpp │ ├── time_thread.cpp │ └── pool_thread.cpp ├── shell ├── README.txt ├── uninstall_crontab.sh ├── find_deleted_files.sh ├── process_stopper.sh ├── mem.sh ├── top_mem.sh ├── top_cpu.sh ├── top_process.sh ├── clean_mysql_user.sh ├── file_utils.sh ├── cpumem.sh ├── check_table_size.sh ├── set_zookeeper_id.sh ├── log_rotater.sh ├── install_crontab.sh ├── udp_drops.sh └── set_hostname.sh ├── CMakeLists.txt ├── include └── mooon │ ├── utils │ ├── crypto.h │ ├── test_any2string.cpp │ ├── make_format_string_h.sh │ ├── file_format_exception.h │ ├── hash_utils.h │ ├── timeoutable.h │ ├── listable.h │ ├── print_color.h │ ├── bit_utils.h │ ├── charset_utils.h │ ├── regex_helper.h │ ├── sha_helper.h │ ├── exception.h │ ├── aes_helper.h │ └── integer_utils.h │ ├── helper │ ├── curl.h │ └── rapidjson_helper.h │ ├── sys │ ├── thread_base.h │ ├── error.h │ ├── time_thread.h │ ├── syscall_exception.h │ ├── sqlite3_db.h │ ├── shared_library.h │ ├── singleton.h │ ├── config.h │ ├── event.h │ ├── dir_utils.h │ ├── stop_watch.h │ ├── shared_memory.h │ ├── compiler.h │ ├── ref_countable.h │ ├── semaphore.h │ ├── read_write_lock.h │ └── db_exception.h │ └── net │ ├── config.h │ ├── sensor.h │ ├── listener.h │ ├── udp_socket.h │ ├── send_machine.h │ └── kafka_producer.h └── README.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .git 2 | .settings 3 | .cproject 4 | .project 5 | -------------------------------------------------------------------------------- /doc/Mooon基础类库编程手册.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyjian/libmooon/HEAD/doc/Mooon基础类库编程手册.doc -------------------------------------------------------------------------------- /doc/Mooon基础类库编程手册.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyjian/libmooon/HEAD/doc/Mooon基础类库编程手册.pdf -------------------------------------------------------------------------------- /doc/开源mooon开发规范说明书.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyjian/libmooon/HEAD/doc/开源mooon开发规范说明书.doc -------------------------------------------------------------------------------- /doc/开源mooon开发规范说明书.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyjian/libmooon/HEAD/doc/开源mooon开发规范说明书.pdf -------------------------------------------------------------------------------- /tools/test.thrift: -------------------------------------------------------------------------------- 1 | namespace cpp test 2 | 3 | service TestService { 4 | string hello() 5 | } 6 | -------------------------------------------------------------------------------- /doc/Linux远程批量工具mooon_ssh和mooon_upload使用示例.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyjian/libmooon/HEAD/doc/Linux远程批量工具mooon_ssh和mooon_upload使用示例.pdf -------------------------------------------------------------------------------- /test/Makefile: -------------------------------------------------------------------------------- 1 | SUB_DIRS=utils sys net 2 | unit_test: 3 | for subdir in $(SUB_DIRS); \ 4 | do \ 5 | cd $$subdir; \ 6 | make; \ 7 | cd -; \ 8 | done 9 | -------------------------------------------------------------------------------- /test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | link_libraries(dl pthread rt z) 4 | add_subdirectory(utils) 5 | add_subdirectory(sys) 6 | add_subdirectory(net) 7 | -------------------------------------------------------------------------------- /test/utils/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export LD_LIBRARY_PATH=.:../../src/utils:$LD_LIBRARY_PATH 4 | 5 | FILES=`ls ut_*|grep -v ".cpp"|grep -v ".o"` 6 | for file in $FILES; 7 | do 8 | sh -c ./$file 9 | done 10 | -------------------------------------------------------------------------------- /tools/README.txt: -------------------------------------------------------------------------------- 1 | mooon_ssh 批量远程执行命令工具 2 | mooon_upload 批量上传到多机器工具 3 | mooon_download 远程下载多个文件工具 4 | md5 计算MD5值工具 5 | disk_benchmark 磁盘性能测试工具 6 | hbase_stress HBase压力和性能测试工具 7 | r3c_stress 基于r3c开发的redis性能测试工具,r3c是一个基于hiredis的C++客户端库 -------------------------------------------------------------------------------- /test/net/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export LD_LIBRARY_PATH=.:../../src/utils:../../src/net:../../src/sys:$LD_LIBRARY_PATH 4 | 5 | FILES=`ls ut_*|grep -v ".cpp"|grep -v ".o"` 6 | for file in $FILES; 7 | do 8 | sh -c ./$file 9 | done 10 | -------------------------------------------------------------------------------- /test/sys/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export LD_LIBRARY_PATH=.:../../src/utils:../../src/net:../../src/sys:$LD_LIBRARY_PATH 4 | 5 | FILES=`ls ut_*|grep -v ".cpp"|grep -v ".o"` 6 | for file in $FILES; 7 | do 8 | sh -c ./$file 9 | done 10 | -------------------------------------------------------------------------------- /test/utils/Makefile: -------------------------------------------------------------------------------- 1 | CPP_FILES=$(shell ls *.cpp) 2 | unit_test: 3 | dos2unix run.sh;chmod +x run.sh; 4 | for cpp_file in $(CPP_FILES); \ 5 | do \ 6 | name=`basename $$cpp_file .cpp`; \ 7 | g++ -g -o $$name -I../../include -L../../src/utils -lmooon_utils $$cpp_file; \ 8 | done 9 | -------------------------------------------------------------------------------- /src/helper/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | # CMAKE_INSTALL_PREFIX 4 | install( 5 | DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon/helper 6 | DESTINATION include/mooon 7 | PATTERN "*.h" 8 | ) 9 | -------------------------------------------------------------------------------- /test/plugin/plugin_mysql/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export LD_LIBRARY_PATH=.:../../../src/utils:../../../src/net:../../../src/sys:../../../src/plugin/plugin_mysql:$LD_LIBRARY_PATH 4 | 5 | FILES=`ls ut_*|grep -v ".cpp"|grep -v ".o"` 6 | for file in $FILES; 7 | do 8 | sh -c ./$file 9 | done -------------------------------------------------------------------------------- /shell/README.txt: -------------------------------------------------------------------------------- 1 | file_utils.sh 2 | 提供文件操作类函数,应当以source file_utils.sh方式使用 3 | 4 | log_rotater.sh 5 | 滚动日志文件脚本,详情请参见文件头说明 6 | 7 | process_monitor.sh 8 | 监控指定进程,挂掉重拉起脚本,详情请参见文件头说明 9 | 10 | process_stopper.sh 11 | 精准停止指定进程脚本,详情请参见文件头说明 12 | 13 | mem.sh 14 | 可用于间隔统计指定进程内存,可用于分析某程序是否存在内存泄漏 15 | 16 | flux.sh 17 | 网卡流量统计工具 18 | 19 | udp_drops.sh 20 | UDP丢包统计工具 21 | -------------------------------------------------------------------------------- /test/plugin/plugin_mysql/Makefile: -------------------------------------------------------------------------------- 1 | CPP_FILES=$(shell ls *.cpp) 2 | unit_test: 3 | dos2unix run.sh;chmod +x run.sh; 4 | for cpp_file in $(CPP_FILES); \ 5 | do \ 6 | name=`basename $$cpp_file .cpp`; \ 7 | g++ -g -o $$name -I../../../include ../../../src/plugin/plugin_mysql/libmooon_mysql.a ../../../src/sys/libmooon_sys.a ../../../src/utils/libmooon_utils.a $$cpp_file; \ 8 | done 9 | -------------------------------------------------------------------------------- /shell/uninstall_crontab.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # writed by yijian on 2013/1/19 3 | # generic script used to uninstall an item from crontab 4 | # http://code.google.com/p/mooon/source/browse/trunk/common_library/shell/install_crontab.sh 5 | 6 | # key is the item need to remove from crontab 7 | key=$1 8 | 9 | crontab -l | grep -v "$key" > crontab.tmp 10 | crontab crontab.tmp 11 | 12 | exit 0 13 | -------------------------------------------------------------------------------- /test/utils/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | include_directories(../../include) 4 | link_directories(../../src) 5 | link_libraries(libmooon.a) 6 | link_libraries(dl pthread rt z) 7 | 8 | add_executable(ut_string_utils ut_string_utils.cpp) 9 | add_executable(ut_tokener ut_tokener.cpp) 10 | add_executable(test_args_parser test_args_parser.cpp) 11 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | # 3.2 4 | cmake_minimum_required(VERSION 2.8.11) 5 | project(mooon) 6 | 7 | include(CMake.common) 8 | 9 | add_subdirectory(src) 10 | add_subdirectory(test) 11 | add_subdirectory(tools) 12 | 13 | # CMAKE_INSTALL_PREFIX 14 | install( 15 | FILES CMake.common 16 | DESTINATION . 17 | ) 18 | -------------------------------------------------------------------------------- /src/README: -------------------------------------------------------------------------------- 1 | GTF: General TCP server Framework 2 | 3 | 注意事项: 4 | 1.不要在src目录下存放无关的cpp文件,也不要在include目录下存放非对外头文件 5 | 2.不支持c文件,只支持cpp和cc文件 6 | 7 | 如何编译? 8 | 每次从SVN下载源代码后,都需要执行一次bootstrap.sh,之后其它步骤和automake完成相同。 9 | 10 | common子目录不是一个库的目录,common-librrary本来是分了util、sys和net三个子库, 11 | 但实际应用中,发现增加了复杂度,使用时需要指定三个库,为了简化使用,在2012-7-25 12 | 日晚下班后,我将它合并成一个名叫mcommon的库,名字中的m是mooon的意思,静态库文件名为 13 | libmcommon.a,共享库文件名为libmcommon.so -------------------------------------------------------------------------------- /tools/hbase_constants.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Autogenerated by Thrift Compiler (0.9.3) 3 | * 4 | * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 5 | * @generated 6 | */ 7 | #include "hbase_constants.h" 8 | 9 | namespace apache { namespace hadoop { namespace hbase { namespace thrift2 { 10 | 11 | const hbaseConstants g_hbase_constants; 12 | 13 | hbaseConstants::hbaseConstants() { 14 | } 15 | 16 | }}}} // namespace 17 | 18 | -------------------------------------------------------------------------------- /include/mooon/utils/crypto.h: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/12/23 2 | #ifndef MOOON_UTILS_CRYPTO_H 3 | #define MOOON_UTILS_CRYPTO_H 4 | #include "mooon/utils/config.h" 5 | UTILS_NAMESPACE_BEGIN 6 | #if MOOON_HAVE_OPENSSL == 1 7 | 8 | void base64_encode(const std::string& src, std::string* dest, bool no_newline=true); 9 | void base64_decode(const std::string& src, std::string* dest, bool no_newline=true); 10 | 11 | #endif // MOOON_HAVE_OPENSSL 12 | UTILS_NAMESPACE_END 13 | #endif // MOOON_UTILS_CRYPTO_H 14 | -------------------------------------------------------------------------------- /shell/find_deleted_files.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Writed by yijian on 2020/9/6 3 | # 查找被删除但仍然占据磁盘的文件 4 | 5 | dirs=(`ls -l --time-style=long-iso /proc 2>/dev/null | awk '{ print $8 }' 2>/dev/null`) 6 | for ((i=0; i<${#dirs[@]}; ++i)) 7 | do 8 | dir=${dirs[i]} 9 | if test -z "$dir"; then 10 | continue 11 | fi 12 | $(expr $dir + 0 > /dev/null 2>&1) 13 | if test $? -ne 0; then 14 | continue 15 | fi 16 | 17 | pid=$dir 18 | lsof -p $pid 2>/dev/null | grep "deleted" | grep -v "$0" 19 | done 20 | -------------------------------------------------------------------------------- /tools/random_string.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/01/10 2 | #include 3 | 4 | int main(int argc, char* argv[]) 5 | { 6 | if (argc != 2) 7 | { 8 | fprintf(stderr, "usage: random_string length\n"); 9 | return 1; 10 | } 11 | else 12 | { 13 | const uint8_t length = mooon::utils::CStringUtils::string2int(argv[1]); 14 | fprintf(stdout, "%s\n", mooon::utils::CStringUtils::generate_random_string(length).c_str()); 15 | return 0; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /tools/hbase_constants.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Autogenerated by Thrift Compiler (0.9.3) 3 | * 4 | * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 5 | * @generated 6 | */ 7 | #ifndef hbase_CONSTANTS_H 8 | #define hbase_CONSTANTS_H 9 | 10 | #include "hbase_types.h" 11 | 12 | namespace apache { namespace hadoop { namespace hbase { namespace thrift2 { 13 | 14 | class hbaseConstants { 15 | public: 16 | hbaseConstants(); 17 | 18 | }; 19 | 20 | extern const hbaseConstants g_hbase_constants; 21 | 22 | }}}} // namespace 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /test/net/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | include_directories(../../include) 4 | link_directories(../../src) 5 | link_libraries(libmooon.a) 6 | link_libraries(dl pthread rt z) 7 | 8 | add_executable(udp_client_test udp_client_test.cpp) 9 | add_executable(udp_server_test udp_server_test.cpp) 10 | add_executable(ut_epollable_queue ut_epollable_queue.cpp) 11 | 12 | if (MOOON_HAVE_LIBSSH2) 13 | add_executable(ut_libssh2 ut_libssh2.cpp) 14 | target_link_libraries(ut_libssh2 libssh2.a libssl.a libcrypto.a) 15 | endif () 16 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | add_subdirectory(utils) 4 | add_subdirectory(sys) 5 | add_subdirectory(net) 6 | add_subdirectory(helper) 7 | 8 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../include) 9 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../include/mooon) 10 | 11 | # libmooon.a 12 | add_library( 13 | mooon 14 | ${MOOON_UTILS_SRC} 15 | ${MOOON_SYS_SRC} 16 | ${MOOON_NET_SRC} 17 | ) 18 | 19 | # CMAKE_INSTALL_PREFIX 20 | install( 21 | TARGETS mooon 22 | DESTINATION lib 23 | ) 24 | -------------------------------------------------------------------------------- /tools/test_types.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Autogenerated by Thrift Compiler (0.15.0) 3 | * 4 | * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 5 | * @generated 6 | */ 7 | #ifndef test_TYPES_H 8 | #define test_TYPES_H 9 | 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #include 19 | #include 20 | 21 | 22 | namespace test { 23 | 24 | } // namespace 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /test/sys/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | include_directories(../../include) 4 | link_directories(../../src) 5 | link_libraries(libmooon.a) 6 | link_libraries(dl pthread rt z) 7 | 8 | add_executable(test_safe_logger test_safe_logger.cpp) 9 | add_executable(ut_datetime_utils ut_datetime_utils.cpp) 10 | add_executable(ut_event_queue ut_event_queue.cpp) 11 | add_executable(ut_fs_utils ut_fs_utils.cpp) 12 | 13 | if (MOOON_HAVE_LIBIDN) 14 | add_executable(curl_get test_curl_wrapper.cpp) 15 | target_link_libraries(curl_get libcurl.a libcares.a libidn.a libssl.a libcrypto.a) 16 | endif () 17 | -------------------------------------------------------------------------------- /include/mooon/utils/test_any2string.cpp: -------------------------------------------------------------------------------- 1 | // Write by yijian on 2014/12/27 2 | // used to test any2string.h 3 | #include "any2string.h" 4 | #include 5 | 6 | int main() 7 | { 8 | printf("%s\n", any2string(1).c_str()); 9 | printf("%s\n", any2string(1, "2").c_str()); 10 | printf("%s\n", any2string(1, "2", 3).c_str()); 11 | printf("%s\n", any2string(1, "2", 3, "4").c_str()); 12 | printf("%s\n", any2string(1, '-', "2", "-", 3, "-", "4", '-', "5").c_str()); 13 | printf("%s\n", any2string("https", ':', "//", "github", '.', std::string("com"), '/', "eyjian", '/', std::string("mooon")).c_str()); 14 | 15 | return 0; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /test/utils/test_args_parser.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | STRING_ARG_DEFINE(ip1, "127.0.0.1", "ip1"); 4 | INTEGER_ARG_DEFINE(uint16_t, port1, 8888, 1000, 5000, "port1"); 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | std::string errmsg; 9 | mooon::utils::g_help_string = "help"; 10 | mooon::utils::g_version_string = "version"; 11 | 12 | if (!mooon::utils::parse_arguments(argc, argv, &errmsg)) 13 | { 14 | fprintf(stderr, "%s\n", errmsg.c_str()); 15 | exit(1); 16 | } 17 | 18 | printf("ip1: %s\n", mooon::argument::ip1->c_value()); 19 | printf("port1: %d\n", mooon::argument::port1->value()); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /include/mooon/helper/curl.h: -------------------------------------------------------------------------------- 1 | // Copyright 2021, Tencent Inc. 2 | // Author: yijian 3 | // Date: 2021/9/4 4 | // 特别说明: 5 | // 多线程环境,应当在创建线程之前调用 CCurlWrapper::global_init() 一次, 6 | // 在进程线程退出后进程退出前调用一次 CCurlWrapper::global_cleanup() 。 7 | #ifndef GONGYI_HELPER_CURL_H 8 | #define GONGYI_HELPER_CURL_H 9 | #include 10 | #include 11 | namespace gongyi { namespace helper { 12 | 13 | // 取得当前线程的 CCurlWrapper 14 | // 15 | // 参数说明: 16 | // 对于CGI等单线程程序,nosignal为false即可,并且也不用指定c-ares, 17 | // 但对于多线程使用curl的程序,则nosignal应当设定为true, 18 | // 指定nosignal为true时,DNS解析将不带超时 。 19 | std::shared_ptr get_thread_curl(bool nosignal=false); 20 | 21 | }} // namespace gongyi { namespace helper { 22 | #endif // GONGYI_HELPER_CURL_H 23 | -------------------------------------------------------------------------------- /test/sys/Makefile: -------------------------------------------------------------------------------- 1 | include ../../src/Make.rules 2 | 3 | CPP_FILES=$(shell ls *.cpp) 4 | unit_test: 5 | CPPFLAGS="-pthread"; \ 6 | CPPFLAGS+=" $(MOOON_HAVE_MYSQL) $(MOOON_HAVE_SQLITE3) $(MOOON_HAVE_CURL)"; \ 7 | CPPFLAGS+=" $(MYSQL_INCLUDE) $(SQLITE3_INCLUDE) $(CURL_INCLUDE)"; \ 8 | LDFLAGS="-lz -lrt -pthread"; \ 9 | LDFLAGS+=" $(MYSQL_LIB) $(SQLITE3_LIB) $(CURL_LIB)"; \ 10 | bits=`getconf LONG_BIT`; \ 11 | if test $$bits = 32; then \ 12 | CPPFLAGS+=" -march=pentium4"; \ 13 | fi; \ 14 | dos2unix run.sh;chmod +x run.sh; \ 15 | for cpp_file in $(CPP_FILES); \ 16 | do \ 17 | name=`basename $$cpp_file .cpp`; \ 18 | g++ -g -c -I../../include $$cpp_file $$CPPFLAGS; \ 19 | g++ -g -o $$name $$name.o ../../src/common/libmooon.a $$CPPFLAGS $$LDFLAGS; \ 20 | done 21 | 22 | clean: 23 | rm -f *.o 24 | 25 | -------------------------------------------------------------------------------- /tools/charset_conv.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/01/10 2 | #include 3 | #include 4 | 5 | int main(int argc, char* argv[]) 6 | { 7 | if (argc != 4) 8 | { 9 | fprintf(stderr, "usage: charset_conv src_charset dest_charset src_str\n"); 10 | return 1; 11 | } 12 | else 13 | { 14 | const std::string src_charset = argv[1]; 15 | const std::string dest_charset = argv[2]; 16 | const std::string src_str = argv[3]; 17 | std::string dest_str; 18 | 19 | try 20 | { 21 | mooon::utils::CStringUtils::charset_conv(&dest_str, src_str, dest_charset, src_charset); 22 | fprintf(stdout, "%s\n", dest_str.c_str()); 23 | } 24 | catch (mooon::utils::CException& ex) 25 | { 26 | fprintf(stderr, "%s\n", ex.str().c_str()); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tools/base64.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/12/23 2 | #include 3 | #include 4 | 5 | int main(int argc, char* argv[]) 6 | { 7 | int action; 8 | std::string base64; 9 | 10 | if (argc < 2) 11 | { 12 | fprintf(stderr, "usage: base64 action(1: encode, 2: deconde) string\n"); 13 | exit(1); 14 | } 15 | if (!mooon::utils::CStringUtils::string2int(argv[1], action) || 16 | (action!=1 && action!=2)) 17 | { 18 | fprintf(stderr, "usage: base64 action(1: encode, 2: deconde) string\n"); 19 | exit(1); 20 | } 21 | else 22 | { 23 | const std::string& src = argv[2]; 24 | std::string dest; 25 | if (1 == action) 26 | mooon::utils::base64_encode(src, &dest); 27 | else 28 | mooon::utils::base64_decode(src, &dest); 29 | printf("%s\n", dest.c_str()); 30 | return 0; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /include/mooon/sys/thread_base.h: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2019/1/25 2 | #ifndef MOOON_SYS_THREAD_BASE_H 3 | #define MOOON_SYS_THREAD_BASE_H 4 | #include "mooon/sys/atomic.h" 5 | #include "mooon/sys/utils.h" 6 | SYS_NAMESPACE_BEGIN 7 | 8 | // The base class for thread 9 | // 10 | // #include 11 | // #include 12 | // class CMyThread: public CThreadBase 13 | // { 14 | // public: 15 | // void run() 16 | // { 17 | // while (!to_stop()) 18 | // { 19 | // std::this_thread::sleep_for(std::chrono::milliseconds(1000)); 20 | // } 21 | // } 22 | // }; 23 | class CThreadBase 24 | { 25 | public: 26 | CThreadBase() 27 | : _stop(false) 28 | { 29 | } 30 | 31 | void stop() 32 | { 33 | _stop = true; 34 | } 35 | 36 | bool to_stop() const 37 | { 38 | return _stop; 39 | } 40 | 41 | protected: 42 | CAtomic _stop; 43 | }; 44 | 45 | SYS_NAMESPACE_END 46 | #endif // MOOON_SYS_THREAD_BASE_H 47 | -------------------------------------------------------------------------------- /tools/rsa256_sign.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/01/09 2 | #include 3 | #include 4 | 5 | int main(int argc, char* argv[]) 6 | { 7 | if (argc < 3) 8 | { 9 | fprintf(stderr, "usage: rsa256_sign private_filepath data_to_sign\n"); 10 | return 1; 11 | } 12 | else 13 | { 14 | const std::string data = argv[2]; 15 | const std::string& private_key_filepath = argv[1]; 16 | mooon::utils::CRsaPrivateHelper rsa_helper(private_key_filepath); 17 | 18 | try 19 | { 20 | std::string signature; 21 | 22 | rsa_helper.init(); 23 | mooon::utils::rsa256sign(&signature, rsa_helper.pkey(), data); 24 | fprintf(stdout, "signature: %s\n", signature.c_str()); 25 | return 0; 26 | } 27 | catch (mooon::utils::CException& ex) 28 | { 29 | fprintf(stderr, "%s\n", ex.str().c_str()); 30 | return 1; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /tools/rsa_pub_encrypt.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/01/10 2 | #include 3 | #include 4 | 5 | int main(int argc, char* argv[]) 6 | { 7 | int sha_type; 8 | std::string sha; 9 | 10 | if (argc < 4) 11 | { 12 | fprintf(stderr, "usage: rsa_pub_encrypt RSAPaddingMode public_key_str data\n"); 13 | return 1; 14 | } 15 | else 16 | { 17 | const uint8_t ras_padding_mode = mooon::utils::CStringUtils::string2int(argv[1]); 18 | const std::string pub_key = argv[2]; // 公钥字符串 19 | const std::string decrypted_data = argv[3]; 20 | std::string encrypted_data; 21 | 22 | try 23 | { 24 | mooon::utils::CRSAHelper::public_encrypt_bykey(pub_key, decrypted_data, &encrypted_data, (mooon::utils::RSAPaddingMode)ras_padding_mode); 25 | } 26 | catch (mooon::utils::CException& ex) 27 | { 28 | fprintf(stderr, "%s\n",ex.str().c_str()); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tools/rsa_priv_decrypt.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/01/10 2 | #include 3 | #include 4 | 5 | int main(int argc, char* argv[]) 6 | { 7 | int sha_type; 8 | std::string sha; 9 | 10 | if (argc < 4) 11 | { 12 | fprintf(stderr, "usage: rsa_priv_decrypt RSAPaddingMode private_key_str data\n"); 13 | return 1; 14 | } 15 | else 16 | { 17 | const uint8_t ras_padding_mode = mooon::utils::CStringUtils::string2int(argv[1]); 18 | const std::string priv_key = argv[2]; // 私钥字符串 19 | const std::string encrypted_data = argv[3]; 20 | std::string decrypted_data; 21 | 22 | try 23 | { 24 | mooon::utils::CRSAHelper::private_decrypt_bykey(priv_key, encrypted_data, &decrypted_data, (mooon::utils::RSAPaddingMode)ras_padding_mode); 25 | } 26 | catch (mooon::utils::CException& ex) 27 | { 28 | fprintf(stderr, "%s\n",ex.str().c_str()); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /shell/process_stopper.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # http://code.google.com/p/mooon 3 | # Created by yijian on 2012/7/23 4 | # 通用的停止指定名的进程 5 | # 特色: 6 | # 1. 只会停止当前用户名下的进程 7 | # 2. 可以指定命令行参数,可执行精准停止 8 | 9 | # 检查参数 10 | # 参数1:需要停止的进程名或它的完整命令行或部分命令行 11 | if test $# -ne 1; then 12 | printf "\033[1;33musage: $0 process_cmdline\033[m\n" 13 | printf "\033[1;33mexample: /usr/local/bin/process_stopper.sh \"/usr/sbin/rinetd\"\033[m\n" 14 | exit 1 15 | fi 16 | 17 | process_cmdline=$1 # 进程名或进程运行命令行 18 | cur_user=`whoami` # 当前用户 19 | uid=`id -u $cur_user` # 用户ID 20 | 21 | # 取得进程名 22 | process_name=$(basename `echo "$process_cmdline"|cut -d" " -f1`) 23 | # 得到进程的ID列表 24 | pid_set=`ps -C "$process_name" h -o euser,pid,args|awk '{ if (($1==uid || $1==cur_user) && match($0, process_cmdline)) printf("%s\n", $2); }' uid=$uid cur_user=$cur_user process_cmdline="$process_cmdline"` 25 | 26 | # 循环kill掉所有的进程 27 | for pid in $pid_set 28 | do 29 | #echo $pid;exit; # 测试用 30 | kill $pid # 先发SIGTERM信号 31 | sleep 2 # 过2秒再发SIGKILL信号 32 | kill -9 $pid 33 | done 34 | -------------------------------------------------------------------------------- /tools/thrift_client.cpp: -------------------------------------------------------------------------------- 1 | #include "TestService.h" 2 | #include 3 | #include 4 | namespace test { 5 | 6 | extern "C" int main(int argc, char* argv[]) 7 | { 8 | if (argc != 3) 9 | { 10 | const std::string myname = mooon::sys::CUtils::get_program_short_name(); 11 | fprintf(stderr, "Usage: %s ip port\n", myname.c_str()); 12 | fprintf(stderr, "Example: %s 127.0.0.1 2020\n", myname.c_str()); 13 | return 1; 14 | } 15 | try 16 | { 17 | const std::string ip = argv[1]; 18 | uint16_t port = mooon::utils::CStringUtils::string2int(argv[2]); 19 | mooon::net::CThriftClientHelper client(ip, port); 20 | std::string str; 21 | client.connect(); 22 | client->hello(str); 23 | fprintf(stdout, "%s\n", str.c_str()); 24 | return 0; 25 | } 26 | catch (apache::thrift::TException& ex) 27 | { 28 | fprintf(stderr, "%s\n", ex.what()); 29 | return 2; 30 | } 31 | } 32 | 33 | } // namespace test { 34 | -------------------------------------------------------------------------------- /include/mooon/sys/error.h: -------------------------------------------------------------------------------- 1 | #ifndef SYS_ERROR_H 2 | #define SYS_ERROR_H 3 | #include "mooon/sys/config.h" 4 | #include 5 | #include 6 | SYS_NAMESPACE_BEGIN 7 | 8 | class ErrorKeeper 9 | { 10 | public: 11 | ErrorKeeper() 12 | :_errcode(errno) 13 | { 14 | } 15 | 16 | ErrorKeeper(int errcode) 17 | :_errcode(errcode) 18 | { 19 | } 20 | 21 | ~ErrorKeeper() 22 | { 23 | errno = _errcode; 24 | } 25 | 26 | operator int() const 27 | { 28 | return _errcode; 29 | } 30 | 31 | private: 32 | int _errcode; 33 | }; 34 | 35 | namespace Error 36 | { 37 | inline int code() 38 | { 39 | return errno; 40 | } 41 | 42 | inline void set(int errcode) 43 | { 44 | errno = errcode; 45 | } 46 | 47 | inline std::string to_string() 48 | { 49 | return strerror(errno); 50 | } 51 | 52 | inline std::string to_string(int errcode) 53 | { 54 | return strerror(errcode); 55 | } 56 | 57 | inline bool is_not(int errcode) 58 | { 59 | return errno != errcode; 60 | } 61 | } 62 | 63 | SYS_NAMESPACE_END 64 | #endif // SYS_ERROR_H 65 | -------------------------------------------------------------------------------- /tools/pidof.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/10/19 2 | // get all pid by process name 3 | #include 4 | 5 | // argv[1] process name 6 | // argv[2] regex 7 | int main(int argc, char* argv[]) 8 | { 9 | if ((argc != 2) && (argc != 3)) 10 | { 11 | fprintf(stderr, "Usage: %s pname [0|1]\n", mooon::sys::CUtils::get_program_short_name().c_str()); 12 | exit(1); 13 | } 14 | 15 | const char* process_name = argv[1]; 16 | bool regex = false; 17 | 18 | if (3 == argc) 19 | { 20 | // 第2个参数 21 | if (0 == strcmp(argv[2], "0")) 22 | regex = false; 23 | else if (0 == strcmp(argv[2], "1")) 24 | regex = true; 25 | else 26 | { 27 | fprintf(stderr, "Usage: %s pname signo [0|1]\n", mooon::sys::CUtils::get_program_short_name().c_str()); 28 | exit(1); 29 | } 30 | } 31 | 32 | std::vector pid_array; 33 | const int n = mooon::sys::CUtils::get_all_pid(process_name, &pid_array, regex); 34 | for (int i=0; i 5 | #include 6 | #include 7 | #include 8 | #include 9 | SYS_NAMESPACE_BEGIN 10 | 11 | // 提供秒级时间, 12 | // 可用于避免多个线程重复调用time(NULL) 13 | // 注:32位平台上的毫秒级不准 14 | class CTimeThread 15 | { 16 | SINGLETON_DECLARE(CTimeThread); 17 | 18 | public: 19 | CTimeThread(); 20 | ~CTimeThread(); 21 | int64_t get_seconds() const; 22 | int64_t get_milliseconds() const; 23 | void stop(); // 同一对象在stop后不能重复使用 24 | bool start(uint32_t interval_milliseconds); 25 | void wait(); 26 | void run(); 27 | 28 | private: 29 | CAtomic _stop; 30 | #if __WORDSIZE==64 31 | CAtomic _seconds; 32 | CAtomic _milliseconds; 33 | #else 34 | CAtomic _seconds; 35 | CAtomic _milliseconds; 36 | #endif // __WORDSIZE==64 37 | uint32_t _interval_milliseconds; 38 | CThreadEngine* _engine; 39 | }; 40 | 41 | SYS_NAMESPACE_END 42 | #endif // MOOON_SYS_TIME_THREAD_H 43 | -------------------------------------------------------------------------------- /test/net/Makefile: -------------------------------------------------------------------------------- 1 | CPP_FILES=$(shell ls *.cpp) 2 | unit_test: 3 | CPPFLAGS="-pthread"; \ 4 | LDFLAGS="-lrt -pthread"; \ 5 | bits=`getconf LONG_BIT`; \ 6 | if test $$bits = 32; then \ 7 | CPPFLAGS+=" -march=pentium4"; \ 8 | fi; \ 9 | MYSQL_HOME=abc; \ 10 | if test /usr/local/thirdparty/mysql/lib; then \ 11 | MYSQL_HOME=/usr/local/thirdparty/mysql; \ 12 | else \ 13 | if test ${HOME}/mysql/lib; then \ 14 | MYSQL_HOME=${HOME}/mysql; \ 15 | else \ 16 | if test /usr/local/mysql/lib; then \ 17 | MYSQL_HOME=/usr/local/mysql; \ 18 | fi; \ 19 | fi; \ 20 | fi; \ 21 | if test $$MYSQL_HOME = "abc"; then \ 22 | echo "error: not found MySQL at:"; \ 23 | echo "1) /usr/local/thirdparty/mysql"; \ 24 | echo "2) ${HOME}/mysql"; \ 25 | echo "3) /usr/local/mysql"; \ 26 | exit; \ 27 | fi; \ 28 | dos2unix run.sh;chmod +x run.sh; \ 29 | for cpp_file in $(CPP_FILES); \ 30 | do \ 31 | name=`basename $$cpp_file .cpp`; \ 32 | g++ -g -c -I../../include $$cpp_file $$CPPFLAGS; \ 33 | g++ -g -o $$name $$name.o -march=pentium4 $$CPPFLAGS $$LDFLAGS ../../src/common/libmooon.a $$MYSQL_HOME/lib/libmysqlclient_r.a; \ 34 | done 35 | 36 | clean: 37 | rm -f *.o 38 | -------------------------------------------------------------------------------- /test/net/udp_client_test.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2015, Tencent Inc. 2 | // Author: yijian 3 | // Date: 2015/4/28 4 | #include "mooon/net/udp_socket.h" 5 | MOOON_NAMESPACE_USE 6 | 7 | int main(int argc, char* argv[]) 8 | { 9 | if (argc != 2) 10 | { 11 | fprintf(stderr, "Usage: udp_client_test message\n"); 12 | exit(1); 13 | } 14 | 15 | try 16 | { 17 | uint16_t port = 2016; 18 | net::CUdpSocket udp_socket; 19 | 20 | udp_socket.listen(port); 21 | printf("udp listen on: %d\n", port); 22 | 23 | udp_socket.send_to(argv[1], strlen(argv[1])+1, "127.0.0.1", 2015); 24 | 25 | char buffer[548+1]; // 1472 26 | struct sockaddr_in from_addr; 27 | 28 | int bytes = udp_socket.receive_from(buffer, sizeof(buffer)-1, &from_addr); 29 | if (bytes > 0) 30 | { 31 | buffer[bytes] = '\0'; 32 | printf("[%s] %s: %s\n", net::to_string(from_addr).c_str(), buffer, argv[1]); 33 | } 34 | } 35 | catch (sys::CSyscallException& syscall_ex) 36 | { 37 | fprintf(stderr, "%s\n", syscall_ex.str().c_str()); 38 | } 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /test/net/udp_server_test.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2015, Tencent Inc. 2 | // Author: yijian 3 | // Date: 2015/4/28 4 | #include "mooon/net/udp_socket.h" 5 | MOOON_NAMESPACE_USE 6 | 7 | int main(int argc, char* argv[]) 8 | { 9 | try 10 | { 11 | uint16_t port = 2015; 12 | net::CUdpSocket udp_socket; 13 | 14 | udp_socket.listen(port); 15 | printf("udp listen on: %d\n", port); 16 | 17 | while (true) 18 | { 19 | char buffer[548+1]; // 1472 20 | struct sockaddr_in from_addr; 21 | 22 | int bytes = udp_socket.receive_from(buffer, sizeof(buffer)-1, &from_addr); 23 | if (bytes > 0) 24 | { 25 | buffer[bytes] = '\0'; 26 | printf("[%s] %s\n", net::to_string(from_addr).c_str(), buffer); 27 | 28 | char response[548+1]; 29 | strcpy(response, "ok"); 30 | udp_socket.send_to(response, strlen(response)+1, from_addr); 31 | } 32 | } 33 | } 34 | catch (sys::CSyscallException& syscall_ex) 35 | { 36 | fprintf(stderr, "%s\n", syscall_ex.str().c_str()); 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /tools/sha.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/12/23 2 | #include 3 | #include 4 | 5 | int main(int argc, char* argv[]) 6 | { 7 | int sha_type; 8 | std::string sha; 9 | 10 | if (argc < 3) 11 | { 12 | fprintf(stderr, "usage: sha type(1/224/256/384/512) string\n"); 13 | exit(1); 14 | } 15 | if (!mooon::utils::CStringUtils::string2int(argv[1], sha_type)) 16 | { 17 | fprintf(stderr, "usage: sha type(1/224/256/384/512) string\n"); 18 | exit(1); 19 | } 20 | else 21 | { 22 | const mooon::utils::SHAType sha_type_ = mooon::utils::int2shatype(sha_type); 23 | 24 | if (mooon::utils::SHA0 == sha_type_) 25 | { 26 | fprintf(stderr, "usage: sha type(1/224/256/384/512) string\n"); 27 | exit(1); 28 | } 29 | else 30 | { 31 | sha = mooon::utils::CSHAHelper::lowercase_sha(sha_type_, "%s", argv[2]); 32 | printf("%s\n", sha.c_str()); 33 | 34 | sha = mooon::utils::CSHAHelper::uppercase_sha(sha_type_, "%s", argv[2]); 35 | printf("%s\n", sha.c_str()); 36 | return 0; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/utils/file_format_exception.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "utils/file_format_exception.h" 20 | UTILS_NAMESPACE_BEGIN 21 | 22 | CFileFormatException::CFileFormatException(const char* file, int line, int field) 23 | :CException("format error", -1, file, line) 24 | ,_field(field) 25 | { 26 | } 27 | 28 | UTILS_NAMESPACE_END 29 | -------------------------------------------------------------------------------- /tools/rsa_decrypt.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/02/06 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | if (argc < 3) 9 | { 10 | fprintf(stderr, "usage: rsa_decrypt private_filepath base64_data_to_decrypt\n"); 11 | return 1; 12 | } 13 | else 14 | { 15 | const std::string base64_data = argv[2]; 16 | const std::string& private_key_filepath = argv[1]; 17 | mooon::utils::CRsaPrivateHelper rsa_helper(private_key_filepath); 18 | 19 | try 20 | { 21 | std::string encrypted_data; 22 | std::string decrypted_data; 23 | 24 | rsa_helper.init(); 25 | mooon::utils::base64_decode(base64_data, &encrypted_data); 26 | mooon::utils::rsa_decrypt(&decrypted_data, encrypted_data, rsa_helper.pkey(), rsa_helper.pkey_ctx()); 27 | fprintf(stdout, "plaintext: %s\n", decrypted_data.c_str()); 28 | return 0; 29 | } 30 | catch (mooon::utils::CException& ex) 31 | { 32 | fprintf(stderr, "%s\n", ex.str().c_str()); 33 | return 1; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /include/mooon/utils/make_format_string_h.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 3 | 4 | format_function="CStringUtils::format_string" 5 | if test $# -eq 0; then 6 | paramter_number=5 7 | else 8 | paramter_number=$1 9 | fi 10 | 11 | echo "// Writed by yijian (eyjian@qq.com, eyjian@gmail.com)" 12 | echo "#ifndef MOOON_UTILS_FORMAT_STRING_H" 13 | echo "#define MOOON_UTILS_FORMAT_STRING_H" 14 | echo "#include " 15 | echo "#include " 16 | echo "#include " 17 | echo "UTILS_NAMESPACE_BEGIN" 18 | echo "" 19 | echo "enum { FORMAT_STRING_SIZE = $paramter_number };" 20 | echo "inline std::string format_string(const char* format, const std::vector& tokens)" 21 | echo "{" 22 | 23 | for ((i=0; i<$paramter_number; ++i)) 24 | do 25 | echo " if ($i == tokens.size())" 26 | echo " {" 27 | 28 | str="$format_function(format" 29 | for ((j=0; j<$i; ++j)) 30 | do 31 | str=${str}", tokens[$j].c_str()" 32 | done 33 | str=${str}");" 34 | echo " return $str" 35 | echo " }" 36 | done 37 | echo " return std::string(\"\");" 38 | echo "}" 39 | echo "" 40 | echo "UTILS_NAMESPACE_END" 41 | echo "#endif // MOOON_UTILS_FORMAT_STRING_H" 42 | echo "" 43 | 44 | exit 0 45 | 46 | -------------------------------------------------------------------------------- /shell/mem.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # writed by yijian on 2016/7/11 3 | # filename mem.sh 4 | # 用于统计指定进程的虚拟内存和物理内存占用,以分析是否有内存泄漏 5 | # 6 | # 如何判断是否有内存泄漏? 7 | # 不能只看物理内存或虚拟内存其中一项数据, 8 | # 如果只是物理内存上涨或只是虚拟内存上涨, 9 | # 则不能判定为内存泄漏。 10 | # 当然实际上物理内存不可能超过虚拟内存, 11 | # 所以内存泄漏必要是虚拟内存和物理内存都会上涨。 12 | # 如果一段时间内,只是虚拟内存或物理内存一项数据上涨, 13 | # 则还看不出内存泄漏,可观察更长时间。 14 | 15 | if test $# -lt 1; then 16 | echo "uage: mem.sh pid interval(seconds)" 17 | exit 1 18 | fi 19 | if test $# -eq 2; then 20 | interval=$2 21 | else 22 | interval=60 23 | fi 24 | if test $interval -lt 2; then 25 | interval=2 26 | fi 27 | 28 | pid=$1 29 | file=$pid.mem 30 | rm -f $file 31 | 32 | # VSS 虚拟内存 33 | # RSS 物理内存 34 | echo " VSS RSS" 35 | while true 36 | do 37 | filesize=$(ls -l /tmp/$pid.mem 2>/dev/null|cut -d' ' -f5) 38 | if test ! -z $filesize; then 39 | if test $filesize -gt 1048576; then 40 | mv /tmp/$file /tmp/$file.old 41 | fi 42 | fi 43 | 44 | virt=0 45 | res=0 46 | eval $(cat /proc/$pid/statm 2>/dev/null| awk '{ printf("virt=%d\nres=%d", $1*4096/1024/1024,$2*4096/1024/1024); }') 47 | if test $virt -eq 0 -a $res -eq 0; then 48 | break 49 | fi 50 | echo "[`date '+%Y-%m-%d %H:%M:%S'`] ${virt}m ${res}m" | tee -a /tmp/$file 51 | sleep $interval 52 | done 53 | -------------------------------------------------------------------------------- /tools/rsa_encrypt.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2024/02/06 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | std::string sha; 9 | 10 | if (argc < 3) 11 | { 12 | fprintf(stderr, "usage: rsa_encrypt public_filepath data_to_encrypt\n"); 13 | return 1; 14 | } 15 | else 16 | { 17 | const std::string plaintext_data = argv[2]; 18 | const std::string& public_key_filepath = argv[1]; 19 | mooon::utils::CRsaPublicHelper rsa_helper(public_key_filepath); 20 | 21 | try 22 | { 23 | std::string base64_encrypted_data; 24 | std::string encrypted_data; 25 | 26 | rsa_helper.init(); 27 | mooon::utils::rsa_encrypt(&encrypted_data, plaintext_data, rsa_helper.public_key()); 28 | mooon::utils::base64_encode(encrypted_data, &base64_encrypted_data); 29 | fprintf(stdout, "ciphertext: %s\n", base64_encrypted_data.c_str()); 30 | return 0; 31 | } 32 | catch (mooon::utils::CException& ex) 33 | { 34 | fprintf(stderr, "%s\n", ex.str().c_str()); 35 | return 1; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /shell/top_mem.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Writed by yijian on 2019/9/5 3 | # 将内存占用率Top10的进程记录到文件/tmp/mem.top中, 4 | # 带一个备份文件/tmp/mem.top.bak 5 | # 记录频率10秒,至少记录最近2小时数据 6 | # 注意不要同时运行多个本脚本。 7 | # 8 | # 可选带两个参数: 9 | # 参数1)记录频率,默认为10秒 10 | # 参数2)记录top多少个,默认为10个 11 | 12 | # 记录频率 13 | # 单位:秒 14 | loginterval=10 15 | # 日志文件 16 | topfile=/tmp/mem.top 17 | # 备份日志文件 18 | topfileback=$topfile.bak 19 | # 日志文件大小(默认10M) 20 | # 因为/tmp目录所在分区可能不大, 21 | # 所以日志文件大小不能过大 22 | topfilesize=10485760 23 | # 记录top多少个 24 | topN=10 25 | 26 | # 带滚动的日志函数 27 | # 带一个参数:需要记录的日志 28 | function writelog() 29 | { 30 | log="$1" 31 | logtime=`date +"%Y-%m-%d %H:%M:%S"` 32 | echo -en "====================\n[$logtime]\n$log\n\n" >> $topfile 33 | 34 | size=`ls -l --time-style=long-iso $topfile | awk '{print $5}'` 35 | if test ! -z "$size" -a $size -ge $topfilesize; then 36 | mv $topfile $topfileback 37 | echo -en "[$logtime]\n$log\n\n" > $topfile 38 | fi 39 | } 40 | 41 | # 如果至少有一个参数 42 | if test $# -ge 1; then 43 | loginterval="$1" 44 | fi 45 | # 如果至少有一个参数 46 | if test $# -ge 2; then 47 | topN="$2" 48 | fi 49 | 50 | # 定时记录, 51 | # 间隔时长由LOG_INTERVAL值决定 52 | set -e 53 | while (true) 54 | do 55 | log=`ps -Ao pcpu,pmem,rss,vsz,comm,pid,user,time,args --sort=-rss | head -n $topN` 56 | writelog "$log" 57 | sleep $loginterval 58 | done 59 | set +e 60 | -------------------------------------------------------------------------------- /shell/top_cpu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Writed by yijian on 2019/9/5 3 | # 将CPU占用率Top10的进程记录到文件/tmp/cpu.top中, 4 | # 带一个备份文件/tmp/cpu.top.bak 5 | # 记录频率10秒,至少记录最近2小时数据 6 | # 注意不要同时运行多个本脚本。 7 | # 8 | # 可选带两个参数: 9 | # 参数1)记录频率,默认为10秒 10 | # 参数2)记录top多少个,默认为10个 11 | 12 | # 记录频率 13 | # 单位:秒 14 | loginterval=10 15 | # 日志文件 16 | topfile=/tmp/cpu.top 17 | # 备份日志文件 18 | topfileback=$topfile.bak 19 | # 日志文件大小(默认10M) 20 | # 因为/tmp目录所在分区可能不大, 21 | # 所以日志文件大小不能过大 22 | topfilesize=10485760 23 | # 记录top多少个 24 | topN=10 25 | 26 | # 带滚动的日志函数 27 | # 带一个参数:需要记录的日志 28 | function writelog() 29 | { 30 | log="$1" 31 | logtime=`date +"%Y-%m-%d %H:%M:%S"` 32 | echo -en "====================\n[$logtime]\n$log\n\n" >> $topfile 33 | 34 | size=`ls -l --time-style=long-iso $topfile | awk '{print $5}'` 35 | if test ! -z "$size" -a $size -ge $topfilesize; then 36 | mv $topfile $topfileback 37 | echo -en "[$logtime]\n$log\n\n" > $topfile 38 | fi 39 | } 40 | 41 | # 如果至少有一个参数 42 | if test $# -ge 1; then 43 | loginterval="$1" 44 | fi 45 | # 如果至少有一个参数 46 | if test $# -ge 2; then 47 | topN="$2" 48 | fi 49 | 50 | # 定时记录, 51 | # 间隔时长由LOG_INTERVAL值决定 52 | set -e 53 | while (true) 54 | do 55 | log=`ps -Ao pcpu,pmem,rss,vsz,comm,pid,user,time,args --sort=-pcpu | head -n $topN` 56 | writelog "$log" 57 | sleep $loginterval 58 | done 59 | set +e 60 | -------------------------------------------------------------------------------- /src/net/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}) 4 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../include) 5 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon) 6 | 7 | # 源代码 8 | set( 9 | MOOON_NET_SRC 10 | ${CMAKE_CURRENT_SOURCE_DIR}/data_channel.cpp 11 | ${CMAKE_CURRENT_SOURCE_DIR}/epollable.cpp 12 | ${CMAKE_CURRENT_SOURCE_DIR}/epoller.cpp 13 | ${CMAKE_CURRENT_SOURCE_DIR}/ip_address.cpp 14 | ${CMAKE_CURRENT_SOURCE_DIR}/libssh2.cpp 15 | ${CMAKE_CURRENT_SOURCE_DIR}/listener.cpp 16 | ${CMAKE_CURRENT_SOURCE_DIR}/sensor.cpp 17 | ${CMAKE_CURRENT_SOURCE_DIR}/tcp_client.cpp 18 | ${CMAKE_CURRENT_SOURCE_DIR}/tcp_waiter.cpp 19 | ${CMAKE_CURRENT_SOURCE_DIR}/udp_socket.cpp 20 | ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp 21 | ${CMAKE_CURRENT_SOURCE_DIR}/kafka_consumer.cpp 22 | ${CMAKE_CURRENT_SOURCE_DIR}/kafka_producer.cpp 23 | CACHE INTERNAL 24 | MOOON_NET_SRC 25 | ) 26 | 27 | # libmooon_net.a 28 | #add_library( 29 | # mooon_net 30 | # STATIC 31 | # ${MOOON_NET_SRC} 32 | #) 33 | 34 | # CMAKE_INSTALL_PREFIX 35 | install( 36 | DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon/net 37 | DESTINATION include/mooon 38 | PATTERN "*.h" 39 | ) 40 | -------------------------------------------------------------------------------- /test/sys/ut_thread.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | MOOON_NAMESPACE_USE 4 | 5 | // 所有非线程池线程都应当是CThread的子类 6 | // Exam线程CDemoThread运行后,每隔1秒往标准输出打印一行“continue...” 7 | class CExamThread: public sys::CThread 8 | { 9 | private: 10 | virtual void run(); 11 | virtual void before_start() throw (utils::CException, sys::CSyscallException); 12 | }; 13 | 14 | void CExamThread::before_start() throw (utils::CException, sys::CSyscallException) 15 | { 16 | } 17 | 18 | // 线程每秒钟往标准输出打印一次continue... 19 | void CExamThread::run() 20 | { 21 | // stop将使得is_stop返回false 22 | while (!is_stop()) 23 | { 24 | // 睡眠1秒钟 25 | // do_millisleep是由CThread提供给子类睡眠使用的, 26 | // 可通过调用wakeup将睡眠中断 27 | do_millisleep(1000); 28 | printf("continue ...\n"); 29 | } 30 | } 31 | 32 | int main() 33 | { 34 | // 创建并启动线程 35 | CExamThread* thread = new CExamThread; 36 | thread->inc_refcount(); 37 | try 38 | { 39 | thread->start(); 40 | } 41 | catch (sys::CSyscallException& ex) 42 | { 43 | printf("Start thread error: %s\n" 44 | , ex.str().c_str()); 45 | thread->dec_refcount(); 46 | exit(1); 47 | } 48 | 49 | // 主线程睡眠10秒钟 50 | sys::CUtils::millisleep(10000); 51 | 52 | thread->stop(); // 停止并待线程退出 53 | thread->dec_refcount(); // 记得增加了引用计数,就需要在使用完后,相应的减引用计数 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /test/sys/ut_object_pool.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class X: public mooon::sys::CPoolObject 6 | { 7 | public: 8 | X() 9 | { 10 | reset(); 11 | } 12 | 13 | void reset() 14 | { 15 | _m = -1; 16 | } 17 | 18 | void s(int m) 19 | { 20 | _m = m; 21 | } 22 | 23 | void p() 24 | { 25 | printf("%d\n", _m); 26 | } 27 | 28 | private: 29 | int _m; 30 | }; 31 | 32 | int main() 33 | { 34 | X* x; 35 | uint32_t i; 36 | uint32_t pool_size = 10; 37 | mooon::sys::CRawObjectPool pool(false); 38 | pool.create(pool_size); 39 | 40 | std::vector vec_x; 41 | for (i=0; i<=pool_size; ++i) 42 | { 43 | printf("[%d] ", i); 44 | 45 | x = pool.borrow(); 46 | if (NULL == x) 47 | { 48 | printf("borrow nothing\n"); 49 | } 50 | else 51 | { 52 | x->s(2015); 53 | x->p(); 54 | 55 | vec_x.push_back(x); 56 | } 57 | } 58 | 59 | for (std::vector::size_type j=0; js(501); 67 | x->p(); 68 | pool.pay_back(x); 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /src/utils/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../include) 4 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon) 5 | 6 | # 源代码 7 | set( 8 | MOOON_UTILS_SRC 9 | ${CMAKE_CURRENT_SOURCE_DIR}/aes_helper.cpp 10 | ${CMAKE_CURRENT_SOURCE_DIR}/args_parser.cpp 11 | ${CMAKE_CURRENT_SOURCE_DIR}/bit_utils.cpp 12 | ${CMAKE_CURRENT_SOURCE_DIR}/charset_utils.cpp 13 | ${CMAKE_CURRENT_SOURCE_DIR}/crypto.cpp 14 | ${CMAKE_CURRENT_SOURCE_DIR}/exception.cpp 15 | ${CMAKE_CURRENT_SOURCE_DIR}/file_format_exception.cpp 16 | ${CMAKE_CURRENT_SOURCE_DIR}/integer_utils.cpp 17 | ${CMAKE_CURRENT_SOURCE_DIR}/md5.cpp 18 | ${CMAKE_CURRENT_SOURCE_DIR}/md5_helper.cpp 19 | ${CMAKE_CURRENT_SOURCE_DIR}/object.cpp 20 | ${CMAKE_CURRENT_SOURCE_DIR}/sha_helper.cpp 21 | ${CMAKE_CURRENT_SOURCE_DIR}/rsa_helper.cpp 22 | ${CMAKE_CURRENT_SOURCE_DIR}/string_utils.cpp 23 | CACHE INTERNAL 24 | MOOON_UTILS_SRC 25 | ) 26 | 27 | # libmooon_utils.a 28 | #add_library( 29 | # mooon_utils 30 | # STATIC 31 | # ${MOOON_UTILS_SRC} 32 | #) 33 | 34 | # CMAKE_INSTALL_PREFIX 35 | install( 36 | DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon/utils 37 | DESTINATION include/mooon 38 | PATTERN "*.h" 39 | ) 40 | -------------------------------------------------------------------------------- /tools/curl_download.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/11/14 2 | #include 3 | #include 4 | 5 | static void usage(const char* argv0) 6 | { 7 | char* s = strdup(argv0); 8 | fprintf(stderr, "Usage: %s <-k> local_filepath url\n", basename(s)); 9 | free(s); 10 | } 11 | 12 | int main(int argc, char* argv[]) 13 | { 14 | bool enable_insecure = false; 15 | 16 | if (argc < 3) 17 | { 18 | usage(argv[0]); 19 | exit(1); 20 | } 21 | if (0 == strcmp(argv[1], "-k")) 22 | { 23 | enable_insecure = true; 24 | } 25 | if (enable_insecure && argc!=4) 26 | { 27 | usage(argv[0]); 28 | exit(1); 29 | } 30 | 31 | try 32 | { 33 | const std::string& local_filepath = enable_insecure? argv[2]: argv[1]; 34 | const std::string& url = enable_insecure? argv[3]: argv[2]; 35 | mooon::sys::CCurlWrapper curl; 36 | std::string response_header; 37 | curl.http_get_download(response_header, local_filepath, url, enable_insecure); 38 | 39 | return 0; 40 | } 41 | catch (mooon::sys::CSyscallException& ex) 42 | { 43 | fprintf(stderr, "%s\n", ex.str().c_str()); 44 | exit(1); 45 | } 46 | catch (mooon::utils::CException& ex) 47 | { 48 | fprintf(stderr, "%s\n", ex.str().c_str()); 49 | exit(1); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /include/mooon/utils/file_format_exception.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_UTILS_FILE_FORMAT_EXCEPTION_H 20 | #define MOOON_UTILS_FILE_FORMAT_EXCEPTION_H 21 | #include "mooon/utils/exception.h" 22 | UTILS_NAMESPACE_BEGIN 23 | 24 | class CFileFormatException: public CException 25 | { 26 | public: 27 | CFileFormatException(const char* file, int line, int field=0); 28 | int field() const { return _field; } 29 | 30 | private: 31 | int _field; /** 错误发生的列号或字段号 */ 32 | }; 33 | 34 | UTILS_NAMESPACE_END 35 | #endif // MOOON_UTILS_FILE_FORMAT_EXCEPTION_H 36 | -------------------------------------------------------------------------------- /tools/md5.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include 20 | #include 21 | 22 | int main(int argc, char* argv[]) 23 | { 24 | std::string md5; 25 | 26 | if (argc < 2) 27 | { 28 | fprintf(stderr, "usage: md5 string\n"); 29 | exit(1); 30 | } 31 | else 32 | { 33 | md5 = mooon::utils::CMd5Helper::lowercase_md5("%s", argv[1]); 34 | printf("%s\n", md5.c_str()); 35 | 36 | md5 = mooon::utils::CMd5Helper::uppercase_md5("%s", argv[1]); 37 | printf("%s\n", md5.c_str()); 38 | return 0; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /include/mooon/utils/hash_utils.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_UTILS_HASH_UTILS_H 20 | #define MOOON_UTILS_HASH_UTILS_H 21 | #include "mooon/utils/config.h" 22 | UTILS_NAMESPACE_BEGIN 23 | 24 | /** 求128类型的hash函数 */ 25 | struct uint128_hasher 26 | { 27 | size_t operator ()(const uint8_t* data) const 28 | { 29 | return *((size_t*)(data+4)); 30 | } 31 | }; 32 | 33 | /** 求128类型比较函数 */ 34 | struct uint128_comparer 35 | { 36 | bool operator ()(const uint8_t* lhs, const uint8_t* rhs) const 37 | { 38 | return 0 == memcmp(lhs, rhs, 16); // 16个字节 39 | } 40 | }; 41 | 42 | UTILS_NAMESPACE_END 43 | #endif // MOOON_UTILS_HASH_UTILS_H 44 | -------------------------------------------------------------------------------- /include/mooon/utils/timeoutable.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_UTILS_TIMEOUTABLE_H 20 | #define MOOON_UTILS_TIMEOUTABLE_H 21 | #include "mooon/utils/config.h" 22 | #include 23 | UTILS_NAMESPACE_BEGIN 24 | 25 | /*** 26 | * 可超时对象的基类 27 | * 不应当直接使用此类,而应当总是继承方式 28 | */ 29 | class CTimeoutable 30 | { 31 | public: 32 | CTimeoutable() 33 | :_timestamp(0) 34 | { 35 | } 36 | 37 | /*** 得到时间戳 */ 38 | time_t get_timestamp() const { return _timestamp; } 39 | 40 | /** 设置新的时间戳 */ 41 | void set_timestamp(time_t timestamp) { _timestamp = timestamp; } 42 | 43 | private: 44 | time_t _timestamp; 45 | }; 46 | 47 | UTILS_NAMESPACE_END 48 | #endif // MOOON_UTILS_TIMEOUTABLE_H 49 | -------------------------------------------------------------------------------- /tools/killall.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/10/19 2 | #include 3 | #include 4 | 5 | // argv[1] process name 6 | // argv[2] signo 7 | // argv[3] regex 8 | int main(int argc, char* argv[]) 9 | { 10 | if ((argc != 3) && (argc != 4)) 11 | { 12 | fprintf(stderr, "Usage: %s pname signo [0|1]\n", mooon::sys::CUtils::get_program_short_name().c_str()); 13 | exit(1); 14 | } 15 | 16 | const char* process_name = argv[1]; 17 | const char* signo_str = argv[2]; 18 | int signo = 0; 19 | bool regex = false; 20 | 21 | // 第2个参数 22 | if (!mooon::utils::CStringUtils::string2int(signo_str, signo)) 23 | { 24 | fprintf(stderr, "Invalid signo: %s\n", signo_str); 25 | fprintf(stderr, "Usage: %s pname signo [0|1]\n", mooon::sys::CUtils::get_program_short_name().c_str()); 26 | exit(1); 27 | } 28 | 29 | if (4 == argc) 30 | { 31 | fprintf(stderr, "Usage: %s pname signo [0|1]\n", mooon::sys::CUtils::get_program_short_name().c_str()); 32 | exit(1); 33 | } 34 | 35 | // 第3个参数 36 | if (0 == strcmp(argv[3], "0")) 37 | regex = false; 38 | else if (0 == strcmp(argv[3], "1")) 39 | regex = true; 40 | else 41 | { 42 | fprintf(stderr, "Usage: %s pname signo [0|1]\n", mooon::sys::CUtils::get_program_short_name().c_str()); 43 | exit(1); 44 | } 45 | 46 | const std::pair ret = mooon::sys::CUtils::killall(process_name, signo, regex); 47 | fprintf(stdout, "SUCCESS: %d, FAILURE: %d\n", ret.first, ret.second); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /src/utils/md5.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This code implements the MD5 message-digest algorithm. 3 | * The algorithm is due to Ron Rivest. This code was 4 | * written by Colin Plumb in 1993, no copyright is claimed. 5 | * This code is in the public domain; do with it what you wish. 6 | * 7 | * Equivalent code is available from RSA Data Security, Inc. 8 | * This code has been tested against that, and is equivalent, 9 | * except that you don't need to include two pages of legalese 10 | * with every copy. 11 | * 12 | * To compute the message digest of a chunk of bytes, declare an 13 | * MD5Context structure, pass it to MD5Init, call MD5Update as 14 | * needed on buffers full of bytes, and then call MD5Final, which 15 | * will fill a supplied 16-byte array with the digest. 16 | */ 17 | #ifndef _H_MD5_H 18 | #define _H_MD5_H 19 | #include 20 | 21 | struct MD5Context { 22 | uint32_t buf[4]; 23 | uint32_t bits[2]; 24 | uint8_t in[64]; 25 | }; 26 | 27 | extern void MD5Init(struct MD5Context *); 28 | extern void MD5Update(struct MD5Context *, unsigned char const *, unsigned int); 29 | extern void MD5Final(unsigned char digest[16], struct MD5Context *ctx); 30 | extern void MD5Digest( const unsigned char *msg, int len, unsigned char *digest); 31 | extern void MD5HMAC(const unsigned char *password, unsigned pass_len, 32 | const unsigned char *challenge, unsigned chal_len, 33 | unsigned char response[16]); 34 | extern void MD5HMAC2(const unsigned char *password, unsigned pass_len, 35 | const unsigned char *challenge, unsigned chal_len, 36 | const unsigned char *challenge2, unsigned chal_len2, 37 | unsigned char response[16]); 38 | #endif 39 | -------------------------------------------------------------------------------- /src/utils/bit_utils.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "utils/bit_utils.h" 20 | UTILS_NAMESPACE_BEGIN 21 | 22 | void CBitUtils::flip(char* bitmap, uint32_t position) 23 | { 24 | bitmap[position / 8] ^= 1 << (position % 8); 25 | } 26 | 27 | bool CBitUtils::test(char* bitmap, uint32_t position) 28 | { 29 | return 1 == get_bit(bitmap, position); 30 | } 31 | 32 | uint8_t CBitUtils::get_bit(char* bitmap, uint32_t position) 33 | { 34 | return bitmap[position / 8] >> (position % 8) & 1; 35 | } 36 | 37 | void CBitUtils::set_bit(char* bitmap, uint32_t position, bool zero) 38 | { 39 | if (zero) 40 | { 41 | bitmap[position / 8] &= ~(1 << (position % 8)); 42 | } 43 | else 44 | { 45 | bitmap[position / 8] |= 1 << (position % 8); 46 | } 47 | } 48 | 49 | UTILS_NAMESPACE_END 50 | -------------------------------------------------------------------------------- /test/sys/ut_thread_pool.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | MOOON_NAMESPACE_USE 7 | 8 | // 测试线程,请注意是继承池线程CPoolThread,而不是线程CThread, 9 | // 另外CPoolThread并不是CThread的子类 10 | class CTestThread: public sys::CPoolThread 11 | { 12 | public: 13 | CTestThread() 14 | :_number_printed(0) 15 | { 16 | } 17 | 18 | private: 19 | virtual void run() 20 | { 21 | // 在这个函数里实现需要池线程干的事 22 | if (_number_printed++ < 3) 23 | { 24 | // 只打印三次,以便观察效率 25 | printf("thread %u say hello.\n", get_thread_id()); 26 | } 27 | 28 | // do_millisleep是由CPoolThread提供给子类睡眠用的, 29 | // 可以通过调用wakeup中断睡眠 30 | do_millisleep(1000); 31 | } 32 | 33 | virtual void before_start() throw (utils::CException, sys::CSyscallException) 34 | { 35 | } 36 | 37 | private: 38 | int _number_printed; // 打印次数 39 | }; 40 | 41 | int main() 42 | { 43 | sys::CThreadPool thread_pool; // 这里定义线程池实例 44 | 45 | try 46 | { 47 | // create可能抛出异常,所以需要捕获 48 | thread_pool.create(10); // 创建10个线程的线程池 49 | 50 | // 池线程创建成功后,并不会立即进行运行状态,而是处于等待状态, 51 | // 所以需要唤醒它们,方法如下: 52 | uint16_t thread_count = thread_pool.get_thread_count(); 53 | CTestThread** test_thread_array = thread_pool.get_thread_array(); 54 | for (uint16_t i=0; iwakeup(); 58 | } 59 | 60 | // 让CTestThread有足够的时间完成任务 61 | sys::CUtils::millisleep(5000); 62 | // 等待所有线程退出,然后销毁线程池 63 | thread_pool.destroy(); 64 | } 65 | catch (sys::CSyscallException& ex) 66 | { 67 | // 将异常信息打印出来,方便定位原因 68 | printf("Create thread pool exception: %s.\n", ex.str().c_str()); 69 | } 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /include/mooon/net/config.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_NET_CONFIG_H 20 | #define MOOON_NET_CONFIG_H 21 | #include 22 | #include 23 | 24 | // 定义名字空间宏 25 | #define NET_NAMESPACE_BEGIN namespace mooon { namespace net { 26 | #define NET_NAMESPACE_END }} 27 | #define NET_NAMESPACE_USE using namespace mooon::net; 28 | 29 | // 断言宏 30 | #define NET_ASSERT assert 31 | 32 | NET_NAMESPACE_BEGIN 33 | 34 | /** 端口类型 */ 35 | typedef uint16_t port_t; 36 | typedef std::vector int_ip_array_t; /** IP地址数组 */ 37 | typedef std::vector string_ip_array_t; /** IP地址数组 */ 38 | typedef std::vector > eth_ip_array_t; /** 网卡名和IP对数组 */ 39 | 40 | /*** 41 | * IP地址类型定义 42 | */ 43 | typedef enum TIPType 44 | { 45 | IP_TYPE_4 = 0, // IP是一个IPV4地址 46 | IP_TYPE_6 = 1 // IP是一个IPV6地址 47 | }ip_type_t; 48 | 49 | NET_NAMESPACE_END 50 | #endif // MOOON_NET_CONFIG_H 51 | -------------------------------------------------------------------------------- /include/mooon/utils/listable.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_UTILS_LISTABLE_H 20 | #define MOOON_UTILS_LISTABLE_H 21 | #include "mooon/utils/config.h" 22 | UTILS_NAMESPACE_BEGIN 23 | 24 | /*** 25 | * 可链表对象的基类 26 | * 使用方法: 27 | * class CMyClass: public CListable 28 | * { 29 | * }; 30 | */ 31 | template 32 | class CListable 33 | { 34 | public: 35 | CListable() 36 | :_next(NULL) 37 | ,_prev(NULL) 38 | { 39 | } 40 | 41 | /** 得到下一个可链表对象 */ 42 | ListableClass* get_next() const { return _next; } 43 | 44 | /** 得到前一个可链表对象 */ 45 | ListableClass* get_prev() const { return _prev; } 46 | 47 | /** 关联下一个可链表对象 */ 48 | void set_next(ListableClass* next) { _next = next; } 49 | 50 | /** 关联前一个可链表对象 */ 51 | void set_prev(ListableClass* prev) { _prev = prev; } 52 | 53 | private: 54 | ListableClass* _next; 55 | ListableClass* _prev; 56 | }; 57 | 58 | UTILS_NAMESPACE_END 59 | #endif // MOOON_UTILS_LISTABLE_H 60 | -------------------------------------------------------------------------------- /src/utils/crypto.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/12/23 2 | #include "utils/crypto.h" 3 | #include "utils/string_utils.h" 4 | #if MOOON_HAVE_OPENSSL == 1 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | UTILS_NAMESPACE_BEGIN 12 | 13 | // https://linux.die.net/man/3/bio 14 | // https://linux.die.net/man/3/bio_push 15 | // https://linux.die.net/man/3/bio_f_base64 16 | // https://linux.die.net/man/3/bio_write 17 | void base64_encode(const std::string& src, std::string* dest, bool no_newline) 18 | { 19 | BUF_MEM* bptr; 20 | BIO* bmem = BIO_new(BIO_s_mem()); 21 | BIO* b64 = BIO_new(BIO_f_base64()); 22 | 23 | if (no_newline) 24 | BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); 25 | b64 = BIO_push(b64, bmem); 26 | BIO_write(b64, src.data(), static_cast(src.length())); 27 | if (BIO_flush(b64)); 28 | BIO_get_mem_ptr(b64, &bptr); 29 | 30 | dest->resize(bptr->length); 31 | memcpy(const_cast(dest->data()), bptr->data, bptr->length); 32 | BIO_free_all(b64); 33 | } 34 | 35 | // https://linux.die.net/man/3/bio_read 36 | // https://www.openssl.org/docs/man1.0.2/crypto/BIO_read.html 37 | void base64_decode(const std::string& src, std::string* dest, bool no_newline) 38 | { 39 | BIO* bmem = BIO_new_mem_buf(const_cast(src.data()), static_cast(src.length())); 40 | BIO* b64 = BIO_new(BIO_f_base64()); 41 | 42 | if (no_newline) 43 | BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); 44 | bmem = BIO_push(b64, bmem); 45 | 46 | dest->resize(src.length()); 47 | const int bytes = BIO_read(bmem, const_cast(dest->data()), static_cast(src.length())); 48 | dest->resize(bytes); 49 | BIO_free_all(bmem); 50 | } 51 | 52 | UTILS_NAMESPACE_END 53 | #endif // MOOON_HAVE_OPENSSL 54 | -------------------------------------------------------------------------------- /src/sys/shared_library.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #include "sys/shared_library.h" 20 | SYS_NAMESPACE_BEGIN 21 | 22 | CSharedLibrary::CSharedLibrary() 23 | :_handle(NULL) 24 | { 25 | } 26 | 27 | CSharedLibrary::~CSharedLibrary() 28 | { 29 | unload(); 30 | } 31 | 32 | bool CSharedLibrary::load(const char *filename, int flag) 33 | { 34 | _handle = dlopen(filename, flag); 35 | if (NULL == _handle) 36 | { 37 | char* error = dlerror(); 38 | _error_message = (NULL == error)? "Unknown error": error; 39 | } 40 | 41 | return (_handle != NULL); 42 | } 43 | 44 | void CSharedLibrary::unload() 45 | { 46 | if (_handle != NULL) 47 | { 48 | dlclose(_handle); 49 | _handle = NULL; 50 | } 51 | } 52 | 53 | void* CSharedLibrary::get_symbol(const char *symbol_name) 54 | { 55 | void* symbol = dlsym(_handle, symbol_name); 56 | if (NULL == symbol) 57 | { 58 | char* error = dlerror(); 59 | _error_message = (NULL == error)? "Unknown error": error; 60 | } 61 | 62 | return symbol; 63 | } 64 | 65 | SYS_NAMESPACE_END 66 | -------------------------------------------------------------------------------- /shell/top_process.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Writed by yijian on 2020/9/6 3 | # 查看指定进程名的 top 数据 4 | # 执行依赖 top 和 awk 两个命令, 5 | # 支持 mooon_ssh 远程批量执行。 6 | # 7 | # 带一个参数: 8 | # 1)参数1:进程名 9 | 10 | # 使用帮助函数 11 | function usage() 12 | { 13 | echo "Top then process with given name." 14 | echo "Usage: `basename $0` process-name" 15 | echo "Example: `basename $0` redis-server" 16 | } 17 | 18 | # 参数检查 19 | if test $# -ne 1; then 20 | usage 21 | exit 1 22 | fi 23 | 24 | # 参数指定的 redis-server 监听端口 25 | PROCESS_NAME="$1" 26 | 27 | # top 命令可能位于不同目录下 28 | TOP=/usr/bin/top 29 | which $TOP > /dev/null 2>&1 30 | if test $? -ne 0; then 31 | TOP=/bin/top 32 | which $TOP > /dev/null 2>&1 33 | if test $? -ne 0; then 34 | echo "\`top\` is not exists or is not executable." 35 | exit 1 36 | fi 37 | fi 38 | 39 | # 取得进程ID(可能多个) 40 | # 命令 ps 输出的时间格式有两种:“7月17”和“20:42”,所以端口所在字段有区别: 41 | PIDs=(`ps -f -C "$PROCESS_NAME" | awk -F'[ :]*' '{ print $2 }'`) 42 | if test -z "$PIDs" -o ${#PIDs[@]} -eq 0; then 43 | echo "Can not get PIDs of \"$PROCESS_NAME\"" 44 | exit 1 45 | fi 46 | 47 | # 执行 top 之前需要设置好环境变量“TERM”,否则执行将报如下错: 48 | # TERM environment variable not set. 49 | export TERM=xterm 50 | 51 | for ((i=0; i<${#PIDs[@]}; ++i)) 52 | do 53 | pid=${PIDs[i]} 54 | # 过滤掉标题 55 | if test "$pid" = "PID"; then 56 | continue 57 | fi 58 | 59 | # 后台方式执行命令 top 时, 60 | # 需要加上参数“-b”(非交互模式),不然报错“top: failed tty get” 61 | #$TOP -b -p $pid -n 1 | grep redis-serv+ 62 | eval $($TOP -b -p $pid -n 1 | awk '{ if (match($12,"redis-serv+")) printf("PID=%s\nUSER=%s\nPR=%s\nNI=%s\nVIRT=%s\nRES=%s\nSHR=%s\nS=%s\nCPU=%s\nMEM=%s\n",$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12); }') 63 | # PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 64 | echo -e "PID:\033[1;33m$PID\033[m USER:$USER PR:$PR NI:$NI VIRT:\033[1;33m$VIRT\033[m RES:\033[1;33m$RES\033[m SHR:$SHR S:$S %CPU:\033[1;33m$CPU\033[m %MEM:\033[1;33m$MEM\033[m" 65 | done 66 | -------------------------------------------------------------------------------- /include/mooon/net/sensor.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_NET_SENSOR_H 20 | #define MOOON_NET_SENSOR_H 21 | #include "mooon/net/epollable.h" 22 | NET_NAMESPACE_BEGIN 23 | 24 | /*** 25 | * 感应器 26 | */ 27 | class CSensor: public CEpollable 28 | { 29 | public: 30 | CSensor(); 31 | 32 | /*** 33 | * 创建感应器 34 | * @exception 如果出错则抛出CSyscallException异常 35 | */ 36 | void create(); 37 | 38 | /*** 39 | * 重写CEpollable的close方法 40 | * 关闭感应器 41 | */ 42 | virtual void close(); 43 | 44 | /*** 45 | * 触摸 46 | * @exception 如果出错则抛出CSyscallException异常 47 | */ 48 | void touch(); 49 | 50 | /*** 51 | * 感觉 52 | * @exception 如果出错则抛出CSyscallException异常 53 | */ 54 | void feel(uint16_t bytes=1); 55 | 56 | private: 57 | virtual epoll_event_t handle_epoll_event(void* input_ptr, uint32_t events, void* ouput_ptr); 58 | 59 | private: 60 | int _pipe_fd[2]; 61 | char _finger[1024]; 62 | }; 63 | 64 | NET_NAMESPACE_END 65 | #endif // MOOON_NET_SENSOR_H 66 | -------------------------------------------------------------------------------- /src/sys/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Writed by yijian (eyjian@qq.com, eyjian@gmail.com) 2 | 3 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../include) 4 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon) 5 | 6 | # 源代码 7 | set( 8 | MOOON_SYS_SRC 9 | ${CMAKE_CURRENT_SOURCE_DIR}/curl_wrapper.cpp 10 | ${CMAKE_CURRENT_SOURCE_DIR}/event.cpp 11 | ${CMAKE_CURRENT_SOURCE_DIR}/info.cpp 12 | ${CMAKE_CURRENT_SOURCE_DIR}/main_template.cpp 13 | ${CMAKE_CURRENT_SOURCE_DIR}/mysql_db.cpp 14 | ${CMAKE_CURRENT_SOURCE_DIR}/safe_logger.cpp 15 | ${CMAKE_CURRENT_SOURCE_DIR}/shared_memory.cpp 16 | ${CMAKE_CURRENT_SOURCE_DIR}/sqlite3_db.cpp 17 | ${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp 18 | ${CMAKE_CURRENT_SOURCE_DIR}/datetime_utils.cpp 19 | ${CMAKE_CURRENT_SOURCE_DIR}/file_utils.cpp 20 | ${CMAKE_CURRENT_SOURCE_DIR}/lock.cpp 21 | ${CMAKE_CURRENT_SOURCE_DIR}/mem_pool.cpp 22 | ${CMAKE_CURRENT_SOURCE_DIR}/pool_thread.cpp 23 | ${CMAKE_CURRENT_SOURCE_DIR}/semaphore.cpp 24 | ${CMAKE_CURRENT_SOURCE_DIR}/signal_handler.cpp 25 | ${CMAKE_CURRENT_SOURCE_DIR}/syscall_exception.cpp 26 | ${CMAKE_CURRENT_SOURCE_DIR}/dir_utils.cpp 27 | ${CMAKE_CURRENT_SOURCE_DIR}/fs_utils.cpp 28 | ${CMAKE_CURRENT_SOURCE_DIR}/logger.cpp 29 | ${CMAKE_CURRENT_SOURCE_DIR}/mmap.cpp 30 | ${CMAKE_CURRENT_SOURCE_DIR}/read_write_lock.cpp 31 | ${CMAKE_CURRENT_SOURCE_DIR}/shared_library.cpp 32 | ${CMAKE_CURRENT_SOURCE_DIR}/simple_db.cpp 33 | ${CMAKE_CURRENT_SOURCE_DIR}/thread.cpp 34 | ${CMAKE_CURRENT_SOURCE_DIR}/time_thread.cpp 35 | CACHE INTERNAL 36 | MOOON_SYS_SRC 37 | ) 38 | 39 | # libmooon_sys.a 40 | #add_library( 41 | # mooon_sys 42 | # STATIC 43 | # ${MOOON_SYS_SRC} 44 | #) 45 | 46 | # CMAKE_INSTALL_PREFIX 47 | install( 48 | DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../include/mooon/sys 49 | DESTINATION include/mooon 50 | PATTERN "*.h" 51 | ) 52 | -------------------------------------------------------------------------------- /src/utils/integer_utils.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include 20 | #include "utils/integer_utils.h" 21 | UTILS_NAMESPACE_BEGIN 22 | 23 | bool CIntegerUtils::is_int16(int32_t num) 24 | { 25 | return (num >= std::numeric_limits::min()) 26 | && (num <= std::numeric_limits::max()); 27 | } 28 | 29 | bool CIntegerUtils::is_uint16(int32_t num) 30 | { 31 | return (num >= 0) && (num <= std::numeric_limits::max()); 32 | } 33 | 34 | bool CIntegerUtils::is_uint16(uint32_t num) 35 | { 36 | return (num <= std::numeric_limits::max()); 37 | } 38 | 39 | bool CIntegerUtils::is_int32(int64_t num) 40 | { 41 | return (num >= std::numeric_limits::min()) 42 | && (num <= std::numeric_limits::max()); 43 | } 44 | 45 | bool CIntegerUtils::is_uint32(int64_t num) 46 | { 47 | return (num >= 0) && (num <= std::numeric_limits::max()); 48 | } 49 | 50 | bool CIntegerUtils::is_uint32(uint64_t num) 51 | { 52 | return (num <= std::numeric_limits::max()); 53 | } 54 | 55 | UTILS_NAMESPACE_END 56 | -------------------------------------------------------------------------------- /include/mooon/sys/syscall_exception.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_SYS_SYSCALL_EXCEPTION_H 20 | #define MOOON_SYS_SYSCALL_EXCEPTION_H 21 | #include "mooon/sys/config.h" 22 | #include "mooon/utils/exception.h" 23 | 24 | #define THROW_SYSCALL_EXCEPTION(errmsg, errcode, syscall) \ 25 | throw ::mooon::sys::CSyscallException(errmsg, errcode, __FILE__, __LINE__, syscall) 26 | 27 | SYS_NAMESPACE_BEGIN 28 | 29 | /** 系统调用出错异常,多数系统调用出错时,均以此异常型反馈给调用者 */ 30 | class CSyscallException: public utils::CException 31 | { 32 | public: 33 | CSyscallException(const char* errmsg, int errcode, const char* file, int line, const char* syscall) throw (); 34 | CSyscallException(const std::string& errmsg, int errcode, const std::string& file, int line, const std::string& syscall) throw (); 35 | virtual ~CSyscallException() throw () {} 36 | 37 | virtual std::string str() const throw (); 38 | const char* syscall() const throw (); 39 | 40 | private: 41 | virtual std::string prefix() const throw (); 42 | 43 | private: 44 | std::string _syscall; // 哪个系统调用失败了 45 | }; 46 | 47 | SYS_NAMESPACE_END 48 | #endif // MOOON_SYS_SYSCALL_EXCEPTION_H 49 | -------------------------------------------------------------------------------- /shell/clean_mysql_user.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Writed by yijian on 2023/08/16 3 | # A tool to clean up mysql specified account. 4 | 5 | if test $# -ne 5; then 6 | echo -e "Usage: \033[1;33m`basename $0`\033[m deleted_user mysql_host mysql_port mysql_root mysql_root_password" 7 | echo -e "Example: `basename $0` 'zhangsan' '127.0.0.1' 3306 'root' 'root123'" 8 | echo -e "\033[1;33mNOTICE\033[m: the tool will not delete the host which is '%'." 9 | exit 1 10 | fi 11 | 12 | deleted_user="$1" # 被清理的账号名 13 | mysql_host="$2" # MySQL 的 host 14 | mysql_port="$3" # MySQL 的 port 15 | mysql_root="$4" # MySQL 的 root 账号名 16 | mysql_root_password="$5" # MySQL 的 root 密码 17 | 18 | set +e 19 | 20 | deleted_count=0 21 | list_sql="SELECT Host FROM mysql.user where User='$deleted_user'" 22 | host_list=(`mysql -N --silent -h$mysql_host -P$mysql_port -u$mysql_root -p"$mysql_root_password" -e"$list_sql"`) 23 | 24 | if test ${#host_list[@]} -eq 0; then 25 | echo -e "\033[0;32;31mNo any, exit now\033[m." 26 | exit 1 27 | else 28 | echo -e "\033[1;33mList of hosts to delete for user '$deleted_user'\033[m:" 29 | fi 30 | for host in ${host_list[@]}; do 31 | if test "X$host" != "X%"; then 32 | delete_sql="DROP USER '$deleted_user'@'$host'" 33 | echo "$delete_sql" 34 | fi 35 | done 36 | 37 | echo -en "continue? [\033[1;33myes\033[m/\033[1;33mno\033[m]" 38 | read -r -p " " choice 39 | if test "$choice" != "yes"; then 40 | echo -e "\033[0;32;31mDo nothing, exit now\033[m." 41 | exit 1 42 | fi 43 | 44 | for host in ${host_list[@]}; do 45 | if test "X$host" != "X%"; then 46 | deleted_count=$((++deleted_count)) 47 | delete_sql="DROP USER '$deleted_user'@'$host'" 48 | mysql -N --silent -h$mysql_host -P$mysql_port -u$mysql_root -p"$mysql_root_password" -e"$delete_sql" 49 | fi 50 | done 51 | 52 | if test $deleted_count -gt 0; then 53 | echo "$deleted_count deleted" 54 | mysql -N --silent -h$mysql_host -P$mysql_port -u$mysql_root -p"$mysql_root_password" -e"FLUSH PRIVILEGES" 55 | fi 56 | 57 | set -e 58 | 59 | -------------------------------------------------------------------------------- /include/mooon/utils/print_color.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_UTILS_PRINT_COLOR_H 20 | #define MOOON_UTILS_PRINT_COLOR_H 21 | #include 22 | 23 | // 示例: 24 | // printf(PRINT_COLOR_YELLOW"[WARN][%s:%d]"PRINT_COLOR_NONE, __FILE__, __LINE__); 25 | 26 | #define PRINT_COLOR_NONE "\033[m" 27 | #define PRINT_COLOR_RED "\033[0;32;31m" 28 | #define PRINT_COLOR_YELLOW "\033[1;33m" 29 | #define PRINT_COLOR_BLUE "\033[0;32;34m" 30 | #define PRINT_COLOR_GREEN "\033[0;32;32m" 31 | #define PRINT_COLOR_WHITE "\033[1;37m" 32 | #define PRINT_COLOR_CYAN "\033[0;36m" // 蓝绿色, 青色 33 | #define PRINT_COLOR_PURPLE "\033[0;35m" // 紫色 34 | #define PRINT_COLOR_BROWN "\033[0;33m" // 褐色, 棕色 35 | #define PRINT_COLOR_DARY_GRAY "\033[1;30m" // 卡里灰色 36 | #define PRINT_COLOR_LIGHT_RED "\033[1;31m" 37 | #define PRINT_COLOR_LIGHT_GREEN "\033[1;32m" 38 | #define PRINT_COLOR_LIGHT_BLUE "\033[1;34m" 39 | #define PRINT_COLOR_LIGHT_CYAN "\033[1;36m" 40 | #define PRINT_COLOR_LIGHT_PURPLE "\033[1;35m" 41 | #define PRINT_COLOR_LIGHT_GRAY "\033[0;37m" // 亮灰色 42 | 43 | #endif // MOOON_UTILS_PRINT_COLOR_H 44 | -------------------------------------------------------------------------------- /include/mooon/utils/bit_utils.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_UTILS_BIT_UTILS_H 20 | #define MOOON_UTILS_BIT_UTILS_H 21 | #include "mooon/utils/config.h" 22 | UTILS_NAMESPACE_BEGIN 23 | 24 | /*** 25 | * 位操作工具类 26 | */ 27 | class CBitUtils 28 | { 29 | public: 30 | /*** 31 | * 对指定位取反,不做越界检查 32 | * @bitmap: 位图,其位数不能小于position 33 | * @position: 在bitmap中的位位置 34 | */ 35 | static void flip(char* bitmap, uint32_t position); 36 | 37 | /*** 38 | * 测试指定位是否为1,不做越界检查 39 | * @bitmap: 位图,其位数不能小于position 40 | * @position: 在bitmap中的位位置 41 | */ 42 | static bool test(char* bitmap, uint32_t position); 43 | 44 | /*** 45 | * 得到指定位的值,不做越界检查 46 | * @bitmap: 位图,其位数不能小于position 47 | * @position: 在bitmap中的位位置 48 | */ 49 | static uint8_t get_bit(char* bitmap, uint32_t position); 50 | 51 | /*** 52 | * 设置指定位的值,不做越界检查 53 | * @bitmap: 位图,其位数不能小于position 54 | * @position: 在bitmap中的位位置 55 | * @zero: 将position所在位设置为0或1,如果为true则设置为0,否则设置为1 56 | */ 57 | static void set_bit(char* bitmap, uint32_t position, bool zero); 58 | }; 59 | 60 | UTILS_NAMESPACE_END 61 | #endif // MOOON_UTILS_BIT_UTILS_H 62 | -------------------------------------------------------------------------------- /shell/file_utils.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Writed by JianYi On 2008-5-20 3 | 4 | # 变量定义 5 | log_filename= # 日志文件名 6 | log_bakeup_nubmer=10 # 日志备份个数 7 | log_rotate_bytes=102400000 # 日志滚动字节数 8 | 9 | # 用途:得到文件大小 10 | # 参数:文件名 11 | # 返回值:如果失败返回0,否则返回文件大小 12 | get_file_size() 13 | { 14 | file_size=`ls --time-style=long-iso -l $1 2>/dev/null|cut -d" " -f5` 15 | if test -z $file_size; then 16 | echo "0" 17 | else 18 | echo $file_size 19 | fi 20 | } 21 | 22 | # 用途:得到日志文件索引 23 | # 参数:日志文件名的基名,即不包括索引部分的名字,如:test.log,而不是test.log.1 24 | # 返回值:成功返回索引值,失败返回-1 25 | get_log_file_index() 26 | { 27 | log_file_basename=$1 28 | index=`ls $log_file_basename.[0-9] 2>/dev/null|cut -d"." -f3|sort -n|sed -n '$p'` 29 | if test -z $index; then 30 | echo "-1" 31 | else 32 | echo $index 33 | fi 34 | } 35 | 36 | # 用途:滚动日志文件 37 | # 参数:日志文件名 38 | rotate_log_file() 39 | { 40 | log_file_basename=$1 41 | index=`get_log_file_index $log_file_basename` 42 | if test $index -eq -1; then 43 | mv $log_file_basename $log_file_basename.0 44 | return 45 | elif test $index -ge $log_file_roll_num; then 46 | index=$log_file_roll_num 47 | fi 48 | 49 | # 循环滚动文件, 索引号越大文件内容越旧 50 | while true 51 | do 52 | let index_next=$index+1 53 | if test -f $log_filename.$index; then 54 | mv $log_file_basename.$index $log_file_basename.$index_next 55 | fi 56 | 57 | if test $index -eq 0; then 58 | # 结束循环 59 | if test -f $log_file_basename; then 60 | mv $log_file_basename $log_file_basename.0 61 | fi 62 | return 63 | else 64 | # 计数器增一 65 | let index=$index-1 66 | fi 67 | done 68 | } 69 | 70 | # 用途:写日志函数 71 | # 参数:日志内容字符串 72 | log_write() 73 | { 74 | # 得到日志文件大小 75 | log_size=`get_file_size $log_filename` 76 | 77 | # 如果大于滚动大小 78 | if test $log_size -gt $log_roll_bytes; then 79 | roll_log_file $log_filename 80 | else 81 | # 得到当前时间 82 | now="`date +'%Y-%m-%d/%H:%M:%S'`" 83 | echo "[$now]$1" >> $log_filename 84 | fi 85 | } 86 | -------------------------------------------------------------------------------- /include/mooon/sys/sqlite3_db.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_SYS_SQLITE3_DB_H 20 | #define MOOON_SYS_SQLITE3_DB_H 21 | #include "mooon/sys/simple_db.h" 22 | #include "mooon/utils/object.h" 23 | #include 24 | 25 | // SQLite3安装后的include目录结构不标准,需要手动调整成: 26 | // 头文件sqlite3.h和sqlite3ext.h放到目录:<安装目录>/include/sqlite3 27 | // 亦即需要在include目录下新建一个sqlite3子目录,然后将sqlite3.h和sqlite3ext.h两个头文件移至到这个目录 28 | 29 | #if MOOON_HAVE_SQLITE3==1 30 | SYS_NAMESPACE_BEGIN 31 | 32 | /** 33 | * SQLite3版本的DB连接 34 | */ 35 | class CSQLite3Connection: public CDBConnectionBase 36 | { 37 | public: 38 | CSQLite3Connection(size_t sql_max=8192); 39 | ~CSQLite3Connection(); 40 | 41 | public: 42 | virtual void open(); 43 | virtual void close() throw (); 44 | virtual void reopen(); 45 | 46 | virtual uint64_t update(const char* format, ...) __attribute__((format(printf, 2, 3))); 47 | virtual std::string str() throw (); 48 | 49 | private: 50 | virtual void do_query(DBTable& db_table, const char* sql, int sql_length); 51 | 52 | private: 53 | void do_open(); 54 | 55 | private: 56 | void* _sqlite; 57 | }; 58 | 59 | SYS_NAMESPACE_END 60 | #endif // MOOON_HAVE_SQLITE3 61 | #endif // MOOON_SYS_SQLITE3_DB_H 62 | -------------------------------------------------------------------------------- /include/mooon/sys/shared_library.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_SYS_SHARED_LIBRARY_H 20 | #define MOOON_SYS_SHARED_LIBRARY_H 21 | #include "mooon/sys/utils.h" 22 | #include 23 | SYS_NAMESPACE_BEGIN 24 | 25 | /*** 26 | * 共享库加载工具类 27 | * 非线程安全类,不要跨线程使用 28 | */ 29 | class CSharedLibrary 30 | { 31 | public: 32 | /** 构造一个共享库加载器 */ 33 | CSharedLibrary(); 34 | ~CSharedLibrary(); 35 | 36 | /** 37 | * 根据文件名加载共享库 38 | * @filename: 共享库文件名 39 | * @flag: 加载标志,可取值RTLD_NOW或RTLD_LAZY 40 | * @return: 如果加载成功返回true,否则返回false,如果返回false, 41 | * 可调用get_error_message获取失败原因 42 | */ 43 | bool load(const char *filename, int flag = RTLD_NOW); 44 | 45 | /** 卸载已经加载的共享库 */ 46 | void unload(); 47 | 48 | /** 49 | * 得到出错信息,load或get_symbol失败时, 50 | * 应当调用它来得到出错信息 51 | */ 52 | const std::string& get_error_message() const { return _error_message; } 53 | 54 | /*** 55 | * 根据符号名得到符号的地址 56 | * @symbol_name: 符号名,通常为函数名 57 | * @return: 返回符号对应的地址,通常为函数地址,如果失败则返回NULL 58 | */ 59 | void* get_symbol(const char *symbol_name); 60 | 61 | private: 62 | void *_handle; 63 | std::string _error_message; 64 | }; 65 | 66 | SYS_NAMESPACE_END 67 | #endif // MOOON_SYS_SHARED_LIBRARY_H 68 | -------------------------------------------------------------------------------- /include/mooon/sys/singleton.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: laocai_liu@qq.com or laocailiu@gmail.com 18 | */ 19 | #ifndef MOOON_SYS_SINGLETON_H 20 | #define MOOON_SYS_SINGLETON_H 21 | #include "mooon/sys/lock.h" 22 | #include 23 | SYS_NAMESPACE_BEGIN 24 | 25 | /** 26 | * utils/configh.h 中的 singleton(SINGLETON_DECLARE) 是非线程安全 27 | * 这里实现的 singleton 是线程安全的 28 | */ 29 | 30 | template 31 | class CSingleton 32 | { 33 | public: 34 | static ObjType* get_singleton() 35 | { 36 | if (NULL == _obj) 37 | { 38 | LockHelper monitor(_lock); 39 | 40 | if (NULL == _obj) 41 | { 42 | _obj = new ObjType; 43 | std::atexit(delete_singleton); 44 | } 45 | } 46 | 47 | return _obj; 48 | } 49 | 50 | private: 51 | static void delete_singleton(void) 52 | { 53 | if (NULL != _obj) 54 | { 55 | delete _obj; 56 | _obj = NULL; 57 | } 58 | } 59 | 60 | private: 61 | static CLock _lock; 62 | static ObjType* _obj; 63 | }; 64 | 65 | template 66 | CLock CSingleton::_lock; 67 | 68 | template 69 | ObjType* CSingleton::_obj = NULL; 70 | 71 | SYS_NAMESPACE_END 72 | 73 | #endif 74 | 75 | -------------------------------------------------------------------------------- /shell/cpumem.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # writed by yijian on 2019/8/20 3 | # filename cpumem.sh 4 | # 统计指定进程ID的CPU和内存数据工具 5 | # 运行时可指定两个参数: 6 | # 1)参数1:进程ID(必指定) 7 | # 2)参数2:统计间隔(单位为秒,可选,如果不指定则默认为2秒) 8 | # 9 | # 运行时输出5列内容: 10 | # [统计日期时间]CPU百分比,内存百分比,物理内存,虚拟内存 11 | 12 | # 显示用法函数 13 | function usage() 14 | { 15 | echo "Usage: cpumem.sh PID " 16 | echo "Example1: cpumem.sh 2019" 17 | echo "Example2: cpumem.sh 2019 1" 18 | echo "The interval parameter specifies the amount of time in seconds between each report." 19 | } 20 | 21 | # 检查参数个数 22 | if test $# -lt 1 -o $# -gt 2; then 23 | usage 24 | exit 1 25 | fi 26 | 27 | pid=$1 28 | interval=2 29 | if test $# -eq 2; then 30 | interval=$2 31 | fi 32 | printf "[StatTime] THREADS %%CPU %%MEM RSS VSZ\n" 33 | while (true) 34 | do 35 | rss=0 36 | vsz=0 37 | stattime="`date +'%Y-%m-%d %H:%M:%S'`" 38 | 39 | # 取得进程的线程数 40 | threads=`awk -F[\ :]. '{if (match($1,"Threads")) print $2}' /proc/$pid/status` 41 | 42 | # rss和vsz的单位均为kb 43 | eval $(ps h -p $pid -o pcpu,pmem,rss,vsz | awk '{printf("cpu=%s\nmem=%s\nrss=%s\nvsz=%s\n",$1,$2,$3,$4);}') 44 | if test $rss -eq 0; then 45 | # 可能是进程已不存在 46 | kill -0 $PID > /dev/null 2>&1 47 | if test $? -ne 0; then 48 | echo "Process($PID) is not exists." 49 | break 50 | fi 51 | fi 52 | 53 | rssize="${rss}KB" 54 | vsize="${vsz}KB" 55 | if test $rss -ge 1048576; then 56 | # 大小达到GB 57 | rssize="`echo "scale=2;$rss/1024/1024" | bc -l`GB" 58 | elif test $rss -ge 1024; then 59 | # 大小达到MB 60 | rssize="`echo "scale=2;$rss/1024" | bc -l`MB" 61 | fi 62 | if test $vsz -ge 1048576; then 63 | # 大小达到GB 64 | vsize="`echo "scale=2;$vsz/1024/1024" | bc -l`GB" 65 | elif test $vsz -ge 1024; then 66 | # 大小达到MB 67 | vsize="`echo "scale=2;$vsz/1024" | bc -l`MB" 68 | fi 69 | 70 | # \033[1;33m 黄色 71 | # \033[1;32m 亮绿色 72 | printf "[%s] \033[0;32;31m%s\033[m \033[1;33m%s\033[m %s \033[1;32m%s\033[m %s\n" "$stattime" "$threads" "$cpu" "$mem" "$rssize" "$vsize"; 73 | sleep $interval 74 | done 75 | -------------------------------------------------------------------------------- /src/net/sensor.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com eyjian@gmail.com 18 | */ 19 | #include "net/sensor.h" 20 | NET_NAMESPACE_BEGIN 21 | 22 | CSensor::CSensor() 23 | { 24 | _pipe_fd[0] = -1; 25 | _pipe_fd[1] = -1; 26 | _finger[0] = '\0'; 27 | } 28 | 29 | void CSensor::create() 30 | { 31 | if (-1 == pipe(_pipe_fd)) 32 | THROW_SYSCALL_EXCEPTION(NULL, errno, "pipe"); 33 | 34 | set_fd(_pipe_fd[0]); 35 | } 36 | 37 | void CSensor::close() 38 | { 39 | if (_pipe_fd[0] != -1) 40 | { 41 | before_close(); 42 | 43 | close_fd(_pipe_fd[0]); 44 | close_fd(_pipe_fd[1]); 45 | 46 | _pipe_fd[0] = -1; 47 | _pipe_fd[1] = -1; 48 | 49 | set_fd(-1); 50 | } 51 | } 52 | 53 | void CSensor::touch() 54 | { 55 | char finger = 'x'; 56 | if (-1 == write(_pipe_fd[1], &finger, sizeof(finger))) 57 | THROW_SYSCALL_EXCEPTION(NULL, errno, "write"); 58 | } 59 | 60 | void CSensor::feel(uint16_t bytes) 61 | { 62 | if (-1 == read(_pipe_fd[0], _finger, bytes 23 | #include 24 | #include 25 | UTILS_NAMESPACE_BEGIN 26 | 27 | class CCharsetUtils 28 | { 29 | public: 30 | // from可包含非gdb、utf8等二进制字符 31 | // ignore_error 是否忽略不能转换的错误 32 | // skip_error 在ignore_error为true的前提下,是否在输出中不包含不能被转换的字节 33 | // 如果from中间部分包含了不能转换的部分,当ignore_error和skip_error均为true时,则结果将不包含这部分 34 | static void convert(const std::string& from_charset, const std::string& to_charset, 35 | const std::string& from, std::string* to, bool ignore_error=true, bool skip_error=true); 36 | 37 | public: 38 | static void gbk_to_utf8(const std::string& from, std::string* to, bool ignore_error=true, bool skip_error=true); 39 | static void utf8_to_gbk(const std::string& from, std::string* to, bool ignore_error=true, bool skip_error=true); 40 | 41 | static void gb2312_to_utf8(const std::string& from, std::string* to, bool ignore_error=true, bool skip_error=true); 42 | static void utf8_to_gb2312(const std::string& from, std::string* to, bool ignore_error=true, bool skip_error=true); 43 | }; 44 | 45 | UTILS_NAMESPACE_END 46 | #endif // MOOON_UTILS_CHARSET_UTILS_H 47 | -------------------------------------------------------------------------------- /include/mooon/sys/config.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_SYS_CONFIG_H 20 | #define MOOON_SYS_CONFIG_H 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | // 编译控制宏 28 | #define HAVE_UIO_H 0 /** 是否可以使用writev和readv */ 29 | #define COMPILE_FS_UTIL_CPP 1 /** 是否编译fs_util.cpp */ 30 | #define ENABLE_SET_LOG_THREAD_NAME 1 /** 是否设置日志线程名 */ 31 | 32 | // 定义名字空间宏 33 | #define SYS_NAMESPACE_BEGIN namespace mooon { namespace sys { 34 | #define SYS_NAMESPACE_END }} 35 | #define SYS_NAMESPACE_USE using namespace mooon::sys; 36 | 37 | #ifndef S_IRGRP 38 | #define S_IRGRP (S_IRUSR >> 3) /* Read by group. */ 39 | #endif // S_IRGRP 40 | 41 | #ifndef S_IXGRP 42 | #define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */ 43 | #endif // S_IXGRP 44 | 45 | #ifndef S_IXOTH 46 | #define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */ 47 | #endif // S_IXOTH 48 | 49 | /** 新创建文件的默认权限 */ 50 | #define FILE_DEFAULT_PERM (S_IRUSR|S_IWUSR | S_IRGRP | S_IROTH) 51 | /** 新创建目录的默认权限 */ 52 | #define DIRECTORY_DEFAULT_PERM (S_IRWXU | S_IXGRP | S_IXOTH) 53 | /** 新创建的IPC(包括shm和sem等)默认权限 */ 54 | #define IPC_DEFAULT_PERM (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) 55 | 56 | /** 网卡名最大字节长度 */ 57 | #define INTERFACE_NAME_MAX 20 58 | 59 | #endif // MOOON_SYS_CONFIG_H 60 | -------------------------------------------------------------------------------- /test/sys/ut_fs_utils.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | * df命令的实现 19 | */ 20 | #include "mooon/sys/fs_utils.h" 21 | SYS_NAMESPACE_USE 22 | 23 | int main() 24 | { 25 | CFSTable fs_table(true, "/"); 26 | CFSTable::fs_entry_t fs_entry; 27 | 28 | printf("%-18s %12s %12s %12s %5s %s\n" 29 | ,"文件系统" 30 | ,"1K-块" 31 | ,"已用" 32 | ,"可用" 33 | ,"已用%" 34 | ,"挂载点" 35 | ); 36 | 37 | while (fs_table.get_entry(fs_entry) != NULL) 38 | { 39 | try 40 | { 41 | CFSUtils::fs_stat_t stat_buf; 42 | CFSUtils::stat_fs(fs_entry.dir_path.c_str(), stat_buf); 43 | 44 | unsigned long total = stat_buf.total_block_nubmer * (stat_buf.block_bytes/1024); 45 | unsigned long used = (stat_buf.total_block_nubmer-stat_buf.free_block_nubmer) * (stat_buf.block_bytes/1024); 46 | unsigned long avail = stat_buf.avail_block_nubmer*(stat_buf.block_bytes/1024); 47 | 48 | printf("%-15s%12lu%12lu%12lu%5lu %s\n" 49 | ,fs_entry.fs_name.c_str() 50 | ,total 51 | ,used 52 | ,avail 53 | ,((total-avail) * 100) / total 54 | ,fs_entry.dir_path.c_str() 55 | ); 56 | } 57 | catch (CSyscallException& syscall_ex) 58 | { 59 | printf("stat_fs exception: %s\n", syscall_ex.str().c_str()); 60 | } 61 | } 62 | 63 | return 0; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /include/mooon/sys/event.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_SYS_EVENT_H 20 | #define MOOON_SYS_EVENT_H 21 | #include "mooon/sys/lock.h" 22 | SYS_NAMESPACE_BEGIN 23 | 24 | /*** 25 | * 通知事件类 26 | * 常用于队列的实现,队列为空时则等待队列有数据,如果往队列push了数据 27 | * ,则唤醒等待线程去队列取数据 28 | */ 29 | class CEvent 30 | { 31 | public: 32 | /*** 33 | * 构造通知事件实例 34 | * @exception: 出错抛出CSyscallException异常,通常可不捕获此异常 35 | */ 36 | CEvent(); 37 | ~CEvent() throw (); 38 | 39 | /*** 40 | * 让调用者进入等待状态,直接到被唤醒 41 | * @exception: 出错抛出CSyscallException异常,通常可不捕获此异常 42 | */ 43 | void wait(CLock& lock); 44 | 45 | /*** 46 | * 让调用者进入等待状态,直接到被唤醒,或等待的时长超过指定的毫秒数 47 | * @return: 如果在指定的毫秒数之前被唤醒,则返回true,否则返回false 48 | * @exception: 出错抛出CSyscallException异常,通常可不捕获此异常 49 | */ 50 | bool timed_wait(CLock& mutex, uint32_t millisecond); 51 | 52 | /*** 53 | * 唤醒一个进入等待状态的线程,如果没有线程正处于等待状态,则唤醒动作忽略 54 | * 只有当signal调用发生在wait调用之后才有效 55 | * @exception: 出错抛出CSyscallException异常,通常可不捕获此异常 56 | */ 57 | void signal(); 58 | 59 | /*** 60 | * 广播唤醒信号,将所有进入等待状态的线程全部唤醒, 61 | * 如果没有线程正处于等待状态,则唤醒动作忽略 62 | * 只有当broadcast调用发生在wait调用之后才有效 63 | * @exception: 出错抛出CSyscallException异常,通常可不捕获此异常 64 | */ 65 | void broadcast(); 66 | 67 | private: 68 | pthread_cond_t _cond; 69 | }; 70 | 71 | SYS_NAMESPACE_END 72 | #endif // MOOON_SYS_EVENT_H 73 | -------------------------------------------------------------------------------- /src/sys/syscall_exception.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #include 20 | #include 21 | #include "sys/utils.h" 22 | #include "sys/syscall_exception.h" 23 | SYS_NAMESPACE_BEGIN 24 | 25 | CSyscallException::CSyscallException( 26 | const char* errmsg, int errcode, const char* file, int line, const char* syscall) throw () 27 | : utils::CException(errmsg, errcode, file, line) 28 | { 29 | if (NULL == errmsg) 30 | _errmsg = strerror(errno); 31 | 32 | if (syscall != NULL) 33 | _syscall = syscall; 34 | } 35 | 36 | CSyscallException::CSyscallException( 37 | const std::string& errmsg, int errcode, const std::string& file, int line, const std::string& syscall) throw () 38 | : CException(errmsg, errcode, file, line) 39 | { 40 | if (errmsg.empty()) 41 | _errmsg = strerror(errno); 42 | 43 | if (!syscall.empty()) 44 | _syscall = syscall; 45 | } 46 | 47 | std::string CSyscallException::str() const throw () 48 | { 49 | std::stringstream ss; 50 | 51 | ss << prefix() << _errmsg << "@" << _file << ":" << _line; 52 | if (!_syscall.empty()) 53 | ss << "#" << _syscall; 54 | 55 | return ss.str(); 56 | } 57 | 58 | const char* CSyscallException::syscall() const throw () 59 | { 60 | return _syscall.c_str(); 61 | } 62 | 63 | std::string CSyscallException::prefix() const throw () 64 | { 65 | return std::string("syscall_exception://"); 66 | } 67 | 68 | SYS_NAMESPACE_END 69 | -------------------------------------------------------------------------------- /include/mooon/sys/dir_utils.h: -------------------------------------------------------------------------------- 1 | // Writed by yijian, eyjian@qq.com or eyjian@gmail.com 2 | #ifndef MOOON_SYS_DIR_UTILS_H 3 | #define MOOON_SYS_DIR_UTILS_H 4 | #include "mooon/sys/utils.h" 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | SYS_NAMESPACE_BEGIN 15 | 16 | class CDirUtils 17 | { 18 | public: 19 | /*** 20 | * 不递归地列出目录下的文件或目录 21 | * @dirpath 目录路径 22 | * @dirs 用来存储dirpath下的子目录名,如果为NULL,表示略过 23 | * @files 用来存储dirpath下的文件名,如果为NULL,表示略过 24 | * @links 用来存储dirpath下的链接名,如果为NULL,表示略过 25 | * @exception 如果发生错误,则抛出sys::CSyscallException异常 26 | */ 27 | static void list(const std::string& dirpath 28 | , std::vector* subdir_names 29 | , std::vector* file_names 30 | , std::vector* link_names=NULL); 31 | 32 | /*** 33 | * 删除一个空目录 34 | * @exception 如果发生错误,则抛出sys::CSyscallException异常 35 | */ 36 | static void remove(const std::string& dirpath); 37 | 38 | // 判断是否存在指定的目录 39 | static bool exist(const std::string& dirpath); 40 | 41 | /*** 42 | * 递归的创建目录 43 | * @dirpath: 需要创建的目录 44 | * @permissions: 目录权限,取值可以为下列的任意组合: 45 | * S_IRWXU, S_IRUSR, S_IWUSR, S_IXUSR 46 | * S_IRWXG, S_IRGRP, S_IWGRP, S_IXGRP 47 | * S_IRWXO, S_IROTH, S_IWOTH, S_IXOTH 48 | * @exception: 出错则抛出CSyscallException 49 | */ 50 | static void create_directory(const char* dirpath, mode_t permissions=DIRECTORY_DEFAULT_PERM); 51 | 52 | /*** 53 | * 递归的创建目录 54 | * @dirpath: 需要创建的目录 55 | * @permissions: 目录权限 56 | * @exception: 出错则抛出CSyscallException 57 | */ 58 | static void create_directory_recursive(const char* dirpath, mode_t permissions=DIRECTORY_DEFAULT_PERM); 59 | 60 | /*** 61 | * 根据文件路径,递归的创建目录 62 | * @dirpath: 文件路径 63 | * @permissions: 目录权限 64 | * @exception: 出错则抛出CSyscallException 65 | */ 66 | static void create_directory_byfilepath(const char* filepath, mode_t permissions=DIRECTORY_DEFAULT_PERM); 67 | }; 68 | 69 | SYS_NAMESPACE_END 70 | #endif // MOOON_SYS_DIR_UTILS_H 71 | -------------------------------------------------------------------------------- /tools/zk_download.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/11/09 2 | // 将一个zookeeper节点的数据写入到本地文件 3 | #include 4 | #include 5 | 6 | // 指定配置文件参数 7 | STRING_ARG_DEFINE(conf, "", "The local configuration file path, example: --conf=/tmp/dist.conf"); 8 | 9 | // 指定存储配置文件的zookeeper 10 | STRING_ARG_DEFINE(zookeeper, "", "The zookeeper nodes, example: --zookeeper=127.0.0.1:2181,127.0.0.2:2181"); 11 | 12 | // 指定存储配置的zookeeper节点(需有写权限) 13 | STRING_ARG_DEFINE(zkpath, "", "The path of zookeeper, example: --zkpath=/tmp/a"); 14 | 15 | int main(int argc, char* argv[]) 16 | { 17 | std::string confdata; 18 | std::string errmsg; 19 | 20 | // 解析命令行参数 21 | if (!mooon::utils::parse_arguments(argc, argv, &errmsg)) 22 | { 23 | if (!errmsg.empty()) 24 | fprintf(stderr, "%s\n", errmsg.c_str()); 25 | fprintf(stderr, "%s\n", mooon::utils::g_help_string.c_str()); 26 | exit(0); 27 | } 28 | 29 | // --conf 30 | if (mooon::argument::conf->value().empty()) 31 | { 32 | fprintf(stderr, "Parameter[--conf] is not set\n"); 33 | fprintf(stderr, "%s\n", mooon::utils::g_help_string.c_str()); 34 | exit(0); 35 | } 36 | 37 | // --zookeeper 38 | if (mooon::argument::zookeeper->value().empty()) 39 | { 40 | fprintf(stderr, "Parameter[--zookeeper] is not set\n"); 41 | fprintf(stderr, "%s\n", mooon::utils::g_help_string.c_str()); 42 | exit(0); 43 | } 44 | 45 | // --zkpath 46 | if (mooon::argument::zkpath->value().empty()) 47 | { 48 | fprintf(stderr, "Parameter[--zkpath] is not set\n"); 49 | fprintf(stderr, "%s\n", mooon::utils::g_help_string.c_str()); 50 | exit(0); 51 | } 52 | 53 | try 54 | { 55 | mooon::net::CZookeeperHelper zookeeper; 56 | zookeeper.create_session(mooon::argument::zookeeper->value()); 57 | const int n = zookeeper.store_data(mooon::argument::conf->value(), mooon::argument::zkpath->value(), false); 58 | fprintf(stdout, "bytes: %d\n", n); 59 | return 0; 60 | } 61 | catch (mooon::sys::CSyscallException& ex) 62 | { 63 | fprintf(stderr, "%s\n", ex.str().c_str()); 64 | exit(1); 65 | } 66 | catch (mooon::utils::CException& ex) 67 | { 68 | fprintf(stderr, "%s\n", ex.str().c_str()); 69 | exit(1); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /test/utils/ut_tokener.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | MOOON_NAMESPACE_USE 3 | 4 | void print(const std::string& source, const std::string& sep, bool skip_sep=false) 5 | { 6 | std::vector tokens; 7 | int num_tokens = utils::CTokener::split(&tokens, source, sep, skip_sep); 8 | 9 | printf("source[%s]:\n", source.c_str()); 10 | for (int i=0; i 22 | #include 23 | #include 24 | #include 25 | #include 26 | UTILS_NAMESPACE_BEGIN 27 | 28 | class CRegexHelper 29 | { 30 | public: 31 | // cflags可选值:REG_EXTENDED, REG_ICASE, REG_NOSUB, REG_NEWLINE,可多个按位组合 32 | // 出错抛异常CException 33 | CRegexHelper(const char* pattern, int cflags=REG_EXTENDED); 34 | ~CRegexHelper(); 35 | std::string get_error_message(int errcode); 36 | 37 | // eflags可选值:REG_NOTBOL, REG_NOTEOL,两种可按位组合 38 | bool match(const char* str, int eflags=REG_NOTBOL); 39 | 40 | private: 41 | regex_t _regex; 42 | }; 43 | 44 | CRegexHelper::CRegexHelper(const char* pattern, int cflags) 45 | { 46 | int errcode = regcomp(&_regex, pattern, cflags); 47 | if (errcode != 0) 48 | THROW_EXCEPTION(get_error_message(errcode), errcode); 49 | } 50 | 51 | CRegexHelper::~CRegexHelper() 52 | { 53 | regfree(&_regex); 54 | } 55 | 56 | bool CRegexHelper::match(const char* str, int eflags) 57 | { 58 | regmatch_t match[1]; 59 | int errcode = regexec(&_regex, str, 1, match, eflags); 60 | return (0 == errcode); 61 | } 62 | 63 | std::string CRegexHelper::get_error_message(int errcode) 64 | { 65 | char errbuf[1024]; 66 | regerror(errcode, &_regex, errbuf, sizeof(errbuf)-1); 67 | return errbuf; 68 | } 69 | 70 | UTILS_NAMESPACE_END 71 | #endif // MOOON_UTILS_REGEX_HELPER_H 72 | -------------------------------------------------------------------------------- /tools/USAGE.txt: -------------------------------------------------------------------------------- 1 | Linux批量远程命令和上传下载工具 2 | 3 | mooon_ssh:批量远程命令工具,在多台机器上执行指定命令 4 | mooon_upload:批量远程上传工具,上传单个或多个文件到单台或多台机器 5 | mooon_download:批量远程下载工具,从指定机器下载一个或多个文件 6 | 7 | mooon-tools-glibc2.17.tar.gz 64位版本,glibc为2.17 8 | mooon-tools-glibc2.4.tar.gz 32位版本,glibc2.4,常常可用于64位版本glibc2.17环境。 9 | 10 | 建议复制到目录/usr/local/bin,或在/usr/local/bin目录下解压,以方便所有用户直接使用,而不用指定文件路径。 11 | 12 | 可以通过环境变量或参数方式指定连接远程机器的用户名、密码和IP地址或IP地址列表,但参数方式优先: 13 | 1) 环境变量H等同参数-h,用于指定远程机器的IP或IP列表,多个IP间以逗号分隔,但mooon_download只能指定一个IP 14 | 2) 环境变量U等同参数-u,用于指定连接远程机器的用户名 15 | 3) 环境变量P等同参数-p,用于指定远程机器的用户密码 16 | 4) 环境变量PORT等同参数-P,用于指定远程机器的端口号 17 | 18 | 环境变量方式和参数方式可以混合使用,即部分通过环境变量设置值,部分以参数方式指定值。 19 | 并建议,参数值尽可能使用单引号,以避免需要对值进行转义处理,除非值本身已包含了单引号。 20 | 21 | 如果使用双引号,则需要做转义,如批量kill掉java进程: 22 | mooon_ssh -c="kill \$(/usr/local/jdk/bin/jps|awk /DataNode/'{print \$1}')" 23 | 24 | 另外,低版本glibc不兼容高版本的glibc,因此glibc2.4的不能用于glibc2.17环境,64位版本也不能用于32位环境。 25 | 64位系统上查看glibc版本方法:/lib64/libc.so.6 26 | 32位系统上查看glibc版本方法:/lib/libc.so.6 27 | 28 | 参数无顺序要求,不带任何参数执行即可查看使用帮助,如: 29 | $ mooon_ssh 30 | parameter[-c]'s value not set 31 | usage: 32 | -P[22/10,65535]: remote hosts port, e.g., -P=22. You can also set environment `PORT` instead of `-P`, e.g., export PORT=1998 33 | -c[]: command to execute remotely, e.g., -c='grep ERROR /tmp/*.log' 34 | -h[]: remote hosts separated by comma, e.g., -h='192.168.1.10,192.168.1.11'. You can also set environment `H` instead of `-h`, e.g., export H=192.168.1.10,192.168.1.11 35 | -p[]: remote host password, e.g., -p='password'. You can also set environment `P` instead of `-p`, e.g., export P=123456 36 | -t[60/1,65535]: timeout seconds to remote host, e.g., -t=100 37 | -u[]: remote host user name, e.g., -u=root. You can also set environment `U` instead of `-u`, e.g., export U=zhangsan 38 | 39 | 对于整数类型的参数,均设有默认值和取值范围,如“-P[22/10,65535]”表示默认值为,取值范围为10~65535。对于字符串类型参数,如果为空中括号“[]”,则表示无默认值,否则中括号“[]”中的内容为默认值,如“-u[root]”表示参数“-u”的默认值为root。 40 | 41 | mooon_ssh使用示例: 42 | 1) 参数方式 43 | mooon_ssh -u=root -p='mypassword' -h=192.168.31.2,192.168.31.3 -c='whoami' 44 | 2) 环境变量方式 45 | export U=root 46 | export P='mypassword' 47 | export H=192.168.31.2,192.168.31.3 48 | mooon_ssh -c='whoami' 49 | 3) 混合方式 50 | export U=root 51 | export P='mypassword' 52 | mooon_ssh -c='whoami' -h=192.168.31.2 53 | 54 | mooon_upload和mooon_download使用方法类似。 55 | 56 | 远程批量添加一条crontab方法: 57 | mooon_ssh -c='echo -e "`crontab -l`\n* * * * * touch /tmp/x.txt" | crontab -' 58 | 完成后,crontab中将添加如下一行: 59 | * * * * * touch /tmp/x.txt 60 | -------------------------------------------------------------------------------- /include/mooon/sys/stop_watch.h: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2015/6/17 2 | // 秒表用于计时 3 | #ifndef MOOON_SYS_STOP_WATCH_H 4 | #define MOOON_SYS_STOP_WATCH_H 5 | #include "mooon/sys/config.h" 6 | #include 7 | SYS_NAMESPACE_BEGIN 8 | 9 | class CStopWatch; 10 | typedef void (*StopWatchTick)(CStopWatch*, void*); 11 | 12 | // 计时器 13 | class CStopWatch 14 | { 15 | public: 16 | CStopWatch(StopWatchTick tick=NULL, void* tick_data=NULL) 17 | : _tick(tick), _tick_data(tick_data) 18 | { 19 | restart(); 20 | 21 | _stop_time.tv_sec = 0; 22 | _stop_time.tv_usec = 0; 23 | _total_time.tv_sec = _start_time.tv_sec; 24 | _total_time.tv_usec = _start_time.tv_usec; 25 | } 26 | 27 | ~CStopWatch() 28 | { 29 | if (_tick != NULL) 30 | (*_tick)(this, _tick_data); 31 | } 32 | 33 | // 重新开始计时 34 | void restart() 35 | { 36 | (void)gettimeofday(&_start_time, NULL); 37 | } 38 | 39 | // 返回微秒级的耗时 40 | // restart 调用之后是否重新开始计时 41 | uint64_t get_elapsed_microseconds(bool restart=true) 42 | { 43 | (void)gettimeofday(&_stop_time, NULL); 44 | const int64_t elapsed_microseconds = static_cast((_stop_time.tv_sec - _start_time.tv_sec) * (__UINT64_C(1000000)) + (_stop_time.tv_usec - _start_time.tv_usec)); 45 | 46 | // 重计时 47 | if (restart) 48 | { 49 | _start_time.tv_sec = _stop_time.tv_sec; 50 | _start_time.tv_usec = _stop_time.tv_usec; 51 | } 52 | if (elapsed_microseconds < 0) 53 | return 0; 54 | else 55 | return static_cast(elapsed_microseconds); 56 | } 57 | 58 | uint64_t get_total_elapsed_microseconds() 59 | { 60 | (void)gettimeofday(&_stop_time, NULL); 61 | const uint64_t total_elapsed_microseconds = static_cast((_stop_time.tv_sec - _total_time.tv_sec) * (__UINT64_C(1000000)) + (_stop_time.tv_usec - _total_time.tv_usec)); 62 | return total_elapsed_microseconds; 63 | } 64 | 65 | // 相当于time(NULL) 66 | // 得到构造时系统的当前时间 67 | time_t get_start_seconds() const 68 | { 69 | return _total_time.tv_sec; 70 | } 71 | 72 | private: 73 | StopWatchTick _tick; 74 | void* _tick_data; 75 | struct timeval _total_time; 76 | struct timeval _start_time; 77 | struct timeval _stop_time; 78 | }; 79 | 80 | SYS_NAMESPACE_END 81 | #endif // MOOON_SYS_STOP_WATCH_H 82 | -------------------------------------------------------------------------------- /src/utils/exception.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #include "utils/exception.h" 20 | #include "utils/string_utils.h" 21 | #include 22 | UTILS_NAMESPACE_BEGIN 23 | 24 | CException::CException(const char* errmsg, int errcode, const char* file, int line) throw () 25 | { 26 | init(errmsg, errcode, file, line); 27 | } 28 | 29 | CException::CException(const std::string& errmsg, int errcode, const std::string& file, int line) throw () 30 | { 31 | init(errmsg.c_str(), errcode, file.c_str(), line); 32 | } 33 | 34 | const char* CException::what() const throw () 35 | { 36 | return _errmsg.c_str(); 37 | } 38 | 39 | const char* CException::file() const throw () 40 | { 41 | return _file.c_str(); 42 | } 43 | 44 | int CException::line() const throw () 45 | { 46 | return _line; 47 | } 48 | 49 | int CException::errcode() const throw () 50 | { 51 | return _errcode; 52 | } 53 | 54 | std::string CException::str() const throw () 55 | { 56 | std::stringstream ss; 57 | ss << prefix() << "[" << _errcode << "]" << _errmsg << "@" << _file << ":" << _line; 58 | 59 | return ss.str(); 60 | } 61 | 62 | std::string CException::prefix() const throw () 63 | { 64 | return "exception://"; 65 | } 66 | 67 | void CException::init(const char* errmsg, int errcode, const char* file, int line) throw () 68 | { 69 | if (errmsg != NULL) 70 | _errmsg = errmsg; 71 | _errcode = errcode; 72 | 73 | _line = line; 74 | if (file != NULL) 75 | { 76 | _file = utils::CStringUtils::extract_filename(file); 77 | } 78 | } 79 | 80 | UTILS_NAMESPACE_END 81 | -------------------------------------------------------------------------------- /include/mooon/utils/sha_helper.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_UTILS_SHA_HELPER_H 20 | #define MOOON_UTILS_SHA_HELPER_H 21 | #include "mooon/utils/string_utils.h" 22 | #include 23 | #include 24 | UTILS_NAMESPACE_BEGIN 25 | 26 | enum SHAType 27 | { 28 | SHA0 = 0, // Invalid 29 | SHA1 = 1, 30 | SHA224 = 224, 31 | SHA256 = 256, 32 | SHA384 = 384, 33 | SHA512 = 512 34 | }; 35 | 36 | SHAType int2shatype(int n); 37 | 38 | class CSHAHelper 39 | { 40 | public: 41 | static std::string sha(SHAType sha_type, const char* format, ...) __attribute__((format(printf, 2, 3))); 42 | static std::string lowercase_sha(SHAType sha_type, const char* format, ...) __attribute__((format(printf, 2, 3))); 43 | static std::string uppercase_sha(SHAType sha_type, const char* format, ...) __attribute__((format(printf, 2, 3))); 44 | 45 | public: 46 | CSHAHelper(SHAType sha_type); 47 | ~CSHAHelper(); 48 | SHAType sha_type() const { return _sha_type; } 49 | 50 | void update(const char* str, size_t size); 51 | void update(const std::string& str); 52 | 53 | public: 54 | void to_string(std::string* str, bool uppercase=true) const; 55 | std::string to_string(bool uppercase=true) const; 56 | 57 | private: 58 | SHAType _sha_type; 59 | void* _sha_context; 60 | }; 61 | 62 | std::string lowercase_hmac_sha256(const std::string &key, const std::string &data); 63 | std::string uppercase_hmac_sha256(const std::string &key, const std::string &data); 64 | 65 | UTILS_NAMESPACE_END 66 | #endif // MOOON_UTILS_SHA_HELPER_H 67 | -------------------------------------------------------------------------------- /test/net/ut_tcp_client.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "mooon/net/utils.h" 20 | #include "mooon/sys/utils.h" 21 | #include "mooon/net/tcp_client.h" 22 | #include "mooon/utils/string_utils.h" 23 | MOOON_NAMESPACE_USE 24 | 25 | // 需要两个参数: 26 | // argv[1]: 连接IP地址 27 | // argv[2]: 连接的端口号 28 | int main(int argc, char* argv[]) 29 | { 30 | uint16_t port; 31 | net::ip_address_t ip; 32 | net::CTcpClient client; 33 | 34 | if (argc != 3) 35 | { 36 | fprintf(stderr, "usage: %s ip port\n" 37 | , sys::CUtils::get_program_short_name()); 38 | exit(1); 39 | } 40 | 41 | ip = argv[1]; 42 | if (!utils::CStringUtils::string2uint16(argv[2], port)) 43 | { 44 | fprintf(stderr, "Invalid port: %s.\n", argv[2]); 45 | exit(1); 46 | } 47 | 48 | try 49 | { 50 | // 设置IP和端口 51 | client.set_peer_ip(ip); 52 | client.set_peer_port(port); 53 | 54 | // 执行连接 55 | client.timed_connect(); 56 | fprintf(stdout, "Connected %s:%d success.\n", ip.to_string().c_str(), port); 57 | 58 | while (true) 59 | { 60 | // 从标准输出读入数据,并发送给远端 61 | char line[LINE_MAX]; 62 | fgets(line, sizeof(line)-1, stdin); 63 | 64 | client.send(line, strlen(line)); 65 | } 66 | } 67 | catch (sys::CSyscallException& ex) 68 | { 69 | // 连接异常退出 70 | fprintf(stderr, "exception %s at %s:%d.\n", ex.str().c_str(), ex.file(), ex.line()); 71 | exit(1); 72 | } 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | libmooon是一个C++静态工具类库,编译和安装libmooon需CMake, 2 | 且CMake版本不低于2.8.11,CMake的下载地址:https://cmake.org/download/。 3 | 如果是C++11或以上开发环境,libmooon中的一些设施可直接使用C++标准库提供的, 4 | 比如std::thread替代mooon::sys::CThreadEngine,std::mutex替代mooon::sys::CLock等, 5 | 建议尽量使用标准库提供的设施,libmooon诞生于C++11之前,可用于C++11之前的开发环境。 6 | 7 | 使用CMake编译和安装libmooon分三个步骤: 8 | 1)执行cmake命令生成Makefile文件,命令格式:cmake -DCMAKE_INSTALL_PREFIX= . 9 | 2)执行make命令编译libmooon源代码 10 | 3)执行make install安装头文件和库文件等 11 | 12 | libmooon所依赖的第三方库是可选的,即使第三方库不存在,也能正常编译libmooon,但会缺乏相应的功能模块, 13 | 比如在执行cmake命令时,未能检测到MySQL,则src/sys/mysql_db.cpp实际为空,同时对应的宏MOOON_HAVE_MYSQL值为0, 14 | 也支持cmake命令行参数指定第三库的安装位置,如:cmake DMYSQL_HOME=/home/mike/mysql 15 | 16 | “-DCMAKE_INSTALL_PREFIX=”后跟安装目录,如/usr/local/mooon: 17 | cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=/usr/local/mooon . 18 | 19 | 如果以debug方式编译,指定参数:-DCMAKE_BUILD_TYPE=Debug 20 | 如果以Release方式编译,指定参数:-DCMAKE_BUILD_TYPE=Release 21 | 22 | 如果机器上没有cmake工具,则需要先安装好。 23 | 对于可连接外网和支持yum的机器只需要执行“yum install cmake”即可安装cmake, 24 | 否则可从https://cmake.org/download/下载后手工安装。 25 | 26 | 注意:使用静态库时有顺序要求,假设静态库libx.a依赖于libz.a, 27 | 则指定顺序须为-lx -lz(或libx.a libz.a),不能反过来为-lz -lx(或libz.a libx.a), 28 | 当然也可以使用链接参数“-Wl,--startgroup”和“-Wl,--endgroup”忽略静态库的顺序。 29 | 30 | 当前libmooon.a直接依赖的可选第三方库列表: 31 | 1)curl(src/sys/curl_wrapper.cpp,curl又依赖openssl、c-ares和libidn) 32 | 2)mysql(src/sys/mysql_db.cpp) 33 | 3)sqlite3(src/sys/sqlite3_db.cpp) 34 | 4)zookeeper(include/net/zookeeper_helper.h) 35 | 5)thrift(include/net/thrift_helper.h,thrift又依赖openssl、libevent和boost) 36 | 6)openssl(src/utils/aes_helper.cpp,thrift也依赖openssl) 37 | 7)libssh2(sys/net/libssh2.cpp,libssh2又依赖openssl) 38 | 39 | 可将所有直接和间接依赖的第三方库安装到“/usr/local”目录下, 40 | 这样在执行cmake命令行时,将自动发现它们, 41 | 比如mysql的安装目录为“/usr/local/mysql”, 42 | zookeeper的安装目录为“/usr/local/zookeeper”。 43 | 44 | 以下第三方库,libmooon库本身未直接和间接依赖,因此不是必须的: 45 | 1)hiredis 46 | 2)r3c 47 | 3)leveldb 48 | 4)protobuf 49 | 5)rapidxml 50 | 6)rapidjson 51 | 7)jsoncpp 52 | 8)Sparsehash 53 | 9)gperftools 54 | 10)libunwind 55 | 11)Cgicc 56 | 57 | 附: 58 | C++版本批量命令工具(支持并行) 59 | https://github.com/eyjian/libmooon/blob/master/tools/mooon_ssh.cpp 60 | C++版本批量上传工具(支持并行) 61 | https://github.com/eyjian/libmooon/blob/master/tools/mooon_upload.cpp 62 | C++版本批量下载工具: 63 | https://github.com/eyjian/libmooon/blob/master/tools/mooon_download.cpp 64 | 65 | GO版本批量命令工具 66 | https://github.com/eyjian/libmooon/blob/master/tools/mooon_ssh.go 67 | GO版本批量上传工具 68 | https://github.com/eyjian/libmooon/blob/master/tools/mooon_upload.go 69 | -------------------------------------------------------------------------------- /include/mooon/utils/exception.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_UTILS_EXCEPTION_H 20 | #define MOOON_UTILS_EXCEPTION_H 21 | #include "mooon/utils/string_formatter.h" 22 | #include 23 | #include 24 | 25 | // 抛出CException异常 26 | #define THROW_EXCEPTION(errmsg, errcode) \ 27 | throw ::mooon::utils::CException(errmsg, errcode, __FILE__, __LINE__) 28 | 29 | // 抛出用户定制异常 30 | #define THROW_CUSTOM_EXCEPTION(errmsg, errcode, exception_class) \ 31 | throw exception_class(errmsg, errcode, __FILE__, __LINE__) 32 | 33 | UTILS_NAMESPACE_BEGIN 34 | 35 | // 异常基类,继承自标准库的exception 36 | class CException: public std::exception 37 | { 38 | public: 39 | // errmsg 错误信息 40 | // errcode 错误代码 41 | // file 发生错误的源代码文件 42 | // line 发生错误的代码行号 43 | CException(const char* errmsg, int errcode, const char* file, int line) throw (); 44 | CException(const std::string& errmsg, int errcode, const std::string& file, int line) throw (); 45 | virtual ~CException() throw () {} 46 | 47 | virtual const char* what() const throw (); 48 | const char* file() const throw (); 49 | int line() const throw (); 50 | int errcode() const throw (); 51 | 52 | // 返回一个可读的字符串 53 | virtual std::string str() const throw (); 54 | 55 | private: 56 | virtual std::string prefix() const throw (); 57 | 58 | private: 59 | void init(const char* errmsg, int errcode, const char* file, int line) throw (); 60 | 61 | protected: 62 | std::string _errmsg; 63 | int _errcode; 64 | std::string _file; 65 | int _line; 66 | }; 67 | 68 | UTILS_NAMESPACE_END 69 | #endif // MOOON_UTILS_EXCEPTION_H 70 | -------------------------------------------------------------------------------- /shell/check_table_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # writed by yijian on 2015/9/10 3 | # 批量检查表大小(记录数)脚本 4 | # 可以针对单个库的所有表,也可以针对所有库的所有表 5 | 6 | db_host=127.0.0.1 7 | db_port=3306 8 | db_user=root 9 | db_password= 10 | db_name= 11 | 12 | if test "$1" = "--help"; then 13 | # 用法1:指定所有参数,依次为DB的IP地址、访问DB的用户名、访问DB的密码、DB的端口号和库名称 14 | echo "usage1: check_table_size.sh db_host db_user db_password db_port db_name" 15 | # 用法2:不指定用户名、密码、端口和库名参数,默认用户名为root,默认密码为空,默认端口号为3306,默认检查所有库 16 | echo "usage2: check_table_size.sh db_host, default [root: root, passowrd empty, port: 3306, all databases]" 17 | # 用法3:不指定密码、端口和库名参数,默认密码为空,默认端口号为3306,默认检查所有库 18 | echo "usage3: check_table_size.sh db_host db_user, default [passowrd empty, port: 3306, all databases]" 19 | # 用法4:不指定端口和库名参数,默认端口号为3306,默认检查所有库 20 | echo "usage4: check_table_size.sh db_host db_user db_password, default [port: 3306, all databases]" 21 | # 使用示例: 22 | echo "example: ./check_table_size.sh 127.0.0.1 root 'test!~@' 3306" 23 | exit 1 24 | fi 25 | 26 | # 如果命令行参数指定了 27 | if test $# -gt 0; then 28 | db_host=$1 29 | fi 30 | if test $# -gt 1; then 31 | db_user=$2 32 | fi 33 | if test $# -gt 2; then 34 | db_password=$3 35 | fi 36 | if test $# -gt 3; then 37 | db_port=$4 38 | fi 39 | if test $# -gt 4; then 40 | db_name=$5 41 | fi 42 | 43 | # 如果没有指定库名,则检查所有库 44 | databases=$db_name 45 | if test -z $db_name; then 46 | echo "mysql -h$db_host -P$db_port -u$db_user -p$db_password" 47 | databases=`mysql -h$db_host -P$db_port -u$db_user -p$db_password -e"show databases"` 48 | if test $? -ne 0; then 49 | exit 1 50 | fi 51 | fi 52 | 53 | # 存放结果的文件 54 | table_size_file=./.table_size.txt 55 | if test $table_size_file; then 56 | rm -f $table_size_file 57 | fi 58 | 59 | for database in $databases 60 | do 61 | if test $database != "Database"; then 62 | tables=`mysql -h$db_host -P$db_port -u$db_user -p$db_password $database -e"show tables"` 63 | if test $? -eq 0; then 64 | for table in $tables 65 | do 66 | if test $table != "Tables_in_$database"; then 67 | echo "checking table[$database.$table] ..." 68 | table_size=`mysql -h$db_host -P$db_port -u$db_user -p$db_password $database -e"SELECT count(1) FROM $table"` 69 | table_size=`echo $table_size |cut -d' ' -f2` 70 | echo "$table_size $database.$table" >> $table_size_file 71 | echo "table[$database.$table] size is $table_size" 72 | fi 73 | done 74 | fi 75 | fi 76 | done 77 | 78 | if test -f $table_size_file; then 79 | sort -r -n $table_size_file 80 | #rm -f $table_size_file 81 | fi 82 | -------------------------------------------------------------------------------- /src/net/ip_address.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "net/utils.h" 20 | #include "net/ip_address.h" 21 | NET_NAMESPACE_BEGIN 22 | 23 | std::string ip_address_t::to_string() const 24 | { 25 | return _is_ipv6? net::CUtils::ipv6_tostring(_ip_data): net::CUtils::ipv4_tostring(_ip_data[0]); 26 | } 27 | 28 | uint32_t ip_address_t::to_ipv4() const 29 | { 30 | return _ip_data[0]; 31 | } 32 | 33 | const uint32_t* ip_address_t::to_ipv6() const 34 | { 35 | return _ip_data; 36 | } 37 | 38 | size_t ip_address_t::get_address_data_length() const 39 | { 40 | return _is_ipv6? 16: 4; 41 | } 42 | 43 | const uint32_t* ip_address_t::get_address_data() const 44 | { 45 | return _ip_data; 46 | } 47 | 48 | bool ip_address_t::is_zero_address() const 49 | { 50 | return !_is_ipv6 && (0 == _ip_data[0]); 51 | } 52 | 53 | bool ip_address_t::is_broadcast_address() const 54 | { 55 | return CUtils::is_broadcast_address(to_string().c_str()); 56 | } 57 | 58 | void ip_address_t::from_string(const char* ip) 59 | { 60 | if (NULL == ip) 61 | { 62 | _is_ipv6 = false; 63 | _ip_data[0] = 0; 64 | _ip_data[1] = 0; 65 | _ip_data[2] = 0; 66 | _ip_data[3] = 0; 67 | } 68 | else if (net::CUtils::string_toipv4(ip, _ip_data[0])) 69 | { 70 | _is_ipv6 = false; 71 | _ip_data[1] = 0; 72 | _ip_data[2] = 0; 73 | _ip_data[3] = 0; 74 | } 75 | else if (net::CUtils::string_toipv6(ip, _ip_data)) 76 | { 77 | _is_ipv6 = true; 78 | } 79 | else 80 | { 81 | THROW_EXCEPTION(ip, EINVAL); 82 | } 83 | } 84 | 85 | NET_NAMESPACE_END 86 | -------------------------------------------------------------------------------- /test/sys/ut_datetime_utils.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "mooon/sys/datetime_utils.h" 20 | SYS_NAMESPACE_USE 21 | 22 | int main() 23 | { 24 | struct tm datetime_struct; 25 | const char* str = "2010-09-18 17:28:30"; 26 | 27 | if (!CDatetimeUtils::datetime_struct_from_string(str, &datetime_struct)) 28 | printf("ERROR datetime_struct_from_string: %s\n", str); 29 | else 30 | printf("%s ==> \n" 31 | "\tyear=%04d\n" 32 | "\tmonth=%02d\n" 33 | "\tday=%02d\n" 34 | "\thour=%02d\n" 35 | "\tminitue=%02d\n" 36 | "\tsecond=%02d\n" 37 | ,str 38 | ,datetime_struct.tm_year+1900 39 | ,datetime_struct.tm_mon+1 40 | ,datetime_struct.tm_mday 41 | ,datetime_struct.tm_hour 42 | ,datetime_struct.tm_min 43 | ,datetime_struct.tm_sec); 44 | 45 | time_t dt = mktime(&datetime_struct); 46 | if (-1 == dt) 47 | printf("Error mktime\n"); 48 | else 49 | { 50 | struct tm result; 51 | localtime_r(&dt, &result); 52 | 53 | printf("%ld ==> \n" 54 | "\tyear=%04d\n" 55 | "\tmonth=%02d\n" 56 | "\tday=%02d\n" 57 | "\thour=%02d\n" 58 | "\tminitue=%02d\n" 59 | "\tsecond=%02d\n" 60 | ,dt 61 | ,result.tm_year+1900 62 | ,result.tm_mon+1 63 | ,result.tm_mday 64 | ,result.tm_hour 65 | ,result.tm_min 66 | ,result.tm_sec); 67 | } 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /shell/set_zookeeper_id.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # https://github.com/eyjian/libmooon 3 | # Created by yijian on 2018/10/10 4 | # 根据IP设置zookeeper的myid, 5 | # 结合mooon_ssh和mooon_upload两个工具,可实现批量操作 6 | # 7 | # 参数1: 8 | # IP和机器名映射关系配置文件 9 | # 参数2: 10 | # 全路径方式的远端myid文件 11 | # 12 | # 先按正常步骤部署好zookeeper, 13 | # 在运行本工具时,会按照映射关系配置文件中定义的进行自动创建和设置myid, 14 | # 结合mooon_ssh和mooon_upload避免了一台台机器低效修改。 15 | # 16 | # 使用方法: 17 | # 1)利用mooon_upload,批量将本脚本文件发布到所有目标机器(需要修改hostname的机器)上 18 | # 2)利用mooon_upload,批量将映射关系配置文件发布到所有目标机器上 19 | # 3)利用mooon_ssh,批量执行本脚本完成主机名设置 20 | # 21 | # 使用示例: 22 | # mooon_ssh -c='/tmp/set_zookeeper_id.sh /tmp/hosts.id /data/zookeeper/data/myid' 23 | 24 | # 本机IP所在网卡 25 | ethX=eth1 26 | 27 | # 参数检查 28 | if test $# -ne 2; then 29 | echo -e "\033[1;33musage\033[m:\n`basename $0` conffile myid" 30 | echo "" 31 | echo "conffile format:" 32 | echo "IP + separator + ID" 33 | echo "" 34 | echo "example:" 35 | echo "192.168.31.1 1" 36 | echo "192.168.31.2 2" 37 | echo "192.168.31.3 3" 38 | echo "" 39 | echo "available separators: space, TAB, semicolon, comma, vertical line" 40 | exit 1 41 | fi 42 | 43 | # 远端的Zookeeper的myid,需要包含全路径 44 | myid=$2 45 | 46 | # 检查配置文件是否存在和可读 47 | conffile=$1 48 | if test ! -f $conffile; then 49 | echo -e "file \`$conffile\` \033[0;32;31mnot exists\033[m" 50 | exit 1 51 | fi 52 | if test ! -r $conffile; then 53 | echo -e "file \`$conffile\` \033[0;32;31mno permission to read\033[m" 54 | exit 1 55 | fi 56 | 57 | # 取本机IP需要用到netstat 58 | which netstat > /dev/null 2>&1 59 | if test $? -ne 0; then 60 | echo "\`netstat\` command \033[0;32;31mnot available\033[m" 61 | exit 1 62 | fi 63 | 64 | # 需要有写权限 65 | if test ! -w $kafkaconf; then 66 | echo "can not write $kafkaconf, or $kafkaconf not exits" 67 | exit 1 68 | fi 69 | 70 | # 取本地IP 71 | local_ip=`netstat -ie|awk -F'[ :]+' -v ethX=$ethX 'BEGIN{ok=0;} {if (match($0, ethX)) ok=1; if ((1==ok) && match($0,"inet")) { ok=0; if (7==NF) printf("%s\n",$3); else printf("%s\n",$4); } }'` 72 | if test -z "$local_ip"; then 73 | echo "can not get local IP of \`$ethX\`" 74 | exit 1 75 | fi 76 | 77 | # 读取文件,找到本机待设置的新主机名 78 | while read line 79 | do 80 | if test -z "$line"; then 81 | break 82 | fi 83 | 84 | eval $(echo $line |awk -F'[ \t|,;]+' '{ printf("ip=%s\nid=%s\n", $1, $2); }') 85 | #echo "[IP] => $ip [ID] => $id" 86 | if test "$ip" = "$local_ip"; then 87 | echo "$ip => $id" 88 | echo "$id" > $myid 89 | exit 0 90 | fi 91 | done < $conffile 92 | 93 | echo "no item for $local_ip" 94 | exit 1 95 | -------------------------------------------------------------------------------- /include/mooon/utils/aes_helper.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Writed on 2015/7/16 18 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 19 | */ 20 | #ifndef MOOON_UTILS_AES_HELPER_H 21 | #define MOOON_UTILS_AES_HELPER_H 22 | #include "mooon/utils/exception.h" 23 | UTILS_NAMESPACE_BEGIN 24 | 25 | // 高级加密标准(Advanced Encryption Standard), 26 | // 在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准,用来替代DES 27 | // 注意: 28 | // CAESHelper基于AES_encrypt和AES_decrypt实现, 29 | // 会对加密的Key和加解密的数据进行自动填充,以满足算法的要求。 30 | // 如果被加密的数据不是16字节或16字节整数倍, 31 | // 则由decrypt解密后的数据长度会大于加密前的,调用者需要处理好。 32 | // 更好的是基于EVP系列的实现,可以参考: 33 | // https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption 34 | class CAESHelper 35 | { 36 | public: 37 | // 加密数据块分组长度,必须为128比特(即4×4的字节矩阵), 38 | // 密钥长度可以是128比特、192比特、256比特中的任意一个 39 | static const int aes_block_size; 40 | 41 | public: 42 | // key 密钥,填充模式为zeropadding 43 | // 44 | // 因为AES要求key长度只能为128或192或256比特中的一种,即16字节或24字节或32字节中的一种, 45 | // 当key的长度不足16字节时,CAESHelper自动补0足16字节, 46 | // 当key的长度间于16字节和24字节时,CAESHelper自动补0足24字节, 47 | // 当key的长度间于24字节和32字节时,CAESHelper自动补0足32字节, 48 | // 当key的长度超出32字节时,CAESHelper自动截取前32字节作为密钥 49 | CAESHelper(const std::string& key); 50 | ~CAESHelper(); 51 | 52 | // encrypt和decrypt为ECB模式(电子密码本模式)的加解密 53 | void encrypt(const std::string& in, std::string* out); // 注意out为二进制数据 54 | void decrypt(const std::string& in, std::string* out); // in对应encrypt的out 55 | 56 | private: 57 | // flag 为true表示加密,为false表示解密 58 | void aes(bool flag, const std::string& in, std::string* out, void* aes_key); 59 | 60 | private: 61 | void* _encrypt_key; 62 | void* _decrypt_key; 63 | std::string _key; 64 | }; 65 | 66 | UTILS_NAMESPACE_END 67 | #endif // MOOON_UTILS_AES_HELPER_H 68 | -------------------------------------------------------------------------------- /include/mooon/net/listener.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_NET_LISTENER_H 20 | #define MOOON_NET_LISTENER_H 21 | #include "mooon/net/ip_node.h" 22 | #include "mooon/net/epollable.h" 23 | NET_NAMESPACE_BEGIN 24 | 25 | /*** 26 | * TCP服务端监听者类 27 | * 用于启动在某端口上的监听和接受连接请求 28 | */ 29 | class CListener: public CEpollable 30 | { 31 | public: 32 | /** 构造一个TCP监控者 */ 33 | CListener(); 34 | 35 | /** 是否为IPV6监听者 */ 36 | bool is_ipv6() const throw () { return _ip.is_ipv6(); } 37 | 38 | /*** 39 | * 启动在指定IP和端口上的监听 40 | * @ip: 监听IP地址 41 | * @port: 监听端口号 42 | * @enabled_address_zero: 是否允许在0.0.0.0上监听,安全起见,默认不允许 43 | * @exception: 如果发生错误,则抛出CSyscallException异常 44 | */ 45 | void listen(const ip_address_t& ip, uint16_t port, bool nonblock=true, bool enabled_address_zero=false, bool reuse_port=false); 46 | void listen(const ipv4_node_t& ip_node, bool nonblock=true, bool enabled_address_zero=false, bool reuse_port=false); 47 | void listen(const ipv6_node_t& ip_node, bool nonblock=true, bool enabled_address_zero=false, bool reuse_port=false); 48 | 49 | /*** 50 | * 接受连接请求 51 | * @peer_ip: 用来存储对端的IP地址 52 | * @peer_port: 用来存储对端端口号 53 | * @return: 新的SOCKET句柄 54 | * @exception: 如果发生错误,则抛出CSyscallException异常 55 | */ 56 | int accept(ip_address_t& peer_ip, uint16_t& peer_port); 57 | 58 | /** 得到监听的IP地址 */ 59 | const ip_address_t& get_listen_ip() const throw () { return _ip; } 60 | 61 | /** 得到监听的端口号 */ 62 | uint16_t get_listen_port() const throw () { return _port; } 63 | 64 | private: 65 | uint16_t _port; 66 | ip_address_t _ip; 67 | }; 68 | 69 | NET_NAMESPACE_END 70 | #endif // MOOON_NET_LISTENER_H 71 | -------------------------------------------------------------------------------- /include/mooon/helper/rapidjson_helper.h: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2021/5/3 2 | #ifndef MOOON_HELPER_RAPIDJSON_HELPER_H 3 | #define MOOON_HELPER_RAPIDJSON_HELPER_H 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | namespace mooon { 12 | 13 | // 使用 schema 效验 JSON 格式 14 | // 实践时,可以使用 Linux 自带的工具 xxd 将 schema 记录在专门文件, 15 | // 然后将该文件编译成 cpp 源代码文件,以 cmake 为例: 16 | // # 将 mooon.schema 编译成 cpp 文件 17 | // exec_program( 18 | // xxd 19 | // ${CMAKE_CURRENT_SOURCE_DIR} 20 | // ARGS 21 | // -i mooon.schema mooon_schema.cpp 22 | // RETURN_VALUE errcode 23 | // ) 24 | // if (errcode) 25 | // return () 26 | // endif () 27 | inline std::shared_ptr 28 | str2rapidjson(const std::string& json_str, const std::string& schema_str, std::string* errmsg) 29 | { 30 | std::shared_ptr doc(new rapidjson::Document); 31 | 32 | if (doc->Parse(json_str.c_str()).HasParseError()) 33 | { 34 | doc.reset(); 35 | if (errmsg != NULL) 36 | *errmsg = "parse JSON error, it is not a JSON format"; 37 | } 38 | else if (!schema_str.empty()) 39 | { 40 | // 指定了 schema 41 | rapidjson::Document schema_doc; 42 | 43 | if (schema_doc.Parse(schema_str.c_str()).HasParseError()) 44 | { 45 | // schema 格式有问题 46 | doc.reset(); 47 | if (errmsg != NULL) 48 | *errmsg = "parse SCHEMA error, it is not a JSON format"; 49 | } 50 | else 51 | { 52 | rapidjson::SchemaDocument schema(schema_doc); 53 | rapidjson::SchemaValidator validator(schema); 54 | 55 | if (!doc->Accept(validator)) 56 | { 57 | if (errmsg != NULL) 58 | { 59 | // 不满足 schema 规则 60 | rapidjson::StringBuffer sb1, sb2; 61 | validator.GetInvalidSchemaPointer().StringifyUriFragment(sb1); 62 | validator.GetInvalidDocumentPointer().StringifyUriFragment(sb2); 63 | *errmsg = mooon::utils::CStringUtils::format_string("validate error (%s, %s, %s)", 64 | sb1.GetString(), validator.GetInvalidSchemaKeyword(), sb2.GetString()); 65 | } 66 | doc.reset(); 67 | } 68 | } 69 | } 70 | return doc; 71 | } 72 | 73 | } // namespace mooon { 74 | #endif // MOOON_HELPER_RAPIDJSON_HELPER_H 75 | -------------------------------------------------------------------------------- /test/utils/ut_string_utils.cpp: -------------------------------------------------------------------------------- 1 | #include "mooon/utils/string_utils.h" 2 | UTILS_NAMESPACE_USE 3 | 4 | int main() 5 | { 6 | // 测试string2int32函数 7 | printf("\n>>>>>>>>>>TEST string2int32<<<<<<<<<<\n\n"); 8 | 9 | // 测试1 10 | int result1; 11 | const char* str1 = "123456"; 12 | if (CStringUtils::string2int32(str1, result1)) 13 | printf("%s ===> %d\n", str1, result1); 14 | else 15 | printf("ERROR string2int32: %s\n", str1); 16 | 17 | // 测试2 18 | int result2; 19 | const char* str2 = "123a456"; 20 | if (CStringUtils::string2int32(str2, result2)) 21 | printf("%s ===> %d\n", str2, result2); 22 | else 23 | printf("ERROR string2int32: %s\n", str2); 24 | 25 | // 测试3 26 | int result3; 27 | const char* str3 = "123a456"; 28 | if (CStringUtils::string2int32(str3, result3, 3)) 29 | printf("%s ===> %d\n", str3, result3); 30 | else 31 | printf("ERROR string2int32: %s\n", str3); 32 | 33 | 34 | // 测试4 35 | int result4; 36 | const char* str4 = "-123456"; 37 | if (CStringUtils::string2int32(str4, result4)) 38 | printf("%s ===> %d\n", str4, result4); 39 | else 40 | printf("ERROR string2int32: %s\n", str4); 41 | 42 | // 测试5 43 | int result5; 44 | const char* str5 = "0123456"; 45 | if (CStringUtils::string2int32(str5, result5)) 46 | printf("%s ===> %d\n", str5, result5); 47 | else 48 | printf("ERROR string2int32: %s\n", str5); 49 | 50 | // 测试6 51 | int result6; 52 | const char* str6 = "-0"; 53 | if (CStringUtils::string2int32(str6, result6)) 54 | printf("%s ===> %d\n", str6, result6); 55 | else 56 | printf("ERROR string2int32: %s\n", str6); 57 | 58 | // 测试7 59 | int result7; 60 | const char* str7 = "-023"; 61 | if (CStringUtils::string2int32(str7, result7)) 62 | printf("%s ===> %d\n", str7, result7); 63 | else 64 | printf("ERROR string2int32: %s\n", str7); 65 | 66 | printf("\n\n>>>>>>>>>>TEST trim/trim_left/trim_right<<<<<<<<<<\n\n"); 67 | 68 | // 测试8 69 | char str8[] = " def"; 70 | printf("abc%s\n", str8); 71 | CStringUtils::trim_left(str8); 72 | printf("abc%s\n", str8); 73 | 74 | // 测试9 75 | char str9[] = "abc "; 76 | printf("%sdef\n", str9); 77 | CStringUtils::trim_right(str9); 78 | printf("%sdef\n", str9); 79 | 80 | // 测试10 81 | char str10[] = " 456 "; 82 | printf("123%s789\n", str10); 83 | CStringUtils::trim(str10); 84 | printf("123%s789\n", str10); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /include/mooon/sys/shared_memory.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_SYS_SHARED_MEMORY_H 20 | #define MOOON_SYS_SHARED_MEMORY_H 21 | #include "mooon/sys/syscall_exception.h" 22 | #include 23 | #include 24 | #include 25 | SYS_NAMESPACE_BEGIN 26 | 27 | /** System V共享内存C++包装类 */ 28 | class CSysVSharedMemory 29 | { 30 | public: 31 | CSysVSharedMemory() throw (); 32 | /*** 33 | * 打开一个已经存在的共享内存 34 | * @path: 用来创建共享内存的路径(包含文件名),不能为NULL 35 | * @exception: 如果出错则抛出CSyscallException异常 36 | */ 37 | void open(const char* path); 38 | 39 | /*** 40 | * 创建一个共享内存 41 | * @path: 用来创建共享内存的路径(包含文件名),如果为NULL则由系统选择独一无二的 42 | * @mode: 权限模式,其值为S_IRWXU和S_IXUSR等 43 | * @return: 如果已经存在则返回false,否则返回true 44 | * @exception: 如果出错则抛出CSyscallException异常 45 | */ 46 | bool create(const char* path, mode_t mode=IPC_DEFAULT_PERM); 47 | 48 | /*** 49 | * 关闭已经创建或打开的共享内存, 50 | * 如果已经没有进程关联到此共享内存,则删除它 51 | * @exception: 如果出错则抛出CSyscallException异常 52 | */ 53 | void close(); 54 | 55 | /*** 56 | * 解除和共享内存的关联,将共享内存从进程空间中移除 57 | * @exception: 如果出错则抛出CSyscallException异常 58 | */ 59 | void detach(); 60 | 61 | /*** 62 | * 关联共享内存,将共享内存映射到进程空间 63 | * @exception: 如果出错则抛出CSyscallException异常 64 | */ 65 | void* attach(int flag); 66 | 67 | /*** 68 | * 得到共享内存的地址 69 | * @return: 如果已经关联则返回指向共享内存的地址,否则返回NULL 70 | */ 71 | void* get_shared_memoty_address(); 72 | void* get_shared_memoty_address() const; 73 | 74 | private: 75 | int _shmid; 76 | void* _shmaddr; /** attach的共享内存地址 */ 77 | }; 78 | 79 | SYS_NAMESPACE_END 80 | #endif // MOOON_SYS_SHARED_MEMORY_H 81 | -------------------------------------------------------------------------------- /src/sys/signal_handler.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #include "sys/signal_handler.h" 20 | SYS_NAMESPACE_BEGIN 21 | 22 | //////////////////////////////////////////////////////////////////////////////// 23 | // 以下是CSignalHandler的实现 24 | // ,将它放在示例代码之后,是为了方便看到如何使用CSignalHandler。 25 | 26 | sigset_t CSignalHandler::_sigset; 27 | std::vector CSignalHandler::_signo_array; 28 | 29 | bool CSignalHandler::ignore_signal(int signo) throw () 30 | { 31 | return signal(signo, SIG_IGN) != SIG_ERR; 32 | } 33 | 34 | bool CSignalHandler::block_signal(int signo) throw () 35 | { 36 | if (_signo_array.empty()) 37 | { 38 | // 初始化_sigset 39 | if (-1 == sigemptyset(&_sigset)) 40 | { 41 | return false; 42 | } 43 | } 44 | 45 | if (-1 == sigaddset(&_sigset, signo)) 46 | { 47 | return false; 48 | } 49 | else 50 | { 51 | errno = pthread_sigmask(SIG_BLOCK, &_sigset, NULL); 52 | if (errno != 0) 53 | { 54 | return false; 55 | } 56 | else 57 | { 58 | _signo_array.push_back(signo); 59 | return true; 60 | } 61 | } 62 | } 63 | 64 | int CSignalHandler::wait_signal() throw () 65 | { 66 | int signo; // 发生的信号 67 | sigset_t sigset; 68 | 69 | // 初始化sigset 70 | if (-1 == sigemptyset(&sigset)) 71 | { 72 | return -1; 73 | } 74 | 75 | // 设置sigset 76 | for (std::vector::size_type i=0; i<_signo_array.size(); ++i) 77 | { 78 | if (-1 == sigaddset(&sigset, _signo_array[i])) 79 | { 80 | return -1; 81 | } 82 | } 83 | 84 | // 等待信号发生 85 | errno = sigwait(&sigset, &signo); 86 | if (errno != 0) 87 | { 88 | return -1; 89 | } 90 | 91 | return signo; 92 | } 93 | 94 | SYS_NAMESPACE_END 95 | -------------------------------------------------------------------------------- /include/mooon/sys/compiler.h: -------------------------------------------------------------------------------- 1 | #ifndef __H_COMPILER_H_ 2 | #define __H_COMPILER_H_ 3 | 4 | #ifndef MIN 5 | #define MIN(a,b) ((ab) ? (a) : (b)) 10 | #endif 11 | 12 | #if __x86_64__ 13 | #define INT2PTR(x) ((void *)(long)(x)) 14 | #define PTR2INT(x) ((int)(long)(x)) 15 | #define PTR2UINT(x) ((unsigned int)(long)(x)) 16 | #else 17 | #define INT2PTR(x) ((void *)(x)) 18 | #define PTR2INT(x) ((int)(x)) 19 | #define PTR2UINT(x) ((unsigned int)(x)) 20 | #endif 21 | 22 | 23 | #if __x86_64__ 24 | #define F64 "l" 25 | #else 26 | #define F64 "ll" 27 | #endif 28 | 29 | #if __GNUC__ < 3 30 | #error You need GCC 3.0 or above to compile. 31 | #endif 32 | 33 | #undef __attr_cdecl__ 34 | #if __x86_64__ 35 | #define __attr_cdecl__ /* */ 36 | #else 37 | #define __attr_cdecl__ __attribute__((__cdecl__)) 38 | #endif 39 | 40 | #undef __attr_regparm__ 41 | #define __attr_regparm__(x) __attribute__((__regparm__(x))) 42 | 43 | #undef __attr_const__ 44 | #define __attr_const__ __attribute__((__const__)) 45 | 46 | #undef __attr_pure__ 47 | #define __attr_pure__ __attribute__((__pure__)) 48 | 49 | #undef __attr_nonnull__ 50 | #define __attr_nonnull__ __attribute__((__nonnull__)) 51 | 52 | #undef __attr_malloc__ 53 | #define __attr_malloc__ __attribute__((__malloc__)) 54 | 55 | #undef __attr_printf__ 56 | #define __attr_printf__(x,y) __attribute__((__format__(printf,x,y))) 57 | 58 | #undef __align1__ 59 | #undef __align2__ 60 | #undef __align4__ 61 | #undef __align8__ 62 | #define __align1__ __attribute__((__aligned__(1))) 63 | #define __align2__ __attribute__((__aligned__(2))) 64 | #define __align4__ __attribute__((__aligned__(4))) 65 | #define __align8__ __attribute__((__aligned__(8))) 66 | #if __WORDSIZE==64 67 | #define __align__ __attribute__((__aligned__(8))) 68 | #else 69 | #define __align__ __attribute__((__aligned__(4))) 70 | #endif 71 | 72 | #if USE_LINKSCRIPT 73 | #define __init__ __attribute__((section(".hdata"))) 74 | #else 75 | #define __init__ /* */ 76 | #endif 77 | 78 | #ifndef likely 79 | #define likely(x) __builtin_expect(!!(x), 1) 80 | #endif 81 | #ifndef unlikely 82 | #define unlikely(x) __builtin_expect(!!(x), 0) 83 | #endif 84 | 85 | #if __WORDSIZE==64 86 | struct stat; 87 | typedef struct stat stat64_t; 88 | #else 89 | struct stat64; 90 | typedef struct stat64 stat64_t; 91 | #endif 92 | 93 | #define BADADDR(x) ((unsigned long )x > (unsigned long)-4096) 94 | 95 | #if __GNUC__ < 4 96 | static inline void barrier(void) { __asm__ volatile("":::"memory"); } 97 | #else 98 | static inline void barrier(void) { __sync_synchronize (); } 99 | #endif 100 | 101 | #endif 102 | -------------------------------------------------------------------------------- /shell/log_rotater.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # https://github.com/eyjian/mooon/blob/master/mooon/shell/log_rotater.sh 3 | # Writed by yijian on 2012/7/22 4 | # 5 | # Linux自带的工具logrotate使用稍复杂,但功能强大 6 | # 7 | # 本脚本功能: 8 | # 1) 实现一个通用的按大小的日志滚动 9 | # 2) 要求日志文件扩展名为“.log”,否则请稍修改代码 10 | # 3) 支持处理多个目录下的日志文件,如果需要使用这个功能, 11 | # 必须启用dirs_list参数 12 | # 13 | # 为何要写一个这样的东东? 14 | # 答:因为在日常中,经常发现程序输出重定向, 15 | # 或脚本的输出,如果不处理的话,就可能导致 16 | # 单个文件过大,甚至爆满整个磁盘;而每套脚本 17 | # 都重复写一个日志滚动逻辑,显然是件无聊的事, 18 | # 甚至一些人懒得做处理,日子一久,就会发现一个超大的 19 | # 日志文件,本脚本希望可以帮助解决这个问题,让大家无 20 | # 后顾之忧。 21 | # 22 | # 使用方法: 23 | # 1) 把脚本复制到日志文件所在目录, 24 | # 然后以nohup ./log_rotater.sh > /dev/null & 等方式启动脚本即可 25 | # 2) 除了上面的方法,也可以将log_rotater.sh任何目录下, 26 | # 但这个时候,应当将backup_dir的值修改为日志文件所在目录 27 | # 28 | # sudo dpkg-reconfigure dash 29 | # 新版本Ubuntu默认使用dash作为shell, 30 | # 这个shell功能较弱,不支持数组等,但速度快, 31 | # 可采取如下办法检测是何种shell: 32 | # ls -l `which sh` 33 | 34 | # BASEDIR为脚本所在目录 35 | BASEDIR=$(dirname $(readlink -f $0)) 36 | 37 | # 可根据需要修改以下参数 38 | backup_count=10 # 日志滚动的个数 39 | backup_size=$((1024 * 1024 * 200)) # 单个日志文件大小 40 | backup_interval=60 # 检测的间隔时间,单位为秒 41 | 42 | # 如果dirs_list指定的文件存在,则从dirs_list中读取目录, 43 | # 否则仅处理backup_dir指定的单个目录 44 | # 往dirs_list指定文件增减目录时,不需要重启log_rotater.sh 45 | backup_dir="." # 日志文件所在目录 46 | dirs_list="$BASEDIR/dirs.list" # 存储目录列表的文件,要求一行一个目录 47 | 48 | handle_single_file() 49 | { 50 | filename="$1" 51 | 52 | # 用到了awk给外部变量赋值的特性 53 | eval $(ls -l --time-style=long-iso "$filename" 2>/dev/null|awk '{ printf("filesize=%s\nfiledate=%s\n", $5,$6); }') 54 | if test $? -ne 0; then 55 | return 56 | fi 57 | if test -z "$filename"; then 58 | return 59 | fi 60 | 61 | if test $filesize -gt $backup_size; then 62 | file_index=$(($backup_count - 1)) 63 | while test $file_index -gt 1; do 64 | new_filename="${filename}.$file_index" 65 | old_filename="${filename}.$(($file_index - 1))" 66 | if test -f "$old_filename"; then 67 | mv "$old_filename" "$new_filename" 68 | fi 69 | 70 | file_index=$(($file_index - 1)) 71 | done 72 | 73 | # 这里需要使用truncate,而不能使用mv, 74 | # 因为需要保持文件的inode不变 75 | cp "$filename" "${filename}.1" 76 | truncate -s 1024 "$filename" 77 | fi 78 | } 79 | 80 | # 处理单个目录下的日志滚动 81 | scan_single_dir() 82 | { 83 | dir="$1" 84 | 85 | files=`ls *.log 2>/dev/null` 86 | for file in $files; do 87 | handle_single_file "$file" 88 | done 89 | 90 | sleep 1 91 | } 92 | 93 | # 循环检测 94 | while true; do 95 | if test ! -f $dirs_list; then 96 | scan_single_dir "$backup_dir" 97 | else 98 | while read dirpath 99 | do 100 | scan_single_dir "$dirpath" 101 | done < $dirs_list 102 | fi 103 | 104 | sleep $backup_interval 105 | done 106 | -------------------------------------------------------------------------------- /include/mooon/net/udp_socket.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_NET_UDP_SOCKET_H 20 | #define MOOON_NET_UDP_SOCKET_H 21 | #include "mooon/net/epollable.h" 22 | NET_NAMESPACE_BEGIN 23 | 24 | // UDP不分服务端和客户端, 25 | // 但如果仅做服务端或即做服务端又做客户端时,都必须调用listen(), 26 | // 仅做客户端使用时,可不必调用listen() 27 | // 多数设备以太网链路层MTU(最大传输单元)大小为1500(但标准为576),IP包头为20,TCP包头为20,UDP包头8 28 | // 29 | // 1500为链路层的数据大小,不包括链路层首部和尾部的18个字节,这1500实际为网络层(IP层)的数据大小 30 | // IP首部为20字节,所以IP数据大小为1480, 31 | // UDP首部8字节,所以UDP数据大小为1472,当UDP发送大小1472的数据时,链路层需要分片(Fragment),这样IP层需要重组数据,可能会重组失败导致数据丢失 32 | // 33 | // 标准的MTU大小为576(Windows默认为1500),减去IP首部和UDP首部后为548,因此UDP发送的数据大小不超过548是最安全的。 34 | class CUdpSocket: public CEpollable 35 | { 36 | public: 37 | CUdpSocket(); 38 | void listen(uint16_t port, bool nonblock=false, bool reuse_port=false); 39 | void listen(const std::string& ip, uint16_t port, bool nonblock=false, bool reuse_port=false); 40 | 41 | // to_ip 目标IP,要求为网络字节序 42 | // to_port 目标端口,同样要求为主机字节序 43 | int send_to(const void* buffer, size_t buffer_size, uint32_t to_ip, uint16_t to_port); 44 | int send_to(const void* buffer, size_t buffer_size, const char* to_ip, uint16_t to_port); 45 | int send_to(const void* buffer, size_t buffer_size, const struct sockaddr_in& to_addr); 46 | 47 | // from_ip 返回的源IP,为网络字节序 48 | // from_port 返回的源端口,为主机字节序 49 | // 出错抛出异常,成功返回接收的字节数,如果返回-1表示为非阻塞模式没有数据可接收 50 | int receive_from(void* buffer, size_t buffer_size, uint32_t* from_ip, uint16_t* from_port); 51 | int receive_from(void* buffer, size_t buffer_size, struct sockaddr_in* from_addr); 52 | 53 | int timed_receive_from(void* buffer, size_t buffer_size, uint32_t* from_ip, uint16_t* from_port, uint32_t milliseconds); 54 | int timed_receive_from(void* buffer, size_t buffer_size, struct sockaddr_in* from_addr, uint32_t milliseconds); 55 | }; 56 | 57 | NET_NAMESPACE_END 58 | #endif // MOOON_NET_UDP_SOCKET_H 59 | -------------------------------------------------------------------------------- /shell/install_crontab.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # writed by yijian on 2013/1/19 3 | # generic script used to install an iterm into crontab 4 | # http://code.google.com/p/mooon/source/browse/trunk/common_library/shell/install_crontab.sh 5 | 6 | # $monitor_name used to monitor the process named by $process_name, 7 | # if $process_name is hangup, $monitor_name will reboot it by $start_name. 8 | # before using $monitor_name, $process_name should be running, 9 | # the installation will get the path information automatically. 10 | # **PLEASE NOTE**: all files must be placed in the same directory. 11 | process_name=$1 # the fullname of process monitored (but not included directory) 12 | monitor_name=$2 # the path of monitor script (maybe included directory) 13 | start_name=$3 # the path of start script (maybe included directory) 14 | timedate_fields=$4 # five time and date fields 15 | me=`whoami` 16 | 17 | # check cmdline 18 | if test $# -ne 4; then 19 | echo "usage: process_name monitor_name start_name time_date" 20 | echo "EXAMPLE1: $0 mooon process_monitor.sh start_test.sh \"* * * * *\"" 21 | echo "EXAMPLE2: $0 mooon /tmp/process_monitor.sh /tmp/start_test.sh \"* * * * *\"" 22 | echo "monitor_name or start_name must be in the same directory with process_name, " 23 | echo "if monitor_name or start_name don't include directory" 24 | exit 1 25 | fi 26 | 27 | # get pid & username 28 | eval $(ps -C $process_name h -o pid,euser | awk -F" " '{ printf("pid=%s\nuser=%s\n",$1,$2); }') 29 | if test $? -ne 0; then 30 | echo "$process_name NOT RUNNING now" 31 | exit 1 32 | fi 33 | 34 | if test "X$me" != "X$user"; then 35 | echo "$process_name NOT RUNNING now" 36 | exit 1 37 | fi 38 | 39 | # get file path 40 | filepath=`readlink /proc/$pid/exe` 41 | if test $? -ne 0; then 42 | exit 1 43 | fi 44 | 45 | # get directory path 46 | binpath=`dirname $filepath` 47 | 48 | # check files 49 | if test -x $monitor_name; then 50 | monitor_path=$monitor_name 51 | else 52 | monitor_path=$binpath/$monitor_name 53 | fi 54 | if test -x $start_name; then 55 | start_path=$start_name 56 | else 57 | start_path=$binpath/$start_name 58 | fi 59 | 60 | if test ! -x $monitor_path; then 61 | echo "$monitor_path not exist" 62 | exit 1 63 | fi 64 | if test ! -x $start_path; then 65 | echo "$start_path not exist" 66 | exit 1 67 | fi 68 | 69 | # install crontab if not exist 70 | crontab -l | grep "$start_path" > /dev/null 2>&1 71 | if test $? -ne 0; then 72 | crontab -l > crontab.tmp 73 | echo -e "\n# the following monitor added by `basename $0`($process_name) on `date +"%Y-%m-%d %H:%M:%S"`" >> crontab.tmp 74 | echo "$timedate_fields $monitor_path $process_name $start_path" >> crontab.tmp 75 | crontab crontab.tmp 76 | if test $? -ne 0; then 77 | exit 1 78 | fi 79 | 80 | rm crontab.tmp 81 | fi 82 | 83 | exit 0 84 | -------------------------------------------------------------------------------- /include/mooon/sys/ref_countable.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #ifndef MOOON_SYS_REF_COUNTABLE_H 20 | #define MOOON_SYS_REF_COUNTABLE_H 21 | #include "mooon/sys/config.h" 22 | #include "mooon/sys/atomic.h" 23 | SYS_NAMESPACE_BEGIN 24 | 25 | /*** 26 | * 引用计数基类 27 | * 不应当直接使用此类,而应当总是从它继承 28 | */ 29 | class CRefCountable 30 | { 31 | public: 32 | CRefCountable() 33 | { 34 | atomic_set(&_refcount, 0); 35 | } 36 | 37 | /** 虚拟析构函数是必须的,否则无法删除子类对象 */ 38 | virtual ~CRefCountable() 39 | { 40 | } 41 | 42 | /** 得到引用计数值 */ 43 | int get_refcount() const 44 | { 45 | return atomic_read(&_refcount); 46 | } 47 | 48 | /** 对引用计数值增一 */ 49 | void inc_refcount() 50 | { 51 | atomic_inc(&_refcount); 52 | } 53 | 54 | /*** 55 | * 对引用计数值减一 56 | * 如果引用计数值减一后,引用计数值变成0,则对象自删除 57 | * @return: 如果对象自删除,则返回true,否则返回false 58 | */ 59 | bool dec_refcount() 60 | { 61 | volatile bool deleted = false; 62 | if (atomic_dec_and_test(&_refcount)) 63 | { 64 | deleted = true; 65 | delete this; 66 | } 67 | 68 | return deleted; 69 | } 70 | 71 | private: 72 | atomic_t _refcount; 73 | }; 74 | 75 | /*** 76 | * 引用计数帮助类,用于自动减引用计数 77 | */ 78 | template 79 | class CRefCountHelper 80 | { 81 | public: 82 | /*** 83 | * 对引用计数增一 84 | * 析构时会将ref_countable指向NULL 85 | */ 86 | CRefCountHelper(RefCountClass*& ref_countable) 87 | :_ref_countable(ref_countable) 88 | { 89 | if (ref_countable != NULL) 90 | ref_countable->inc_refcount(); 91 | } 92 | 93 | /** 析构函数,自动减引用计数 */ 94 | ~CRefCountHelper() 95 | { 96 | if (_ref_countable != NULL) 97 | { 98 | _ref_countable->dec_refcount(); 99 | _ref_countable = NULL; 100 | } 101 | } 102 | 103 | private: 104 | RefCountClass*& _ref_countable; 105 | }; 106 | 107 | SYS_NAMESPACE_END 108 | #endif // MOOON_SYS_REF_COUNTABLE_H 109 | -------------------------------------------------------------------------------- /include/mooon/sys/semaphore.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_SYS_SEMAPHORE_H 20 | #define MOOON_SYS_SEMAPHORE_H 21 | #include "mooon/sys/syscall_exception.h" 22 | #include 23 | #include 24 | #include 25 | SYS_NAMESPACE_BEGIN 26 | 27 | /** System V信号量C++包装类 */ 28 | class CSysVSemaphore 29 | { 30 | public: 31 | CSysVSemaphore() throw (); 32 | 33 | /*** 34 | * 打开一个已经存在的信号量 35 | * @path: 用来创建信号量的路径(包含文件名),不能为NULL 36 | * @exception: 如果出错则抛出CSyscallException异常 37 | */ 38 | void open(const char* path); 39 | 40 | /*** 41 | * 创建一个信号量 42 | * @path: 用来创建信号量的路径(包含文件名),如果为NULL则由系统选择独一无二的 43 | * @init_value: 初始值 44 | * @mode: 权限模式,其值为S_IRWXU和S_IXUSR等 45 | * @return: 如果已经存在则返回false,否则返回true 46 | * @exception: 如果出错则抛出CSyscallException异常 47 | */ 48 | bool create(const char* path, int16_t init_value=0, mode_t mode=IPC_DEFAULT_PERM); 49 | 50 | /*** 51 | * 删除信号量 52 | * @exception: 如果出错则抛出CSyscallException异常 53 | */ 54 | void remove(); 55 | 56 | /*** 57 | * 信号量V操作,对信号量进行增操作,如果相加结果信号量值不小于0,则不阻塞 58 | * @exception: 如果出错则抛出CSyscallException异常 59 | */ 60 | void verhoog(uint16_t value); 61 | 62 | /*** 63 | * 信号量P操作,对信号量减操作,如果减后仍大于或等于0,则不阻塞,否则阻塞 64 | * @exception: 如果出错则抛出CSyscallException异常 65 | */ 66 | void passeren(uint16_t value); 67 | 68 | /*** 69 | * 尝试进行信号量P操作 70 | * @return: 如果P操作成功返回true,否则返回false 71 | * @exception: 如果出错则抛出CSyscallException异常 72 | */ 73 | bool try_passeren(uint16_t value); 74 | 75 | /*** 76 | * 超时方式进行信号量P操作 77 | * @milliseconds: 等待超时的毫秒数 78 | * @return: 如果在指定的时间内成功,则返回true,否则返回false 79 | * @exception: 如果出错则抛出CSyscallException异常 80 | */ 81 | bool timed_passeren(uint16_t value, int milliseconds); 82 | 83 | private: 84 | bool semaphore_operation(int value, int flag, int milliseconds); 85 | 86 | private: 87 | int _semid; /** 信号量句柄 */ 88 | }; 89 | 90 | SYS_NAMESPACE_END 91 | #endif // MOOON_SYS_SEMAPHORE_H 92 | -------------------------------------------------------------------------------- /include/mooon/sys/read_write_lock.h: -------------------------------------------------------------------------------- 1 | #ifndef MOOON_SYS_READ_WRITE_LOCK 2 | #define MOOON_SYS_READ_WRITE_LOCK 3 | #include "mooon/sys/utils.h" 4 | #include 5 | SYS_NAMESPACE_BEGIN 6 | 7 | // 命令行工具debuginfo-install用于安装debug信息,示例(为glibc安装debug信息,以方便跟踪调试):debuginfo-install glibc 8 | 9 | /*** 10 | * 读写锁类 11 | * 请注意: 谁加锁谁解锁原则,即一个线程加的锁,不能由另一线程来解锁 12 | * 而且加锁和解锁必须成对调用,否则会造成死锁 13 | */ 14 | class CReadWriteLock 15 | { 16 | public: 17 | CReadWriteLock(); 18 | ~CReadWriteLock() throw (); 19 | 20 | /*** 21 | * 释放读或写锁 22 | * @exception: 出错抛出CSyscallException异常 23 | */ 24 | void unlock(); 25 | 26 | /*** 27 | * 获取读锁,如果写锁正被持有则一直等待直到可获取到读锁 28 | * 注意同一个线程加了同一个对象的读锁后再加写锁会死锁!!! 29 | * @exception: 出错抛出CSyscallException异常 30 | */ 31 | void lock_read(); 32 | 33 | /*** 34 | * 获取写锁,如果写锁正被持有则一直等待直到可获取到写锁 35 | * 注意同一个线程加了同一个对象的读锁后再加写锁会死锁!!! 36 | * @exception: 出错抛出CSyscallException异常 37 | */ 38 | void lock_write(); 39 | 40 | /*** 41 | * 尝试去获取读锁,如果写锁正被持有则立即返回 42 | * @return: 如果成功获取了读锁,则返回true,否则返回false 43 | * @exception: 出错抛出CSyscallException异常 44 | */ 45 | bool try_lock_read(); 46 | 47 | /*** 48 | * 尝试去获取写锁,如果写锁正被持有则立即返回 49 | * @return: 如果成功获取了写锁,则返回true,否则返回false 50 | * @exception: 出错抛出CSyscallException异常 51 | */ 52 | bool try_lock_write(); 53 | 54 | /*** 55 | * 以超时方式获取读锁,如果写锁正被持有则等待指定的毫秒数, 56 | * 如果在指定的毫秒时间内,仍不能得到读锁,则立即返回 57 | * @millisecond: 等待获取读锁的毫秒数 58 | * @return: 如果在指定的毫秒时间内获取到了读锁,则返回true,否则如果超时则返回false 59 | * @exception: 出错抛出CSyscallException异常 60 | */ 61 | bool timed_lock_read(uint32_t millisecond); 62 | 63 | /*** 64 | * 以超时方式获取写锁,如果写锁正被持有则等待指定的毫秒数, 65 | * 如果在指定的毫秒时间内,仍不能得到写锁,则立即返回 66 | * @millisecond: 等待获取写锁的毫秒数 67 | * @return: 如果在指定的毫秒时间内获取到了写锁,则返回true,否则如果超时则返回false 68 | * @exception: 出错抛出CSyscallException异常 69 | */ 70 | bool timed_lock_write(uint32_t millisecond); 71 | 72 | private: 73 | pthread_rwlock_t _rwlock; 74 | }; 75 | 76 | /*** 77 | * 读锁帮助类,用于自动释放读锁 78 | */ 79 | class ReadLockHelper 80 | { 81 | public: 82 | ReadLockHelper(CReadWriteLock& lock) 83 | :_read_lock(lock) 84 | { 85 | _read_lock.lock_read(); 86 | } 87 | 88 | /** 析构函数,会自动调用unlock解锁 */ 89 | ~ReadLockHelper() 90 | { 91 | _read_lock.unlock(); 92 | } 93 | 94 | private: 95 | CReadWriteLock& _read_lock; 96 | }; 97 | 98 | /*** 99 | * 读锁帮助类,用于自动释放写锁 100 | */ 101 | class WriteLockHelper 102 | { 103 | public: 104 | WriteLockHelper(CReadWriteLock& lock) 105 | :_write_lock(lock) 106 | { 107 | _write_lock.lock_write(); 108 | } 109 | 110 | /** 析构函数,会自动调用unlock解锁 */ 111 | ~WriteLockHelper() 112 | { 113 | _write_lock.unlock(); 114 | } 115 | 116 | private: 117 | CReadWriteLock& _write_lock; 118 | }; 119 | 120 | SYS_NAMESPACE_END 121 | #endif // MOOON_SYS_READ_WRITE_LOCK 122 | -------------------------------------------------------------------------------- /test/net/ut_net_utils.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include 20 | #include 21 | #include 22 | MOOON_NAMESPACE_USE 23 | 24 | void test_host2net() 25 | { 26 | ////////////////////////////////// 27 | printf("\n\nTEST host2net\n"); 28 | ////////////////////////////////// 29 | 30 | // 转换2字节整数 31 | uint16_t b1; 32 | uint16_t a1 = 0x0103; 33 | 34 | net::CUtils::host2net(a1, b1); 35 | printf("a1 = 0x%04x, b1=0x%04x\n", a1, b1); 36 | if (b1 == htons(a1)) /** 和系统库函数比较,以验证是否正确 */ 37 | printf("host2net success\n"); 38 | else 39 | printf("host2net failure\n"); 40 | 41 | // 转换4字节整数 42 | printf("\n"); 43 | uint32_t b2; 44 | uint32_t a2 = 0x01016070; 45 | 46 | net::CUtils::host2net(a2, b2); 47 | printf("a2 = 0x%04x, b2=0x%04x\n", a2, b2); 48 | if (b2 == htonl(a2)) /** 和系统库函数比较,以验证是否正确 */ 49 | printf("host2net success\n"); 50 | else 51 | printf("host2net failure\n"); 52 | 53 | // 按长度转换,应用到单字节字符串上,相当于反转字符串 54 | printf("\n"); 55 | char str[] = "123456789"; 56 | size_t length = strlen(str); 57 | char* dst = new char[length+1]; 58 | utils::DeleteHelper dh(dst, true); // 自动调用delete []dst 59 | net::CUtils::host2net(str, dst, length); 60 | dst[length] = '\0'; 61 | printf("%s ==> %s\n",str, dst); 62 | } 63 | 64 | void test_get_ip_address() 65 | { 66 | ////////////////////////////////// 67 | printf("\n\nTEST test_get_ip_address\n"); 68 | ////////////////////////////////// 69 | 70 | std::string errinfo; 71 | net::string_ip_array_t ip_array; 72 | std::string hostname = "www.sina.com.cn"; 73 | 74 | if (!net::CUtils::get_ip_address(hostname.c_str(), ip_array, errinfo)) 75 | { 76 | fprintf(stderr, "get_ip_address error: %s.\n", errinfo.c_str()); 77 | } 78 | else 79 | { 80 | for (net::string_ip_array_t::size_type i=0; i %s\n", hostname.c_str(), ip_array[i].c_str()); 83 | } 84 | } 85 | } 86 | 87 | int main() 88 | { 89 | test_host2net(); 90 | test_get_ip_address(); 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /include/mooon/net/send_machine.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_NET_SEND_MACHINE_H 20 | #define MOOON_NET_SEND_MACHINE_H 21 | #include 22 | NET_NAMESPACE_BEGIN 23 | 24 | template 25 | class CSendMachine 26 | { 27 | public: 28 | CSendMachine(Connector* connector); 29 | bool is_finish() const; 30 | utils::handle_result_t continue_send(); 31 | utils::handle_result_t send(const char* msg, size_t msg_size); 32 | void reset(bool delete_message); 33 | 34 | private: 35 | Connector* _connector; 36 | 37 | private: 38 | const char* _message; 39 | const char* _cursor; 40 | size_t _remain_size; 41 | }; 42 | 43 | template 44 | CSendMachine::CSendMachine(Connector* connector) 45 | :_connector(connector) 46 | { 47 | reset(false); 48 | } 49 | 50 | // 当前消息是否已经发送完 51 | template 52 | bool CSendMachine::is_finish() const 53 | { 54 | return 0 == _remain_size; 55 | } 56 | 57 | // 发送消息,可能是一个消息的第一次发送,也可能是一个消息的非第一次发送 58 | template 59 | utils::handle_result_t CSendMachine::continue_send() 60 | { 61 | ssize_t bytes_sent = _connector->send(_cursor, _remain_size); 62 | if (bytes_sent > -1) 63 | { 64 | _cursor += bytes_sent; 65 | _remain_size -= bytes_sent; 66 | } 67 | 68 | return is_finish() 69 | ? utils::handle_finish 70 | : utils::handle_continue; 71 | } 72 | 73 | // 发送消息,总是一个消息的第一次发送 74 | // 参数说明: 75 | // msg - 需要发送的消息 76 | // msg_size - 需要发送的消息字节数 77 | template 78 | utils::handle_result_t CSendMachine::send(const char* msg, size_t msg_size) 79 | { 80 | _message = msg; 81 | _cursor = msg; 82 | _remain_size = msg_size; 83 | 84 | return continue_send(); 85 | } 86 | 87 | template 88 | void CSendMachine::reset(bool delete_message) 89 | { 90 | if (delete_message) 91 | delete []_message; 92 | 93 | _message = NULL; 94 | _cursor = NULL; 95 | _remain_size = 0; 96 | } 97 | 98 | NET_NAMESPACE_END 99 | #endif // MOOON_NET_SEND_MACHINE_H 100 | -------------------------------------------------------------------------------- /include/mooon/net/kafka_producer.h: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2018/11/18 2 | #ifndef MOOON_NET_KAFKA_PRODUCER_H 3 | #define MOOON_NET_KAFKA_PRODUCER_H 4 | #if MOOON_HAVE_LIBRDKAFKA==1 // 宏MOOON_HAVE_LIBRDKAFKA的值须为1 5 | #include 6 | #include 7 | #include 8 | #include 9 | NET_NAMESPACE_BEGIN 10 | 11 | class DefDeliveryReportImpl; 12 | class DefEventImpl; 13 | class DefPartitionerImpl; 14 | 15 | // 非线程安全 16 | // 一个CKafkaProducer只能处理一个topic 17 | class CKafkaProducer 18 | { 19 | public: 20 | // CKafkaProducer负责dr_cb、event_cb和partitioner_cb的销毁。 21 | // 22 | // 如果dr_cb为空,则使用DefDeliveryReportImpl作为DeliveryReportCb,每个消息递送成功或失败(如超时)均会调用一次dr_cb, 23 | // 如果event_cb为空,则使用DefEventImpl作为EventCb, 24 | // 如果partitioner_cb为空,则使用DefPartitionerImpl作为PartitionerCb。 25 | CKafkaProducer(RdKafka::DeliveryReportCb* dr_cb=NULL, RdKafka::EventCb* event_cb=NULL, RdKafka::PartitionerCb* partitioner_cb=NULL); 26 | bool init(const std::string& brokers_str, const std::string& topic_str, std::string* errmsg=NULL); 27 | 28 | // 调用produce并不一定立即发送消息,而是将消息放到发送队列中缓存, 29 | // 发送队列大小由配置queue.buffering.max.message指定,如果队列满应调用poll去触发消息发送。 30 | // 31 | // 返回true表示成功 32 | // 返回false为出错,可通过errcode和errmsg得到出错信息 33 | // 34 | // errcode取值: 35 | // 1) RdKafka::ERR_MSG_SIZE_TOO_LARGE 消息字节数超过配置messages.max.bytes指定的值 36 | // 2) RdKafka::ERR__QUEUE_FULL 发送队列满(达到配置queue.buffering.max.message指定的值) 37 | // 3) RdKafka::ERR__UNKNOWN_PARTITION 未知分区 38 | // 4) RdKafka::ERR__UNKNOWN_TOPIC 未知主题 39 | // 40 | // 入队有两种方式: 41 | // 1) 非阻塞方式,如果队列满返回错误代码RD_KAFKA_RESP_ERR__QUEUE_FULL 42 | // 2) 阻塞方式 43 | bool produce(const std::string& key, const std::string& log, int32_t partition=RdKafka::Topic::PARTITION_UA, int* errcode=NULL, std::string* errmsg=NULL); 44 | 45 | // errcode和errmsg存储最近一次的出错信息 46 | // 返回实际数,为0表示一个也没有 47 | int produce_batch(const std::string& key, const std::vector& logs, int32_t partition=RdKafka::Topic::PARTITION_UA, int* errcode=NULL, std::string* errmsg=NULL); 48 | 49 | // librdkafka要求定时调用timed_poll, 50 | // 否则事件不会被回调,消息会被积压(发送队列满,但因为没调用poll,即使数据已发送出去,然而发送队列的状态值没有改变)。 51 | // 返回回调的次数(RdKafka::DeliveryCb、RdKafka::EventCb)。 52 | int timed_poll(int timeout_ms=0); 53 | 54 | // 通过调用timed_poll等待所有的发送完成,直到达到timeout_ms指定的超时时长 55 | // 返回RdKafka::ERR__TIMED_OUT表示达到timeout_ms指定的超时时长 56 | // 会触发回调 57 | int flush(int timeout_ms); 58 | 59 | private: 60 | std::string _brokers_str; 61 | std::string _topic_str; 62 | 63 | private: 64 | mooon::utils::ScopedPtr _global_conf; 65 | mooon::utils::ScopedPtr _topic_conf; 66 | mooon::utils::ScopedPtr _producer; 67 | mooon::utils::ScopedPtr _topic; 68 | 69 | private: 70 | mooon::utils::ScopedPtr _dr_cb; 71 | mooon::utils::ScopedPtr _event_cb; 72 | mooon::utils::ScopedPtr _partitioner_cb; 73 | }; 74 | 75 | NET_NAMESPACE_END 76 | #endif // MOOON_HAVE_LIBRDKAFKA 77 | #endif // MOOON_NET_KAFKA_PRODUCER_H 78 | -------------------------------------------------------------------------------- /src/sys/shared_memory.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "sys/shared_memory.h" 20 | SYS_NAMESPACE_BEGIN 21 | 22 | CSysVSharedMemory::CSysVSharedMemory() throw () 23 | :_shmid(-1) 24 | ,_shmaddr(NULL) 25 | { 26 | } 27 | 28 | void CSysVSharedMemory::open(const char* path) 29 | { 30 | if (NULL == path) 31 | THROW_SYSCALL_EXCEPTION(NULL, EINVAL, NULL); 32 | 33 | key_t key = ftok(path, getpid()); 34 | if (-1 == key) 35 | THROW_SYSCALL_EXCEPTION(NULL, errno, "ftok"); 36 | 37 | _shmid = shmget(key, 1, 0); 38 | if (-1 == _shmid) 39 | THROW_SYSCALL_EXCEPTION(NULL, errno, "shmget"); 40 | } 41 | 42 | bool CSysVSharedMemory::create(const char* path, mode_t mode) 43 | { 44 | key_t key = IPC_PRIVATE; 45 | 46 | // 得到IPC键 47 | if (path != NULL) 48 | { 49 | key_t key = ftok(path, getpid()); 50 | if (-1 == key) 51 | THROW_SYSCALL_EXCEPTION(NULL, errno, "ftok"); 52 | } 53 | 54 | // 创建共享内存 55 | _shmid = shmget(key, 1, IPC_CREAT | IPC_EXCL | mode); 56 | if (-1 == _shmid) 57 | { 58 | if (EEXIST == errno) return false; 59 | THROW_SYSCALL_EXCEPTION(NULL, errno, "shmget"); 60 | } 61 | 62 | return true; 63 | } 64 | 65 | void CSysVSharedMemory::close() 66 | { 67 | if (_shmid != -1) 68 | { 69 | //struct shmid_ds buf; 70 | if (-1 == shmctl(_shmid, IPC_RMID, NULL)) 71 | THROW_SYSCALL_EXCEPTION(NULL, errno, "shmctl"); 72 | 73 | _shmid = -1; 74 | } 75 | } 76 | 77 | void CSysVSharedMemory::detach() 78 | { 79 | if (_shmaddr != NULL) 80 | { 81 | shmdt(_shmaddr); 82 | _shmaddr = NULL; 83 | } 84 | } 85 | 86 | void* CSysVSharedMemory::attach(int flag) 87 | { 88 | if (_shmaddr != NULL) 89 | { 90 | _shmaddr = shmat(_shmid, NULL, flag); 91 | if ((void *)-1 == _shmaddr) 92 | THROW_SYSCALL_EXCEPTION(NULL, errno, "shmat"); 93 | } 94 | 95 | return _shmaddr; 96 | } 97 | 98 | void* CSysVSharedMemory::get_shared_memoty_address() 99 | { 100 | return _shmaddr; 101 | } 102 | 103 | void* CSysVSharedMemory::get_shared_memoty_address() const 104 | { 105 | return _shmaddr; 106 | } 107 | 108 | SYS_NAMESPACE_END 109 | -------------------------------------------------------------------------------- /src/sys/time_thread.cpp: -------------------------------------------------------------------------------- 1 | // Writed by yijian on 2019/2/27 2 | #include "sys/time_thread.h" 3 | #include "sys/log.h" 4 | #include 5 | SYS_NAMESPACE_BEGIN 6 | 7 | SINGLETON_IMPLEMENT(CTimeThread); 8 | 9 | CTimeThread::CTimeThread() 10 | : _stop(false), 11 | _interval_milliseconds(1000), 12 | _engine(NULL) 13 | { 14 | struct timeval tv; 15 | gettimeofday(&tv, NULL); 16 | 17 | #if __WORDSIZE==64 18 | _seconds = static_cast(tv.tv_sec); 19 | _milliseconds = static_cast(tv.tv_usec); 20 | #else 21 | _seconds = static_cast(tv.tv_sec); 22 | _milliseconds = static_cast(tv.tv_usec); 23 | #endif // __WORDSIZE==64 24 | } 25 | 26 | CTimeThread::~CTimeThread() 27 | { 28 | wait(); 29 | } 30 | 31 | int64_t CTimeThread::get_seconds() const 32 | { 33 | #if __WORDSIZE==64 34 | return _seconds.operator int64_t(); 35 | #else 36 | return _seconds.operator int(); 37 | #endif // __WORDSIZE==64 38 | } 39 | 40 | int64_t CTimeThread::get_milliseconds() const 41 | { 42 | #if __WORDSIZE==64 43 | return _milliseconds.operator int64_t(); 44 | #else 45 | return _milliseconds.operator int(); 46 | #endif // __WORDSIZE==64 47 | } 48 | 49 | void CTimeThread::stop() 50 | { 51 | _stop = true; 52 | } 53 | 54 | bool CTimeThread::start(uint32_t interval_milliseconds) 55 | { 56 | try 57 | { 58 | _interval_milliseconds = interval_milliseconds; 59 | _engine = new mooon::sys::CThreadEngine(mooon::sys::bind(&CTimeThread::run, this)); 60 | return true; 61 | } 62 | catch (sys::CSyscallException& ex) 63 | { 64 | MYLOG_ERROR("Start time-thread failed: %s\n", ex.str().c_str()); 65 | return false; 66 | } 67 | } 68 | 69 | void CTimeThread::wait() 70 | { 71 | if (_engine != NULL) 72 | { 73 | _engine->join(); 74 | delete _engine; 75 | _engine = NULL; 76 | } 77 | } 78 | 79 | void CTimeThread::run() 80 | { 81 | struct timeval start_tv, exit_tv; 82 | gettimeofday(&start_tv, NULL); 83 | 84 | MYLOG_INFO("Time-thread start now\n"); 85 | while (!_stop) 86 | { 87 | struct timeval tv; 88 | gettimeofday(&tv, NULL); 89 | 90 | const int64_t milliseconds = static_cast(tv.tv_sec*1000 + tv.tv_usec/1000); 91 | #if __WORDSIZE==64 92 | _seconds = static_cast(tv.tv_sec); 93 | _milliseconds = milliseconds; 94 | #else 95 | _seconds = static_cast(tv.tv_sec); 96 | _milliseconds = static_cast(milliseconds); 97 | #endif // __WORDSIZE==64 98 | 99 | CUtils::millisleep(_interval_milliseconds); 100 | } 101 | 102 | gettimeofday(&exit_tv, NULL); 103 | if (start_tv.tv_sec<=exit_tv.tv_sec || 104 | start_tv.tv_usec<=exit_tv.tv_usec) 105 | { 106 | const uint64_t interval_milliseconds = (exit_tv.tv_sec-start_tv.tv_sec)*1000 + (exit_tv.tv_usec-start_tv.tv_usec)/1000; 107 | MYLOG_INFO("Time-thread exit now: %" PRIu64"ms\n", interval_milliseconds); 108 | } 109 | else 110 | { 111 | MYLOG_INFO("Time-thread exit now\n"); 112 | } 113 | } 114 | 115 | SYS_NAMESPACE_END 116 | -------------------------------------------------------------------------------- /shell/udp_drops.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Writed by yijian on 2018/9/3 3 | # 统计UPD丢包工具 4 | # 可选参数1:统计间隔(单位:秒,默认10秒) 5 | # 可选参数2:是否输出丢包为0的记录,注意有参数1时,参数2才会生效 6 | # 7 | # 运行结果会写日志,日志文件优先存工具相同的目录, 8 | # 但如果没有权限,则选择当前目录, 9 | # 当前目录无权限,则存tmp目录, 10 | # 如果tmp目录还无权限,则报错退出。 11 | # 12 | # 输出格式:统计日期 统计时间 丢包数 13 | # 输出示例: 14 | # 2018-09-03 17:22:49 5 15 | # 2018-09-03 17:22:51 3 16 | # 17 | # 可用UDP测试工具:https://iperf.fr/ 18 | 19 | flag=0 20 | stat_seconds=10 21 | if test $# -gt 2; then 22 | echo "Usage: `basename $0` [seconds] [0|1]" 23 | exit 1 24 | fi 25 | if test $# -gt 1; then 26 | flag=$2 # 值为1表示输出丢包为0的记录 27 | fi 28 | if test $# -gt 0; then 29 | stat_seconds=$1 30 | fi 31 | 32 | # 下段不允许出错 33 | set -e 34 | 35 | # 日志文件 36 | basedir=$(dirname $(readlink -f $0)) 37 | logname=`basename $0 .sh` 38 | logfile=$basedir/$logname.log 39 | if test ! -w $basedir; then 40 | basedir=`pwd` 41 | logfile=$basedir/$logname 42 | 43 | if test ! -w $basedir; then 44 | basedir=/tmp 45 | logfile=$basedir/$logname 46 | fi 47 | fi 48 | 49 | # 备份日志文件 50 | bak_logfile=$logfile.bak 51 | if test -f $logfile; then 52 | rm --interactive=never $logfile 53 | touch $logfile 54 | fi 55 | 56 | # 恢复 57 | set +e 58 | 59 | # 统计哪些网卡,不填写则自动取 60 | #ethX_array=() 61 | # 62 | #if test $# -eq 0; then 63 | # ethX_array=(`cat /proc/net/dev| awk -F[\ \:]+ '/eth/{printf("%s\n",$2);}'`) 64 | #else 65 | # ethX_array=($*) 66 | #fi 67 | 68 | old_num_errors=0 69 | for ((;;)) 70 | do 71 | # 相关命令: 72 | # 1) 查看队列中的包数:netstat –alupt 73 | # 2) 查看socket读缓冲区大小:cat /proc/sys/net/core/rmem_default 74 | # 3) 查看socket读缓冲区大小:cat /proc/sys/net/core/wmem_default 75 | # 4) 查看网卡队列大小:ethtool -g eth1 76 | # 5) 查看arp缓存队列大小:cat /proc/sys/net/ipv4/neigh/eth1/unres_qlen 77 | # 6) 查看CPU负载:mpstat -P ALL 1 或 vmstat 1 或 top 或 htop 或uptime 78 | # 79 | # 取得丢包数 80 | # 命令“cat /proc/net/snmp | grep Udp”比命令“netstat –su”好 81 | # num_drops=`netstat -su | awk -F[\ ]+ 'BEGIN{flag=0;}{ if ($0=="Udp:") flag=1; if ((flag==1) && (match($0, "packet receive errors"))) printf("%s\n", $2); }'` 82 | num_errors=`cat /proc/net/snmp | awk -F'[ ]'+ 'BEGIN{ line=0; }/Udp/{ ++line; if (2==line) printf("%s\n", $4); }'` 83 | 84 | if test $old_num_errors -eq 0; then 85 | old_num_errors=$num_errors 86 | elif test $num_errors -ge $old_num_errors; then 87 | num_drops=$(($num_errors - $old_num_errors)) 88 | 89 | if test $flag -eq 1 -o $num_drops -ne 0; then 90 | line="`date '+%Y-%m-%d %H:%M:%S'` $num_drops" 91 | 92 | # 得到日志文件大小(5368709120 = 5 \* 1024 \* 1024 \* 1024) 93 | logfile_size=`ls -l --time-style=long-iso $logfile 2>/dev/null| awk -F[\ ]+ '{ printf("%s\n", $5); }'` 94 | if test ! -z "$logfile_size"; then 95 | if test $logfile_size -gt 5368709120; then 96 | echo $line | tee -a $logfile 97 | mv $logfile $bak_logfile 98 | rm -f $logfile 99 | fi 100 | fi 101 | 102 | echo $line | tee -a $logfile 103 | fi 104 | fi 105 | 106 | sleep $stat_seconds 107 | done 108 | -------------------------------------------------------------------------------- /include/mooon/utils/integer_utils.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #ifndef MOOON_UTILS_INTEGER_UTILS_H 20 | #define MOOON_UTILS_INTEGER_UTILS_H 21 | #include "mooon/utils/config.h" 22 | #include 23 | UTILS_NAMESPACE_BEGIN 24 | 25 | /*** 26 | * 整数数字操作工具类 27 | */ 28 | class CIntegerUtils 29 | { 30 | public: 31 | template 32 | static bool is_prime_number(DataType x) 33 | { 34 | if (x < 2) 35 | return false; 36 | 37 | DataType k = (DataType)sqrt(x); 38 | for (DataType m=2; m<=k; ++m) 39 | if (0 == x % m) 40 | return false; 41 | 42 | return true; 43 | } 44 | 45 | /** 返回不超过指定宽度的整数,如果超过则溢出从0开始 */ 46 | template 47 | static IntType dec_with_width(IntType m, int width) 48 | { 49 | // __UINT64_C(999999999) 50 | // 使用宏__UINT64_C,编译时需要定义__STDC_LIMIT_MACROS 51 | MOOON_ASSERT(width > 0 && width < 10 && m >= 0); 52 | static uint64_t dec_width_table[] = { (__UINT64_C(0)), (__UINT64_C(9)), (__UINT64_C(99)), (__UINT64_C(999)), (__UINT64_C(9999)), (__UINT64_C(99999)), (__UINT64_C(999999)), (__UINT64_C(9999999)), (__UINT64_C(99999999)), (__UINT64_C(999999999)) }; 53 | return static_cast(m % dec_width_table[width]); 54 | } 55 | 56 | template 57 | static IntType hex_with_width(IntType m, int width) 58 | { 59 | // 0x999999999 == 41231686041 60 | MOOON_ASSERT(width > 0 && width < 10 && m >= 0); 61 | static uint64_t hex_width_table[] = { (__UINT64_C(0x0)), (__UINT64_C(0x9)), (__UINT64_C(0x99)), (__UINT64_C(0x999)), (__UINT64_C(0x9999)), (__UINT64_C(0x99999)), (__UINT64_C(0x999999)), (__UINT64_C(0x9999999)), (__UINT64_C(0x99999999)), (__UINT64_C(0x999999999)) }; 62 | return static_cast(m % hex_width_table[width]); 63 | } 64 | 65 | /** 判断一个数字是否可为int16_t数字 */ 66 | static bool is_int16(int32_t num); 67 | 68 | /** 判断一个数字是否可为uint16_t数字 */ 69 | static bool is_uint16(int32_t num); 70 | static bool is_uint16(uint32_t num); 71 | 72 | /** 判断一个数字是否可为int32_t数字 */ 73 | static bool is_int32(int64_t num); 74 | 75 | /** 判断一个数字是否可为uint32_t数字 */ 76 | static bool is_uint32(int64_t num); 77 | static bool is_uint32(uint64_t num); 78 | }; 79 | 80 | UTILS_NAMESPACE_END 81 | #endif // MOOON_UTILS_INTEGER_UTILS_H 82 | -------------------------------------------------------------------------------- /shell/set_hostname.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # https://github.com/eyjian/mooon 3 | # Created by yijian on 2018/8/10 4 | # 根据IP设置机器名工具, 5 | # 结合mooon_ssh和mooon_upload两个工具,可实现批量操作,需要以root运行 6 | # 7 | # 参数: 8 | # IP和机器名映射关系配置文件 9 | # 10 | # IP和机器名映射关系配置文件格式: 11 | # IP+分隔符+机器名 12 | # 示例: 13 | # 192.168.31.32 zhangsan-32 14 | # 分隔符可为空格、TAB、逗号、分号和竖线这几种 15 | # 16 | # 注意:hadoop要求hostname不能带下划线 17 | # 18 | # 使用方法: 19 | # 1)利用mooon_upload,批量将本脚本文件发布到所有目标机器(需要修改hostname的机器)上 20 | # 2)利用mooon_upload,批量将映射关系配置文件发布到所有目标机器上 21 | # 3)利用mooon_ssh,批量执行本脚本完成主机名设置 22 | # 23 | # 执行示例: 24 | # mooon_ssh -c='/tmp/set_hostname.sh /tmp/hosts.name' 25 | # 注意文件set_hostname.sh和hosts.name需事先发布到所有目标机器上。 26 | 27 | # 本机IP所在网卡 28 | ethX=eth0 29 | 30 | # 参数检查 31 | if test $# -ne 1; then 32 | echo -e "\033[1;33musage\033[m:\nset_hostname.sh conffile" 33 | echo "" 34 | echo "conffile format:" 35 | echo "IP + separator + hostname" 36 | echo "" 37 | echo "example:" 38 | echo "192.168.31.1 zhangsan-1" 39 | echo "192.168.31.2 zhangsan-2" 40 | echo "192.168.31.3 zhangsan-3" 41 | echo "" 42 | echo "available separators: space, TAB, semicolon, comma, vertical line" 43 | exit 1 44 | fi 45 | 46 | # 检查配置文件是否存在和可读 47 | conffile=$1 48 | if test ! -f $conffile; then 49 | echo -e "file \`$conffile\` \033[0;32;31mnot exists\033[m" 50 | exit 1 51 | fi 52 | if test ! -r $conffile; then 53 | echo -e "file \`$conffile\` \033[0;32;31mno permission to read\033[m" 54 | exit 1 55 | fi 56 | 57 | # 取本机IP需要用到netstat 58 | which netstat > /dev/null 2>&1 59 | if test $? -ne 0; then 60 | echo "\`netstat\` command \033[0;32;31mnot available\033[m" 61 | exit 1 62 | fi 63 | 64 | # 重启之前需要hostnamectl来使用hostname对全系统有效 65 | which hostnamectl > /dev/null 2>&1 66 | if test $? -ne 0; then 67 | echo "\`hostnamectl\` command \033[0;32;31mnot available\033[m" 68 | exit 1 69 | fi 70 | 71 | # 取得hostname的配置文件 72 | # 注意不同Linux发行版本的hostname文件可能不同 73 | hostname_file=/etc/hostname 74 | if test -w $hostname_file; then 75 | echo "checked $hostname_file ok" 76 | else 77 | hostname_file=/etc/HOSTNAME 78 | if test -w $hostname_file; then 79 | echo "checked $hostname_file ok" 80 | else 81 | echo "can not write $hostname_file, or $hostname_file not exits" 82 | exit 1 83 | fi 84 | fi 85 | 86 | # 取本地IP 87 | local_ip=`netstat -ie|awk -F'[ :]+' -v ethX=$ethX 'BEGIN{ok=0;} {if ($1==ethX) ok=1; if ((1==ok) && match($0,"inet")) { ok=0; if (7==NF) printf("%s\n",$3); else printf("%s\n",$4); } }'` 88 | if test -z "$local_ip"; then 89 | echo "can not get local IP of \`$ethX\`" 90 | exit 1 91 | fi 92 | 93 | # 读取文件,找到本机待设置的新主机名 94 | while read line 95 | do 96 | if test -z "$line"; then 97 | break 98 | fi 99 | 100 | eval $(echo $line |awk -F'[ \t|,;]+' '{ printf("ip=%s\nhostname=%s\n", $1, $2); }') 101 | #echo "[IP] => $ip [HOSTNAME] => $hostname" 102 | if test "$ip" = "$local_ip"; then 103 | echo "$ip => $hostname" 104 | echo "$hostname" > $hostname_file 105 | hostnamectl --transient set-hostname $hostname 106 | exit $? 107 | fi 108 | done < $conffile 109 | 110 | echo "no item for $local_ip" 111 | exit 1 112 | -------------------------------------------------------------------------------- /include/mooon/sys/db_exception.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | * 代码采用商业友好的Apache协议,可任意修改和分发,但请保留版权说明文字。 19 | * 如遇到的问题,请发送到上述邮箱,以便及时修复。谢谢合作,共创开源! 20 | * 21 | * 数据库操作出错时,均要求以CDBException异常的方式处理 22 | */ 23 | #ifndef MOOON_SYS_DB_EXCEPTION_H 24 | #define MOOON_SYS_DB_EXCEPTION_H 25 | #include "mooon/sys/config.h" 26 | #include "mooon/utils/exception.h" 27 | 28 | #define THROW_DB_EXCEPTION(sql, errmsg, errcode) \ 29 | throw ::mooon::sys::CDBException(sql, errmsg, errcode, __FILE__, __LINE__) 30 | 31 | SYS_NAMESPACE_BEGIN 32 | 33 | /*** 34 | * 错误码定义 35 | */ 36 | enum 37 | { 38 | DB_NOT_SUPPORTED, // 不支持的功能 39 | DB_ERROR_TOO_MANY_COLS, // 查询结果返回超出预期的列数(即返回的字段数过多) 40 | DB_ERROR_TOO_MANY_ROWS // 查询结果返回超出预期的行数 41 | }; 42 | 43 | class CDBException: public utils::CException 44 | { 45 | public: 46 | /*** 47 | * 构造一个异常对象 48 | * 请注意不应当显示调用构造函数 49 | * 对于MySQL返回的出错码1062,表示重复插入 50 | */ 51 | CDBException(const char* sql, const char* errmsg, int errcode=-1, const char* file=__FILE__, int line=__LINE__) 52 | : CException(errmsg, errcode, file, line) 53 | { 54 | if (sql != NULL) 55 | { 56 | _sql = sql; 57 | } 58 | } 59 | 60 | CDBException(const char* sql, const std::string& errmsg, int errcode=-1, const char* file=__FILE__, int line=__LINE__) 61 | : CException(errmsg, errcode, file, line) 62 | { 63 | if (sql != NULL) 64 | { 65 | _sql = sql; 66 | } 67 | } 68 | 69 | CDBException(const std::string& sql, const std::string& errmsg, int errcode=-1, const char* file=__FILE__, int line=__LINE__) 70 | : CException(errmsg, errcode, file, line) 71 | { 72 | _sql = sql; 73 | } 74 | 75 | virtual ~CDBException() throw () 76 | { 77 | } 78 | 79 | virtual std::string prefix() const throw () 80 | { 81 | return "dbexception://"; 82 | } 83 | 84 | /** 返回执行出错的SQL语句,如果不是执行SQL语句,则仅返回一个字符串结尾符 */ 85 | const char* sql() const 86 | { 87 | return _sql.c_str(); 88 | } 89 | 90 | /** 返回SQL语句长度(字节数) */ 91 | size_t sql_length() const 92 | { 93 | return _sql.size(); 94 | } 95 | 96 | private: 97 | std::string _sql; 98 | }; 99 | 100 | SYS_NAMESPACE_END 101 | #endif // MOOON_SYS_DB_EXCEPTION_H 102 | -------------------------------------------------------------------------------- /src/sys/pool_thread.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: jian yi, eyjian@qq.com 18 | */ 19 | #include "sys/pool_thread.h" 20 | SYS_NAMESPACE_BEGIN 21 | 22 | ////////////////////////////////////////////////////////////////////////// 23 | // CPoolThread::CPoolThreadHelper 24 | 25 | CPoolThread::CPoolThreadHelper::CPoolThreadHelper(CPoolThread* pool_thread) 26 | :_pool_thread(pool_thread) 27 | { 28 | } 29 | 30 | void CPoolThread::CPoolThreadHelper::run() 31 | { 32 | // wait用于和主线程同步 33 | do_millisleep(-1); 34 | 35 | if (!is_stop()) 36 | { 37 | if (_pool_thread->before_run()) 38 | { 39 | while (!is_stop()) 40 | { 41 | _pool_thread->run(); 42 | } 43 | 44 | _pool_thread->after_run(); 45 | } 46 | } 47 | } 48 | 49 | void CPoolThread::CPoolThreadHelper::before_start() 50 | { 51 | _pool_thread->before_start(); 52 | } 53 | 54 | void CPoolThread::CPoolThreadHelper::before_stop() 55 | { 56 | _pool_thread->before_stop(); 57 | } 58 | 59 | void CPoolThread::CPoolThreadHelper::millisleep(int milliseconds) 60 | { 61 | do_millisleep(milliseconds); 62 | } 63 | 64 | ////////////////////////////////////////////////////////////////////////// 65 | // CPoolThread 66 | 67 | CPoolThread::CPoolThread() 68 | :_index(std::numeric_limits::max()) 69 | { 70 | _pool_thread_helper = new CPoolThreadHelper(this); 71 | _pool_thread_helper->inc_refcount(); // 保证生命周期内都是可以用的 72 | } 73 | 74 | CPoolThread::~CPoolThread() 75 | { 76 | _pool_thread_helper->dec_refcount(); 77 | } 78 | 79 | void CPoolThread::wakeup() 80 | { 81 | _pool_thread_helper->wakeup(); 82 | } 83 | 84 | void CPoolThread::start() 85 | { 86 | _pool_thread_helper->start(); 87 | } 88 | 89 | void CPoolThread::stop() 90 | { 91 | _pool_thread_helper->stop(); 92 | } 93 | 94 | void CPoolThread::set_stack_size(size_t stack_size) throw () 95 | { 96 | _pool_thread_helper->set_stack_size(stack_size); 97 | } 98 | 99 | size_t CPoolThread::get_stack_size() const 100 | { 101 | return _pool_thread_helper->get_stack_size(); 102 | } 103 | 104 | uint32_t CPoolThread::get_thread_id() const throw () 105 | { 106 | return _pool_thread_helper->get_thread_id(); 107 | } 108 | 109 | void CPoolThread::do_millisleep(int milliseconds) 110 | { 111 | _pool_thread_helper->millisleep(milliseconds); 112 | } 113 | 114 | SYS_NAMESPACE_END 115 | -------------------------------------------------------------------------------- /src/utils/object.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: JianYi, eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "utils/object.h" 20 | UTILS_NAMESPACE_BEGIN 21 | 22 | void CObject::set_type_name(const std::string& type_name) 23 | { 24 | _type_name = type_name; 25 | } 26 | 27 | //////////////////////////////////////////////////////////////////////////////// 28 | SINGLETON_IMPLEMENT(CObjectFacotry) 29 | 30 | CObjectFacotry::~CObjectFacotry() 31 | { 32 | // 注意:Creator 是全局对象,不需要 delete 显示释放 33 | // for (ObjectCreatorTable::iterator iter=_object_creator_table.begin(); iter!=_object_creator_table.end(); ++iter) 34 | // { 35 | // CObjectCreator* object_creator = iter->second; 36 | // delete object_creator; 37 | // } 38 | _object_creator_table.clear(); 39 | } 40 | 41 | void CObjectFacotry::register_object_creater(const std::string& type_name, CObjectCreator* object_creator) 42 | { 43 | std::pair ret = 44 | _object_creator_table.insert(std::make_pair(type_name, object_creator)); 45 | MOOON_ASSERT(ret.second); // 在调试阶段即可发现问题 46 | } 47 | 48 | CObjectCreator* CObjectFacotry::get_object_creator(const std::string& type_name) const 49 | { 50 | CObjectCreator* object_creator = NULL; 51 | ObjectCreatorTable::const_iterator iter = _object_creator_table.find(type_name); 52 | 53 | if (iter != _object_creator_table.end()) 54 | object_creator = iter->second; 55 | return object_creator; 56 | } 57 | 58 | CObject* CObjectFacotry::create_object(const std::string& type_name) const 59 | { 60 | if (type_name.empty()) 61 | { 62 | return NULL; 63 | } 64 | else 65 | { 66 | CObject* object = NULL; 67 | CObjectCreator* object_creator = get_object_creator(type_name); 68 | 69 | if (object_creator != NULL) 70 | object = object_creator->create_object(); 71 | return object; 72 | } 73 | } 74 | 75 | bool CObjectFacotry::object_type_exists(const std::string& type_name) const 76 | { 77 | return _object_creator_table.count(type_name) > 0; 78 | } 79 | 80 | std::string CObjectFacotry::get_type_list() const 81 | { 82 | std::string str; 83 | for (ObjectCreatorTable::const_iterator iter=_object_creator_table.begin(); iter!=_object_creator_table.end(); ++iter) 84 | { 85 | if (str.empty()) 86 | str = iter->first; 87 | else 88 | str = str + std::string(",") + iter->first; 89 | } 90 | return str; 91 | } 92 | 93 | UTILS_NAMESPACE_END 94 | -------------------------------------------------------------------------------- /test/net/ut_libssh2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | * Author: eyjian@qq.com or eyjian@gmail.com 18 | */ 19 | #include "mooon/net/libssh2.h" 20 | #include "mooon/utils/tokener.h" 21 | MOOON_NAMESPACE_USE 22 | 23 | // 示例: 24 | // ./ut_libssh2 tom@127.0.0.1:22#tom2015 whoami 25 | int main(int argc, char* argv[]) 26 | { 27 | #if HAVE_LIBSSH2 == 1 28 | net::CLibssh2::init(); 29 | if (argc != 3) 30 | { 31 | fprintf(stderr, "usage: ut_libssh2 username@ip:port#password command\n"); 32 | exit(1); 33 | } 34 | 35 | std::string login = argv[1]; 36 | std::string command = argv[2]; 37 | 38 | std::vector login_infos; 39 | int num = utils::CLoginTokener::parse(&login_infos, login, ","); 40 | 41 | if (-1 == num) 42 | { 43 | fprintf(stderr, "invalid paramter: %s\n", login.c_str()); 44 | fprintf(stderr, "usage: ut_libssh2 username@ip:port#password command\n"); 45 | exit(1); 46 | } 47 | for (int i=0; i