tc_epoll_server.h 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #ifndef __TARS_TC_EPOLL_SERVER_H_
  17. #define __TARS_TC_EPOLL_SERVER_H_
  18. #include <string>
  19. #include <memory>
  20. #include <map>
  21. #include <unordered_map>
  22. #include <vector>
  23. #include <list>
  24. #include <algorithm>
  25. #include <functional>
  26. #include "util/tc_epoller.h"
  27. #include "util/tc_thread.h"
  28. #include "util/tc_clientsocket.h"
  29. #include "util/tc_logger.h"
  30. #include "util/tc_common.h"
  31. #include "util/tc_network_buffer.h"
  32. #include "util/tc_cas_queue.h"
  33. #include "util/tc_openssl.h"
  34. using namespace std;
  35. namespace tars
  36. {
  37. /////////////////////////////////////////////////
  38. /**
  39. * @file tc_epoll_server.h
  40. * @brief EpollServer类
  41. * @brief EpollServer Class
  42. *
  43. */
  44. /////////////////////////////////////////////////
  45. /**
  46. * Server基类
  47. * Server Basic Class
  48. * 注册协议解析器
  49. * Register Protocol Resolver
  50. * 注册逻辑处理器
  51. * Register Logical Processor
  52. * 注册管理端口处理器
  53. * Register Management Port Processor
  54. */
  55. class PropertyReport;
  56. class TC_EpollServer : public TC_HandleBase
  57. {
  58. public:
  59. enum EM_CLOSE_T
  60. {
  61. /**Client active shutdown*/
  62. EM_CLIENT_CLOSE = 0, //客户端主动关闭
  63. /**The service-side business proactively calls 'close' to close the connection,
  64. * or the framework proactively closes the connection due to an exception.*/
  65. EM_SERVER_CLOSE = 1, //服务端业务主动调用close关闭连接,或者框架因某种异常主动关闭连接
  66. /**Connection timed out, server actively closed*/
  67. EM_SERVER_TIMEOUT_CLOSE = 2 //连接超时了,服务端主动关闭
  68. };
  69. enum
  70. {
  71. /**Empty connection timeout (ms)*/
  72. MIN_EMPTY_CONN_TIMEOUT = 2*1000, /*空链接超时时间(ms)*/
  73. /**The size of received buffer of the default data*/
  74. DEFAULT_RECV_BUFFERSIZE = 64*1024 /*缺省数据接收buffer的大小*/
  75. };
  76. //定义加入到网络线程的fd类别
  77. //Define the FD categories added to network threads
  78. enum CONN_TYPE
  79. {
  80. TCP_CONNECTION = 0,
  81. UDP_CONNECTION = 1,
  82. };
  83. /**
  84. * 定义协议解析接口的操作对象
  85. * 注意必须是线程安全的或是可以重入的
  86. * Define the Operating Object of the Protocol Resolution Interface
  87. * Note that it must be thread safe or reentrant
  88. */
  89. typedef std::function<TC_NetWorkBuffer::PACKET_TYPE(TC_NetWorkBuffer::PACKET_TYPE, vector<char>&)> header_filter_functor;
  90. class NetThread;
  91. class Connection;
  92. class BindAdapter;
  93. typedef TC_AutoPtr<BindAdapter> BindAdapterPtr;
  94. class Handle;
  95. typedef TC_AutoPtr<Handle> HandlePtr;
  96. class RecvContext;
  97. /**
  98. * 发送包的上下文
  99. * 由RecvContext创建出来
  100. * Context of sending packets
  101. * Created by RecvContext
  102. */
  103. class SendContext
  104. {
  105. public:
  106. SendContext(const shared_ptr<RecvContext> &context, char cmd) : _context(context), _cmd(cmd)
  107. {
  108. _sbuffer = std::make_shared<TC_NetWorkBuffer::Buffer>();
  109. }
  110. const shared_ptr<RecvContext> &getRecvContext() { return _context; }
  111. const shared_ptr<TC_NetWorkBuffer::Buffer> & buffer() { return _sbuffer; }
  112. char cmd() const { return _cmd; }
  113. uint32_t uid() const { return _context->uid(); }
  114. int fd() const { return _context->fd(); }
  115. const string &ip() const { return _context->ip(); }
  116. uint16_t port() const { return _context->port(); }
  117. friend class RecvContext;
  118. protected:
  119. shared_ptr<RecvContext> _context;
  120. /**Send package is valid. Command: 'c', close FD; 's', data need to be sent*/
  121. char _cmd; /**send包才有效, 命令:'c',关闭fd; 's',有数据需要发送*/
  122. /**Sent context*/
  123. shared_ptr<TC_NetWorkBuffer::Buffer> _sbuffer; /**发送的内容*/
  124. };
  125. ////////////////////////////////////////////////////////////////////////////
  126. /**
  127. * 接收包的上下文
  128. * Context of receiving package
  129. */
  130. class RecvContext : public std::enable_shared_from_this<RecvContext>
  131. {
  132. public:
  133. RecvContext(uint32_t uid, const string &ip, int64_t port, int fd, const BindAdapterPtr &adapter, bool isClosed = false, int closeType = EM_CLIENT_CLOSE)
  134. : _uid(uid), _ip(ip), _port(port), _fd(fd), _adapter(adapter), _isClosed(isClosed), _closeType(closeType), _recvTimeStamp(TNOWMS)
  135. {
  136. }
  137. uint32_t uid() const { return _uid; }
  138. const string &ip() const { return _ip; }
  139. uint16_t port() const { return _port; }
  140. vector<char> &buffer() { return _rbuffer; }
  141. const vector<char> &buffer() const { return _rbuffer; }
  142. int64_t recvTimeStamp() const { return _recvTimeStamp; }
  143. bool isOverload() const { return _isOverload; }
  144. void setOverload() { _isOverload = true; }
  145. bool isClosed() const { return _isClosed; }
  146. int fd() const { return _fd; }
  147. BindAdapterPtr &adapter() { return _adapter; }
  148. int closeType() const { return _closeType; }
  149. void setCloseType(int closeType) { _closeType = closeType;}
  150. shared_ptr<SendContext> createSendContext() { return std::make_shared<SendContext>(shared_from_this(), 's'); }
  151. shared_ptr<SendContext> createCloseContext() { return std::make_shared<SendContext>(shared_from_this(), 'c'); }
  152. protected:
  153. /**Connection Label*/
  154. uint32_t _uid; /**连接标示*/
  155. /**IP for remote connection*/
  156. string _ip; /**远程连接的ip*/
  157. /**Port for remote connection*/
  158. uint16_t _port; /**远程连接的端口*/
  159. /**Save the FD that generated the message to select the network thread when returning the package*/
  160. int _fd; /*保存产生该消息的fd,用于回包时选择网络线程*/
  161. /**Message identifying which adapter*/
  162. BindAdapterPtr _adapter; /**标识哪一个adapter的消息*/
  163. /**Received message*/
  164. vector<char> _rbuffer; /**接收的内容*/
  165. /**Is overloaded*/
  166. bool _isOverload = false; /**是否已过载 */
  167. /**Is closed*/
  168. bool _isClosed = false; /**是否已关闭*/
  169. /**If the message package is closed, the type of closure is identified,
  170. * 0: the client actively closes,
  171. * 1: the server actively closes,
  172. * 2: the connection timeout server actively closes.
  173. * */
  174. int _closeType; /*如果是关闭消息包,则标识关闭类型,0:表示客户端主动关闭;1:服务端主动关闭;2:连接超时服务端主动关闭*/
  175. /**Time to receive data*/
  176. int64_t _recvTimeStamp; /**接收到数据的时间*/
  177. };
  178. // typedef TC_CasQueue<shared_ptr<RecvContext>> recv_queue;
  179. typedef TC_ThreadQueue<shared_ptr<RecvContext>> recv_queue;
  180. // typedef TC_CasQueue<shared_ptr<SendContext>> send_queue;
  181. typedef TC_ThreadQueue<shared_ptr<SendContext>> send_queue;
  182. typedef recv_queue::queue_type recv_queue_type;
  183. ////////////////////////////////////////////////////////////////////////////
  184. /**
  185. * 链接状态
  186. * Connection state
  187. */
  188. struct ConnStatus
  189. {
  190. string ip;
  191. int32_t uid;
  192. uint16_t port;
  193. int timeout;
  194. int iLastRefreshTime;
  195. size_t recvBufferSize;
  196. size_t sendBufferSize;
  197. };
  198. ////////////////////////////////////////////////////////////////////////////
  199. /**
  200. * @brief 定义服务逻辑处理的接口
  201. * @brief Define interfaces for logical processing of services
  202. *
  203. */
  204. /**
  205. * 服务的逻辑处理代码
  206. * Logical Processing Code for Services
  207. */
  208. class Handle : public TC_Thread, public TC_HandleBase
  209. {
  210. public:
  211. /**
  212. * 构造, 默认没有请求, 等待10s
  213. * Constructor, default no request, wait 10s
  214. */
  215. Handle();
  216. /**
  217. * 析构函数
  218. * Destructor
  219. */
  220. virtual ~Handle();
  221. /**
  222. * 获取服务
  223. * Get Service
  224. * @return TC_EpollServer*
  225. */
  226. TC_EpollServer* getEpollServer() const { return _pEpollServer; };
  227. /**
  228. * 获取adapter
  229. * Get adapter
  230. * @return
  231. */
  232. BindAdapter *getBindAdapter() const { return _bindAdapter; }
  233. /**
  234. * 获取Handle的索引(0~handle个数-1)
  235. * Get the index of Handle(0~handle count-1)
  236. * @return
  237. */
  238. uint32_t getHandleIndex() const { return _handleIndex; }
  239. /**
  240. * 设置网络线程
  241. * Set up network thread
  242. */
  243. void setNetThread(NetThread *netThread);
  244. /**
  245. * 获取网络线程
  246. * Get network thread
  247. * @return
  248. */
  249. NetThread *getNetThread() { return _netThread; }
  250. /**
  251. * 处理
  252. * Process
  253. */
  254. void process(shared_ptr<RecvContext> data);
  255. /**
  256. * 线程处理方法
  257. * Thread processing method
  258. */
  259. virtual void run();
  260. public:
  261. /**
  262. * 发送数据
  263. * Send data
  264. * @param stRecvData
  265. * @param sSendBuffer
  266. */
  267. void sendResponse(const shared_ptr<SendContext> &data);
  268. /**
  269. * 关闭链接
  270. * Close connection
  271. * @param stRecvData
  272. */
  273. void close(const shared_ptr<RecvContext> &data);
  274. /**
  275. * 设置等待时间
  276. * Set up waiting time
  277. * @param iWaitTime
  278. */
  279. void setWaitTime(uint32_t iWaitTime);
  280. /**
  281. * 对象初始化
  282. * Object initialization
  283. */
  284. virtual void initialize() {};
  285. /**
  286. * 唤醒handle对应的处理线程
  287. * Wake up the process thread corresponding to the handle
  288. */
  289. virtual void notifyFilter();
  290. /**
  291. * 心跳(每处理完一个请求或者等待请求超时都会调用一次)
  292. * Heartbeat(Called every time a request has been processed or the waiting request has timed out)
  293. */
  294. virtual void heartbeat() {}
  295. protected:
  296. /**
  297. * 具体的处理逻辑
  298. * Specific processing logic
  299. */
  300. virtual void handleImp();
  301. /**
  302. * 处理函数
  303. * Processing Function
  304. * @param stRecvData: 接收到的数据
  305. * @param stRecvData: received data
  306. */
  307. virtual void handle(const shared_ptr<RecvContext> &data) = 0;
  308. /**
  309. * 处理超时数据, 即数据在队列中的时间已经超过
  310. * 默认直接关闭连接
  311. * Processing timeout data, i.e. data has been queued longer than
  312. * Close connection directly by default
  313. * @param stRecvData: 接收到的数据
  314. * @param stRecvData: received data
  315. */
  316. virtual void handleTimeout(const shared_ptr<TC_EpollServer::RecvContext> &data);
  317. /**
  318. * 处理连接关闭通知,包括
  319. * Handle connection shutdown notifications, including:
  320. * 1.close by peer
  321. * 2.recv/send fail
  322. * 3.close by timeout or overload
  323. * @param stRecvData:
  324. */
  325. virtual void handleClose(const shared_ptr<TC_EpollServer::RecvContext> &data);
  326. /**
  327. * 处理overload数据 即数据队列中长度已经超过允许值
  328. * 默认直接关闭连接
  329. * Processing overload data means that the length of the data queue has exceeded the allowable value
  330. * Close connection directly by default
  331. * @param stRecvData: 接收到的数据
  332. * @param stRecvData: received data
  333. */
  334. virtual void handleOverload(const shared_ptr<TC_EpollServer::RecvContext> &data);
  335. /**
  336. * 处理异步回调队列
  337. * Handle asynchronous callback queues
  338. */
  339. virtual void handleAsyncResponse() {}
  340. /**
  341. * handleFilter拆分的第二部分,处理用户自有数据
  342. * 非游戏逻辑可忽略bExpectIdle参数
  343. * The second part of handleFilter splitting, dealing with user-owned data
  344. * Non-game logic ignores bExpectIdle parameter
  345. */
  346. virtual void handleCustomMessage(bool bExpectIdle = false) {}
  347. /**
  348. * 线程已经启动, 进入具体处理前调用
  349. * Thread has been started and called before entering specific processing
  350. */
  351. virtual void startHandle() {}
  352. /**
  353. * 线程马上要退出时调用
  354. * Call when the thread is about to exit
  355. */
  356. virtual void stopHandle() {}
  357. /**
  358. * 是否所有的Adpater队列都为空
  359. * Whether all adapter queues are empty.
  360. * @return bool
  361. */
  362. virtual bool allAdapterIsEmpty();
  363. /**
  364. * 是否所有的servant都没有resp消息待处理
  365. * Whether all servant don't have resp message to deal.
  366. * @return bool
  367. */
  368. virtual bool allFilterIsEmpty();
  369. /**
  370. * 设置服务
  371. * Set up service
  372. * @param pEpollServer
  373. */
  374. void setEpollServer(TC_EpollServer *pEpollServer);
  375. /**
  376. * 设置Adapter
  377. * Set up Apdater
  378. * @param pEpollServer
  379. */
  380. void setBindAdapter(BindAdapter* bindAdapter);
  381. /**
  382. * 设置index
  383. * Set up index
  384. * @param index
  385. */
  386. void setHandleIndex(uint32_t index);
  387. /**
  388. * 等待在队列上
  389. * On the waiting queue
  390. */
  391. void wait();
  392. /**
  393. * 从队列中获取数据
  394. * Receive data from the queue
  395. * @param recv
  396. * @return
  397. */
  398. bool popRecvQueue(shared_ptr<RecvContext> &recv);
  399. /**
  400. * 友元类
  401. * Friend Class
  402. */
  403. friend class BindAdapter;
  404. protected:
  405. /**
  406. * 服务
  407. * Service
  408. */
  409. TC_EpollServer *_pEpollServer;
  410. /**
  411. * handle对应的网路线程(网络线程和handle线程合并的情况下有效)
  412. * Network threads corresponding to handle (valid when network threads and handle threads are merged)
  413. */
  414. NetThread *_netThread = NULL;
  415. /**
  416. * 所属handle组
  417. * The handle group to which one belongs
  418. */
  419. BindAdapter* _bindAdapter;
  420. /**
  421. * 等待时间
  422. * Waiting time
  423. */
  424. uint32_t _iWaitTime;
  425. /**
  426. * Handle的索引
  427. * Index of the Handle
  428. */
  429. uint32_t _handleIndex;
  430. };
  431. using close_functor = std::function<void (void*, EM_CLOSE_T )>;
  432. using auth_process_wrapper_functor = std::function<bool (Connection *c, const shared_ptr<RecvContext> &recv )>;
  433. ////////////////////////////////////////////////////////////////////////////
  434. // 服务端口管理,监听socket信息
  435. // Service port management, listening for socket information
  436. class BindAdapter : public TC_HandleBase
  437. {
  438. public:
  439. /**
  440. * 缺省的一些定义
  441. * Defualt definitions
  442. */
  443. enum
  444. {
  445. /**Flow*/
  446. DEFAULT_QUEUE_CAP = 10*1024, /**流量*/
  447. /**Queue minimum timeout (ms)*/
  448. MIN_QUEUE_TIMEOUT = 3*1000, /**队列最小超时时间(ms)*/
  449. /**Default maximum connections*/
  450. DEFAULT_MAX_CONN = 1024, /**缺省最大连接数*/
  451. /**Default queue timeout (ms)*/
  452. DEFAULT_QUEUE_TIMEOUT = 60*1000, /**缺省的队列超时时间(ms)*/
  453. };
  454. /**
  455. * 顺序
  456. * Order
  457. */
  458. enum EOrder
  459. {
  460. ALLOW_DENY,
  461. DENY_ALLOW
  462. };
  463. /**
  464. * 数据队列
  465. * Data Queue
  466. */
  467. struct DataQueue
  468. {
  469. /**
  470. * 接收的数据队列
  471. * Received data queue
  472. */
  473. recv_queue _rbuffer;
  474. /**
  475. * 锁
  476. * Lock
  477. */
  478. TC_ThreadLock _monitor;
  479. };
  480. /**
  481. * 构造函数
  482. * Constructor
  483. */
  484. BindAdapter(TC_EpollServer *pEpollServer);
  485. /**
  486. * 析够函数
  487. * Destructor
  488. */
  489. ~BindAdapter();
  490. /**
  491. * 设置需要手工监听
  492. * Set requires manual listening
  493. */
  494. void enableManualListen() { _manualListen = true; }
  495. /**
  496. * 是否手工监听端口
  497. * Whether to manual listen the port or not
  498. * @return
  499. */
  500. bool isManualListen() const { return _manualListen; }
  501. /**
  502. * 手工绑定端口
  503. * Manual port binding
  504. */
  505. void manualListen();
  506. /**
  507. * 设置adapter name
  508. * Set up adapter name
  509. * @param name
  510. */
  511. void setName(const string &name);
  512. /**
  513. * 获取adapter name
  514. * Get adapter name
  515. * @return string
  516. */
  517. string getName() const;
  518. /**
  519. * 增加处理线程对应的接收队列
  520. * Add the corresponding receiving queue for processing threads
  521. * @return string
  522. */
  523. void initThreadRecvQueue(uint32_t handeIndex);
  524. /**
  525. * 获取queue capacity
  526. * Get queue capacity
  527. * @return int
  528. */
  529. int getQueueCapacity() const;
  530. /**
  531. * 设置queue capacity
  532. * Set up queue capacity
  533. * @param n
  534. */
  535. void setQueueCapacity(int n);
  536. /**
  537. * 设置协议名称
  538. * Set up the protocol name
  539. * @param name
  540. */
  541. void setProtocolName(const string& name);
  542. /**
  543. * 获取协议名称
  544. * Get the protocol name
  545. * @return const string&
  546. */
  547. const string& getProtocolName();
  548. /**
  549. * 是否tars协议
  550. * Whether it is the tars protocol
  551. * @return bool
  552. */
  553. bool isTarsProtocol();
  554. /**
  555. * 判断是否需要过载保护
  556. * Determine whether it needs overload protection
  557. * @return bool
  558. */
  559. int isOverloadorDiscard();
  560. /**
  561. * 设置消息在队列中的超时时间, t为毫秒
  562. * (超时时间精度只能是s)
  563. * Set the timeout time of the message in the queue, t is milliseconds
  564. * (timeout precision can only be s)
  565. *
  566. * @param t
  567. */
  568. void setQueueTimeout(int t);
  569. /**
  570. * 获取消息在队列中的超时时间, 毫秒
  571. * Get timeout of message in queue, MS
  572. * @return int
  573. */
  574. int getQueueTimeout() const;
  575. /**
  576. * 设置endpoint
  577. * Set up endpoint
  578. * @param str
  579. */
  580. void setEndpoint(const string &str);
  581. /**
  582. * 获取ip
  583. * Get ip
  584. * @return const string&
  585. */
  586. TC_Endpoint getEndpoint() const;
  587. /**
  588. * 监听socket
  589. * Listen socket
  590. * @return TC_Socket
  591. */
  592. TC_Socket &getSocket();
  593. /**
  594. * 设置最大连接数
  595. * Set the maximum connection number
  596. * @param iMaxConns
  597. */
  598. void setMaxConns(int iMaxConns);
  599. /**
  600. * 获取最大连接数
  601. * Get the maximum connection number
  602. * @return size_t
  603. */
  604. size_t getMaxConns() const;
  605. /**
  606. * 设置HeartBeat时间
  607. * Set the HeartBeat time
  608. * @param n
  609. */
  610. void setHeartBeatTime(time_t t);
  611. /**
  612. * 获取HeartBeat时间
  613. * Get the HeartBeat time
  614. * @return size_t
  615. */
  616. time_t getHeartBeatTime() const;
  617. /**
  618. * 设置allow deny次序
  619. * Set the allow deny order
  620. * @param eOrder
  621. */
  622. void setOrder(EOrder eOrder);
  623. /**
  624. * 设置允许ip
  625. * Set allowed ip
  626. * @param vtAllow
  627. */
  628. void setAllow(const vector<string> &vtAllow);
  629. /**
  630. * 设置禁止ip
  631. * Set the disabled ip
  632. * @param vtDeny
  633. */
  634. void setDeny(const vector<string> &vtDeny);
  635. /**
  636. * 获取允许ip
  637. * Get the allowed ip
  638. * @return vector<string>: ip列表
  639. * @return vector<string>: ip list
  640. */
  641. const vector<string> &getAllow() const;
  642. /**
  643. * 获取禁止ip
  644. * Get the disable ip
  645. * @return vector<string>: ip列表
  646. * @return vector<string>: ip list
  647. */
  648. const vector<string> &getDeny() const;
  649. /**
  650. * 获取allow deny次序
  651. * Get the allow deny order
  652. * @return EOrder
  653. */
  654. EOrder getOrder() const;
  655. /**
  656. * 是否Ip被允许
  657. * Whether the ip is allowed or not
  658. * @param ip
  659. * @return bool
  660. */
  661. bool isIpAllow(const string& ip) const;
  662. /**
  663. * 是否超过了最大连接数
  664. * Whether it exceeds the maximum connection number
  665. * @return bool
  666. */
  667. bool isLimitMaxConnection() const;
  668. /**
  669. * 减少当前连接数
  670. * Reduce current connections
  671. */
  672. void decreaseNowConnection();
  673. /**
  674. * 增加当前连接数
  675. * Increase current connections
  676. */
  677. void increaseNowConnection();
  678. /**
  679. * 获取所有链接状态
  680. * Get all connection states
  681. * @return ConnStatus
  682. */
  683. vector<ConnStatus> getConnStatus();
  684. /**
  685. * 获取当前连接数
  686. * Get current connections
  687. * @return int
  688. */
  689. int getNowConnection() const;
  690. /**
  691. * 获取服务
  692. * Get service
  693. * @return TC_EpollServer*
  694. */
  695. TC_EpollServer* getEpollServer() const { return _pEpollServer; };
  696. /**
  697. * 获取对应的网络线程
  698. * Get the corresponding network thread
  699. * @param fd
  700. * @return
  701. */
  702. inline NetThread* getNetThreadOfFd(int fd) const { return _pEpollServer->getNetThreadOfFd(fd); }
  703. /**
  704. * 注册协议解析器
  705. * Registration Protocol parser
  706. * @param pp
  707. */
  708. void setProtocol(const TC_NetWorkBuffer::protocol_functor& pf, int iHeaderLen = 0, const header_filter_functor& hf = echo_header_filter);
  709. /**
  710. * 获取协议解析器
  711. * Get Registration Protocol parser
  712. * @return protocol_functor&
  713. */
  714. TC_NetWorkBuffer::protocol_functor &getProtocol();
  715. /**
  716. * 解析包头处理对象
  717. * Resolve Package Header Processing Objects
  718. * @return protocol_functor&
  719. */
  720. header_filter_functor &getHeaderFilterFunctor();
  721. /**
  722. * 增加数据到队列中
  723. * Add data to the queue
  724. * @param vtRecvData
  725. * @param bPushBack 后端插入
  726. * @param bPushBack Backend insert
  727. * @param sBuffer
  728. */
  729. void insertRecvQueue(const shared_ptr<RecvContext> &recv);//, bool bPushBack = true);
  730. /**
  731. * 等待数据
  732. * Wait for data
  733. * @return bool
  734. */
  735. bool waitForRecvQueue(uint32_t handleIndex, shared_ptr<RecvContext> &recv);
  736. /**
  737. * 接收队列的大小
  738. * Size of the received queue
  739. * @return size_t
  740. */
  741. size_t getRecvBufferSize() const;
  742. /**
  743. * 发送队列的大小
  744. * Size of the sent queue
  745. * @return size_t
  746. */
  747. size_t getSendBufferSize() const;
  748. /**
  749. * add send buffer size
  750. */
  751. inline void increaseSendBufferSize() { ++_iSendBufferSize; }
  752. /**
  753. * increase send buffer size
  754. */
  755. inline void decreaseSendBufferSize(size_t s = 1) { _iSendBufferSize.fetch_sub(s); }
  756. /**
  757. * 默认的协议解析类, 直接echo
  758. * Default protocol resolution class, direct echo
  759. * @param r
  760. * @param o
  761. * @return int
  762. */
  763. static TC_NetWorkBuffer::PACKET_TYPE echo_protocol(TC_NetWorkBuffer &r, vector<char> &o);
  764. /**
  765. * 默认的包头处理
  766. * Default header handling
  767. * @param i
  768. * @param o
  769. * @return int
  770. */
  771. static TC_NetWorkBuffer::PACKET_TYPE echo_header_filter(TC_NetWorkBuffer::PACKET_TYPE i, vector<char> &o);
  772. /**
  773. * 获取需要过滤的包头长度
  774. * Get the header length that needs to be filtered
  775. */
  776. int getHeaderFilterLen();
  777. /**
  778. * 所属handle组的handle数(每个handle一个对象)
  779. * Number of handles belonging to the handle group (one object per handle)
  780. * @return int
  781. */
  782. int getHandleNum();
  783. /**
  784. * 初始化处理线程,线程将会启动
  785. * Initialize the processing thread, which will start
  786. */
  787. template<typename T, typename ...Args>
  788. void setHandle(size_t n, Args&&... args)
  789. {
  790. if(!_handles.empty())
  791. {
  792. getEpollServer()->error("[BindAdapter::setHandle] handle is not empty!");
  793. return;
  794. }
  795. _iHandleNum = n;
  796. _threadDataQueue.resize(_iHandleNum + 1);
  797. _threadDataQueue[0] = std::make_shared<BindAdapter::DataQueue>();
  798. if(_pEpollServer->isMergeHandleNetThread())
  799. {
  800. _iHandleNum = _pEpollServer->_netThreadNum;
  801. }
  802. for (int32_t i = 0; i < _iHandleNum ; ++i)
  803. {
  804. HandlePtr handle = new T(args...);
  805. handle->setHandleIndex(i);
  806. handle->setEpollServer(this->getEpollServer());
  807. handle->setBindAdapter(this);
  808. _handles.push_back(handle);
  809. }
  810. }
  811. /**
  812. * 获取第几个句柄
  813. * Get the index of the handle
  814. * @param index
  815. * @return
  816. */
  817. HandlePtr getHandle(size_t index) {
  818. assert(index <= _iHandleNum);
  819. assert(getEpollServer()->isMergeHandleNetThread());
  820. return _handles[index];
  821. }
  822. /*
  823. * 设置服务端积压缓存的大小限制(超过大小启用)
  824. * Set the size limit of the server's backlog cache (exceeding the size enabled)
  825. */
  826. void setBackPacketBuffLimit(size_t iLimitSize) { _iBackPacketBuffLimit = iLimitSize; }
  827. /**
  828. * 获取服务端回包缓存的大小限制(超过大小启用)
  829. * Get the size limit of the server-side packet back cache (exceeding the size enabled)
  830. */
  831. size_t getBackPacketBuffLimit() const { return _iBackPacketBuffLimit; }
  832. /*
  833. * 设置服务端5/s最低发送字节
  834. * Set the Server 5/s Minimum Sending Bytes
  835. */
  836. void setBackPacketBuffMin(size_t iMinLimit) { _iBackPacketBuffMin = iMinLimit; }
  837. /**
  838. * 获取服务端5/s最低发送字节
  839. * Get the Server 5/s Minimum Sending Bytes
  840. */
  841. size_t getBackPacketBuffMin() const { return _iBackPacketBuffMin; }
  842. /**
  843. * 获取服务端接收队列(如果_rnbuffer有多个, 则根据调用者的线程id来hash获取)
  844. * Get the server receive queue (if there's more than one _rnbuffer, get from the hash based on the caller's thread id)
  845. *
  846. */
  847. recv_queue &getRecvQueue(uint32_t handleIndex);
  848. /**
  849. * 获取handles
  850. * Get handles
  851. */
  852. const vector<HandlePtr> &getHandles() { return _handles; }
  853. /**
  854. * 是否是队列模式(默认是False的)
  855. * Whether it is the queue mode (Defualt false)
  856. */
  857. bool isQueueMode() const { return _queueMode; }
  858. /**
  859. * 开启队列模式(同一个连接的请求, 落在同一个handle处理线程中)
  860. * Open queue mode (The requests from the same connecion will fall in the same handle processing thread )
  861. */
  862. void enableQueueMode() { _queueMode = true; }
  863. /**
  864. * 等待队列数据
  865. * Wait for the queue data
  866. */
  867. void waitAtQueue(uint32_t handleIndex, uint32_t waitTime);
  868. /**
  869. * 通知某个具体handle醒过来
  870. * Notify a specific handle to wake up
  871. * @param handleIndex
  872. */
  873. void notifyHandle(uint32_t handleIndex);
  874. /**
  875. * 设置close回调函数
  876. * Set close callback function
  877. */
  878. void setOnClose(const close_functor& f) { _closeFunc = f; }
  879. /**
  880. * 注册鉴权包裹函数
  881. * Regist Authentication Package Function
  882. * @param apwf
  883. */
  884. void setAuthProcessWrapper(const auth_process_wrapper_functor& apwf) { _authWrapper = apwf; }
  885. void setAkSk(const std::string& ak, const std::string& sk) { _accessKey = ak; _secretKey = sk; }
  886. bool checkAkSk(const std::string& ak, const std::string& sk) { return ak == _accessKey && sk == _secretKey; }
  887. std::string getSk(const std::string& ak) const { return (_accessKey == ak) ? _secretKey : ""; }
  888. void setSSLCtx(const shared_ptr<TC_OpenSSL::CTX>& ctx) { _ctx = ctx; }
  889. shared_ptr<TC_OpenSSL::CTX> getSSLCtx() { return _ctx; };
  890. private:
  891. /**
  892. * 获取等待的队列锁
  893. * Get the waiting queue lock
  894. * @return
  895. */
  896. TC_ThreadLock &getLock(uint32_t handleIndex);
  897. public:
  898. //统计上报的对象
  899. //Count reporting objects
  900. PropertyReport * _pReportQueue = NULL;
  901. PropertyReport * _pReportConRate = NULL;
  902. PropertyReport * _pReportTimeoutNum = NULL;
  903. protected:
  904. friend class TC_EpollServer;
  905. /**
  906. * 加锁
  907. * Add lock
  908. */
  909. mutable std::mutex _mutex;
  910. /**
  911. * 服务
  912. * Service
  913. */
  914. TC_EpollServer *_pEpollServer = NULL;
  915. /**
  916. * Adapter所用的HandleGroup
  917. * the HandleGroup used by Adapter
  918. */
  919. vector<HandlePtr> _handles;
  920. /**
  921. * 协议解析
  922. * Destruct the protocol
  923. */
  924. TC_NetWorkBuffer::protocol_functor _pf;
  925. /**
  926. * 首个数据包包头过滤
  927. * First packet header filtering
  928. */
  929. header_filter_functor _hf;
  930. /**
  931. * adapter的名字
  932. * adapter name
  933. */
  934. string _name;
  935. /**
  936. * 监听fd
  937. * listen fd
  938. */
  939. TC_Socket _s;
  940. /**
  941. * 绑定的IP
  942. * binded ip
  943. */
  944. TC_Endpoint _ep;
  945. /**
  946. * 最大连接数
  947. * the maximum number of connections
  948. */
  949. int _iMaxConns;
  950. /**
  951. * 当前连接数
  952. * the current number of connections
  953. */
  954. std::atomic<int> _iCurConns;
  955. /**
  956. * Handle个数
  957. * the number of Handle
  958. */
  959. size_t _iHandleNum;
  960. /**
  961. * 允许的Order
  962. * the Allowed Order
  963. */
  964. volatile EOrder _eOrder;
  965. /**
  966. * 允许的ip
  967. * the Allowed IP
  968. */
  969. vector<string> _vtAllow;
  970. /**
  971. * 禁止的ip
  972. * the Disabled IP
  973. */
  974. vector<string> _vtDeny;
  975. /**
  976. * 每个线程都有自己的队列
  977. * 0: 给共享队列模式时使用
  978. * 1~handle个数: 队列模式时使用
  979. * Every thread has its own queue.
  980. * 0: Use when sharing queue mode
  981. * 1~handle count: Use when queue mode
  982. */
  983. vector<shared_ptr<DataQueue>> _threadDataQueue;
  984. /**
  985. * 接收队列数据总个数
  986. * the total amount of the received queue data
  987. */
  988. atomic<size_t> _iRecvBufferSize{0};
  989. /**
  990. * 发送队列数据总个数
  991. * the total amount of the sent queue data
  992. */
  993. atomic<size_t> _iSendBufferSize{0};
  994. /**
  995. * 队列最大容量
  996. * the maximum capacity of the queue
  997. */
  998. int _iQueueCapacity;
  999. /**
  1000. * 消息超时时间(从入队列到出队列间隔)(毫秒)
  1001. * Message timeout (from queue entry to queue exit interval) (milliseconds)
  1002. */
  1003. int _iQueueTimeout;
  1004. /**
  1005. * 首个数据包包头长度
  1006. * First packet header length
  1007. */
  1008. int _iHeaderLen;
  1009. /**
  1010. * 上次心跳发送时间
  1011. * Last heartbeat sent time
  1012. */
  1013. volatile time_t _iHeartBeatTime;
  1014. /**
  1015. * 协议名称,缺省为"tars"
  1016. * Protocol name, default is "tars"
  1017. */
  1018. string _protocolName;
  1019. /**
  1020. * 回包缓存限制大小
  1021. * Packet Back Cache Limit Size
  1022. */
  1023. size_t _iBackPacketBuffLimit = 0;
  1024. /**
  1025. * 回包速度最低限制(5/s), 默认1K
  1026. * Minimum Packet Return Speed Limit (5/s), default 1K
  1027. */
  1028. size_t _iBackPacketBuffMin = 1024;
  1029. //队列模式
  1030. //Queue Mode
  1031. bool _queueMode = false;
  1032. //listen模式
  1033. //Listen Mode
  1034. bool _manualListen = false;
  1035. /**
  1036. * 包裹认证函数,不能为空
  1037. * Package authentication function, cannot be empty
  1038. */
  1039. auth_process_wrapper_functor _authWrapper;
  1040. /**
  1041. * 该obj的AK SK
  1042. * the AK SK of the object
  1043. */
  1044. std::string _accessKey;
  1045. std::string _secretKey;
  1046. /**
  1047. * ssl ctx
  1048. */
  1049. shared_ptr<TC_OpenSSL::CTX> _ctx;
  1050. //连接关闭的回调函数
  1051. //Callback function with connection closed
  1052. close_functor _closeFunc;
  1053. };
  1054. ////////////////////////////////////////////////////////////////////////////
  1055. // 服务连接管理
  1056. // Service Connection Management
  1057. /**
  1058. * 建立连接的socket信息
  1059. * Socket information for establishing connections
  1060. */
  1061. class Connection
  1062. {
  1063. public:
  1064. enum EnumConnectionType
  1065. {
  1066. EM_TCP = 0,
  1067. EM_UDP = 1,
  1068. };
  1069. /**
  1070. * 构造函数
  1071. * Constructor
  1072. * @param lfd
  1073. * @param s
  1074. * @param ip
  1075. * @param port
  1076. */
  1077. Connection(BindAdapter *pBindAdapter, int lfd, int timeout, int fd, const string& ip, uint16_t port);
  1078. /**
  1079. * udp连接
  1080. * UDP connection
  1081. * @param fd
  1082. */
  1083. Connection(BindAdapter *pBindAdapter, int fd);
  1084. /**
  1085. * 析构函数
  1086. * Destructor
  1087. */
  1088. virtual ~Connection();
  1089. /**
  1090. * 链接所属的adapter
  1091. * the adapter of the connection
  1092. */
  1093. BindAdapterPtr& getBindAdapter() { return _pBindAdapter; }
  1094. /**
  1095. * 初始化
  1096. * Initialization
  1097. * @param id, 连接的唯一id
  1098. * @param id, the connection unique id
  1099. */
  1100. void init(unsigned int uid) { _uid = uid; }
  1101. /**
  1102. * 获取连接超时时间
  1103. * Get connection timeout
  1104. *
  1105. * @return int
  1106. */
  1107. int getTimeout() const { return _timeout; }
  1108. /**
  1109. * 获取线程的惟一id
  1110. * Get thread unique id
  1111. *
  1112. * @return unsigned int
  1113. */
  1114. uint32_t getId() const { return _uid; }
  1115. /**
  1116. * 获取监听fd
  1117. * Get listening id
  1118. *
  1119. * @return int
  1120. */
  1121. int getListenfd() const { return _lfd; }
  1122. /**
  1123. * 当前连接fd
  1124. * Current connection fd
  1125. *
  1126. * @return int
  1127. */
  1128. int getfd() const { return _sock.getfd(); }
  1129. /**
  1130. * 是否有效
  1131. * Whether it is valid
  1132. *
  1133. * @return bool
  1134. */
  1135. bool isValid() const { return _sock.isValid();}
  1136. /**
  1137. * 远程IP
  1138. * Remote IP
  1139. *
  1140. * @return string
  1141. */
  1142. string getIp() const { return _ip; }
  1143. /**
  1144. * 远程端口
  1145. * Remote Port
  1146. *
  1147. * @return uint16_t
  1148. */
  1149. uint16_t getPort() const { return _port; }
  1150. /**
  1151. * 设置首个数据包包头需要过滤的字节数
  1152. * Set the number of bytes the first packet header needs to filter
  1153. */
  1154. void setHeaderFilterLen(int iHeaderLen) { _iHeaderLen = iHeaderLen; }
  1155. /**
  1156. * 设置关闭,发送完当前数据就关闭连接
  1157. * Set shutdown to close connection after sending current data
  1158. */
  1159. bool setClose();
  1160. /**
  1161. * 获取连接类型
  1162. * Get the type of the connection
  1163. */
  1164. EnumConnectionType getType() const { return _enType; }
  1165. /**
  1166. * 是否是空连接
  1167. * Whether there's empty connection.
  1168. */
  1169. bool isEmptyConn() const {return _bEmptyConn;}
  1170. /**
  1171. * Init Auth State;
  1172. */
  1173. void tryInitAuthState(int initState);
  1174. /**
  1175. * 接收数据buffer
  1176. * Receive data buffer
  1177. */
  1178. TC_NetWorkBuffer &getRecvBuffer() { return _recvBuffer; }
  1179. /**
  1180. * 发送数据buffer
  1181. * Send data buffer
  1182. */
  1183. TC_NetWorkBuffer &getSendBuffer() { return _sendBuffer; }
  1184. /**
  1185. * 发送buffer里面数据
  1186. * Send the data in the bufer
  1187. * @return
  1188. */
  1189. int sendBuffer();
  1190. /**
  1191. * 关闭连接
  1192. * Close the connection
  1193. * @param fd
  1194. */
  1195. void close();
  1196. friend class NetThread;
  1197. protected:
  1198. /**
  1199. * 添加发送buffer
  1200. * Add sanding buffer
  1201. * @param buffer
  1202. * @return int, -1:发送出错, 0:无数据, 1:发送完毕, 2:还有数据
  1203. * @return int, -1: sending error, 0: no data, 1: send completely, 2: data retains
  1204. */
  1205. int send(const shared_ptr<SendContext> &data);
  1206. /**
  1207. * 读取数据
  1208. * Read data
  1209. * @param fd
  1210. * @return int, -1:接收出错, 0:接收不全, 1:接收到一个完整包
  1211. * @return int, -1: received error, 0: not receive completely, 1: receive a complete package
  1212. */
  1213. int recv();
  1214. /**
  1215. * 接收TCP
  1216. * Receive TCP
  1217. */
  1218. int recvTcp();
  1219. /**
  1220. * 接收Udp
  1221. * Receive UDP
  1222. */
  1223. int recvUdp();
  1224. /**
  1225. * 解析协议
  1226. * Destruct protocol
  1227. * @param o
  1228. */
  1229. int parseProtocol(TC_NetWorkBuffer &rbuf);
  1230. /**
  1231. * 增加数据到队列中
  1232. * Add data to the queue
  1233. * @param vtRecvData
  1234. */
  1235. void insertRecvQueue(const shared_ptr<RecvContext> &recv);
  1236. /**
  1237. * 对于udp方式的连接,分配指定大小的接收缓冲区
  1238. * For udp-mode connections, allocate receive buffers of a specified size
  1239. *@param nSize
  1240. */
  1241. bool setRecvBuffer(size_t nSize=DEFAULT_RECV_BUFFERSIZE);
  1242. /**
  1243. * 是否是tcp连接
  1244. * Whether it is TCP connection.
  1245. * @return
  1246. */
  1247. bool isTcp() const { return _lfd != -1; }
  1248. public:
  1249. /**
  1250. * 最后刷新时间
  1251. * Last refresh time
  1252. */
  1253. time_t _iLastRefreshTime;
  1254. protected:
  1255. /**
  1256. * 适配器
  1257. * Adapter
  1258. */
  1259. BindAdapterPtr _pBindAdapter;
  1260. /**
  1261. * TC_Socket
  1262. */
  1263. TC_Socket _sock;
  1264. /**
  1265. * 连接的唯一编号
  1266. * the unique id of the connection
  1267. */
  1268. volatile uint32_t _uid;
  1269. /**
  1270. * 监听的socket
  1271. * Listening socket
  1272. */
  1273. int _lfd;
  1274. /**
  1275. * 超时时间
  1276. * Timeout
  1277. */
  1278. int _timeout;
  1279. /**
  1280. * ip
  1281. */
  1282. string _ip;
  1283. /**
  1284. * 端口
  1285. * Port
  1286. */
  1287. uint16_t _port;
  1288. /**
  1289. * 接收数据buffer
  1290. * the buffer to receive data
  1291. */
  1292. TC_NetWorkBuffer _recvBuffer;
  1293. /**
  1294. * 发送数据buffer
  1295. * the buffer to send data
  1296. */
  1297. TC_NetWorkBuffer _sendBuffer;
  1298. /**
  1299. * 发送数据
  1300. * Send data
  1301. */
  1302. size_t _sendBufferSize = 0;
  1303. /**
  1304. * 检查时间
  1305. * Check time
  1306. */
  1307. time_t _lastCheckTime = 0;
  1308. /**
  1309. * 发送的检查<已经发送数据, 剩余buffer大小>
  1310. * Check Sent <Data Sent, Remaining Buffer Size>
  1311. */
  1312. vector<pair<size_t, size_t>> _checkSend;
  1313. /**
  1314. * 需要过滤的头部字节数
  1315. * Number of header bytes to filter
  1316. */
  1317. int _iHeaderLen;
  1318. /**
  1319. * 发送完当前数据就关闭连接
  1320. * Close connection after sending current data
  1321. */
  1322. bool _bClose;
  1323. /**
  1324. * 连接类型
  1325. * Connection Type
  1326. */
  1327. EnumConnectionType _enType;
  1328. bool _bEmptyConn;
  1329. /*
  1330. *接收数据的临时buffer,加这个目的是对udp接收数据包大小进行设置
  1331. *Temporary buffer to receive data, plus this is to set the UDP receive packet size
  1332. */
  1333. char *_pRecvBuffer = NULL;
  1334. size_t _nRecvBufferSize;
  1335. public:
  1336. /*
  1337. *该连接的鉴权状态
  1338. *Authentication status of the connection
  1339. */
  1340. int _authState;
  1341. /*
  1342. *该连接的鉴权状态是否初始化了
  1343. */
  1344. bool _authInit;
  1345. std::shared_ptr<TC_OpenSSL> _openssl;
  1346. };
  1347. ////////////////////////////////////////////////////////////////////////////
  1348. /**
  1349. * 带有时间链表的map
  1350. * Map with Time Chain Table
  1351. */
  1352. class ConnectionList
  1353. {
  1354. public:
  1355. /**
  1356. * 构造函数
  1357. * Constructor
  1358. */
  1359. ConnectionList(NetThread *pEpollServer);
  1360. /**
  1361. * 析够函数
  1362. * Destructor
  1363. */
  1364. ~ConnectionList()
  1365. {
  1366. if(_vConn)
  1367. {
  1368. //服务停止时, 主动关闭一下连接, 这样客户端会检测到, 不需要等下一个发送包时, 发送失败才知道连接被关闭
  1369. for (auto it = _tl.begin(); it != _tl.end(); ++it) {
  1370. if (_vConn[it->second].first != NULL) {
  1371. _vConn[it->second].first->close();
  1372. }
  1373. }
  1374. delete[] _vConn;
  1375. }
  1376. // if(_vConn) { delete[] _vConn; }
  1377. }
  1378. /**
  1379. * 初始化大小
  1380. * Initial size
  1381. * @param size
  1382. */
  1383. void init(uint32_t size, uint32_t iIndex = 0);
  1384. /**
  1385. * 获取惟一ID
  1386. * Get the unique ID
  1387. *
  1388. * @return unsigned int
  1389. */
  1390. uint32_t getUniqId();
  1391. /**
  1392. * 添加连接
  1393. * Add Connection
  1394. * @param cPtr
  1395. * @param iTimeOutStamp
  1396. */
  1397. void add(Connection *cPtr, time_t iTimeOutStamp);
  1398. /**
  1399. * 刷新时间链
  1400. * Refresh the connectiom
  1401. * @param uid
  1402. * @param iTimeOutStamp, 超时时间点
  1403. * @param iTimeOutStamp, Timeout Point
  1404. */
  1405. void refresh(uint32_t uid, time_t iTimeOutStamp);
  1406. /**
  1407. * 检查超时数据
  1408. * Check Timeout
  1409. */
  1410. void checkTimeout(time_t iCurTime);
  1411. /**
  1412. * 获取某个监听端口的连接
  1413. * Get a connection to a listening port
  1414. * @param lfd
  1415. * @return vector<TC_EpollServer::ConnStatus>
  1416. */
  1417. vector<ConnStatus> getConnStatus(int lfd);
  1418. /**
  1419. * 获取某一个连接
  1420. * Get a certain connection
  1421. * @param p
  1422. * @return T
  1423. */
  1424. Connection* get(uint32_t uid);
  1425. /**
  1426. * 删除连接
  1427. * Delete connection
  1428. * @param uid
  1429. */
  1430. void del(uint32_t uid);
  1431. /**
  1432. * 大小
  1433. * Size
  1434. * @return size_t
  1435. */
  1436. size_t size();
  1437. protected:
  1438. typedef pair<Connection*, multimap<time_t, uint32_t>::iterator> list_data;
  1439. /**
  1440. * 内部删除, 不加锁
  1441. * Internal Delete, No Lock
  1442. * @param uid
  1443. */
  1444. void _del(uint32_t uid);
  1445. protected:
  1446. /**
  1447. * 无锁
  1448. * No Lock
  1449. */
  1450. TC_ThreadMutex _mutex;
  1451. /**
  1452. * 服务
  1453. * Service
  1454. */
  1455. NetThread *_pEpollServer;
  1456. /**
  1457. * 总计连接数
  1458. * Total connection amount
  1459. */
  1460. volatile uint32_t _total;
  1461. /**
  1462. * 空闲链表
  1463. * Empty link list
  1464. */
  1465. list<uint32_t> _free;
  1466. /**
  1467. * 空闲链元素个数
  1468. * number of the elements in the empty link
  1469. */
  1470. volatile size_t _free_size;
  1471. /**
  1472. * 链接
  1473. * Connection
  1474. */
  1475. list_data *_vConn;
  1476. /**
  1477. * 超时链表
  1478. * Timeout link list
  1479. */
  1480. multimap<time_t, uint32_t> _tl;
  1481. /**
  1482. * 上次检查超时时间
  1483. * Last timeout time
  1484. */
  1485. time_t _lastTimeoutTime;
  1486. /**
  1487. * 链接ID的魔数
  1488. * Magic Number of Link IDs
  1489. */
  1490. uint32_t _iConnectionMagic;
  1491. };
  1492. ////////////////////////////////////////////////////////////////////////////
  1493. class NetThread : public TC_Thread, public TC_HandleBase
  1494. {
  1495. public:
  1496. ////////////////////////////////////////////////////////////////////////////
  1497. public:
  1498. /**
  1499. * 构造函数
  1500. * Constructor
  1501. */
  1502. NetThread(TC_EpollServer *epollServer, int index);
  1503. /**
  1504. * 析构函数
  1505. * Destructor
  1506. */
  1507. virtual ~NetThread();
  1508. /**
  1509. * 获取网络线程的index
  1510. * Get the index for the network threads
  1511. * @return
  1512. */
  1513. int getIndex() const { return _threadIndex; }
  1514. /**
  1515. * 网络线程执行函数
  1516. * Network thread execution function
  1517. */
  1518. virtual void run();
  1519. /**
  1520. * 停止网络线程
  1521. * Stop the network thread
  1522. */
  1523. void terminate();
  1524. /**
  1525. * 生成epoll
  1526. * Generate epoll
  1527. */
  1528. void createEpoll(uint32_t maxAllConn);
  1529. /**
  1530. * 初始化udp监听
  1531. * Initialize UDP listening
  1532. */
  1533. void initUdp(const unordered_map<int, BindAdapterPtr> &listeners);
  1534. /**
  1535. * 是否服务结束了
  1536. * Whether the service is end.
  1537. *
  1538. * @return bool
  1539. */
  1540. bool isTerminate() const { return _bTerminate; }
  1541. /**
  1542. * 获取Epoller对象
  1543. * Get the Epoller Object
  1544. *
  1545. * @return TC_Epoller*
  1546. */
  1547. TC_Epoller* getEpoller() { return &_epoller; }
  1548. /**
  1549. * 唤醒网络线程
  1550. * Wake up the network thread
  1551. */
  1552. void notify();
  1553. /**
  1554. * 关闭连接
  1555. * Close Connection
  1556. * @param uid
  1557. */
  1558. void close(const shared_ptr<RecvContext> &data);
  1559. /**
  1560. * 发送数据
  1561. * Send data
  1562. * @param uid
  1563. * @param s
  1564. */
  1565. void send(const shared_ptr<SendContext> &data);
  1566. /**
  1567. * 获取某一监听端口的连接数
  1568. * Get the number of connections for a listening port
  1569. * @param lfd
  1570. *
  1571. * @return vector<TC_EpollServer::ConnStatus>
  1572. */
  1573. vector<TC_EpollServer::ConnStatus> getConnStatus(int lfd);
  1574. /**
  1575. * 获取连接数
  1576. * Get the number of connections
  1577. *
  1578. * @return size_t
  1579. */
  1580. size_t getConnectionCount() { return _list.size(); }
  1581. /**
  1582. * 记录日志
  1583. * Logging
  1584. * @param s
  1585. */
  1586. void debug(const string &s) const;
  1587. /**
  1588. * INFO日志
  1589. * INFO LOG
  1590. * @param s
  1591. */
  1592. void info(const string &s) const;
  1593. /**
  1594. * TARS日志
  1595. * TARS LOG
  1596. * @param s
  1597. */
  1598. void tars(const string &s) const;
  1599. /**
  1600. * 记录错误日志
  1601. * Log errors
  1602. * @param s
  1603. */
  1604. void error(const string &s) const;
  1605. /**
  1606. * 是否启用防止空链接攻击的机制
  1607. * Whether the mechanism to prevent null link attacks is enabled.
  1608. * @param bEnable
  1609. */
  1610. void enAntiEmptyConnAttack(bool bEnable);
  1611. /**
  1612. *设置空连接超时时间
  1613. *Set empty connection timeout
  1614. */
  1615. void setEmptyConnTimeout(int timeout);
  1616. /**
  1617. *设置udp的接收缓存区大小,单位是B,最小值为8192,最大值为DEFAULT_RECV_BUFFERSIZE
  1618. *Sets the size of the receiving buffer in UDP in B, with a minimum of 8192 and a maximum of DEFAULT_RECV_BUFFERSIZE
  1619. */
  1620. void setUdpRecvBufferSize(size_t nSize=DEFAULT_RECV_BUFFERSIZE);
  1621. protected:
  1622. /**
  1623. * 获取连接
  1624. * Get connection
  1625. * @param id
  1626. *
  1627. * @return ConnectionPtr
  1628. */
  1629. Connection *getConnectionPtr(uint32_t uid) { return _list.get(uid); }
  1630. /**
  1631. * 添加tcp链接
  1632. * Add TCP connection
  1633. * @param cPtr
  1634. * @param iIndex
  1635. */
  1636. void addTcpConnection(Connection *cPtr);
  1637. /**
  1638. * 添加udp连接
  1639. * Add UDP connection
  1640. * @param cPtr
  1641. * @param index
  1642. */
  1643. void addUdpConnection(Connection *cPtr);
  1644. /**
  1645. * 删除链接
  1646. * Delete connection
  1647. * @param cPtr
  1648. * @param bEraseList 是否是超时连接的删除
  1649. * @param bEraseList Whether it is deletion of timeout connection
  1650. * @param closeType 关闭类型,0:表示客户端主动关闭;1:服务端主动关闭;2:连接超时服务端主动关闭
  1651. * @param closeType Close type, 0: indicates active closure of client, 1: active closure of server, 2: active closure of connection timeout server
  1652. */
  1653. void delConnection(Connection *cPtr, bool bEraseList = true, EM_CLOSE_T closeType=EM_CLIENT_CLOSE);
  1654. /**
  1655. * 处理管道消息
  1656. * Processing Pipeline Messages
  1657. */
  1658. void processPipe();
  1659. /**
  1660. * 处理网络请求
  1661. * Processing Network Request
  1662. */
  1663. void processNet(const epoll_event &ev);
  1664. /**
  1665. * 空连接超时时间
  1666. * Empty connection timeout
  1667. */
  1668. int getEmptyConnTimeout() const;
  1669. /**
  1670. *是否空连接检测
  1671. *Empty connection detection examination
  1672. */
  1673. bool isEmptyConnCheck() const;
  1674. friend class BindAdapter;
  1675. friend class ConnectionList;
  1676. friend class TC_EpollServer;
  1677. private:
  1678. /**
  1679. * 服务
  1680. * Service
  1681. */
  1682. TC_EpollServer *_epollServer;
  1683. /**
  1684. * net线程的id
  1685. * the net thread id
  1686. */
  1687. std::thread::id _threadId;
  1688. /**
  1689. * 线程索引
  1690. * the thread index
  1691. */
  1692. int _threadIndex;
  1693. /**
  1694. * epoll
  1695. */
  1696. TC_Epoller _epoller;
  1697. /**
  1698. * 停止
  1699. * Stop
  1700. */
  1701. bool _bTerminate;
  1702. /**
  1703. * 通知epoll
  1704. * Notify epoll
  1705. */
  1706. TC_Epoller::NotifyInfo _notify;
  1707. /**
  1708. * 管理的连接链表
  1709. * Managed Link List
  1710. */
  1711. ConnectionList _list;
  1712. /**
  1713. * 发送队列
  1714. * Sending Queue
  1715. */
  1716. send_queue _sbuffer;
  1717. /**
  1718. *空连接检测机制开关
  1719. *Switch for empty connection detection mechanism
  1720. */
  1721. bool _bEmptyConnAttackCheck;
  1722. /**
  1723. * 空连接超时时间,单位是毫秒,默认值2s,
  1724. * 该时间必须小于等于adapter自身的超时时间
  1725. * Empty connection timeout in milliseconds, default 2s,
  1726. * The time must be less than or equal to the adapter's own timeout
  1727. */
  1728. int _iEmptyCheckTimeout;
  1729. /**
  1730. * udp连接时接收包缓存大小,针对所有udp接收缓存有效
  1731. * Received packet cache size on UDP connection, valid for all UDP receive caches
  1732. */
  1733. size_t _nUdpRecvBufferSize;
  1734. /**
  1735. * 通知信号
  1736. * Notification signal
  1737. */
  1738. bool _notifySignal = false;
  1739. };
  1740. ////////////////////////////////////////////////////////////////////////////
  1741. public:
  1742. /**
  1743. * 构造函数
  1744. * Constructor
  1745. */
  1746. TC_EpollServer(unsigned int iNetThreadNum = 1);
  1747. /**
  1748. * 析构函数
  1749. * Destructor
  1750. */
  1751. ~TC_EpollServer();
  1752. /**
  1753. * 是否启用防止空链接攻击的机制
  1754. * Whether mechanisms to prevent empty link attacks are enabled
  1755. * @param bEnable
  1756. */
  1757. void enAntiEmptyConnAttack(bool bEnable);
  1758. /**
  1759. *设置空连接超时时间
  1760. *Set empty connection timeout
  1761. */
  1762. void setEmptyConnTimeout(int timeout);
  1763. /**
  1764. * 设置本地日志
  1765. * Set local log
  1766. * @param plocalLogger
  1767. */
  1768. void setLocalLogger(RollWrapperInterface *pLocalLogger) { _pLocalLogger = pLocalLogger; }
  1769. /**
  1770. * 选择网络线程
  1771. * Select network threads
  1772. * @param fd
  1773. */
  1774. inline NetThread* getNetThreadOfFd(int fd) { return _netThreads[fd % _netThreads.size()]; }
  1775. /**
  1776. * 合并handle线程和网络线程
  1777. * Merge handle and network threads
  1778. * @param merge
  1779. */
  1780. void setMergeHandleNetThread(bool merge) { _mergeHandleNetThread = merge; }
  1781. /**
  1782. * 是否合并handle线程网络线程
  1783. * Whether to merge handle thread network threads
  1784. * @return
  1785. */
  1786. inline bool isMergeHandleNetThread() const { return _mergeHandleNetThread; }
  1787. /**
  1788. * 绑定监听socket
  1789. * Bind listening socket
  1790. * @param ls
  1791. */
  1792. int bind(BindAdapterPtr &lsPtr);
  1793. /**
  1794. * 启动业务处理线程
  1795. * Start Business Processing Thread
  1796. */
  1797. void startHandle();
  1798. /**
  1799. * 生成epoll
  1800. * Generate epoll
  1801. */
  1802. void createEpoll();
  1803. /**
  1804. * 运行
  1805. * Run
  1806. */
  1807. void waitForShutdown();
  1808. /**
  1809. * 停止服务
  1810. * Stop Service
  1811. */
  1812. void terminate();
  1813. /**
  1814. * 是否服务结束了
  1815. * Whether the service is over
  1816. *
  1817. * @return bool
  1818. */
  1819. bool isTerminate() const { return _bTerminate; }
  1820. /**
  1821. * 根据名称获取BindAdapter
  1822. * Get BindAdapter according to the name
  1823. * @param sName
  1824. * @return BindAdapterPtr
  1825. */
  1826. BindAdapterPtr getBindAdapter(const string &sName);
  1827. /**
  1828. * 获取所有adatapters
  1829. * Get all adapters
  1830. * @return
  1831. */
  1832. vector<BindAdapterPtr> getBindAdapters();
  1833. /**
  1834. * 向网络线程添加连接
  1835. * Add remote connection to the network thread
  1836. */
  1837. void addConnection(Connection * cPtr, int fd, CONN_TYPE iType);
  1838. /**
  1839. * 关闭连接
  1840. * Close connection
  1841. * @param uid
  1842. */
  1843. void close(const shared_ptr<TC_EpollServer::RecvContext> &data);
  1844. /**
  1845. * 发送数据
  1846. * Send data
  1847. * @param uid
  1848. * @param s
  1849. */
  1850. void send(const shared_ptr<SendContext> &data);
  1851. /**
  1852. * 获取某一监听端口的连接数
  1853. * Get the connection amount of a certain listening port
  1854. * @param lfd
  1855. *
  1856. * @return vector<TC_EpollServer::ConnStatus>
  1857. */
  1858. vector<ConnStatus> getConnStatus(int lfd);
  1859. /**
  1860. * 获取监听socket信息
  1861. * Get the information of the listening socket
  1862. *
  1863. * @return map<int,ListenSocket>
  1864. */
  1865. unordered_map<int, BindAdapterPtr> getListenSocketInfo();
  1866. /**
  1867. * 获取所有连接的数目
  1868. * Get the amount of all connections
  1869. *
  1870. * @return size_t
  1871. */
  1872. size_t getConnectionCount();
  1873. /**
  1874. * 记录日志
  1875. * Logging
  1876. * @param s
  1877. */
  1878. void debug(const string &s) const;
  1879. /**
  1880. * INFO日志
  1881. * INFO LOG
  1882. * @param s
  1883. */
  1884. void info(const string &s) const;
  1885. /**
  1886. * 记录错误日志
  1887. * Log errors
  1888. * @param s
  1889. */
  1890. void error(const string &s) const;
  1891. /**
  1892. * tars日志
  1893. * tars log
  1894. * @param s
  1895. */
  1896. void tars(const string &s) const;
  1897. /**
  1898. * 获取网络线程的数目
  1899. * Get the amount of the network threads
  1900. */
  1901. unsigned int getNetThreadNum() { return _netThreadNum; }
  1902. /**
  1903. * 获取网络线程的指针集合
  1904. * Get the collection of pointers for a network thread
  1905. */
  1906. vector<TC_EpollServer::NetThread*> getNetThread() { return _netThreads; }
  1907. /**
  1908. * 停止线程
  1909. * Stop the thread
  1910. */
  1911. void stopThread();
  1912. /**
  1913. * 获取所有业务线程的数目
  1914. * Get the amount of all the bussiness threads
  1915. */
  1916. size_t getLogicThreadNum();
  1917. // 接收新的客户端链接时的回调
  1918. typedef std::function<void (TC_EpollServer::Connection*)> accept_callback_functor;
  1919. /*
  1920. * 设置接收链接的回调
  1921. */
  1922. void setOnAccept(const accept_callback_functor& f) { _acceptFunc = f; }
  1923. //回调给应用服务
  1924. //Callback to application service
  1925. typedef std::function<void(TC_EpollServer*)> application_callback_functor;
  1926. /**
  1927. * 设置waitForShutdown线程回调的心跳
  1928. * Set the heartbeat of the thread callback of the waitForShutdown
  1929. * @param hf [description]
  1930. */
  1931. void setCallbackFunctor(const application_callback_functor &hf) { _hf = hf; }
  1932. //网络线程发送心跳的函数
  1933. //Function for network threads to send heartbeats
  1934. typedef std::function<void(const string &)> heartbeat_callback_functor;
  1935. /**
  1936. * 设置netthread网络线程发送心跳的函数
  1937. * Function for setting netthreaded network threads to send heartbeats
  1938. * @param hf [description]
  1939. */
  1940. void setHeartBeatFunctor(const heartbeat_callback_functor& heartFunc) { _heartFunc = heartFunc; }
  1941. heartbeat_callback_functor& getHeartBeatFunctor() { return _heartFunc; }
  1942. protected:
  1943. friend class BindAdapter;
  1944. /**
  1945. * 接收句柄
  1946. * Receiving handle
  1947. * @param fd
  1948. * @return
  1949. */
  1950. bool accept(int fd, int domain = AF_INET);
  1951. /**
  1952. * 绑定端口
  1953. * Bind Port
  1954. * @param ep
  1955. * @param s
  1956. * @param manualListen
  1957. */
  1958. void bind(const TC_Endpoint &ep, TC_Socket &s, bool manualListen);
  1959. static void applicationCallback(TC_EpollServer *epollServer);
  1960. private:
  1961. /**
  1962. * 网络线程
  1963. * Network Thread
  1964. */
  1965. std::vector<NetThread*> _netThreads;
  1966. /*
  1967. * 网络线程数目
  1968. * Network Thread Amount
  1969. */
  1970. unsigned int _netThreadNum;
  1971. /**
  1972. * epoll
  1973. */
  1974. TC_Epoller _epoller;
  1975. /**
  1976. * 通知epoll
  1977. * Notify epoll
  1978. */
  1979. TC_Epoller::NotifyInfo _notify;
  1980. /*
  1981. * 服务是否停止
  1982. * Whether the service is stopped
  1983. */
  1984. bool _bTerminate;
  1985. /*
  1986. * 业务线程是否启动
  1987. * Whether the bussiness thread is started.
  1988. */
  1989. bool _handleStarted;
  1990. /**
  1991. * 合并网络和业务线程
  1992. * Merge network and business threads
  1993. */
  1994. bool _mergeHandleNetThread = false;
  1995. /**
  1996. * 本地循环日志
  1997. * Local Loop Log
  1998. */
  1999. RollWrapperInterface *_pLocalLogger;
  2000. /**
  2001. *
  2002. */
  2003. vector<BindAdapterPtr> _bindAdapters;
  2004. /**
  2005. * 监听socket
  2006. * Listening socket
  2007. */
  2008. unordered_map<int, BindAdapterPtr> _listeners;
  2009. /**
  2010. * 应用回调
  2011. * Application callback
  2012. */
  2013. application_callback_functor _hf;
  2014. /**
  2015. * 发送心跳的函数
  2016. * Heartbeat Sending Function
  2017. */
  2018. heartbeat_callback_functor _heartFunc;
  2019. /**
  2020. * 接收链接的回调函数
  2021. */
  2022. accept_callback_functor _acceptFunc;
  2023. };
  2024. typedef TC_AutoPtr<TC_EpollServer> TC_EpollServerPtr;
  2025. }
  2026. #endif