├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── examples ├── CMakeLists.txt ├── chinese_chess_game │ ├── CMakeLists.txt │ ├── ChessGame.h │ ├── Config.h │ ├── README.md │ ├── StartClient.cc │ ├── StartServer.cc │ └── StartTest.cc ├── file_transfer │ ├── CMakeLists.txt │ ├── README.md │ ├── StartClient.cc │ └── StartServer.cc └── quick_start │ ├── CMakeLists.txt │ ├── README.md │ ├── SimpleCrawler.cc │ └── SimpleServer.cc ├── include └── kingpin │ ├── AsyncLogger.h │ ├── Buffer.h │ ├── Context.h │ ├── EpollTP.h │ ├── Exception.h │ ├── IOHandler.h │ ├── Mutex.h │ ├── TPSharedData.h │ └── Utils.h ├── lib ├── AsyncLogger.cc ├── Buffer.cc ├── CMakeLists.txt ├── Context.cc └── Utils.cc ├── pictures └── PlayChess.png └── unittest ├── CMakeLists.txt ├── test_buffer.cc ├── test_context.cc ├── test_logger.cc └── test_utils.cc /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | .vscode 35 | examples/**/bin/* 36 | examples/big_file_transfer/src/bigfile.test.copy 37 | build/ 38 | todo 39 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.12) 2 | project(KINGPIN CXX) 3 | 4 | set(CMAKE_CXX_FLAGS "-g -O0 -Wall -std=c++11") 5 | 6 | find_package(GTest REQUIRED) 7 | 8 | include_directories("./include") 9 | link_libraries("gtest") 10 | link_libraries("pthread") 11 | 12 | add_subdirectory("./lib") 13 | add_subdirectory("./examples") 14 | add_subdirectory("./unittest") 15 | 16 | install ( 17 | TARGETS kingpin_static kingpin_shared 18 | ARCHIVE DESTINATION lib 19 | LIBRARY DESTINATION lib 20 | ) 21 | install ( 22 | DIRECTORY include/kingpin DESTINATION include 23 | ) 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Kingpin is a C++ network library based on TCP/IP + epoll + pthread for the high concurrent servers and clients. Inspired by *nginx* / *muduo*.** 2 | 3 | # Features 4 | 5 | * One connected socket handled only by one thread. 6 | 7 | * Thread pool and IO multiplexing for both server's and client's concurrency. 8 | 9 | * IO threads compete for listening socket or target host pool in server and client. 10 | 11 | * Avoid excessive wrapper of classes and functions to get things complicated. 12 | 13 | # Quick Start 14 | 15 | Please refer to: [Quick Start](https://github.com/GeniusDai/kingpin/tree/dev/examples/quick_start) 16 | 17 | # Prerequirement 18 | 19 | * Linux: Support epoll, and glibc > 2.15 to avoid pthread_rwlock deadlock bug! 20 | 21 | * g++: Support C++ 11. 22 | 23 | * googletest / cmake / make. 24 | 25 | # Header Files 26 | 27 | * IOHandler.h: Both server's and client's IO thread. 28 | 29 | * TPSharedData.h: Data shared among thread pool. 30 | 31 | * EpollTP.h: Thread pool initialized by IOHandler and TPSharedData. 32 | 33 | * AsyncLogger.h: Thread safe logger, using backend thread for asynchronous output, line buffered. 34 | 35 | * Buffer.h: IO Buffer pre-allocated on heap, support nonblock socket and disk fd. NOT thread safe. 36 | 37 | * Mutex.h: Easy to debug wrapper for read-write lock and recursive lock in libpthread. 38 | 39 | * Context.h: Function call timeout wrapper. 40 | 41 | * Utils.h: Some utility functions. 42 | 43 | # Examples 44 | 45 | A wealth of cases: 46 | 47 | * [Chinese Chess Game](https://github.com/GeniusDai/kingpin/tree/dev/examples/chinese_chess_game): Chess game server and client, also implements a high concurrency test client. 48 | 49 | * [File Transfer](https://github.com/GeniusDai/kingpin/tree/dev/examples/file_transfer): File transfer server and client, IO and exceptions are both well handled. 50 | 51 | Build and run: 52 | 53 | $ mkdir build && cd build 54 | $ cmake .. && make 55 | $ cd unittest && ctest 56 | 57 | # Others 58 | 59 | Architecture design for this repo is poor, although performance is very good. 60 | 61 | A more well designed repo that have similar function : https://github.com/GeniusDai/cppev 62 | -------------------------------------------------------------------------------- /examples/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | link_libraries(kingpin_static) 2 | 3 | add_subdirectory(quick_start) 4 | add_subdirectory(file_transfer) 5 | add_subdirectory(chinese_chess_game) 6 | -------------------------------------------------------------------------------- /examples/chinese_chess_game/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(ChessServer StartServer.cc) 2 | add_executable(ChessTest StartTest.cc) 3 | add_executable(ChessClient StartClient.cc) 4 | -------------------------------------------------------------------------------- /examples/chinese_chess_game/ChessGame.h: -------------------------------------------------------------------------------- 1 | #ifndef _ChessGame_H_de485c8f1246_ 2 | #define _ChessGame_H_de485c8f1246_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | class ChessGame { 15 | public: 16 | enum class Player { RED = 1, BLACK }; 17 | 18 | enum class ChessType { ROOK = 1, KNIGHT, ELEPHANT, MANDARIN, KING, CANNON, PAWN }; 19 | 20 | struct Chess { 21 | Chess(ChessType t, Player p) : _t(t), _p(p) {} 22 | ChessType _t; 23 | Player _p; 24 | 25 | struct ChessHash { 26 | size_t operator()(const Chess &chess) const { 27 | return static_cast(chess._t) * 10 + 28 | static_cast(chess._p) / 19; 29 | } 30 | }; 31 | 32 | bool operator==(const Chess &chess) const { 33 | return _t == chess._t && _p == chess._p; 34 | } 35 | }; 36 | 37 | struct EnumHash { 38 | template 39 | size_t operator()(const T &t) const { return static_cast(t); } 40 | }; 41 | 42 | typedef shared_ptr _chess_ptr; 43 | 44 | static const string RED_COLOR; 45 | static const string BLACK_COLOR; 46 | static const int COLUMNS = 9; 47 | static const int ROWS = 10; 48 | static const unordered_map playerHash; 49 | static const unordered_map chessHash; 50 | 51 | vector > _board; 52 | 53 | ChessGame() { 54 | _board = vector >(ROWS, vector<_chess_ptr>(COLUMNS, nullptr)); 55 | initRows(0, Player::RED); initRows(ROWS - 1, Player::BLACK); 56 | initRows(2, Player::RED); initRows(ROWS - 3, Player::BLACK); 57 | initRows(3, Player::RED); initRows(ROWS - 4, Player::BLACK); 58 | } 59 | 60 | void initRows(int row, Player p) { 61 | if (row == 0 or row == ROWS - 1) { 62 | _board[row][0] = _chess_ptr(new Chess(ChessType::ROOK, p)); 63 | _board[row][1] = _chess_ptr(new Chess(ChessType::KNIGHT, p)); 64 | _board[row][2] = _chess_ptr(new Chess(ChessType::ELEPHANT, p)); 65 | _board[row][3] = _chess_ptr(new Chess(ChessType::MANDARIN, p)); 66 | _board[row][4] = _chess_ptr(new Chess(ChessType::KING, p)); 67 | _board[row][COLUMNS - 4] = _chess_ptr(new Chess(ChessType::MANDARIN, p)); 68 | _board[row][COLUMNS - 3] = _chess_ptr(new Chess(ChessType::ELEPHANT, p)); 69 | _board[row][COLUMNS - 2] = _chess_ptr(new Chess(ChessType::KNIGHT, p)); 70 | _board[row][COLUMNS - 1] = _chess_ptr(new Chess(ChessType::ROOK, p)); 71 | } else if (row == 2 or row == ROWS - 3) { 72 | _board[row][1] = _chess_ptr(new Chess(ChessType::CANNON, p)); 73 | _board[row][COLUMNS - 2] = _chess_ptr(new Chess(ChessType::CANNON, p)); 74 | } else if (row == 3 or row == ROWS - 4) { 75 | _board[row][0] = _chess_ptr(new Chess(ChessType::PAWN, p)); 76 | _board[row][2] = _chess_ptr(new Chess(ChessType::PAWN, p)); 77 | _board[row][4] = _chess_ptr(new Chess(ChessType::PAWN, p)); 78 | _board[row][COLUMNS - 3] = _chess_ptr(new Chess(ChessType::PAWN, p)); 79 | _board[row][COLUMNS - 1] = _chess_ptr(new Chess(ChessType::PAWN, p)); 80 | } 81 | } 82 | 83 | void showGameBoard() const { 84 | ::system("clear"); 85 | for (int i = 0; i < ROWS; ++i) { 86 | cout << i << " "; 87 | for (int j = 0; j < COLUMNS; ++j) { 88 | if (_board[i][j] == nullptr) { cout << " " << " " << " "; } 89 | else { 90 | cout << playerHash.at(_board[i][j]->_p) << chessHash.at(*_board[i][j]); 91 | cout << "\033[0m" << " "; 92 | } 93 | } 94 | cout << endl; 95 | } 96 | cout << " "; 97 | for (int i = 0; i < COLUMNS; ++i) { cout << i << " " << " "; } 98 | cout << endl; 99 | } 100 | 101 | void moveChess(int fx, int fy, int tx, int ty) { 102 | if (fx == tx && fy == ty) return; 103 | _board[tx][ty] = _board[fx][fy]; 104 | _board[fx][fy] = nullptr; 105 | } 106 | 107 | void moveChess(string move) { 108 | char sep = ' '; 109 | vector ans; 110 | for (size_t i = 0; i < move.size() - 1; ++i) { 111 | if (move[i] != sep) { ans.push_back(move[i]-'0'); } 112 | } 113 | assert(ans.size() == 4); 114 | moveChess(ans[0], ans[1], ans[2], ans[3]); 115 | } 116 | 117 | string askMove() { 118 | vector ans(4); 119 | cout << "Enter the chess move[row column]" << endl; 120 | cout << "-> From : "; 121 | cin >> ans[0] >> ans[1]; 122 | cout << "-> To : "; 123 | cin >> ans[2] >> ans[3]; 124 | string data; 125 | for (size_t i = 0; i < ans.size(); ++i) { 126 | data += to_string(ans[i]); 127 | if (i != ans.size() - 1) { data += " "; } 128 | else { data += "\n"; } 129 | } 130 | return data; 131 | } 132 | }; 133 | 134 | const string ChessGame::RED_COLOR = "\033[47;31m"; 135 | const string ChessGame::BLACK_COLOR = "\033[47;30m"; 136 | 137 | const unordered_map 138 | ChessGame::playerHash = { 139 | { ChessGame::Player::RED, ChessGame::RED_COLOR}, 140 | { ChessGame::Player::BLACK, ChessGame::BLACK_COLOR} 141 | }; 142 | 143 | const unordered_map 144 | ChessGame::chessHash = { 145 | {{ChessGame::ChessType::ROOK, ChessGame::Player::RED}, "车"}, 146 | {{ChessGame::ChessType::KNIGHT, ChessGame::Player::RED}, "马"}, 147 | {{ChessGame::ChessType::ELEPHANT, ChessGame::Player::RED}, "象"}, 148 | {{ChessGame::ChessType::MANDARIN, ChessGame::Player::RED}, "士"}, 149 | {{ChessGame::ChessType::KING, ChessGame::Player::RED}, "帅"}, 150 | {{ChessGame::ChessType::CANNON, ChessGame::Player::RED}, "炮"}, 151 | {{ChessGame::ChessType::PAWN, ChessGame::Player::RED}, "兵"}, 152 | {{ChessGame::ChessType::ROOK, ChessGame::Player::BLACK}, "车"}, 153 | {{ChessGame::ChessType::KNIGHT, ChessGame::Player::BLACK}, "马"}, 154 | {{ChessGame::ChessType::ELEPHANT, ChessGame::Player::BLACK}, "象"}, 155 | {{ChessGame::ChessType::MANDARIN, ChessGame::Player::BLACK}, "仕"}, 156 | {{ChessGame::ChessType::KING, ChessGame::Player::BLACK}, "将"}, 157 | {{ChessGame::ChessType::CANNON, ChessGame::Player::BLACK}, "炮"}, 158 | {{ChessGame::ChessType::PAWN, ChessGame::Player::BLACK}, "卒"}, 159 | }; 160 | 161 | #endif // ChessGame.h 162 | -------------------------------------------------------------------------------- /examples/chinese_chess_game/Config.h: -------------------------------------------------------------------------------- 1 | #ifndef _CONFIG_H_cbda4c090b9d_ 2 | #define _CONFIG_H_cbda4c090b9d_ 3 | 4 | class Config { 5 | public: 6 | static const int _port; 7 | static const int _concurrency_num; 8 | static const char *const _ip; 9 | static const char *const _init_msg_red; 10 | static const char *const _init_msg_black; 11 | static const char *const _end_msg; 12 | virtual ~Config() = 0; 13 | }; 14 | 15 | const int Config::_port = 8889; 16 | const int Config::_concurrency_num = 20000; 17 | const char *const Config::_ip = "127.0.0.1"; 18 | const char *const Config::_init_msg_red = "0 0 0 0\n"; 19 | const char *const Config::_init_msg_black = "1 1 1 1\n"; 20 | const char *const Config::_end_msg = "2 2 2 2\n"; 21 | 22 | 23 | #endif -------------------------------------------------------------------------------- /examples/chinese_chess_game/README.md: -------------------------------------------------------------------------------- 1 | # Chinese Chess Game 2 | 3 | About 4 | ----- 5 | 6 | Default: 7 | 8 | * TCP Port: "8889" 9 | 10 | * Server IP: "127.0.0.1" 11 | 12 | * Concurrency test number: "20000" (Need to modify system config) 13 | 14 | Screenshot 15 | ---------- 16 | 17 | ![image](https://github.com/GeniusDai/kingpin/raw/dev/pictures/PlayChess.png) 18 | 19 | For example, if player red want to move chess "KING", shall enter: 20 | 21 | -> From : 0 4 22 | -> To : 1 4 23 | -------------------------------------------------------------------------------- /examples/chinese_chess_game/StartClient.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "kingpin/Exception.h" 12 | #include "kingpin/Utils.h" 13 | #include "kingpin/Buffer.h" 14 | #include "Config.h" 15 | #include "ChessGame.h" 16 | 17 | using namespace std; 18 | using namespace kingpin; 19 | 20 | class Client { 21 | public: 22 | char _player = 'U'; 23 | 24 | void start() { 25 | int conn = connectIp(Config::_ip, Config::_port, 15); 26 | Buffer buffer; 27 | cout << "Welcome! Now waiting for another player to join..." << endl; 28 | ChessGame game; 29 | while (true) { 30 | buffer.clear(); 31 | try { 32 | buffer.readNioToBufferTillEnd(conn, "\n", 1); 33 | } catch(const NonFatalException &e) { 34 | cout << e.what() << endl; 35 | break; 36 | } 37 | if (_player == 'U') { 38 | if (!::strcmp(buffer._buffer, Config::_init_msg_red)) { _player = 'R'; } 39 | else { _player = 'B'; } 40 | } 41 | if (!::strcmp(buffer._buffer, Config::_end_msg)) { ::close(conn); exit(0); } 42 | game.moveChess(buffer._buffer); 43 | game.showGameBoard(); 44 | cout << "You are player: " << ((_player == 'R') ? "red" : "black") << endl; 45 | if (!::strcmp(buffer._buffer, Config::_init_msg_black)) { continue; } 46 | string move = game.askMove(); 47 | game.moveChess(move); 48 | game.showGameBoard(); 49 | cout << "You are player: " << ((_player == 'R') ? "red" : "black") << endl; 50 | ::write(conn, move.c_str(), move.size()); 51 | } 52 | ::close(conn); 53 | } 54 | }; 55 | 56 | int main() { 57 | Client client; 58 | client.start(); 59 | return 0; 60 | } -------------------------------------------------------------------------------- /examples/chinese_chess_game/StartServer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "kingpin/EpollTP.h" 17 | #include "kingpin/IOHandler.h" 18 | #include "kingpin/TPSharedData.h" 19 | #include "kingpin/Exception.h" 20 | #include "kingpin/AsyncLogger.h" 21 | #include "kingpin/Buffer.h" 22 | #include "Config.h" 23 | 24 | using namespace std; 25 | using namespace kingpin; 26 | 27 | class ChessData : public TPSharedDataForServer { 28 | public: 29 | recursive_mutex _m; 30 | unordered_map _match; 31 | set _single; 32 | map _message; 33 | }; 34 | 35 | template 36 | class ChessIO : public IOHandlerForServer { 37 | public: 38 | ChessIO(ChessData *tsd) : 39 | IOHandlerForServer(tsd) {} 40 | 41 | void onConnect(int conn) { 42 | unique_lock lg(this->_tsd->_m); 43 | if (this->_tsd->_single.empty()) { 44 | this->_tsd->_single.insert(conn); 45 | INFO << "single client " << conn << " arrived"<< END; 46 | } else { 47 | auto iter = this->_tsd->_single.begin(); 48 | int oppo = *iter; 49 | this->_tsd->_match[oppo] = conn; 50 | this->_tsd->_match[conn] = *iter; 51 | INFO << "match client " << conn << " & " << oppo << END; 52 | ::write(conn, Config::_init_msg_black, strlen(Config::_init_msg_black)); 53 | ::write(oppo, Config::_init_msg_red, strlen(Config::_init_msg_red)); 54 | this->_tsd->_single.erase(oppo); 55 | } 56 | } 57 | 58 | void onMessage(int conn) { 59 | unique_lock lg(this->_tsd->_m); 60 | if (this->_tsd->_match.find(conn) == this->_tsd->_match.end()) { return; } 61 | int oppo = this->_tsd->_match[conn]; 62 | Buffer *rb = this->_rbh[conn].get(); 63 | if (!rb->endsWith("\n")) { return; } 64 | INFO << "receive full message " << rb->_buffer << " from " << conn << END; 65 | this->_tsd->_message[oppo] = rb->_buffer; 66 | rb->clear(); 67 | assert(rb->writeComplete()); 68 | } 69 | 70 | void onEpollLoop() { 71 | unique_lock lg(this->_tsd->_m); 72 | map &message = this->_tsd->_message; 73 | for (auto iter = message.begin(); iter != message.end(); ) { 74 | if (this->_wbh.find(iter->first) != this->_wbh.cend()) { 75 | INFO << "find message for " << iter->first << END; 76 | this->_wbh[iter->first]->appendToBuffer(message[iter->first].c_str()); 77 | this->writeToBuffer(iter->first); 78 | iter = message.erase(iter); 79 | } else { ++iter; } 80 | } 81 | } 82 | 83 | void onWriteComplete(int conn) { 84 | INFO << "write to " << conn << " complete" << END; 85 | assert(this->_wbh[conn]->writeComplete()); 86 | } 87 | 88 | void onPassivelyClosed(int conn) { 89 | unique_lock lg(this->_tsd->_m); 90 | int oppo = -1; 91 | INFO << "client " << conn << " closed the socket" << END; 92 | ::close(conn); 93 | if (this->_tsd->_match.find(conn) != this->_tsd->_match.cend()) { 94 | oppo = this->_tsd->_match[conn]; 95 | this->_tsd->_match.erase(conn); 96 | ::write(oppo, Config::_end_msg, strlen(Config::_end_msg)); 97 | } else { 98 | this->_tsd->_single.erase(conn); 99 | } 100 | } 101 | }; 102 | 103 | int main() { 104 | ChessData data; 105 | data._batch = 5; 106 | data._port = Config::_port; 107 | EpollTPServer server(32, &data); 108 | server.run(); 109 | return 0; 110 | } -------------------------------------------------------------------------------- /examples/chinese_chess_game/StartTest.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "kingpin/EpollTP.h" 8 | #include "kingpin/IOHandler.h" 9 | #include "kingpin/TPSharedData.h" 10 | #include "kingpin/AsyncLogger.h" 11 | #include "kingpin/Utils.h" 12 | #include "kingpin/Buffer.h" 13 | 14 | #include "Config.h" 15 | 16 | using namespace std; 17 | using namespace kingpin; 18 | 19 | template 20 | class HighConHandler : public IOHandlerForClient<_Data> { 21 | public: 22 | HighConHandler(_Data *tsd) : IOHandlerForClient<_Data>(tsd) {} 23 | 24 | void onMessage(int conn) { 25 | Buffer *rb = this->_rbh[conn].get(); 26 | INFO << "Receive message " << rb->_buffer << " from " << conn << END; 27 | // sleep(1); 28 | rb->writeNioFromBufferTillEnd(conn); 29 | } 30 | }; 31 | 32 | int main() { 33 | TPSharedDataForClient data; 34 | data._batch = 50; 35 | for (int i = 0; i < Config::_concurrency_num; ++i) 36 | { data.raw_add(Config::_ip, Config::_port, ""); } 37 | EpollTPClient hc_client(32, &data); 38 | hc_client.run(); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /examples/file_transfer/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(file_transfer) 2 | 3 | add_executable(FileServer StartServer.cc) 4 | add_executable(FileClient StartClient.cc) 5 | -------------------------------------------------------------------------------- /examples/file_transfer/README.md: -------------------------------------------------------------------------------- 1 | # File Transfer 2 | 3 | About 4 | ----- 5 | 6 | The file transfer server will load the disk file to RAM, so DONOT transfer file with too big a size! 7 | 8 | How to Start 9 | ------------ 10 | 11 | $ touch /tmp/file.test && echo -e "hello\nkingpin" >> /tmp/file.test 12 | $ ./FileClient 13 | $ md5sum /tmp/file.test /tmp/file.test.copy 14 | 15 | -------------------------------------------------------------------------------- /examples/file_transfer/StartClient.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "kingpin/AsyncLogger.h" 9 | #include "kingpin/Buffer.h" 10 | #include "kingpin/Utils.h" 11 | #include "kingpin/Exception.h" 12 | 13 | using namespace std; 14 | using namespace kingpin; 15 | 16 | class Client { 17 | public: 18 | static const int _port; 19 | static const int _step; 20 | static const char *const _ip; 21 | 22 | void start() { 23 | int sock = connectIp(_ip, _port, 15); 24 | const char *str; 25 | 26 | str = "/tmp/file.test"; 27 | ::write(sock, str, strlen(str)); 28 | sleep(1); 29 | str = "\n"; 30 | ::write(sock, str, strlen(str)); 31 | 32 | int fd = ::open("/tmp/file.test.copy", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); 33 | if (fd < 0) { 34 | fatalError("syscall open failed"); 35 | } 36 | Buffer buffer; 37 | bool end = false; 38 | while(!end) { 39 | try { 40 | buffer.readNioToBuffer(sock, _step); 41 | } catch(const EOFException &e) { 42 | INFO << e << END; 43 | end = true; 44 | } 45 | buffer.writeNioFromBufferTillEnd(fd); 46 | } 47 | ::close(fd); 48 | } 49 | }; 50 | 51 | const int Client::_port = 8890; 52 | const int Client::_step = 1024 * 10; 53 | const char *const Client::_ip = "127.0.0.1"; 54 | 55 | int main() { 56 | Client client; 57 | client.start(); 58 | return 0; 59 | } -------------------------------------------------------------------------------- /examples/file_transfer/StartServer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "kingpin/TPSharedData.h" 10 | #include "kingpin/EpollTP.h" 11 | #include "kingpin/IOHandler.h" 12 | #include "kingpin/Buffer.h" 13 | #include "kingpin/Exception.h" 14 | 15 | using namespace std; 16 | using namespace kingpin; 17 | 18 | static const int PORT = 8890; 19 | 20 | template 21 | class BigFileTransferIOHandler : public IOHandlerForServer<_Data> { 22 | public: 23 | BigFileTransferIOHandler(_Data *tsd) : IOHandlerForServer<_Data>(tsd) {} 24 | void onMessage(int conn) { 25 | int fd; 26 | Buffer *rb, *wb; 27 | try { 28 | rb = this->_rbh[conn].get(); 29 | wb = this->_wbh[conn].get(); 30 | rb->stripEnd('\n'); 31 | INFO << "client requests file [" << rb->_buffer << "]" << END; 32 | fd = open(rb->_buffer, O_RDONLY); 33 | if (fd < 0) { fatalError("syscall open failed"); } 34 | wb->readNioToBufferTillBlock(fd); 35 | INFO << "load file completed" << END; 36 | } catch(const EOFException &e) { 37 | INFO << e << END; 38 | } 39 | this->writeToBuffer(conn); 40 | } 41 | 42 | void onWriteComplete(int conn) { 43 | INFO << "write complete, will close socket" << END; 44 | ::close(conn); 45 | } 46 | }; 47 | 48 | int main() { 49 | TPSharedDataForServer data; 50 | data._port = PORT; 51 | EpollTPServer 52 | server(8, &data); 53 | server.run(); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /examples/quick_start/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(SimpleServer SimpleServer.cc) 2 | add_executable(SimpleCrawler SimpleCrawler.cc) 3 | -------------------------------------------------------------------------------- /examples/quick_start/README.md: -------------------------------------------------------------------------------- 1 | # Quick Start: 2 | 3 | ## --> Build a Simple Server 4 | 5 | In this guide, we will build a server that echo "Hello, kingpin!" to the client and then close the connection. Just several codes. 6 | 7 | ### Step 1. Define your own IOHandler 8 | 9 | Implement a IOHandler, this could tell the thread what to do when handling a connection. We just echo the string and close the connection when write completes. 10 | 11 | ``` 12 | template 13 | class SimpleHandler : public IOHandlerForServer<_Data> { 14 | public: 15 | SimpleHandler(_Data *d) : IOHandlerForServer<_Data>(d) {} 16 | 17 | void onConnect(int conn) { this->writeToBuffer(conn, "Hello, kingpin!"); } 18 | 19 | void onWriteComplete(int conn) { ::close(conn); } 20 | }; 21 | ``` 22 | 23 | The template _Data refers to the data shared between threads. This template is essential for the IOHandler. 24 | 25 | ### Step 2. Define you own TPSharedData 26 | 27 | Define the data shared between threads. Since no EXTRA DATA to be shared in the simple demo, just derive from the base class (or use the base class). 28 | 29 | ``` 30 | class SharedData : public TPSharedDataForServer {}; 31 | ``` 32 | 33 | ### Step 3. Init the data and run the server 34 | 35 | Use 8 threads to handle the connnections, and listen in 8888 port. 36 | 37 | ``` 38 | int main() { 39 | SharedData data; 40 | data._port = 8888; 41 | EpollTPServer server(8, &data); 42 | server.run(); 43 | return 0; 44 | } 45 | ``` 46 | 47 | Since as long as the server alives, the thread pool alives, so the data shared between TP shall have the same life cycle as the server. Usually we place them in the main function's stack. 48 | 49 | ### Step 4. Connect to server 50 | 51 | Use netcat to connect. 52 | 53 | ``` 54 | $ nc localhost 8888 55 | Hello, kingpin! 56 | 57 | Ncat: Broken pipe. 58 | ``` 59 | 60 | ## --> Build a Simple Crawler 61 | 62 | Now let's use the client to build a crawler just send a simple HTTP request. 63 | 64 | ### Step 1. Define your own IOHandler 65 | 66 | This step is always essential for you thread pool. We just print the page we crawled. 67 | 68 | ``` 69 | template 70 | class CrawlerHandler : public IOHandlerForClient<_Data> { 71 | public: 72 | CrawlerHandler(_Data *d) : IOHandlerForClient<_Data>(d) {} 73 | void _print(int conn) { 74 | if (0 == this->_rbh[conn]->_offset) return; 75 | INFO << "Host of socket " << conn << ": " << this->_conn_info[conn].first 76 | << "\nMessage of socket " << conn << ":\n" 77 | << this->_rbh[conn]->_buffer << END; 78 | this->_rbh[conn]->clear(); 79 | } 80 | 81 | void onMessage(int conn) { _print(conn); } 82 | 83 | void onPassivelyClosed(int conn) { _print(conn); } 84 | }; 85 | ``` 86 | 87 | ### Step 2. Define you own TPSharedData 88 | 89 | In this simple crawler, we just use the default structure for client. 90 | 91 | ### Step 3. Init the data and run the crawler 92 | 93 | Since our client will not just support crawler but also concurrency test. Our connection pool is identified by a tuple (ip, port, init_message). We could use the raw_add to add our data to the pool shared by crawler.Then Use 2 threads to handle the connnections. 94 | 95 | ``` 96 | int main() { 97 | TPSharedDataForClient data; 98 | EpollTPClient crawler(2, &data); 99 | vector hosts = { "www.taobao.com", "www.bytedance.com", "www.baidu.com" }; 100 | for (auto &h : hosts) { 101 | string ip = getHostIp(h.c_str()); 102 | const char *request = "GET /TEST HTTP/1.1\r\n\r\n"; 103 | data.raw_add(ip, 80, request); 104 | } 105 | crawler.run(); 106 | return 0; 107 | } 108 | ``` 109 | 110 | # Tutorial 111 | 112 | **Override 5 functions for IOHandlerForServer:** 113 | 114 | * void onEpollLoop() : Epoll loop starts 115 | 116 | * void onConnect(int conn) : Socket accepted 117 | 118 | * void onMessage(int conn) : Message arrives, has been read automatically to read buffer 119 | 120 | * void onWriteComplete(int conn) : Async write finished 121 | 122 | * void onPassivelyClosed(int conn) : Oppo closed socket or crash 123 | 124 | **Override 6 functions for IOHandlerForClient:** 125 | 126 | * void onEpollLoop() : Epoll loop starts 127 | 128 | * void onConnect(int conn) : Connection established 129 | 130 | * void onConnectFailed(int conn) : Connect to host failed 131 | 132 | * void onMessage(int conn) : Message arrives, has been read automatically to read buffer 133 | 134 | * void onWriteComplete(int conn) : Async write finished 135 | 136 | * void onPassivelyClosed(int conn) : Oppo closed socket or crash 137 | -------------------------------------------------------------------------------- /examples/quick_start/SimpleCrawler.cc: -------------------------------------------------------------------------------- 1 | #include "kingpin/EpollTP.h" 2 | #include "kingpin/TPSharedData.h" 3 | #include "kingpin/IOHandler.h" 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | using namespace kingpin; 9 | 10 | template 11 | class CrawlerHandler : public IOHandlerForClient<_Data> { 12 | public: 13 | CrawlerHandler(_Data *d) : IOHandlerForClient<_Data>(d) {} 14 | void _print(int conn) { 15 | if (0 == this->_rbh[conn]->_offset) return; 16 | INFO << "Host of socket " << conn << ": " << this->_conn_info[conn].first 17 | << "\nMessage of socket " << conn << ":\n" 18 | << this->_rbh[conn]->_buffer << END; 19 | this->_rbh[conn]->clear(); 20 | } 21 | 22 | void onMessage(int conn) { _print(conn); } 23 | 24 | void onPassivelyClosed(int conn) { _print(conn); } 25 | }; 26 | 27 | int main() { 28 | TPSharedDataForClient data; 29 | EpollTPClient crawler(2, &data); 30 | vector hosts = { "www.taobao.com", "www.bytedance.com", "www.baidu.com" }; 31 | for (auto &h : hosts) { 32 | string ip = getHostIp(h.c_str()); 33 | const char *request = "GET /TEST HTTP/1.1\r\n\r\n"; 34 | data.raw_add(ip, 80, request); 35 | } 36 | crawler.run(); 37 | return 0; 38 | } -------------------------------------------------------------------------------- /examples/quick_start/SimpleServer.cc: -------------------------------------------------------------------------------- 1 | #include "kingpin/IOHandler.h" 2 | #include "kingpin/TPSharedData.h" 3 | #include "kingpin/EpollTP.h" 4 | #include 5 | 6 | using namespace std; 7 | using namespace kingpin; 8 | 9 | template 10 | class SimpleHandler : public IOHandlerForServer<_Data> { 11 | public: 12 | SimpleHandler(_Data *d) : IOHandlerForServer<_Data>(d) {} 13 | 14 | void onConnect(int conn) { this->writeToBuffer(conn, "Hello, kingpin!"); } 15 | 16 | void onWriteComplete(int conn) { ::close(conn); } 17 | }; 18 | 19 | class SharedData : public TPSharedDataForServer {}; 20 | 21 | int main() { 22 | SharedData data; 23 | data._port = 8888; 24 | EpollTPServer server(8, &data); 25 | server.run(); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /include/kingpin/AsyncLogger.h: -------------------------------------------------------------------------------- 1 | #ifndef __LOGGER_H_de3094e9a992_ 2 | #define __LOGGER_H_de3094e9a992_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "kingpin/Mutex.h" 13 | #include "kingpin/Utils.h" 14 | #include "kingpin/Buffer.h" 15 | 16 | using namespace std; 17 | 18 | namespace kingpin { 19 | 20 | class AsyncLogger final { 21 | RWLock _map_lock; 22 | condition_variable_any _thr_cv; 23 | unique_ptr _thr_ptr; 24 | bool _stop = false; 25 | public: 26 | int _level; 27 | unordered_map, shared_ptr, 28 | int, time_t> > _t_buffers; 29 | time_t _expired = 120; 30 | 31 | explicit AsyncLogger(int level); 32 | ~AsyncLogger(); 33 | 34 | AsyncLogger &operator<<(const long num); 35 | AsyncLogger &operator<<(const char *str); 36 | AsyncLogger &operator<<(const string &s); 37 | AsyncLogger &operator<<(const exception &e); 38 | AsyncLogger &operator<<(const AsyncLogger &); 39 | 40 | void _write_head(); 41 | void _write_time(); 42 | void _write_tid(); 43 | void _write_debug(); 44 | void _init_buffer(pid_t tid); 45 | bool _no_log(); 46 | void _run(); 47 | }; 48 | 49 | extern AsyncLogger INFO; 50 | extern AsyncLogger ERROR; 51 | extern const AsyncLogger END; 52 | 53 | } 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /include/kingpin/Buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef __BUFFER_H_d992a38e4d2d_ 2 | #define __BUFFER_H_d992a38e4d2d_ 3 | 4 | using namespace std; 5 | 6 | namespace kingpin { 7 | 8 | // NOT thread safe 9 | class Buffer final { 10 | private: 11 | unique_ptr __buffer; 12 | public: 13 | int _cap; // capacity size 14 | int _offset = 0; // data size total 15 | int _start = 0; // data size that have been consumed 16 | char *_buffer; 17 | int _delay = 1; 18 | static const int _default_cap; 19 | static const int _default_step; 20 | 21 | explicit Buffer(); 22 | explicit Buffer(int cap); 23 | Buffer &operator=(const Buffer &) = delete; 24 | Buffer(const Buffer &) = delete; 25 | ~Buffer(); 26 | 27 | void resize(int cap); 28 | void clear(); 29 | int readNioToBuffer(int fd, int len); 30 | int readNioToBufferTillBlock(int fd); 31 | int readNioToBufferTillBlockOrEOF(int fd); 32 | int readNioToBufferTillEnd(int fd, const char *end, int step = _default_step); 33 | int writeNioFromBuffer(int fd, int len); 34 | int writeNioFromBufferTillBlock(int fd); 35 | int writeNioFromBufferTillEnd(int fd, int step = _default_step); 36 | void appendToBuffer(const char *str); 37 | void appendToBuffer(const string &str); 38 | void stripEnd(char end); 39 | bool writeComplete(); 40 | bool endsWith(const char *str) const; 41 | 42 | }; 43 | 44 | } 45 | #endif 46 | -------------------------------------------------------------------------------- /include/kingpin/Context.h: -------------------------------------------------------------------------------- 1 | #ifndef __CONTEXT_H_f2b87e623d0d_ 2 | #define __CONTEXT_H_f2b87e623d0d_ 3 | 4 | namespace kingpin { 5 | 6 | class Context final { 7 | public: 8 | explicit Context(int timeout); 9 | void done(); 10 | bool wait(); 11 | private: 12 | int _pfd[2]; 13 | int _timeout; 14 | }; 15 | 16 | class ThrWithCtx { 17 | public: 18 | typedef void*(*ThrFuncPtr)(void *); 19 | struct ArgWithCtx { 20 | ThrWithCtx::ThrFuncPtr _f; 21 | void *_arg; 22 | Context *_ctx; 23 | ArgWithCtx(ThrFuncPtr f, void *arg, Context *ctx) : _f(f), _arg(arg), _ctx(ctx) {} 24 | }; 25 | 26 | ThrWithCtx(ThrFuncPtr f, void *arg, Context *ctx); 27 | bool run(); 28 | static void *_thread_wrapper(void *arg); 29 | private: 30 | ThrFuncPtr _f; 31 | void *_arg; 32 | Context *_ctx; 33 | }; 34 | 35 | } 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /include/kingpin/EpollTP.h: -------------------------------------------------------------------------------- 1 | #ifndef __EPOLLTP_H_f2b87e623d0d_ 2 | #define __EPOLLTP_H_f2b87e623d0d_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "kingpin/AsyncLogger.h" 14 | #include "kingpin/IOHandler.h" 15 | #include "kingpin/Utils.h" 16 | 17 | using namespace std; 18 | 19 | namespace kingpin { 20 | 21 | template class _IOHandler, 22 | typename _TPSharedData> 23 | class EpollTP final { 24 | using Handler = _IOHandler<_TPSharedData>; 25 | vector > _handlers; 26 | int _thr_num; 27 | _TPSharedData *_tsd; 28 | public: 29 | EpollTP(int thr_num, _TPSharedData *tsd) : _thr_num(thr_num), _tsd(tsd) { 30 | for (int i = 0; i < thr_num; ++i) 31 | { _handlers.emplace_back(new Handler(_tsd)); } 32 | } 33 | 34 | void run() { 35 | ignoreSignal(SIGPIPE); 36 | for (auto &h : _handlers) { h->run(); } 37 | for (auto &h : _handlers) { h->join(); } 38 | } 39 | }; 40 | 41 | template class _IOHandler, 42 | typename _TPSharedData> 43 | class EpollTPClient final { 44 | using TP = EpollTP<_IOHandler, _TPSharedData>; 45 | public: 46 | unique_ptr _tp; 47 | 48 | EpollTPClient(int thr_num, _TPSharedData *tsd) 49 | { _tp = unique_ptr(new TP(thr_num, tsd)); } 50 | 51 | void run() { _tp->run(); } 52 | }; 53 | 54 | template class _IOHandler, 55 | typename _TPSharedData> 56 | class EpollTPServer final { 57 | using TP = EpollTP<_IOHandler, _TPSharedData>; 58 | public: 59 | unique_ptr _tp; 60 | 61 | EpollTPServer(int thr_num, _TPSharedData *tsd) { 62 | tsd->_listenfd = initListen(tsd->_port, tsd->_listen_num); 63 | _tp = unique_ptr(new TP(thr_num, tsd)); 64 | } 65 | 66 | void run() { _tp->run(); } 67 | }; 68 | 69 | } 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /include/kingpin/Exception.h: -------------------------------------------------------------------------------- 1 | #ifndef __EXCEPTION_H_83b86438e787_ 2 | #define __EXCEPTION_H_83b86438e787_ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | namespace kingpin { 10 | 11 | class FatalException : public exception { 12 | const char *_what_arg; 13 | public: 14 | FatalException() : FatalException("fatal") {} 15 | explicit FatalException(const char *what_arg) : _what_arg(what_arg){} 16 | explicit FatalException(const string &what_arg) : FatalException(what_arg.c_str()) {} 17 | virtual ~FatalException() {} 18 | 19 | virtual const char *what() const noexcept { return _what_arg; } 20 | }; 21 | 22 | class NonFatalException : public exception { 23 | const char *_what_arg; 24 | public: 25 | NonFatalException() : NonFatalException("nonfatal") {} 26 | explicit NonFatalException(const char *what_arg) : _what_arg(what_arg) {} 27 | explicit NonFatalException(const string &what_arg) : NonFatalException(what_arg.c_str()) {} 28 | virtual ~NonFatalException() {} 29 | 30 | virtual const char *what() const noexcept { return _what_arg; } 31 | }; 32 | 33 | class EOFException final : public NonFatalException { 34 | public: 35 | EOFException() : NonFatalException("EOF encountered") {} 36 | }; 37 | 38 | class FdClosedException final : public NonFatalException { 39 | public: 40 | FdClosedException() : NonFatalException("fd closed") {} 41 | }; 42 | 43 | class TimeoutException final : public NonFatalException { 44 | public: 45 | TimeoutException() : NonFatalException("operation timeout") {} 46 | }; 47 | 48 | class DNSException final : public NonFatalException { 49 | public: 50 | DNSException() : NonFatalException("dns error") {} 51 | }; 52 | 53 | } 54 | 55 | #endif -------------------------------------------------------------------------------- /include/kingpin/IOHandler.h: -------------------------------------------------------------------------------- 1 | #ifndef __IOHANDLER_H_de3094e9a992_ 2 | #define __IOHANDLER_H_de3094e9a992_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #include "kingpin/Exception.h" 20 | #include "kingpin/AsyncLogger.h" 21 | #include "kingpin/Utils.h" 22 | 23 | using namespace std; 24 | 25 | namespace kingpin { 26 | 27 | // Base IO Thread 28 | template 29 | class IOHandler { 30 | unique_ptr __evs_ptr; 31 | vector > _buffer_pool; 32 | public: 33 | _TPSharedData *_tsd; 34 | int _epfd = ::epoll_create(1); 35 | struct epoll_event *_evs; 36 | unique_ptr _t; 37 | int _fd_num = 0; 38 | 39 | unordered_map > _rbh; 40 | unordered_map > _wbh; 41 | 42 | explicit IOHandler(_TPSharedData *tsd); 43 | IOHandler(const IOHandler &) = delete; 44 | IOHandler &operator=(const IOHandler &) = delete; 45 | virtual ~IOHandler() = 0; 46 | 47 | virtual void onEpollLoop(); 48 | virtual void onConnect(int conn); 49 | virtual void onMessage(int conn); 50 | virtual void onWriteComplete(int conn); 51 | virtual void onPassivelyClosed(int conn); 52 | virtual void run() = 0; 53 | 54 | void join(); 55 | void createBuffer(int conn); 56 | void destoryBuffer(int conn); 57 | void writeToBuffer(int conn); 58 | void writeToBuffer(int conn, const char *str); 59 | void onWritable(int conn); 60 | void onReadable(int conn); 61 | void onClean(int conn); 62 | void processEvent(struct epoll_event &event); 63 | }; 64 | 65 | template 66 | IOHandler<_TPSharedData>::IOHandler(_TPSharedData *tsd) : _tsd(tsd) { 67 | __evs_ptr = unique_ptr(new epoll_event[_tsd->_max_client_per_thr]); 68 | _evs = __evs_ptr.get(); 69 | } 70 | 71 | template 72 | IOHandler<_TPSharedData>::~IOHandler() {} 73 | 74 | template 75 | void IOHandler<_TPSharedData>::onEpollLoop() {} 76 | 77 | template 78 | void IOHandler<_TPSharedData>::onConnect(int conn) {} 79 | 80 | template 81 | void IOHandler<_TPSharedData>::onMessage(int conn) {} 82 | 83 | template 84 | void IOHandler<_TPSharedData>::onWriteComplete(int conn) {} 85 | 86 | template 87 | void IOHandler<_TPSharedData>::onPassivelyClosed(int conn) {} 88 | 89 | template 90 | void IOHandler<_TPSharedData>::join() { _t->join(); } 91 | 92 | template 93 | void IOHandler<_TPSharedData>::createBuffer(int conn) { 94 | int size = _buffer_pool.size(); 95 | if (size < 2) { 96 | _rbh[conn] = shared_ptr(new Buffer()); 97 | _wbh[conn] = shared_ptr(new Buffer()); 98 | } else { 99 | _rbh[conn] = _buffer_pool[size-1]; 100 | _wbh[conn] = _buffer_pool[size-2]; 101 | _buffer_pool.pop_back(); 102 | _buffer_pool.pop_back(); 103 | } 104 | 105 | } 106 | 107 | template 108 | void IOHandler<_TPSharedData>::destoryBuffer(int conn) { 109 | _buffer_pool.push_back(_rbh[conn]); 110 | _buffer_pool.push_back(_wbh[conn]); 111 | _rbh.erase(conn); 112 | _wbh.erase(conn); 113 | } 114 | 115 | template 116 | void IOHandler<_TPSharedData>::onClean(int conn) { 117 | onPassivelyClosed(conn); 118 | destoryBuffer(conn); 119 | ::close(conn); 120 | } 121 | 122 | // This function would be executed by one thread serially 123 | // with onMessage, so NO worry about write buffer's parallel 124 | // write. And conn be registered EPOLLIN while write is not 125 | // completed. 126 | template 127 | void IOHandler<_TPSharedData>::writeToBuffer(int conn) { 128 | Buffer *wb; 129 | try { 130 | wb = _wbh[conn].get(); 131 | wb->writeNioFromBufferTillBlock(conn); 132 | if (wb->writeComplete() ) { 133 | wb->clear(); 134 | onWriteComplete(conn); } 135 | else { 136 | epollRemove(_epfd, conn); 137 | epollRegister(_epfd, conn, EPOLLOUT); 138 | } 139 | } catch(const exception &e) { 140 | INFO << e << END; 141 | onClean(conn); 142 | } 143 | } 144 | 145 | template 146 | void IOHandler<_TPSharedData>::writeToBuffer(int conn, const char *str) { 147 | _wbh[conn]->appendToBuffer(str); 148 | writeToBuffer(conn); 149 | } 150 | 151 | 152 | template 153 | void IOHandler<_TPSharedData>::onWritable(int conn) { 154 | Buffer *wb; 155 | try { 156 | wb = _wbh[conn].get(); 157 | wb->writeNioFromBufferTillBlock(conn); 158 | if (wb->writeComplete() ) { 159 | wb->clear(); 160 | onWriteComplete(conn); 161 | epollRegister(_epfd, conn, EPOLLIN); 162 | } 163 | } catch(const exception &e) { 164 | INFO << e << END; 165 | onClean(conn); 166 | } 167 | } 168 | 169 | template 170 | void IOHandler<_TPSharedData>::onReadable(int conn) { 171 | Buffer *rb; 172 | try { 173 | rb = _rbh[conn].get(); 174 | rb->readNioToBufferTillBlock(conn); 175 | onMessage(conn); 176 | } catch(const exception &e) { 177 | INFO << e << END; 178 | onClean(conn); 179 | } 180 | } 181 | 182 | template 183 | void IOHandler<_TPSharedData>::processEvent(struct epoll_event &event) { 184 | int fd = event.data.fd; 185 | uint32_t events = event.events; 186 | if (events & EPOLLIN) { 187 | INFO << "conn " << fd << " readable" << END; 188 | this->onReadable(fd); 189 | } 190 | if (events & EPOLLOUT) { 191 | INFO << "conn " << fd << " writable" << END; 192 | this->onWritable(fd); 193 | } 194 | } 195 | 196 | 197 | // Client IO Thread 198 | template 199 | class IOHandlerForClient : public IOHandler<_TPSharedData> { 200 | public: 201 | unordered_map _conn_init_message; 202 | unordered_map > _conn_info; 203 | unordered_set _syn_sent; 204 | 205 | explicit IOHandlerForClient(_TPSharedData *tsd); 206 | IOHandlerForClient(const IOHandlerForClient &) = delete; 207 | IOHandlerForClient &operator=(const IOHandlerForClient &) = delete; 208 | virtual ~IOHandlerForClient() = 0; 209 | 210 | virtual void onConnectFailed(int conn); // only client 211 | 212 | void run(); 213 | void _get_from_pool(int batch); 214 | void _run(); 215 | }; 216 | 217 | 218 | template 219 | IOHandlerForClient<_TPSharedData>::IOHandlerForClient(_TPSharedData *tsd) 220 | : IOHandler<_TPSharedData>(tsd) {} 221 | 222 | template 223 | IOHandlerForClient<_TPSharedData>::~IOHandlerForClient() {} 224 | 225 | template 226 | void IOHandlerForClient<_TPSharedData>::onConnectFailed(int conn) {} 227 | 228 | template 229 | void IOHandlerForClient<_TPSharedData>::run() { 230 | this->_t = unique_ptr(new thread(&IOHandlerForClient::_run, this)); 231 | } 232 | 233 | template 234 | void IOHandlerForClient<_TPSharedData>::_get_from_pool(int batch) { 235 | while(batch--) { 236 | if (this->_tsd->_pool.size() == 0) { break; } 237 | ++(this->_fd_num); 238 | tuple t = this->_tsd->raw_get(); 239 | int sock = connectIp(get<0>(t).c_str(), get<1>(t), 0); 240 | INFO << "connecting to " << get<0>(t).c_str() << ":" << get<1>(t) << END; 241 | epollRegister(this->_epfd, sock, EPOLLOUT); 242 | _conn_init_message[sock] = get<2>(t); 243 | _conn_info[sock] = make_pair(get<0>(t), get<1>(t)); 244 | _syn_sent.insert(sock); 245 | } 246 | } 247 | 248 | 249 | template 250 | void IOHandlerForClient<_TPSharedData>::_run() { 251 | INFO << "thread start" << END; 252 | while (true) { 253 | this->onEpollLoop(); 254 | if (0 == this->_fd_num) { 255 | unique_lock m(this->_tsd->_pool_lock); 256 | this->_tsd->_cv.wait(m, [this]()->bool{ 257 | return this->_tsd->_pool.size() != 0; }); 258 | INFO << "thread get lock" << END; 259 | _get_from_pool(this->_tsd->_batch); 260 | } else if (this->_tsd->_pool.size() != 0 && 261 | this->_tsd->_pool_lock.try_lock()) { 262 | INFO << "thread get lock" << END; 263 | _get_from_pool(this->_tsd->_batch); 264 | this->_tsd->_pool_lock.unlock(); 265 | } 266 | assert(this->_fd_num > 0); 267 | int num = ::epoll_wait(this->_epfd, this->_evs, 268 | this->_tsd->_max_client_per_thr, this->_tsd->_ep_timeout); 269 | for (int i = 0; i < num; ++i) { 270 | int fd = this->_evs[i].data.fd; 271 | if (0 == _syn_sent.count(fd)) { 272 | this->processEvent(this->_evs[i]); 273 | } else { 274 | assert(this->_evs[i].events & EPOLLOUT); 275 | epollRemove(this->_epfd, fd); 276 | int optval; 277 | socklen_t len = sizeof(optval); 278 | if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &len) < 0) { 279 | fatalError("syscall getsockopt error"); 280 | } 281 | _syn_sent.erase(fd); 282 | if (0 == optval) { 283 | INFO << "connect succeeded with conn " << fd << END; 284 | this->createBuffer(fd); 285 | this->writeToBuffer(fd, _conn_init_message[fd].c_str()); 286 | this->onConnect(fd); 287 | epollRegister(this->_epfd, fd, EPOLLIN); 288 | } else { 289 | INFO << "connect failed with conn " << fd << END; 290 | this->onConnectFailed(fd); 291 | ::close(fd); 292 | } 293 | } 294 | } 295 | } 296 | } 297 | 298 | 299 | // Server IO Thread 300 | template 301 | class IOHandlerForServer : public IOHandler<_TPSharedData> { 302 | public: 303 | explicit IOHandlerForServer(_TPSharedData *tsd); 304 | IOHandlerForServer(const IOHandlerForServer &) = delete; 305 | IOHandlerForServer &operator=(const IOHandlerForServer &) = delete; 306 | virtual ~IOHandlerForServer() = 0; 307 | 308 | void run(); 309 | void _run(); 310 | void _remove_listen(); 311 | }; 312 | 313 | template 314 | IOHandlerForServer<_TPSharedData>::IOHandlerForServer(_TPSharedData *tsd) 315 | : IOHandler<_TPSharedData>(tsd) {} 316 | 317 | template 318 | IOHandlerForServer<_TPSharedData>::~IOHandlerForServer() {} 319 | 320 | template 321 | void IOHandlerForServer<_TPSharedData>::run() { 322 | this->_t = unique_ptr(new thread(&IOHandlerForServer::_run, this)); 323 | } 324 | 325 | template 326 | void IOHandlerForServer<_TPSharedData>::_remove_listen() { 327 | epollRemove(this->_epfd, this->_tsd->_listenfd); 328 | this->_tsd->_listenfd_lock.unlock(); 329 | INFO << "thread release lock" << END; 330 | } 331 | 332 | template 333 | void IOHandlerForServer<_TPSharedData>::_run() { 334 | INFO << "thread start" << END; 335 | while (true) { 336 | this->onEpollLoop(); 337 | bool hold_listen_lock = false; 338 | if (0 == this->_fd_num) { 339 | this->_tsd->_listenfd_lock.lock(); 340 | hold_listen_lock = true; 341 | } 342 | else if (this->_tsd->_listenfd_lock.try_lock()) { 343 | hold_listen_lock = true; 344 | } 345 | if (hold_listen_lock) { 346 | INFO << "thread get lock" << END; 347 | ++(this->_fd_num); 348 | epollRegister(this->_epfd, this->_tsd->_listenfd, EPOLLIN); 349 | } 350 | assert(this->_fd_num > 0); 351 | int num = epoll_wait(this->_epfd, this->_evs, 352 | this->_tsd->_max_client_per_thr, this->_tsd->_ep_timeout); 353 | for (int i = 0; i < num; ++i) { 354 | int fd = this->_evs[i].data.fd; 355 | if (fd != this->_tsd->_listenfd) { 356 | this->processEvent(this->_evs[i]); 357 | } else { 358 | for (int j = 0; j < this->_tsd->_batch; ++j) { 359 | int conn = ::accept4(fd, NULL, NULL, SOCK_NONBLOCK); 360 | if (conn < 0) { 361 | if (errno == EAGAIN || errno == EWOULDBLOCK) { 362 | INFO << "accepted " << j << " sock(s), will release lock" << END; 363 | break; 364 | } else { fatalError("syscall accept4 error"); } 365 | } 366 | INFO << "new connection " << conn << " accepted" << END; 367 | this->createBuffer(conn); 368 | try { 369 | epollRegister(this->_epfd, conn, EPOLLIN); 370 | this->onConnect(conn); 371 | } catch (...) { 372 | this->destoryBuffer(conn); 373 | ::close(conn); 374 | } 375 | } 376 | _remove_listen(); 377 | } 378 | } 379 | } 380 | } 381 | 382 | 383 | } 384 | 385 | #endif 386 | -------------------------------------------------------------------------------- /include/kingpin/Mutex.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "kingpin/Utils.h" 6 | 7 | using namespace std; 8 | 9 | namespace kingpin { 10 | 11 | class RWLock final { 12 | pid_t _wr_owner; 13 | #ifdef _KINGPIN_DEBUG_ 14 | unordered_set _rd_owner; 15 | mutex _debug_lock; 16 | #endif 17 | public: 18 | enum LOCK_TYPE { 19 | READ, 20 | WRITE 21 | }; 22 | shared_ptr __rw_lock; 23 | pthread_rwlock_t *_rw_lock; 24 | 25 | LOCK_TYPE _default_lock = LOCK_TYPE::READ; 26 | 27 | RWLock() { 28 | __rw_lock = unique_ptr (new pthread_rwlock_t); 29 | _rw_lock = __rw_lock.get(); 30 | if (::pthread_rwlock_init(_rw_lock, nullptr) != 0) 31 | { fatalError("syscall pthread_rwlock_init error"); } 32 | } 33 | RWLock(const RWLock &) = delete; 34 | RWLock &operator=(const RWLock &) = delete; 35 | ~RWLock() { 36 | if (::pthread_rwlock_destroy(_rw_lock) < 0) 37 | { fatalError("syscall pthread_rwlock_destroy error"); } 38 | } 39 | 40 | void lock() { 41 | if (LOCK_TYPE::READ == _default_lock) { rd_lock(); } 42 | else { wr_lock(); } 43 | } 44 | void unlock() { 45 | if (_wr_owner == gettid()) { _wr_owner = 0; } 46 | #ifdef _KINGPIN_DEBUG_ 47 | { 48 | unique_lock lock(_debug_lock); 49 | _rd_owner.erase(gettid()); 50 | } 51 | #endif 52 | if (::pthread_rwlock_unlock(_rw_lock) != 0) 53 | { fatalError("syscall pthread_rwlock_unlock error"); } 54 | } 55 | void rd_lock() { 56 | if (_wr_owner == gettid()) { fatalError("cannot rd_lock() when already wr_lock()"); } 57 | if (::pthread_rwlock_rdlock(_rw_lock) != 0) 58 | { fatalError("syscall pthread_rwlock_rdlock error"); } 59 | assert(_wr_owner == 0); 60 | #ifdef _KINGPIN_DEBUG_ 61 | { 62 | unique_lock lock(_debug_lock); 63 | _rd_owner.insert(gettid()); 64 | } 65 | #endif 66 | } 67 | void wr_lock() { 68 | if (::pthread_rwlock_wrlock(_rw_lock) != 0) 69 | { fatalError("syscall pthread_rwlock_wrlock error"); } 70 | #ifdef _KINGPIN_DEBUG_ 71 | assert(_rd_owner.empty()); 72 | #endif 73 | _wr_owner = gettid(); 74 | } 75 | }; 76 | 77 | class WRLockGuard { 78 | RWLock *_lock; 79 | public: 80 | WRLockGuard(RWLock &m) { _lock = &m; _lock->wr_lock(); } 81 | WRLockGuard(const WRLockGuard &) = delete; 82 | WRLockGuard &operator=(const WRLockGuard &) = delete; 83 | ~WRLockGuard() { _lock->unlock(); } 84 | void lock() { _lock->wr_lock(); } 85 | void unlock() { _lock->unlock(); } 86 | }; 87 | 88 | class RDLockGuard { 89 | RWLock *_lock; 90 | public: 91 | RDLockGuard(RWLock &m) { _lock = &m; _lock->rd_lock(); } 92 | RDLockGuard(const RDLockGuard &) = delete; 93 | RDLockGuard &operator=(const RDLockGuard &) = delete; 94 | ~RDLockGuard() { _lock->unlock(); } 95 | void lock() { _lock->rd_lock(); } 96 | void unlock() { _lock->unlock(); } 97 | }; 98 | 99 | class RecursiveLock { 100 | pthread_mutex_t _lock; 101 | pid_t _owner; 102 | int _count; 103 | public: 104 | RecursiveLock() { 105 | pthread_mutexattr_t attr; 106 | if (::pthread_mutexattr_init(&attr) != 0) { 107 | fatalError("syscall pthread_mutexattr_init error"); 108 | } 109 | if (::pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) { 110 | fatalError("syscall pthread_mutexattr_settype error"); 111 | } 112 | if (::pthread_mutex_init(&_lock, &attr) != 0) { 113 | fatalError("syscall pthread_mutex_init error"); 114 | } 115 | if (::pthread_mutexattr_destroy(&attr) != 0) { 116 | fatalError("syscall pthread_mutexattr_destroy error"); 117 | } 118 | } 119 | RecursiveLock(const RecursiveLock &) = delete; 120 | RecursiveLock &operator=(const RecursiveLock &) = delete; 121 | ~RecursiveLock() { 122 | if (::pthread_mutex_destroy(&_lock) != 0) { 123 | fatalError("syscall pthread_mutex_destory error"); 124 | } 125 | } 126 | void lock() { 127 | if (::pthread_mutex_lock(&_lock) != 0) { 128 | fatalError("syscall pthread_mutex_lock error"); 129 | } 130 | _owner = gettid(); 131 | _count++; 132 | } 133 | void unlock() { 134 | if (--_count == 0) { _owner = 0; } 135 | if (::pthread_mutex_unlock(&_lock) != 0) { 136 | fatalError("syscall pthread_mutex_unlock error"); 137 | } 138 | } 139 | }; 140 | 141 | 142 | } -------------------------------------------------------------------------------- /include/kingpin/TPSharedData.h: -------------------------------------------------------------------------------- 1 | #ifndef __TPSHAREDDARA_H_f2b87e623d0d_ 2 | #define __TPSHAREDDARA_H_f2b87e623d0d_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "kingpin/Buffer.h" 13 | 14 | using namespace std; 15 | 16 | namespace kingpin { 17 | 18 | class TPSharedData { 19 | public: 20 | TPSharedData() = default; 21 | TPSharedData(const TPSharedData &) = delete; 22 | TPSharedData& operator=(const TPSharedData &) = delete; 23 | virtual ~TPSharedData() {} 24 | 25 | // Config Param 26 | int _max_client_per_thr = 2048; 27 | int _ep_timeout = 1; 28 | int _batch = 1; 29 | }; 30 | 31 | class TPSharedDataForServer : public TPSharedData { 32 | public: 33 | virtual ~TPSharedDataForServer() {} 34 | int _port; 35 | // DONOT use this lock again unless you know what you're doing 36 | mutex _listenfd_lock; 37 | int _listenfd; 38 | 39 | // Config Param 40 | int _listen_num = 1024; 41 | }; 42 | 43 | class TPSharedDataForClient : public TPSharedData { 44 | public: 45 | virtual ~TPSharedDataForClient() {} 46 | using _t_host = pair; 47 | struct _HostCompare { 48 | size_t _hash(const _t_host &s) const { 49 | return hash()(s.first) * 100 + hash()(s.second); 50 | } 51 | bool operator()(const _t_host &lhs, const _t_host &rhs) const { 52 | return _hash(lhs) < _hash(rhs); 53 | } 54 | }; 55 | 56 | // DONOT use this lock again unless you know what you're doing 57 | mutex _pool_lock; 58 | condition_variable _cv; 59 | map<_t_host, vector, _HostCompare> _pool; 60 | 61 | void raw_add(string host, int port, string init) { 62 | pair target = make_pair(move(host), move(port)); 63 | _pool[target].emplace_back(init); 64 | } 65 | 66 | void add(string host, int port, string init) { 67 | { 68 | unique_lock _tl(this->_pool_lock); 69 | raw_add(host, port, init); 70 | } 71 | _cv.notify_all(); 72 | } 73 | 74 | tuple raw_get() { 75 | assert(this->_pool.size() > 0); 76 | auto iter = _pool.begin(); 77 | string host = iter->first.first; 78 | int port = iter->first.second; 79 | string init = iter->second.back(); 80 | iter->second.pop_back(); 81 | if (iter->second.size() == 0) { _pool.erase(iter->first); } 82 | return make_tuple(move(host), move(port), move(init)); 83 | } 84 | 85 | tuple get() { 86 | unique_lock _tl(this->_pool_lock); 87 | return move(raw_get()); 88 | } 89 | }; 90 | 91 | } 92 | 93 | #endif 94 | -------------------------------------------------------------------------------- /include/kingpin/Utils.h: -------------------------------------------------------------------------------- 1 | #ifndef __UTILS_H_de3094e9a992_ 2 | #define __UTILS_H_de3094e9a992_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | static_assert(sizeof(sockaddr) == sizeof(sockaddr_in)); 13 | 14 | namespace kingpin { 15 | 16 | pid_t gettid(); 17 | 18 | time_t scTime(); 19 | 20 | string timestamp(time_t t = 0, const char *format = nullptr); 21 | 22 | void fatalError(const char *str); 23 | 24 | void nonFatalError(const char *str); 25 | 26 | void fdClosedError(const char *str); 27 | 28 | void timeoutError(const char *str); 29 | 30 | void dnsError(const char *str); 31 | 32 | void setTcpSockaddr(struct sockaddr_in *addr_ptr, const char *ip, int port); 33 | 34 | void getTcpHostAddr(struct sockaddr_in *addr_ptr, const char *host, int port); 35 | 36 | string getHostIp(const char *host); 37 | 38 | void setNonBlock(int fd); 39 | 40 | int connectAddr(struct sockaddr_in *addr_ptr, int timeout = 0); 41 | 42 | int connectHost(const char *host, int port, int timeout = 0); 43 | 44 | int connectIp(const char *ip, int port, int timeout = 0); 45 | 46 | int initListen(int port, int listen_num = 1024, bool nio = true); 47 | 48 | void epollRegister(int epfd, int fd, uint32_t events); 49 | 50 | void epollRemove(int epfd, int fd); 51 | 52 | void split(string s, string sep, vector& subs); 53 | 54 | void ignoreSignal(int sig); 55 | 56 | } 57 | 58 | #endif 59 | -------------------------------------------------------------------------------- /lib/AsyncLogger.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "kingpin/Exception.h" 14 | #include "kingpin/Buffer.h" 15 | #include "kingpin/AsyncLogger.h" 16 | #include "kingpin/Utils.h" 17 | 18 | using namespace std; 19 | 20 | namespace kingpin { 21 | 22 | AsyncLogger::AsyncLogger(int level) : _level(level) { 23 | if (_level != 1 && _level != 2) { return; } 24 | _thr_ptr = unique_ptr(new thread(&AsyncLogger::_run, this)); 25 | } 26 | 27 | void AsyncLogger::_write_head() { 28 | assert(_level == 1 || _level == 2); 29 | const char *str = "- [INFO] "; 30 | if (_level == 2) { str = "- [ERROR] "; } 31 | pid_t id = gettid(); 32 | get<0>(_t_buffers[id])->appendToBuffer(str); 33 | } 34 | 35 | void AsyncLogger::_write_time() { 36 | string str = timestamp(); 37 | pid_t id = gettid(); 38 | get<0>(_t_buffers[id])->appendToBuffer("["); 39 | get<0>(_t_buffers[id])->appendToBuffer(str); 40 | get<0>(_t_buffers[id])->appendToBuffer("] "); 41 | } 42 | 43 | void AsyncLogger::_write_tid() { 44 | std::stringstream ss; ss << this_thread::get_id(); 45 | pid_t id = gettid(); 46 | get<0>(_t_buffers[id])->appendToBuffer("[TID "); 47 | get<0>(_t_buffers[id])->appendToBuffer(ss.str().c_str()); 48 | get<0>(_t_buffers[id])->appendToBuffer("] "); 49 | } 50 | 51 | void AsyncLogger::_write_debug() { 52 | _write_head(); 53 | _write_time(); 54 | _write_tid(); 55 | } 56 | 57 | bool AsyncLogger::_no_log() { 58 | for (auto iter = _t_buffers.cbegin(); iter != _t_buffers.cend(); ++iter) { 59 | if (get<0>(iter->second).get()->_offset) { return false; } 60 | } 61 | return true; 62 | } 63 | 64 | AsyncLogger &AsyncLogger::operator<<(const long num) { 65 | stringstream ss; 66 | ss << num; 67 | return (*this << ss.str().c_str()); 68 | } 69 | 70 | AsyncLogger &AsyncLogger::operator<<(const string &s) { 71 | return (*this << s.c_str()); 72 | } 73 | 74 | AsyncLogger &AsyncLogger::operator<<(const exception &e) { 75 | return (*this << e.what()); 76 | } 77 | 78 | void AsyncLogger::_init_buffer(pid_t tid) { 79 | WRLockGuard lock(_map_lock); 80 | _t_buffers[tid] = make_tuple<> 81 | (shared_ptr(new Buffer), shared_ptr(new RecursiveLock), 0, scTime()); 82 | } 83 | 84 | // All the overloads except END will call "operator<<(const char *str)" 85 | AsyncLogger &AsyncLogger::operator<<(const char *str) { 86 | pid_t tid = gettid(); 87 | { 88 | RDLockGuard lock(_map_lock); 89 | if (0 == _t_buffers.count(tid)) { 90 | lock.unlock(); 91 | _init_buffer(tid); 92 | lock.lock(); 93 | } 94 | get<1>(_t_buffers[tid])->lock(); 95 | ++get<2>(_t_buffers[tid]); 96 | if (1 == get<2>(_t_buffers[tid])) { _write_debug(); } 97 | get<0>(_t_buffers[tid])->appendToBuffer(str); 98 | } 99 | return *this; 100 | } 101 | 102 | // Release lock and notify cv 103 | AsyncLogger &AsyncLogger::operator<<(const AsyncLogger &) { 104 | pid_t tid = gettid(); 105 | { 106 | RDLockGuard lock(_map_lock); 107 | if (0 == _t_buffers.count(tid)) { 108 | lock.unlock(); 109 | _init_buffer(tid); 110 | lock.lock(); 111 | } 112 | get<1>(_t_buffers[tid])->lock(); 113 | int recur_num = get<2>(_t_buffers[tid]) + 1; 114 | get<2>(_t_buffers[tid]) = 0; 115 | get<0>(_t_buffers[tid])->appendToBuffer("\n"); 116 | get<3>(_t_buffers[tid]) = scTime(); 117 | for (int i = 0; i < recur_num; ++i) { get<1>(_t_buffers[tid])->unlock(); } 118 | } 119 | _thr_cv.notify_one(); 120 | return *this; 121 | } 122 | 123 | void AsyncLogger::_run() { 124 | while (true) { 125 | bool shall_delay = true; 126 | set remove_list; 127 | { 128 | RDLockGuard lock(_map_lock); 129 | for (auto iter = _t_buffers.cbegin(); iter != _t_buffers.cend(); ++iter) { 130 | unique_lock lock(*((get<1>(iter->second)).get())); 131 | Buffer *buffer = get<0>(iter->second).get(); 132 | if (buffer->_offset) { 133 | buffer->writeNioFromBufferTillEnd(_level); 134 | shall_delay = false; 135 | } else { 136 | if (get<3>(iter->second) + _expired < scTime()) 137 | { remove_list.insert(iter->first); } 138 | } 139 | } 140 | } 141 | if (remove_list.size()) { 142 | WRLockGuard lock(_map_lock); 143 | for (auto iter = remove_list.cbegin(); iter != remove_list.cend(); ++iter) { 144 | if (0 == get<0>(_t_buffers[*iter])->_offset) 145 | { _t_buffers.erase(*iter); } 146 | } 147 | } 148 | if (shall_delay) { 149 | WRLockGuard lock(_map_lock); 150 | shall_delay = _no_log(); 151 | if (shall_delay && _stop) { break; } 152 | } 153 | if (shall_delay) { 154 | RDLockGuard lock(_map_lock); 155 | _thr_cv.wait(lock); 156 | } 157 | } 158 | } 159 | 160 | AsyncLogger::~AsyncLogger() { 161 | if (_level != 1 && _level != 2) { return; } 162 | { 163 | RDLockGuard map_lock(_map_lock); 164 | _stop = true; 165 | } 166 | _thr_cv.notify_one(); 167 | _thr_ptr->join(); 168 | } 169 | 170 | AsyncLogger INFO(1); 171 | AsyncLogger ERROR(2); 172 | const AsyncLogger END(-1); 173 | 174 | } 175 | -------------------------------------------------------------------------------- /lib/Buffer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "kingpin/Exception.h" 11 | #include "kingpin/Utils.h" 12 | #include "kingpin/Buffer.h" 13 | 14 | using namespace std; 15 | 16 | namespace kingpin { 17 | 18 | Buffer::Buffer() : Buffer(_default_cap) {} 19 | 20 | Buffer::Buffer(int cap) : _cap(cap) { 21 | __buffer = unique_ptr(new char[_cap]); 22 | _buffer = __buffer.get(); 23 | ::memset(_buffer, 0, _cap); 24 | } 25 | 26 | Buffer::~Buffer() {} 27 | 28 | // resize to at least cap 29 | void Buffer::resize(int cap) { 30 | if (_cap >= cap) return; 31 | while(_cap < cap) { _cap *= 2; } 32 | unique_ptr nbuffer = unique_ptr(new char[_cap]); 33 | ::memset(nbuffer.get(), 0, _cap); 34 | for (int i = _start; i < _offset; ++i) { nbuffer.get()[i] = _buffer[i]; } 35 | __buffer = move(nbuffer); 36 | _buffer = __buffer.get(); 37 | } 38 | 39 | void Buffer::clear() { 40 | ::memset(_buffer, 0, _cap); 41 | _start = 0; 42 | _offset = 0; 43 | } 44 | 45 | // Read "len" bytes from NIO to buffer: 46 | // If no data for conn or read complete, return "length" 47 | // If read until EOF(conn closed or fd end), throw "EOFException" 48 | // If oppo collapses, throw "fdClosedException" 49 | int Buffer::readNioToBuffer(int fd, int len) { 50 | resize(_offset + len); 51 | int total = 0; 52 | const char *str = "syscall read error"; 53 | while (true) { 54 | int curr = ::read(fd, _buffer + _offset, len - total); 55 | if (curr == -1) { 56 | if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } 57 | else if (errno == ECONNRESET) { 58 | fdClosedError(str); 59 | } else { fatalError(str); } 60 | } 61 | total += curr; 62 | _offset += curr; 63 | if (curr == 0) { throw EOFException(); } 64 | if (total == len) { break; } 65 | } 66 | return total; 67 | } 68 | 69 | // Read all data available 70 | int Buffer::readNioToBufferTillBlock(int fd) { 71 | int total = 0; 72 | while(true) { 73 | int curr = readNioToBuffer(fd, _default_step); 74 | total += curr; 75 | if (curr == 0) break; 76 | } 77 | return total; 78 | } 79 | 80 | int Buffer::readNioToBufferTillBlockOrEOF(int fd) { 81 | int start = _offset; 82 | try { readNioToBufferTillBlock(fd); } 83 | catch (const EOFException &e) {} 84 | return _offset - start; 85 | } 86 | 87 | // Read until end, if no data available, will sleep 88 | int Buffer::readNioToBufferTillEnd(int fd, const char *end, int step) { 89 | assert(step > 0); 90 | int str_len = strlen(end); 91 | while(true) { 92 | int curr = readNioToBuffer(fd, step); 93 | if (curr == 0) { this_thread::sleep_for(chrono::milliseconds(_delay)); continue; } 94 | for (int i = max(_offset-curr, str_len-1); i <= _offset; ++i) { 95 | bool found = true; 96 | int start = i - str_len + 1; 97 | for (int k = 0; k < str_len; ++k) { 98 | if (_buffer[start+k] != end[k]) { found = false; break; } 99 | } 100 | if (found) return start; 101 | } 102 | } 103 | } 104 | 105 | // Write "len" bytes to NIO from buffer: 106 | // If NIO's buffer is full or write complete, return "length" 107 | // If oppo collapses, throw "fdClosedException" 108 | int Buffer::writeNioFromBuffer(int fd, int len) { 109 | assert((len <= _offset - _start ) && (len > 0)); 110 | int total = 0; 111 | const char *str = "syscall write error"; 112 | while (0 != len) { 113 | int curr = ::write(fd, _buffer + _start, len); 114 | if (curr == -1) { 115 | if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } 116 | else if (errno == EPIPE || errno == ECONNRESET) { 117 | fdClosedError(str); 118 | } else { fatalError(str); } 119 | } 120 | assert (curr != 0); 121 | _start += curr; 122 | len -= curr; 123 | total += curr; 124 | } 125 | return total; 126 | } 127 | 128 | // Write until NIO's buffer is full or no more to write 129 | int Buffer::writeNioFromBufferTillBlock(int fd) { 130 | int total = 0; 131 | int step = _default_step; 132 | while (_start != _offset) { 133 | if (step > _offset - _start) { step = _offset - _start; } 134 | int curr = writeNioFromBuffer(fd, step); 135 | total += curr; 136 | if (curr == 0) { break; } 137 | } 138 | return total; 139 | } 140 | 141 | // Write all data to buffer, if NIO's buffer is full, will sleep 142 | int Buffer::writeNioFromBufferTillEnd(int fd, int step) { 143 | int total = 0; 144 | while (_start != _offset) { 145 | if (step > _offset - _start) { step = _offset - _start; } 146 | int curr = writeNioFromBuffer(fd, step); 147 | total += curr; 148 | if (curr == 0) { this_thread::sleep_for(chrono::milliseconds(_delay)); } 149 | } 150 | clear(); 151 | return total; 152 | } 153 | 154 | void Buffer::appendToBuffer(const char *str) { 155 | int str_len = ::strlen(str); 156 | resize(_offset + str_len); 157 | for (int i = 0; i < str_len; ++i) { _buffer[_offset+i] = str[i]; } 158 | _offset += str_len; 159 | } 160 | 161 | void Buffer::appendToBuffer(const string &str) { 162 | appendToBuffer(str.c_str()); 163 | } 164 | 165 | void Buffer::stripEnd(char end) { 166 | for (int i = _offset-1; i >= 0; --i) { 167 | if (_buffer[i] == end) { _buffer[i] = '\0'; _offset--; } 168 | else { break; } 169 | } 170 | } 171 | 172 | bool Buffer::writeComplete() { return _start == _offset; } 173 | 174 | bool Buffer::endsWith(const char *str) const { 175 | return _offset > 0 && ::strcmp(str, _buffer + _offset - ::strlen(str)) == 0; 176 | } 177 | 178 | const int Buffer::_default_cap = 64; 179 | const int Buffer::_default_step = 1024; 180 | 181 | } 182 | -------------------------------------------------------------------------------- /lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set ( LIB 2 | Buffer.cc 3 | Context.cc 4 | Utils.cc 5 | AsyncLogger.cc 6 | ) 7 | 8 | add_library(kingpin_static STATIC ${LIB}) 9 | add_library(kingpin_shared SHARED ${LIB}) 10 | set_target_properties(kingpin_static PROPERTIES OUTPUT_NAME "kingpin") 11 | set_target_properties(kingpin_shared PROPERTIES OUTPUT_NAME "kingpin") 12 | -------------------------------------------------------------------------------- /lib/Context.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "kingpin/Context.h" 6 | #include "kingpin/Utils.h" 7 | 8 | namespace kingpin { 9 | 10 | Context::Context(int timeout) : _timeout(timeout) { 11 | if (::pipe(_pfd) == -1) { fatalError("syscall pipe error"); } 12 | } 13 | 14 | void Context::done() { ::close(_pfd[1]); } 15 | 16 | bool Context::wait() { 17 | int epfd = ::epoll_create(1); 18 | if (epfd < 0) { fatalError("syscall epoll_create error"); } 19 | struct epoll_event ev; 20 | ev.data.fd = _pfd[0]; 21 | ev.events = EPOLLRDHUP; 22 | if (::epoll_ctl(epfd, EPOLL_CTL_ADD, _pfd[0], &ev) < 0) { 23 | fatalError("syscall epoll_ctl error"); 24 | } 25 | int n = ::epoll_wait(epfd, &ev, 1, _timeout); 26 | ::close(_pfd[0]); 27 | ::close(_pfd[1]); 28 | ::close(epfd); 29 | if (n == -1) { fatalError("syscall epoll_wait error"); } 30 | return n == 1; 31 | } 32 | 33 | ThrWithCtx::ThrWithCtx(ThrFuncPtr f, void *arg, Context *ctx) : _f(f), _arg(arg), _ctx(ctx) {} 34 | 35 | bool ThrWithCtx::run() { 36 | pthread_t thr; 37 | ArgWithCtx argCtx(_f, _arg, _ctx); 38 | if (::pthread_create(&thr, NULL, _thread_wrapper, (void *)(&argCtx)) < 0) { 39 | fatalError("syscall pthread_create error"); 40 | } 41 | bool ok = _ctx->wait(); 42 | if (!ok && ::pthread_cancel(thr) < 0) { 43 | fatalError("syscall pthread_create error"); 44 | } 45 | if (::pthread_join(thr, NULL) < 0) { fatalError("syscall pthread_join error"); } 46 | return ok; 47 | } 48 | 49 | void *ThrWithCtx::_thread_wrapper(void *arg) { 50 | ArgWithCtx *ptr = static_cast(arg); 51 | ptr->_f(ptr->_arg); 52 | ptr->_ctx->done(); 53 | return NULL; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /lib/Utils.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include "kingpin/Exception.h" 19 | #include "kingpin/Utils.h" 20 | #include "kingpin/AsyncLogger.h" 21 | 22 | namespace kingpin { 23 | 24 | pid_t gettid() { 25 | return syscall(SYS_gettid); 26 | } 27 | 28 | time_t scTime() { 29 | time_t t = ::time(NULL); 30 | if (t == -1) { fatalError("syscall time error"); } 31 | return t; 32 | } 33 | 34 | string timestamp(time_t t, const char *format) { 35 | if (t == 0) { t = scTime(); } 36 | if (format == nullptr) { format = "%F %T %Z"; } 37 | tm s_tm; 38 | localtime_r(&t, &s_tm); 39 | char buf[1024]; ::memset(buf, 0, 1024); 40 | if (0 == strftime(buf, 1024, format, &s_tm)) { 41 | fatalError("syscall strftime error"); 42 | } 43 | return buf; 44 | } 45 | 46 | void fatalError(const char *str) { 47 | INFO << str << ": " << ::strerror(errno) << END; 48 | throw FatalException(str); 49 | } 50 | 51 | void nonFatalError(const char *str) { 52 | INFO << str << ": " << ::strerror(errno) << END; 53 | throw NonFatalException(str); 54 | } 55 | 56 | void fdClosedError(const char *str) { 57 | INFO << str << ": " << ::strerror(errno) << END; 58 | throw FdClosedException(); 59 | } 60 | 61 | void timeoutError(const char *str) { 62 | INFO << str << ": " << ::strerror(errno) << END; 63 | throw TimeoutException(); 64 | } 65 | 66 | void dnsError(const char *str) { 67 | INFO << str << ": " << ::strerror(errno) << END; 68 | throw DNSException(); 69 | } 70 | 71 | void setTcpSockaddr(struct sockaddr_in *addr_ptr, const char *ip, int port) { 72 | ::memset(addr_ptr, 0, sizeof(struct sockaddr)); 73 | addr_ptr->sin_family = AF_INET; 74 | addr_ptr->sin_port = htons(port); 75 | int ret = ::inet_pton(AF_INET, ip, (void *)&(addr_ptr->sin_addr.s_addr)); 76 | if (ret == -1 || ret == 0) { fatalError("Unknown error"); } 77 | } 78 | 79 | void getTcpHostAddr(struct sockaddr_in *addr_ptr, const char *host, int port) { 80 | struct addrinfo *p_info; 81 | struct addrinfo info; 82 | ::memset(&info, 0, sizeof(info)); 83 | info.ai_family = AF_INET; 84 | info.ai_socktype = SOCK_STREAM; 85 | info.ai_flags = AI_NUMERICSERV; 86 | if (::getaddrinfo(host, to_string(port).c_str(), &info, &p_info) < 0) { 87 | dnsError("syscall getaddrinfo error"); 88 | } 89 | ::memcpy(addr_ptr, p_info[0].ai_addr, sizeof(struct sockaddr_in)); 90 | ::freeaddrinfo(p_info); 91 | } 92 | 93 | string getHostIp(const char *host) { 94 | int ip_len = 32; 95 | char ip[ip_len]; 96 | ::memset(ip, 0, ip_len); 97 | struct addrinfo *p_info; 98 | if (::getaddrinfo(host, NULL, NULL, &p_info) < 0) { 99 | dnsError("syscall getaddrinfo error"); 100 | } 101 | struct sockaddr_in addr; 102 | ::memcpy(&addr, p_info[0].ai_addr, sizeof(struct sockaddr_in)); 103 | ::freeaddrinfo(p_info); 104 | if (::getnameinfo((struct sockaddr *)&addr, sizeof(struct sockaddr_in), ip, ip_len, 105 | NULL, 0, NI_NUMERICHOST) < 0) { 106 | dnsError("syscall getnameinfo error"); 107 | } 108 | return string(ip); 109 | } 110 | 111 | void setNonBlock(int fd) { 112 | const char *str = "syscall fcntl error"; 113 | int flags = fcntl(fd, F_GETFL); 114 | if (flags < 0) { fatalError(str); } 115 | if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) { 116 | fatalError(str); 117 | } 118 | } 119 | 120 | int connectAddr(struct sockaddr_in *addr_ptr, int timeout) { 121 | int sock; 122 | if ((sock = ::socket(AF_INET, SOCK_STREAM, 0))== -1) { 123 | fatalError("syscall socket error"); 124 | } 125 | if (0 == timeout) { setNonBlock(sock); } 126 | else if (timeout > 0) { 127 | struct timeval tos{timeout, 0}; 128 | if (::setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tos, sizeof(tos)) == -1) { 129 | fatalError("syscall setsockopt error"); 130 | } 131 | } 132 | if (::connect(sock, (sockaddr *)addr_ptr, sizeof(sockaddr)) < 0) { 133 | const char *err_msg = "syscall connect error"; 134 | if (errno != EINPROGRESS) { nonFatalError(err_msg); } 135 | else if (0 != timeout) { timeoutError(err_msg); } 136 | } 137 | return sock; 138 | } 139 | 140 | int connectHost(const char *host, int port, int timeout) { 141 | struct sockaddr_in addr; 142 | getTcpHostAddr(&addr, host, port); 143 | int sock = connectAddr(&addr, timeout); 144 | return sock; 145 | } 146 | 147 | int connectIp(const char *ip, int port, int timeout) { 148 | struct sockaddr_in addr; 149 | setTcpSockaddr(&addr, ip, port); 150 | return connectAddr(&addr, timeout); 151 | } 152 | 153 | int initListen(int port, int listen_num, bool nio) { 154 | int sock = ::socket(AF_INET, SOCK_STREAM, 0); 155 | if (sock < 0) { fatalError("syscall socket error"); } 156 | if (nio) { setNonBlock(sock); } 157 | int optval = 1; 158 | if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) { 159 | fatalError("syscall setsockopt error"); 160 | } 161 | struct sockaddr_in addr; 162 | ::bzero(&addr, sizeof(addr)); 163 | addr.sin_family = AF_INET; 164 | addr.sin_port = ::htons(port); 165 | addr.sin_addr.s_addr = ::htonl(INADDR_ANY); 166 | if (::bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { 167 | fatalError("syscall bind error"); 168 | } 169 | ::listen(sock, listen_num); 170 | return sock; 171 | } 172 | 173 | void epollRegister(int epfd, int fd, uint32_t events) { 174 | struct epoll_event ev; 175 | ev.data.fd = fd; 176 | ev.events = events; 177 | if (::epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1) { 178 | stringstream ss; 179 | ss << "register fd " << fd << " error"; 180 | fatalError(ss.str().c_str()); 181 | } 182 | } 183 | 184 | void epollRemove(int epfd, int fd) { 185 | if (::epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL) == -1) { 186 | stringstream ss; 187 | ss << "remove fd " << fd << " error"; 188 | fatalError(ss.str().c_str()); 189 | } 190 | } 191 | 192 | void split(string s, string sep, vector& subs) { 193 | if (s.size() == 0 || s.size() < sep.size()) return; 194 | uint start = 0; 195 | uint end = s.find(sep); 196 | while (end + sep.size() <= s.size()) { 197 | subs.emplace_back(s.substr(start, end)); 198 | start = end + sep.size(); 199 | end = s.find(sep, start); 200 | } 201 | if (start != s.size()) { 202 | subs.emplace_back(s.substr(start, s.size())); 203 | } 204 | } 205 | 206 | void ignoreSignal(int sig) { 207 | struct sigaction sigact; 208 | ::memset(&sigact, 0, sizeof(struct sigaction)); 209 | sigact.sa_handler = SIG_IGN; 210 | sigact.sa_flags = SA_RESTART; 211 | if (::sigaction(sig, &sigact, NULL) == -1) { 212 | fatalError("ignore signal error"); 213 | } 214 | } 215 | 216 | } 217 | -------------------------------------------------------------------------------- /pictures/PlayChess.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GeniusDai/kingpin/e9a96fdafd2585b11a8c84db8571177a0bc16e35/pictures/PlayChess.png -------------------------------------------------------------------------------- /unittest/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | link_libraries(kingpin_static) 2 | 3 | add_executable(test_context test_context.cc) 4 | add_executable(test_logger test_logger.cc) 5 | add_executable(test_buffer test_buffer.cc) 6 | add_executable(test_utils test_utils.cc) 7 | 8 | enable_testing() 9 | include(GoogleTest) 10 | gtest_discover_tests(test_utils) 11 | gtest_discover_tests(test_buffer) 12 | gtest_discover_tests(test_context) 13 | -------------------------------------------------------------------------------- /unittest/test_buffer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "kingpin/Buffer.h" 13 | 14 | using namespace std; 15 | using namespace kingpin; 16 | 17 | class BufferTest : public testing::Test { 18 | protected: 19 | const char *_file = "./file_for_test"; 20 | const char *_str = "Kingpin is a high performance network library!"; 21 | void SetUp() override { 22 | int fd = open(this->_file, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); 23 | EXPECT_GT(fd, 2); 24 | EXPECT_EQ(write(fd, _str, strlen(_str)), strlen(_str)); 25 | EXPECT_EQ(fsync(fd), 0); 26 | EXPECT_EQ(close(fd), 0); 27 | } 28 | 29 | void TearDown() override { 30 | EXPECT_EQ(remove(this->_file), 0); 31 | } 32 | }; 33 | 34 | TEST_F(BufferTest, test_read) { 35 | Buffer buffer; 36 | int fd = open(this->_file, O_RDONLY); 37 | EXPECT_GT(fd, 2); 38 | int pos = buffer.readNioToBufferTillEnd(fd, "high", 5); 39 | EXPECT_THAT(buffer._buffer + pos, testing::HasSubstr("high")); 40 | buffer.readNioToBufferTillEnd(fd, "k ", 1); 41 | EXPECT_EQ(buffer.readNioToBufferTillBlockOrEOF(fd), 8); 42 | EXPECT_EQ(strcmp(buffer._buffer, this->_str), 0); 43 | EXPECT_EQ(close(fd), 0); 44 | } 45 | 46 | TEST_F(BufferTest, test_write) { 47 | Buffer buffer; 48 | int fd = open(this->_file, O_RDWR); 49 | EXPECT_GT(fd, 2); 50 | const char *str = "Hello, C++!"; 51 | for (int i = 0; i < 10; ++i) { buffer.appendToBuffer(str); } 52 | EXPECT_EQ(buffer._start, 0); 53 | EXPECT_EQ(buffer._offset, 10 * strlen(str)); 54 | EXPECT_EQ(buffer.writeNioFromBufferTillBlock(fd), 10 * strlen(str)); 55 | EXPECT_EQ(fsync(fd), 0); 56 | EXPECT_EQ(close(fd), 0); 57 | } 58 | 59 | int main(int argc, char **argv) { 60 | testing::InitGoogleTest(&argc, argv); 61 | return RUN_ALL_TESTS(); 62 | } -------------------------------------------------------------------------------- /unittest/test_context.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "kingpin/Context.h" 6 | using namespace std; 7 | using namespace kingpin; 8 | 9 | class ContextTest : public testing::TestWithParam { 10 | protected: 11 | int _time_out = 500; 12 | struct SimpleArgs { 13 | int a; 14 | int b; 15 | int ret; 16 | SimpleArgs(int a, int b) : a(a), b(b) {} 17 | }; 18 | 19 | static void *simple_func(void *arg) { 20 | SimpleArgs *ptr = static_cast(arg); 21 | this_thread::sleep_for(chrono::milliseconds(ptr->a)); 22 | ptr->ret = ptr->a + ptr->b; 23 | return NULL; 24 | } 25 | public: 26 | void SetUp() override {} 27 | void TearDown() override {} 28 | }; 29 | 30 | TEST_P(ContextTest, test_with_args) { 31 | // Param : time to sleep 32 | int a = GetParam(); 33 | int b = 8888; 34 | Context ctx(_time_out); 35 | SimpleArgs arg(a, 8888); 36 | ThrWithCtx thr(simple_func, &arg, &ctx); 37 | if (a < _time_out) { EXPECT_TRUE(thr.run()); EXPECT_EQ(arg.ret, a + b); } 38 | else { EXPECT_FALSE(thr.run()); } 39 | } 40 | 41 | INSTANTIATE_TEST_SUITE_P(tc, ContextTest, testing::Values(100, 1000)); 42 | 43 | int main(int argc, char **argv) { 44 | testing::InitGoogleTest(&argc, argv); 45 | return RUN_ALL_TESTS(); 46 | } 47 | -------------------------------------------------------------------------------- /unittest/test_logger.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "kingpin/AsyncLogger.h" 10 | 11 | using namespace std; 12 | using namespace kingpin; 13 | 14 | void log() { 15 | int n = 10; 16 | while (n--) { 17 | ERROR << "TEST" << END << "NEW " << "ERROR" << END; 18 | ERROR << "ERROR LINE:\n"; 19 | ERROR << "ERROR LINE " << 1 << "\n" << "ERROR LINE 2" << END; 20 | } 21 | } 22 | 23 | int main() { 24 | ERROR._expired = 1; 25 | int n_thr = 50; 26 | vector > tp; 27 | for (int i = 0; i < n_thr; ++i) { 28 | tp.push_back(shared_ptr(new thread(&log))); 29 | } 30 | for (int i = 0; i < n_thr; ++i) { 31 | tp[i]->join(); 32 | } 33 | tp.clear(); 34 | sleep(2); 35 | for (int i = 0; i < n_thr; ++i) { 36 | tp.push_back(shared_ptr(new thread(&log))); 37 | } 38 | for (int i = 0; i < n_thr; ++i) { 39 | tp[i]->join(); 40 | } 41 | assert(ERROR._t_buffers.size() == 42 | static_cast(n_thr)); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /unittest/test_utils.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "kingpin/AsyncLogger.h" 6 | #include "kingpin/Utils.h" 7 | #include "kingpin/Exception.h" 8 | 9 | using namespace kingpin; 10 | 11 | TEST(FUNC_split, test) { 12 | vector > args = { 13 | {"hello, kingpin", ","}, 14 | {"hello, kingpin", ", "}, 15 | {"hello, kingpin", " "} 16 | }; 17 | vector > ans = { 18 | {"hello", " kingpin"}, 19 | {"hello", "kingpin"}, 20 | {"hello, kingpin"} 21 | }; 22 | for (uint i = 0; i < ans.size(); ++i) { 23 | vector res; 24 | split(args[i].first, args[i].second, res); 25 | EXPECT_EQ(res, ans[i]); 26 | } 27 | } 28 | 29 | class UtilsTest : public testing::Test { 30 | protected: 31 | static condition_variable _cv_listen; 32 | static condition_variable _cv_conn; 33 | static mutex _m; 34 | static const int _port; 35 | static bool _end; 36 | static bool _listen_ready; 37 | static unique_ptr_t; 38 | 39 | static void _run_listen() { 40 | initListen(_port, 1); 41 | unique_lock lk(_m); 42 | _listen_ready = true; 43 | _cv_conn.notify_all(); 44 | _cv_listen.wait(lk, []()->bool { return _end; } ); 45 | } 46 | 47 | static void _run_connect(int n) { 48 | { 49 | unique_lock lk(_m); 50 | _cv_conn.wait(lk, []()->bool { return _listen_ready; } ); 51 | } 52 | int sock; 53 | int timeout = 1; 54 | try { 55 | if (n % 2) { sock = connectHost("localhost", _port, timeout); } 56 | else { sock = connectIp("127.0.0.1", _port, timeout); } 57 | } catch (const TimeoutException &e) { 58 | return; 59 | } 60 | const char *str = "hello, kingpin"; 61 | if (::write(sock, str, ::strlen(str)) < 0) { 62 | fatalError("syscall write error"); 63 | } 64 | INFO << "write complete" << END; 65 | } 66 | 67 | static void SetUpTestSuite() { 68 | _t = unique_ptr(new thread(UtilsTest::_run_listen)); 69 | } 70 | 71 | static void TearDownTestSuite() { 72 | { 73 | unique_lock lk(_m); 74 | _end = true; 75 | } 76 | _cv_listen.notify_one(); 77 | _t->join(); 78 | } 79 | }; 80 | 81 | const int UtilsTest::_port = 9000; 82 | condition_variable UtilsTest::_cv_listen; 83 | condition_variable UtilsTest::_cv_conn; 84 | mutex UtilsTest::_m; 85 | bool UtilsTest::_end = false; 86 | bool UtilsTest::_listen_ready = false; 87 | unique_ptr UtilsTest::_t; 88 | 89 | TEST_F(UtilsTest, test_connect) { 90 | vector vt; 91 | for (uint i = 0; i < 30; ++i) { 92 | vt.emplace_back(_run_connect, i); 93 | } 94 | for (uint i = 0; i < vt.size(); ++i) { 95 | vt[i].join(); 96 | } 97 | } 98 | 99 | int main(int argc, char **argv) { 100 | ::testing::InitGoogleTest(&argc, argv); 101 | return RUN_ALL_TESTS(); 102 | } 103 | --------------------------------------------------------------------------------