tc_epoll_server.h 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  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 <vector>
  22. #include <list>
  23. #include <algorithm>
  24. #include <functional>
  25. #include "util/tc_epoller.h"
  26. #include "util/tc_thread.h"
  27. #include "util/tc_clientsocket.h"
  28. #include "util/tc_logger.h"
  29. // #include "util/tc_shm.h"
  30. #include "util/tc_common.h"
  31. // #include "util/tc_mem_queue.h"
  32. // #include "util/tc_squeue.h"
  33. // #include "util/tc_mmap.h"
  34. // #include "util/tc_fifo.h"
  35. #include "util/tc_network_buffer.h"
  36. // #include "util/tc_buffer.h"
  37. // #include "util/tc_buffer_pool.h"
  38. #include "util/tc_cas_queue.h"
  39. using namespace std;
  40. namespace tars
  41. {
  42. #if TARS_SSL
  43. class TC_OpenSSL;
  44. #endif
  45. /////////////////////////////////////////////////
  46. /**
  47. * @file tc_epoll_server.h
  48. * @brief EpollServer类
  49. *
  50. */
  51. /////////////////////////////////////////////////
  52. /**
  53. * Server基类
  54. * 注册协议解析器
  55. * 注册逻辑处理器
  56. * 注册管理端口处理器
  57. */
  58. class PropertyReport;
  59. class TC_EpollServer : public TC_ThreadLock, public TC_HandleBase
  60. {
  61. public:
  62. ////////////////////////////////////////////////////////////////////////////
  63. /**
  64. * 定义协议解析的返回值
  65. */
  66. // enum
  67. // {
  68. // PACKET_LESS = 0,
  69. // PACKET_FULL = 1,
  70. // PACKET_ERR = -1,
  71. // };
  72. enum EM_CLOSE_T
  73. {
  74. EM_CLIENT_CLOSE = 0, //客户端主动关闭
  75. EM_SERVER_CLOSE = 1, //服务端业务主动调用close关闭连接,或者框架因某种异常主动关闭连接
  76. EM_SERVER_TIMEOUT_CLOSE = 2 //连接超时了,服务端主动关闭
  77. };
  78. //定义事件类型
  79. // enum
  80. // {
  81. // ET_LISTEN = 1,
  82. // ET_CLOSE = 2,
  83. // ET_NOTIFY = 3,
  84. // ET_NET = 0,
  85. // };
  86. enum
  87. {
  88. MIN_EMPTY_CONN_TIMEOUT = 2*1000, /*空链接超时时间(ms)*/
  89. DEFAULT_RECV_BUFFERSIZE = 64*1024 /*缺省数据接收buffer的大小*/
  90. };
  91. //定义加入到网络线程的fd类别
  92. enum CONN_TYPE
  93. {
  94. TCP_CONNECTION = 0,
  95. UDP_CONNECTION = 1,
  96. };
  97. /**
  98. * 定义协议解析接口的操作对象
  99. * 注意必须是线程安全的或是可以重入的
  100. */
  101. // using protocol_functor = std::function<TC_NetWorkBuffer::PACKET_TYPE(string&, string&)>;
  102. // using header_filter_functor = std::function<int (int, string&)>;
  103. // using conn_protocol_functor = std::function<TC_NetWorkBuffer::PACKET_TYPE(string&, string&, void*)>;
  104. typedef std::function<TC_NetWorkBuffer::PACKET_TYPE(TC_NetWorkBuffer::PACKET_TYPE, vector<char>&)> header_filter_functor;
  105. class NetThread;
  106. class Connection;
  107. class BindAdapter;
  108. typedef TC_AutoPtr<BindAdapter> BindAdapterPtr;
  109. class Handle;
  110. typedef TC_AutoPtr<Handle> HandlePtr;
  111. class RecvContext;
  112. /**
  113. * 发送包的上下文
  114. * 由RecvContext创建出来
  115. */
  116. class SendContext
  117. {
  118. public:
  119. SendContext(const shared_ptr<RecvContext> &context, char cmd) : _context(context), _cmd(cmd)
  120. {
  121. _sbuffer = std::make_shared<TC_NetWorkBuffer::Buffer>();
  122. }
  123. const shared_ptr<RecvContext> &getRecvContext() { return _context; }
  124. const shared_ptr<TC_NetWorkBuffer::Buffer> & buffer() { return _sbuffer; }
  125. char cmd() const { return _cmd; }
  126. uint32_t uid() const { return _context->uid(); }
  127. int fd() const { return _context->fd(); }
  128. const string &ip() const { return _context->ip(); }
  129. uint16_t port() const { return _context->port(); }
  130. friend class RecvContext;
  131. protected:
  132. shared_ptr<RecvContext> _context;
  133. char _cmd; /**send包才有效, 命令:'c',关闭fd; 's',有数据需要发送*/
  134. shared_ptr<TC_NetWorkBuffer::Buffer> _sbuffer; /**发送的内容*/
  135. };
  136. ////////////////////////////////////////////////////////////////////////////
  137. /**
  138. * 接收包的上下文
  139. */
  140. class RecvContext : public std::enable_shared_from_this<RecvContext>
  141. {
  142. public:
  143. RecvContext(uint32_t uid, const string &ip, int64_t port, int fd, const BindAdapterPtr &adapter, bool isClosed = false, int closeType = EM_CLIENT_CLOSE)
  144. : _uid(uid), _ip(ip), _port(port), _fd(fd), _adapter(adapter), _isClosed(isClosed), _closeType(closeType), _recvTimeStamp(TNOWMS)
  145. {
  146. }
  147. uint32_t uid() const { return _uid; }
  148. const string &ip() const { return _ip; }
  149. uint16_t port() const { return _port; }
  150. vector<char> &buffer() { return _rbuffer; }
  151. const vector<char> &buffer() const { return _rbuffer; }
  152. int64_t recvTimeStamp() const { return _recvTimeStamp; }
  153. bool isOverload() const { return _isOverload; }
  154. void setOverload() { _isOverload = true; }
  155. bool isClosed() const { return _isClosed; }
  156. int fd() const { return _fd; }
  157. BindAdapterPtr &adapter() { return _adapter; }
  158. int closeType() const { return _closeType; }
  159. void setCloseType(int closeType) { _closeType = closeType;}
  160. shared_ptr<SendContext> createSendContext() { return std::make_shared<SendContext>(shared_from_this(), 's'); }
  161. shared_ptr<SendContext> createCloseContext() { return std::make_shared<SendContext>(shared_from_this(), 'c'); }
  162. // int64_t _recvUS;
  163. protected:
  164. uint32_t _uid; /**连接标示*/
  165. string _ip; /**远程连接的ip*/
  166. uint16_t _port; /**远程连接的端口*/
  167. int _fd; /*保存产生该消息的fd,用于回包时选择网络线程*/
  168. BindAdapterPtr _adapter; /**标识哪一个adapter的消息*/
  169. vector<char> _rbuffer; /**接收的内容*/
  170. bool _isOverload = false; /**是否已过载 */
  171. bool _isClosed = false; /**是否已关闭*/
  172. int _closeType; /*如果是关闭消息包,则标识关闭类型,0:表示客户端主动关闭;1:服务端主动关闭;2:连接超时服务端主动关闭*/
  173. int64_t _recvTimeStamp; /**接收到数据的时间*/
  174. };
  175. typedef TC_CasQueue<shared_ptr<RecvContext>> recv_queue;
  176. typedef TC_CasQueue<shared_ptr<SendContext>> send_queue;
  177. typedef recv_queue::queue_type recv_queue_type;
  178. ////////////////////////////////////////////////////////////////////////////
  179. /**
  180. * 链接状态
  181. */
  182. struct ConnStatus
  183. {
  184. string ip;
  185. int32_t uid;
  186. uint16_t port;
  187. int timeout;
  188. int iLastRefreshTime;
  189. };
  190. ////////////////////////////////////////////////////////////////////////////
  191. /**
  192. * @brief 定义服务逻辑处理的接口
  193. *
  194. */
  195. /**
  196. * 服务的逻辑处理代码
  197. */
  198. class Handle : public TC_Thread, public TC_ThreadLock, public TC_HandleBase
  199. {
  200. public:
  201. /**
  202. * 构造, 默认没有请求, 等待10s
  203. */
  204. Handle();
  205. /**
  206. * 析构函数
  207. */
  208. virtual ~Handle();
  209. /**
  210. * 设置服务
  211. * @param pEpollServer
  212. */
  213. void setEpollServer(TC_EpollServer *pEpollServer);
  214. /**
  215. * 获取服务
  216. * @return TC_EpollServer*
  217. */
  218. TC_EpollServer* getEpollServer();
  219. /**
  220. * 获取Handle的索引(0~handle个数-1)
  221. * @return
  222. */
  223. uint32_t getHandleIndex() const { return _handleIndex; }
  224. /**
  225. * 设置网络线程
  226. */
  227. void setNetThread(NetThread *netThread);
  228. /**
  229. * 获取网络线程
  230. * @return
  231. */
  232. NetThread *getNetThread() { return _netThread; }
  233. /**
  234. * 处理
  235. */
  236. void process(shared_ptr<RecvContext> data);
  237. /**
  238. * 线程处理方法
  239. */
  240. virtual void run();
  241. public:
  242. /**
  243. * 发送数据
  244. * @param stRecvData
  245. * @param sSendBuffer
  246. */
  247. void sendResponse(const shared_ptr<SendContext> &data);
  248. /**
  249. * 关闭链接
  250. * @param stRecvData
  251. */
  252. void close(const shared_ptr<RecvContext> &data);
  253. /**
  254. * 设置等待时间
  255. * @param iWaitTime
  256. */
  257. void setWaitTime(uint32_t iWaitTime);
  258. /**
  259. * 对象初始化
  260. */
  261. virtual void initialize() {};
  262. /**
  263. * 唤醒HandleGroup中的handle线程
  264. */
  265. virtual void notifyFilter();
  266. /**
  267. * 心跳(每处理完一个请求或者等待请求超时都会调用一次)
  268. */
  269. virtual void heartbeat() {}
  270. protected:
  271. /**
  272. * 具体的处理逻辑
  273. */
  274. virtual void handleImp();
  275. /**
  276. * 处理函数
  277. * @param stRecvData: 接收到的数据
  278. */
  279. virtual void handle(const shared_ptr<RecvContext> &data) = 0;
  280. /**
  281. * 处理超时数据, 即数据在队列中的时间已经超过
  282. * 默认直接关闭连接
  283. * @param stRecvData: 接收到的数据
  284. */
  285. virtual void handleTimeout(const shared_ptr<TC_EpollServer::RecvContext> &data);
  286. /**
  287. * 处理连接关闭通知,包括
  288. * 1.close by peer
  289. * 2.recv/send fail
  290. * 3.close by timeout or overload
  291. * @param stRecvData:
  292. */
  293. virtual void handleClose(const shared_ptr<TC_EpollServer::RecvContext> &data);
  294. /**
  295. * 处理overload数据 即数据队列中长度已经超过允许值
  296. * 默认直接关闭连接
  297. * @param stRecvData: 接收到的数据
  298. */
  299. virtual void handleOverload(const shared_ptr<TC_EpollServer::RecvContext> &data);
  300. /**
  301. * 处理Filter的消息
  302. */
  303. //virtual void handleFilter() {};
  304. /**
  305. * 处理异步回调队列
  306. */
  307. virtual void handleAsyncResponse() {}
  308. /**
  309. * handleFilter拆分的第二部分,处理用户自有数据
  310. * 非游戏逻辑可忽略bExpectIdle参数
  311. */
  312. virtual void handleCustomMessage(bool bExpectIdle = false) {}
  313. /**
  314. * 线程已经启动, 进入具体处理前调用
  315. */
  316. virtual void startHandle() {}
  317. /**
  318. * 线程马上要退出时调用
  319. */
  320. virtual void stopHandle() {}
  321. /**
  322. * 是否所有的Adpater队列都为空
  323. * @return bool
  324. */
  325. virtual bool allAdapterIsEmpty();
  326. /**
  327. * 是否所有的servant都没有resp消息待处理
  328. * @return bool
  329. */
  330. virtual bool allFilterIsEmpty();
  331. /**
  332. * 设置Adapter
  333. * @param pEpollServer
  334. */
  335. void setBindAdapter(BindAdapter* bindAdapter);
  336. /**
  337. * 设置index
  338. * @param index
  339. */
  340. void setHandleIndex(uint32_t index);
  341. /**
  342. * 等待在队列上
  343. */
  344. void wait();
  345. /**
  346. * 从队列中获取数据
  347. * @param recv
  348. * @return
  349. */
  350. bool popRecvQueue(shared_ptr<RecvContext> &recv);
  351. /**
  352. * 友元类
  353. */
  354. friend class BindAdapter;
  355. protected:
  356. /**
  357. * 服务
  358. */
  359. TC_EpollServer *_pEpollServer;
  360. /**
  361. * handle对应的网路线程(网络线程和handle线程合并的情况下有效)
  362. */
  363. NetThread *_netThread = NULL;
  364. /**
  365. * 所属handle组
  366. */
  367. BindAdapter* _bindAdapter;
  368. /**
  369. * 等待时间
  370. */
  371. uint32_t _iWaitTime;
  372. /**
  373. * Handle的索引
  374. */
  375. uint32_t _handleIndex;
  376. /**
  377. * 所属handle组
  378. */
  379. // HandleGroupPtr _handleGroup;
  380. };
  381. using close_functor = std::function<void (void*, EM_CLOSE_T )>;
  382. using auth_process_wrapper_functor = std::function<bool (Connection *c, const shared_ptr<RecvContext> &recv )>;
  383. ////////////////////////////////////////////////////////////////////////////
  384. // 服务端口管理,监听socket信息
  385. class BindAdapter : public TC_ThreadLock, public TC_HandleBase
  386. {
  387. public:
  388. /**
  389. * 缺省的一些定义
  390. */
  391. enum
  392. {
  393. DEFAULT_QUEUE_CAP = 10*1024, /**流量*/
  394. MIN_QUEUE_TIMEOUT = 3*1000, /**队列最小超时时间(ms)*/
  395. DEFAULT_MAX_CONN = 1024, /**缺省最大连接数*/
  396. DEFAULT_QUEUE_TIMEOUT = 60*1000, /**缺省的队列超时时间(ms)*/
  397. };
  398. /**
  399. * 顺序
  400. */
  401. enum EOrder
  402. {
  403. ALLOW_DENY,
  404. DENY_ALLOW
  405. };
  406. /**
  407. * 数据队列
  408. */
  409. struct DataQueue
  410. {
  411. /**
  412. * 接收的数据队列
  413. */
  414. recv_queue _rbuffer;
  415. /**
  416. * 锁
  417. */
  418. TC_ThreadLock _monitor;
  419. };
  420. // BindAdapter()
  421. // {
  422. // _pReportQueue = NULL;
  423. // _pReportConRate = NULL;
  424. // _pReportTimeoutNum = NULL;
  425. // }
  426. /**
  427. * 构造函数
  428. */
  429. BindAdapter(TC_EpollServer *pEpollServer);
  430. /**
  431. * 析够函数
  432. */
  433. ~BindAdapter();
  434. /**
  435. * 设置需要手工监听
  436. */
  437. void enableManualListen() { _manualListen = true; }
  438. /**
  439. * 是否手工监听端口
  440. * @return
  441. */
  442. bool isManualListen() const { return _manualListen; }
  443. /**
  444. * 手工绑定端口
  445. */
  446. void manualListen();
  447. /**
  448. * 设置adapter name
  449. * @param name
  450. */
  451. void setName(const string &name);
  452. /**
  453. * 获取adapter name
  454. * @return string
  455. */
  456. string getName() const;
  457. /**
  458. * 增加处理线程对应的接收队列
  459. * @return string
  460. */
  461. void initThreadRecvQueue(uint32_t handeIndex);
  462. /**
  463. * 获取queue capacity
  464. * @return int
  465. */
  466. int getQueueCapacity() const;
  467. /**
  468. * 设置queue capacity
  469. * @param n
  470. */
  471. void setQueueCapacity(int n);
  472. /**
  473. * 设置协议名称
  474. * @param name
  475. */
  476. void setProtocolName(const string& name);
  477. /**
  478. * 获取协议名称
  479. * @return const string&
  480. */
  481. const string& getProtocolName();
  482. /**
  483. * 是否tars协议
  484. * @return bool
  485. */
  486. bool isTarsProtocol();
  487. /**
  488. * 判断是否需要过载保护
  489. * @return bool
  490. */
  491. int isOverloadorDiscard();
  492. /**
  493. * 设置消息在队列中的超时时间, t为毫秒
  494. * (超时时间精度只能是s)
  495. * @param t
  496. */
  497. void setQueueTimeout(int t);
  498. /**
  499. * 获取消息在队列中的超时时间, 毫秒
  500. * @return int
  501. */
  502. int getQueueTimeout() const;
  503. /**
  504. * 设置endpoint
  505. * @param str
  506. */
  507. void setEndpoint(const string &str);
  508. /**
  509. * 获取ip
  510. * @return const string&
  511. */
  512. TC_Endpoint getEndpoint() const;
  513. /**
  514. * 监听socket
  515. * @return TC_Socket
  516. */
  517. TC_Socket &getSocket();
  518. /**
  519. * 设置最大连接数
  520. * @param iMaxConns
  521. */
  522. void setMaxConns(int iMaxConns);
  523. /**
  524. * 获取最大连接数
  525. * @return size_t
  526. */
  527. size_t getMaxConns() const;
  528. /**
  529. * 设置HeartBeat时间
  530. * @param n
  531. */
  532. void setHeartBeatTime(time_t t);
  533. /**
  534. * 获取HeartBeat时间
  535. * @return size_t
  536. */
  537. time_t getHeartBeatTime() const;
  538. /**
  539. * 设置allow deny次序
  540. * @param eOrder
  541. */
  542. void setOrder(EOrder eOrder);
  543. /**
  544. * 设置允许ip
  545. * @param vtAllow
  546. */
  547. void setAllow(const vector<string> &vtAllow);
  548. /**
  549. * 设置禁止ip
  550. * @param vtDeny
  551. */
  552. void setDeny(const vector<string> &vtDeny);
  553. /**
  554. * 获取允许ip
  555. * @return vector<string>: ip列表
  556. */
  557. vector<string> getAllow() const;
  558. /**
  559. * 获取禁止ip
  560. * @return vector<string>: ip列表
  561. */
  562. vector<string> getDeny() const;
  563. /**
  564. * 获取allow deny次序
  565. * @return EOrder
  566. */
  567. EOrder getOrder() const;
  568. /**
  569. * 是否Ip被允许
  570. * @param ip
  571. * @return bool
  572. */
  573. bool isIpAllow(const string& ip) const;
  574. /**
  575. * 是否超过了最大连接数
  576. * @return bool
  577. */
  578. bool isLimitMaxConnection() const;
  579. /**
  580. * 减少当前连接数
  581. */
  582. void decreaseNowConnection();
  583. /**
  584. * 增加当前连接数
  585. */
  586. void increaseNowConnection();
  587. /**
  588. * 获取所有链接状态
  589. * @return ConnStatus
  590. */
  591. vector<ConnStatus> getConnStatus();
  592. /**
  593. * 获取当前连接数
  594. * @return int
  595. */
  596. int getNowConnection() const;
  597. /**
  598. * 获取EpollServer
  599. * @return TC_EpollServer*
  600. */
  601. TC_EpollServer* getEpollServer();
  602. /**
  603. * 获取对应的网络线程
  604. * @param fd
  605. * @return
  606. */
  607. inline NetThread* getNetThreadOfFd(int fd) const { return _pEpollServer->getNetThreadOfFd(fd); }
  608. /**
  609. * 注册协议解析器
  610. * @param pp
  611. */
  612. // void setProtocol(const protocol_functor& pf, int iHeaderLen = 0, const header_filter_functor& hf = echo_header_filter);
  613. /**
  614. * 注册协议解析器
  615. * @param pp
  616. */
  617. void setProtocol(const TC_NetWorkBuffer::protocol_functor& pf, int iHeaderLen = 0, const header_filter_functor& hf = echo_header_filter);
  618. /**
  619. * 获取协议解析器
  620. * @return protocol_functor&
  621. */
  622. TC_NetWorkBuffer::protocol_functor &getProtocol();
  623. /**
  624. * 解析包头处理对象
  625. * @return protocol_functor&
  626. */
  627. header_filter_functor &getHeaderFilterFunctor();
  628. /**
  629. * 增加数据到队列中
  630. * @param vtRecvData
  631. * @param bPushBack 后端插入
  632. * @param sBuffer
  633. */
  634. void insertRecvQueue(const shared_ptr<RecvContext> &recv);//, bool bPushBack = true);
  635. /**
  636. * 等待数据
  637. * @return bool
  638. */
  639. bool waitForRecvQueue(uint32_t handleIndex, shared_ptr<RecvContext> &recv);
  640. /**
  641. * 接收队列的大小
  642. * @return size_t
  643. */
  644. size_t getRecvBufferSize() const;
  645. /**
  646. * 默认的协议解析类, 直接echo
  647. * @param r
  648. * @param o
  649. * @return int
  650. */
  651. static TC_NetWorkBuffer::PACKET_TYPE echo_protocol(TC_NetWorkBuffer &r, vector<char> &o);
  652. /**
  653. * 默认的包头处理
  654. * @param i
  655. * @param o
  656. * @return int
  657. */
  658. static TC_NetWorkBuffer::PACKET_TYPE echo_header_filter(TC_NetWorkBuffer::PACKET_TYPE i, vector<char> &o);
  659. /**
  660. * 获取需要过滤的包头长度
  661. */
  662. int getHeaderFilterLen();
  663. /**
  664. * 设置ServantHandle数目
  665. * @param n
  666. */
  667. void setHandleNum(int n);
  668. /**
  669. * 所属handle组的handle数(每个handle一个对象)
  670. * @return int
  671. */
  672. int getHandleNum();
  673. /**
  674. * 初始化处理线程,线程将会启动
  675. */
  676. template<typename T> void setHandle(size_t n)
  677. {
  678. if(!_handles.empty())
  679. {
  680. getEpollServer()->error("[BindAdapter::setHandle] handle is not empty!");
  681. return;
  682. }
  683. _iHandleNum = n;
  684. _threadDataQueue.resize(_iHandleNum + 1);
  685. _threadDataQueue[0] = std::make_shared<BindAdapter::DataQueue>();
  686. if(_pEpollServer->isMergeHandleNetThread())
  687. {
  688. _iHandleNum = _pEpollServer->_netThreadNum;
  689. }
  690. for (int32_t i = 0; i < _iHandleNum ; ++i)
  691. {
  692. HandlePtr handle = new T();
  693. handle->setHandleIndex(i);
  694. handle->setEpollServer(this->getEpollServer());
  695. handle->setBindAdapter(this);
  696. _handles.push_back(handle);
  697. }
  698. }
  699. /**
  700. * 获取第几个句柄
  701. * @param index
  702. * @return
  703. */
  704. HandlePtr getHandle(size_t index) {
  705. assert(index <= _iHandleNum);
  706. assert(getEpollServer()->isMergeHandleNetThread());
  707. return _handles[index];
  708. }
  709. /**
  710. * 设置服务端回包缓存的大小限制
  711. */
  712. void setBackPacketBuffLimit(size_t iLimitSize);
  713. /**
  714. * 获取服务端回包缓存的大小限制
  715. */
  716. size_t getBackPacketBuffLimit();
  717. /**
  718. * 获取服务端接收队列(如果_rnbuffer有多个, 则根据调用者的线程id来hash获取)
  719. */
  720. recv_queue &getRecvQueue(uint32_t handleIndex);
  721. /**
  722. * 获取handles
  723. */
  724. const vector<HandlePtr> &getHandles() { return _handles; }
  725. /**
  726. * 是否是队列模式(默认是False的)
  727. */
  728. bool isQueueMode() const { return _queueMode; }
  729. /**
  730. * 开启队列模式(同一个连接的请求, 落在同一个handle处理线程中)
  731. */
  732. void enableQueueMode() { _queueMode = true; }
  733. /**
  734. * 等待队列数据
  735. */
  736. void waitAtQueue(uint32_t handleIndex, uint32_t waitTime);
  737. /**
  738. * 通知某个具体handle醒过来
  739. * @param handleIndex
  740. */
  741. void notifyHandle(uint32_t handleIndex);
  742. /**
  743. * 设置close回调函数
  744. */
  745. void setOnClose(const close_functor& f) { _closeFunc = f; }
  746. /**
  747. * 注册协议解析器
  748. */
  749. // void setConnProtocol(const TC_NetWorkBuffer::protocol_functor& cpf, int iHeaderLen = 0, const header_filter_functor& hf = echo_header_filter);
  750. /**
  751. * 获取协议解析器
  752. * @return protocol_functor&
  753. */
  754. // const TC_NetWorkBuffer::protocol_functor& getConnProtocol() { return _cpf; }
  755. /**
  756. * 注册鉴权包裹函数
  757. * @param apwf
  758. */
  759. void setAuthProcessWrapper(const auth_process_wrapper_functor& apwf) { _authWrapper = apwf; }
  760. void setAkSk(const std::string& ak, const std::string& sk) { _accessKey = ak; _secretKey = sk; }
  761. bool checkAkSk(const std::string& ak, const std::string& sk) { return ak == _accessKey && sk == _secretKey; }
  762. std::string getSk(const std::string& ak) const { return (_accessKey == ak) ? _secretKey : ""; }
  763. private:
  764. /**
  765. * 获取等待的队列锁
  766. * @return
  767. */
  768. TC_ThreadLock &getLock(uint32_t handleIndex);
  769. public:
  770. //统计上报的对象
  771. PropertyReport * _pReportQueue = NULL;
  772. PropertyReport * _pReportConRate = NULL;
  773. PropertyReport * _pReportTimeoutNum = NULL;
  774. protected:
  775. friend class TC_EpollServer;
  776. // friend class NetThread;
  777. /**
  778. * 服务
  779. */
  780. TC_EpollServer *_pEpollServer;
  781. /**
  782. * 加锁
  783. */
  784. mutable std::mutex _mutex;
  785. /**
  786. * Adapter所用的HandleGroup
  787. */
  788. // HandleGroupPtr _handleGroup;
  789. /**
  790. * Adapter所用的HandleGroup
  791. */
  792. vector<HandlePtr> _handles;
  793. /**
  794. * 协议解析
  795. */
  796. TC_NetWorkBuffer::protocol_functor _pf;
  797. /**
  798. * 首个数据包包头过滤
  799. */
  800. header_filter_functor _hf;
  801. /**
  802. * adapter的名字
  803. */
  804. string _name;
  805. /**
  806. * 监听fd
  807. */
  808. TC_Socket _s;
  809. /**
  810. * 绑定的IP
  811. */
  812. TC_Endpoint _ep;
  813. /**
  814. * 最大连接数
  815. */
  816. int _iMaxConns;
  817. /**
  818. * 当前连接数
  819. */
  820. std::atomic<int> _iCurConns;
  821. /**
  822. * Handle个数
  823. */
  824. size_t _iHandleNum;
  825. /**
  826. * 允许的Order
  827. */
  828. volatile EOrder _eOrder;
  829. /**
  830. * 允许的ip
  831. */
  832. vector<string> _vtAllow;
  833. /**
  834. * 禁止的ip
  835. */
  836. vector<string> _vtDeny;
  837. /**
  838. * 每个线程都有自己的队列
  839. * 0: 给共享队列模式时使用
  840. * 1~handle个数: 队列模式时使用
  841. */
  842. vector<shared_ptr<DataQueue>> _threadDataQueue;
  843. /**
  844. * 接收队列数据总个数
  845. */
  846. atomic<size_t> _iBufferSize{0};
  847. /**
  848. * 接收的数据队列
  849. */
  850. // recv_queue _rbuffer;
  851. /**
  852. * 队列最大容量
  853. */
  854. int _iQueueCapacity;
  855. /**
  856. * 消息超时时间(从入队列到出队列间隔)(毫秒)
  857. */
  858. int _iQueueTimeout;
  859. /**
  860. * 首个数据包包头长度
  861. */
  862. int _iHeaderLen;
  863. /**
  864. * 上次心跳发送时间
  865. */
  866. volatile time_t _iHeartBeatTime;
  867. /**
  868. * 协议名称,缺省为"tars"
  869. */
  870. string _protocolName;
  871. //回包缓存限制大小
  872. size_t _iBackPacketBuffLimit;
  873. //队列模式
  874. bool _queueMode = false;
  875. //listen模式
  876. bool _manualListen = false;
  877. /**
  878. * 包裹认证函数,不能为空
  879. */
  880. auth_process_wrapper_functor _authWrapper;
  881. /**
  882. * 该obj的AK SK
  883. */
  884. std::string _accessKey;
  885. std::string _secretKey;
  886. //连接关闭的回调函数
  887. close_functor _closeFunc;
  888. // 协议解析
  889. // TC_NetWorkBuffer::protocol_functor _cpf;
  890. };
  891. ////////////////////////////////////////////////////////////////////////////
  892. // 服务连接管理
  893. /**
  894. * 建立连接的socket信息
  895. */
  896. class Connection
  897. {
  898. public:
  899. enum EnumConnectionType
  900. {
  901. EM_TCP = 0,
  902. EM_UDP = 1,
  903. };
  904. /**
  905. * 构造函数
  906. * @param lfd
  907. * @param s
  908. * @param ip
  909. * @param port
  910. */
  911. Connection(BindAdapter *pBindAdapter, int lfd, int timeout, int fd, const string& ip, uint16_t port);
  912. /**
  913. * udp连接
  914. * @param fd
  915. */
  916. Connection(BindAdapter *pBindAdapter, int fd);
  917. /**
  918. * 析构函数
  919. */
  920. virtual ~Connection();
  921. /**
  922. * 链接所属的adapter
  923. */
  924. BindAdapterPtr& getBindAdapter() { return _pBindAdapter; }
  925. /**
  926. * 初始化
  927. * @param id, 连接的唯一id
  928. */
  929. void init(unsigned int uid) { _uid = uid; }
  930. /**
  931. * 获取连接超时时间
  932. *
  933. * @return int
  934. */
  935. int getTimeout() const { return _timeout; }
  936. /**
  937. * 获取线程的惟一id
  938. *
  939. * @return unsigned int
  940. */
  941. uint32_t getId() const { return _uid; }
  942. /**
  943. * 获取监听fd
  944. *
  945. * @return int
  946. */
  947. int getListenfd() const { return _lfd; }
  948. /**
  949. * 当前连接fd
  950. *
  951. * @return int
  952. */
  953. int getfd() const { return _sock.getfd(); }
  954. /**
  955. * 是否有效
  956. *
  957. * @return bool
  958. */
  959. bool isValid() const { return _sock.isValid();}
  960. /**
  961. * 远程IP
  962. *
  963. * @return string
  964. */
  965. string getIp() const { return _ip; }
  966. /**
  967. * 远程端口
  968. *
  969. * @return uint16_t
  970. */
  971. uint16_t getPort() const { return _port; }
  972. /**
  973. * 设置首个数据包包头需要过滤的字节数
  974. */
  975. void setHeaderFilterLen(int iHeaderLen) { _iHeaderLen = iHeaderLen; }
  976. /**
  977. * 设置关闭,发送完当前数据就关闭连接
  978. */
  979. bool setClose();
  980. /**
  981. * 获取连接类型
  982. */
  983. EnumConnectionType getType() const { return _enType; }
  984. /**
  985. * 是否是空连接
  986. */
  987. bool isEmptyConn() const {return _bEmptyConn;}
  988. /**
  989. * Init Auth State;
  990. */
  991. void tryInitAuthState(int initState);
  992. friend class NetThread;
  993. protected:
  994. /**
  995. * 关闭连接
  996. * @param fd
  997. */
  998. void close();
  999. /**
  1000. * 发送TCP
  1001. */
  1002. int sendTcp(const shared_ptr<SendContext> &data);
  1003. /**
  1004. * 发送Udp
  1005. */
  1006. int sendUdp(const shared_ptr<SendContext> &data);
  1007. /**
  1008. * 添加发送buffer
  1009. * @param buffer
  1010. * @return int, -1:发送出错, 0:无数据, 1:发送完毕, 2:还有数据
  1011. */
  1012. int send(const shared_ptr<SendContext> &data);
  1013. /**
  1014. * 发送buffer里面数据
  1015. * @return
  1016. */
  1017. int sendBuffer();
  1018. /**
  1019. * 读取数据
  1020. * @param fd
  1021. * @return int, -1:接收出错, 0:接收不全, 1:接收到一个完整包
  1022. */
  1023. int recv();
  1024. /**
  1025. * 接收TCP
  1026. */
  1027. int recvTcp();
  1028. /**
  1029. * 接收Udp
  1030. */
  1031. int recvUdp();
  1032. /**
  1033. * 解析协议
  1034. * @param o
  1035. * @return int: <0:协议错误, 0:没有一个完整的包, 1:收到至少一个包
  1036. */
  1037. int parseProtocol();
  1038. /**
  1039. * 增加数据到队列中
  1040. * @param vtRecvData
  1041. */
  1042. void insertRecvQueue(const shared_ptr<RecvContext> &recv);
  1043. /**
  1044. * 对于udp方式的连接,分配指定大小的接收缓冲区
  1045. *@param nSize
  1046. */
  1047. bool setRecvBuffer(size_t nSize=DEFAULT_RECV_BUFFERSIZE);
  1048. /**
  1049. * 是否是tcp连接
  1050. * @return
  1051. */
  1052. bool isTcp() const { return _lfd != -1; }
  1053. public:
  1054. /**
  1055. * 最后刷新时间
  1056. */
  1057. time_t _iLastRefreshTime;
  1058. protected:
  1059. /**
  1060. * 适配器
  1061. */
  1062. BindAdapterPtr _pBindAdapter;
  1063. /**
  1064. * TC_Socket
  1065. */
  1066. TC_Socket _sock;
  1067. /**
  1068. * 连接的唯一编号
  1069. */
  1070. volatile uint32_t _uid;
  1071. /**
  1072. * 监听的socket
  1073. */
  1074. int _lfd;
  1075. /**
  1076. * 超时时间
  1077. */
  1078. int _timeout;
  1079. /**
  1080. * ip
  1081. */
  1082. string _ip;
  1083. /**
  1084. * 端口
  1085. */
  1086. uint16_t _port;
  1087. /**
  1088. * 接收数据buffer
  1089. */
  1090. TC_NetWorkBuffer _recvBuffer;
  1091. /**
  1092. * 发送数据buffer
  1093. */
  1094. TC_NetWorkBuffer _sendBuffer;
  1095. /**
  1096. * 需要过滤的头部字节数
  1097. */
  1098. int _iHeaderLen;
  1099. /**
  1100. * 发送完当前数据就关闭连接
  1101. */
  1102. bool _bClose;
  1103. /**
  1104. * 连接类型
  1105. */
  1106. EnumConnectionType _enType;
  1107. bool _bEmptyConn;
  1108. /*
  1109. *接收数据的临时buffer,加这个目的是对udp接收数据包大小进行设置
  1110. */
  1111. char *_pRecvBuffer = NULL;
  1112. size_t _nRecvBufferSize;
  1113. public:
  1114. /*
  1115. *该连接的鉴权状态
  1116. */
  1117. int _authState;
  1118. /*
  1119. *该连接的鉴权状态是否初始化了
  1120. */
  1121. bool _authInit;
  1122. #if TARS_SSL
  1123. std::unique_ptr<TC_OpenSSL> _openssl;
  1124. #endif
  1125. };
  1126. ////////////////////////////////////////////////////////////////////////////
  1127. /**
  1128. * 带有时间链表的map
  1129. */
  1130. class ConnectionList : public TC_ThreadLock
  1131. {
  1132. public:
  1133. /**
  1134. * 构造函数
  1135. */
  1136. ConnectionList(NetThread *pEpollServer);
  1137. /**
  1138. * 析够函数
  1139. */
  1140. ~ConnectionList() { if(_vConn) { delete[] _vConn; } }
  1141. /**
  1142. * 初始化大小
  1143. * @param size
  1144. */
  1145. void init(uint32_t size, uint32_t iIndex = 0);
  1146. /**
  1147. * 获取惟一ID
  1148. *
  1149. * @return unsigned int
  1150. */
  1151. uint32_t getUniqId();
  1152. /**
  1153. * 添加连接
  1154. * @param cPtr
  1155. * @param iTimeOutStamp
  1156. */
  1157. void add(Connection *cPtr, time_t iTimeOutStamp);
  1158. /**
  1159. * 刷新时间链
  1160. * @param uid
  1161. * @param iTimeOutStamp, 超时时间点
  1162. */
  1163. void refresh(uint32_t uid, time_t iTimeOutStamp);
  1164. /**
  1165. * 检查超时数据
  1166. */
  1167. void checkTimeout(time_t iCurTime);
  1168. /**
  1169. * 获取某个监听端口的连接
  1170. * @param lfd
  1171. * @return vector<TC_EpollServer::ConnStatus>
  1172. */
  1173. vector<ConnStatus> getConnStatus(int lfd);
  1174. /**
  1175. * 获取某一个连接
  1176. * @param p
  1177. * @return T
  1178. */
  1179. Connection* get(uint32_t uid);
  1180. /**
  1181. * 删除连接
  1182. * @param uid
  1183. */
  1184. void del(uint32_t uid);
  1185. /**
  1186. * 大小
  1187. * @return size_t
  1188. */
  1189. size_t size();
  1190. protected:
  1191. typedef pair<Connection*, multimap<time_t, uint32_t>::iterator> list_data;
  1192. /**
  1193. * 内部删除, 不加锁
  1194. * @param uid
  1195. */
  1196. void _del(uint32_t uid);
  1197. protected:
  1198. /**
  1199. * 无锁
  1200. */
  1201. TC_SpinLock _mutex;
  1202. /**
  1203. * 服务
  1204. */
  1205. NetThread *_pEpollServer;
  1206. /**
  1207. * 总计连接数
  1208. */
  1209. volatile uint32_t _total;
  1210. /**
  1211. * 空闲链表
  1212. */
  1213. list<uint32_t> _free;
  1214. /**
  1215. * 空闲链元素个数
  1216. */
  1217. volatile size_t _free_size;
  1218. /**
  1219. * 链接
  1220. */
  1221. list_data *_vConn;
  1222. /**
  1223. * 超时链表
  1224. */
  1225. multimap<time_t, uint32_t> _tl;
  1226. /**
  1227. * 上次检查超时时间
  1228. */
  1229. time_t _lastTimeoutTime;
  1230. /**
  1231. * 链接ID的魔数
  1232. */
  1233. uint32_t _iConnectionMagic;
  1234. };
  1235. ////////////////////////////////////////////////////////////////////////////
  1236. class NetThread : public TC_Thread, public TC_HandleBase
  1237. {
  1238. public:
  1239. ////////////////////////////////////////////////////////////////////////////
  1240. public:
  1241. /**
  1242. * 构造函数
  1243. */
  1244. NetThread(TC_EpollServer *epollServer, int index);
  1245. /**
  1246. * 析构函数
  1247. */
  1248. virtual ~NetThread();
  1249. /**
  1250. * 获取网络线程的index
  1251. * @return
  1252. */
  1253. int getIndex() const { return _threadIndex; }
  1254. /**
  1255. * 绑定监听socket
  1256. * @param ls
  1257. */
  1258. // int bind(BindAdapterPtr &lsPtr);
  1259. /**
  1260. * 网络线程执行函数
  1261. */
  1262. virtual void run();
  1263. /**
  1264. * 停止网络线程
  1265. */
  1266. void terminate();
  1267. /**
  1268. * 生成epoll
  1269. */
  1270. void createEpoll(uint32_t iIndex = 0);
  1271. /**
  1272. * 初始化udp监听
  1273. */
  1274. void initUdp(const unordered_map<int, BindAdapterPtr> &listeners);
  1275. /**
  1276. * 是否服务结束了
  1277. *
  1278. * @return bool
  1279. */
  1280. bool isTerminate() const { return _bTerminate; }
  1281. /**
  1282. * 获取Epoller对象
  1283. * @return TC_Epoller*
  1284. */
  1285. TC_Epoller* getEpoller() { return &_epoller; }
  1286. /**
  1287. * 唤醒网络线程
  1288. */
  1289. void notify();
  1290. /**
  1291. * 关闭连接
  1292. * @param uid
  1293. */
  1294. void close(const shared_ptr<RecvContext> &data);
  1295. /**
  1296. * 发送数据
  1297. * @param uid
  1298. * @param s
  1299. */
  1300. void send(const shared_ptr<SendContext> &data);
  1301. /**
  1302. * 获取某一监听端口的连接数
  1303. * @param lfd
  1304. *
  1305. * @return vector<TC_EpollServer::ConnStatus>
  1306. */
  1307. vector<TC_EpollServer::ConnStatus> getConnStatus(int lfd);
  1308. /**
  1309. * 获取连接数
  1310. *
  1311. * @return size_t
  1312. */
  1313. size_t getConnectionCount() { return _list.size(); }
  1314. /**
  1315. * 记录日志
  1316. * @param s
  1317. */
  1318. void debug(const string &s);
  1319. /**
  1320. * INFO日志
  1321. * @param s
  1322. */
  1323. void info(const string &s);
  1324. /**
  1325. * 记录错误日志
  1326. * @param s
  1327. */
  1328. void error(const string &s);
  1329. /**
  1330. * tars日志
  1331. * @param s
  1332. */
  1333. void tars(const string &s) const;
  1334. /**
  1335. * 是否启用防止空链接攻击的机制
  1336. * @param bEnable
  1337. */
  1338. void enAntiEmptyConnAttack(bool bEnable);
  1339. /**
  1340. *设置空连接超时时间
  1341. */
  1342. void setEmptyConnTimeout(int timeout);
  1343. /**
  1344. *设置udp的接收缓存区大小,单位是B,最小值为8192,最大值为DEFAULT_RECV_BUFFERSIZE
  1345. */
  1346. void setUdpRecvBufferSize(size_t nSize=DEFAULT_RECV_BUFFERSIZE);
  1347. /**
  1348. * 发送队列的大小
  1349. * @return size_t
  1350. */
  1351. size_t getSendRspSize();
  1352. protected:
  1353. /**
  1354. * 获取连接
  1355. * @param id
  1356. *
  1357. * @return ConnectionPtr
  1358. */
  1359. Connection *getConnectionPtr(uint32_t uid) { return _list.get(uid); }
  1360. /**
  1361. * 添加tcp链接
  1362. * @param cPtr
  1363. * @param iIndex
  1364. */
  1365. void addTcpConnection(Connection *cPtr);
  1366. /**
  1367. * 添加udp连接
  1368. * @param cPtr
  1369. * @param index
  1370. */
  1371. void addUdpConnection(Connection *cPtr);
  1372. /**
  1373. * 删除链接
  1374. * @param cPtr
  1375. * @param bEraseList 是否是超时连接的删除
  1376. * @param closeType 关闭类型,0:表示客户端主动关闭;1:服务端主动关闭;2:连接超时服务端主动关闭
  1377. */
  1378. void delConnection(Connection *cPtr, bool bEraseList = true,EM_CLOSE_T closeType=EM_CLIENT_CLOSE);
  1379. /**
  1380. * 处理管道消息
  1381. */
  1382. void processPipe();
  1383. /**
  1384. * 处理网络请求
  1385. */
  1386. void processNet(const epoll_event &ev);
  1387. /**
  1388. * 空连接超时时间
  1389. */
  1390. int getEmptyConnTimeout() const;
  1391. /**
  1392. *是否空连接检测
  1393. */
  1394. bool isEmptyConnCheck() const;
  1395. friend class BindAdapter;
  1396. friend class ConnectionList;
  1397. friend class TC_EpollServer;
  1398. private:
  1399. /**
  1400. * 服务
  1401. */
  1402. TC_EpollServer *_epollServer;
  1403. /**
  1404. * net线程的id
  1405. */
  1406. std::thread::id _threadId;
  1407. /**
  1408. * 线程索引
  1409. */
  1410. int _threadIndex;
  1411. /**
  1412. * epoll
  1413. */
  1414. TC_Epoller _epoller;
  1415. /**
  1416. * 停止
  1417. */
  1418. bool _bTerminate;
  1419. /**
  1420. * handle是否已经启动
  1421. */
  1422. bool _handleStarted;
  1423. /**
  1424. * 通知epoll
  1425. */
  1426. TC_Epoller::NotifyInfo _notify;
  1427. /**
  1428. * 管理的连接链表
  1429. */
  1430. ConnectionList _list;
  1431. /**
  1432. * 发送队列
  1433. */
  1434. send_queue _sbuffer;
  1435. /**
  1436. *空连接检测机制开关
  1437. */
  1438. bool _bEmptyConnAttackCheck;
  1439. /**
  1440. * 空连接超时时间,单位是毫秒,默认值2s,
  1441. * 该时间必须小于等于adapter自身的超时时间
  1442. */
  1443. int _iEmptyCheckTimeout;
  1444. /**
  1445. * udp连接时接收包缓存大小,针对所有udp接收缓存有效
  1446. */
  1447. size_t _nUdpRecvBufferSize;
  1448. /**
  1449. * 通知信号
  1450. */
  1451. bool _notifySignal = false;
  1452. };
  1453. ////////////////////////////////////////////////////////////////////////////
  1454. public:
  1455. /**
  1456. * 构造函数
  1457. */
  1458. TC_EpollServer(unsigned int iNetThreadNum = 1);
  1459. /**
  1460. * 析构函数
  1461. */
  1462. ~TC_EpollServer();
  1463. /**
  1464. * 是否启用防止空链接攻击的机制
  1465. * @param bEnable
  1466. */
  1467. void enAntiEmptyConnAttack(bool bEnable);
  1468. /**
  1469. *设置空连接超时时间
  1470. */
  1471. void setEmptyConnTimeout(int timeout);
  1472. /**
  1473. *设置NetThread的内存池信息
  1474. */
  1475. // void setNetThreadBufferPoolInfo(size_t minBlock, size_t maxBlock, size_t maxBytes);
  1476. /**
  1477. * 设置本地日志
  1478. * @param plocalLogger
  1479. */
  1480. void setLocalLogger(RollWrapperInterface *pLocalLogger) { _pLocalLogger = pLocalLogger; }
  1481. /**
  1482. * 选择网络线程
  1483. * @param fd
  1484. */
  1485. inline NetThread* getNetThreadOfFd(int fd) { return _netThreads[fd % _netThreads.size()]; }
  1486. /**
  1487. * 合并handle线程和网络线程
  1488. * @param merge
  1489. */
  1490. void setMergeHandleNetThread(bool merge) { _mergeHandleNetThread = merge; }
  1491. /**
  1492. * 是否合并handle线程网络线程
  1493. * @return
  1494. */
  1495. inline bool isMergeHandleNetThread() const { return _mergeHandleNetThread; }
  1496. // /**
  1497. // * 绑定到一个已经有的handle组上
  1498. // * @param groupName
  1499. // * @param handleNum
  1500. // * @param adapter
  1501. // */
  1502. // void setHandleGroup(const string& groupName, BindAdapterPtr adapter)
  1503. // {
  1504. // map<string, HandleGroupPtr>::iterator it = _handleGroups.find(groupName);
  1505. // if (it != _handleGroups.end())
  1506. // {
  1507. // it->second->adapters[adapter->getName()] = adapter;
  1508. // adapter->_handleGroup = it->second;
  1509. // }
  1510. // }
  1511. // /**
  1512. // * 创建一个handle对象组,如果已经存在则直接返回
  1513. // * @param name
  1514. // * @return HandlePtr
  1515. // */
  1516. // template<class T> void setHandleGroup(const string& groupName, int32_t handleNum, BindAdapterPtr adapter)
  1517. // {
  1518. // map<string, HandleGroupPtr>::iterator it = _handleGroups.find(groupName);
  1519. // if (it == _handleGroups.end())
  1520. // {
  1521. // HandleGroupPtr hg = new HandleGroup();
  1522. // hg->name = groupName;
  1523. // adapter->_handleGroup = hg;
  1524. // for (int32_t i = 0; i < handleNum; ++i)
  1525. // {
  1526. // HandlePtr handle = new T();
  1527. // handle->setEpollServer(this);
  1528. // handle->setHandleGroup(hg);
  1529. // hg->handles.push_back(handle);
  1530. // }
  1531. // _handleGroups[groupName] = hg;
  1532. // it = _handleGroups.find(groupName);
  1533. // }
  1534. // it->second->adapters[adapter->getName()] = adapter;
  1535. // adapter->_handleGroup = it->second;
  1536. // }
  1537. // /**
  1538. // * 选择网络线程
  1539. // * @param fd
  1540. // */
  1541. // NetThread* getNetThreadOfFd(int fd)
  1542. // {
  1543. // return _netThreads[fd % _netThreads.size()];
  1544. // }
  1545. /**
  1546. * 绑定监听socket
  1547. * @param ls
  1548. */
  1549. int bind(BindAdapterPtr &lsPtr);
  1550. /**
  1551. * 启动业务处理线程
  1552. */
  1553. void startHandle();
  1554. /**
  1555. * 生成epoll
  1556. */
  1557. void createEpoll();
  1558. /**
  1559. * 运行
  1560. */
  1561. void waitForShutdown();
  1562. /**
  1563. * 停止服务
  1564. */
  1565. void terminate();
  1566. /**
  1567. * 是否服务结束了
  1568. *
  1569. * @return bool
  1570. */
  1571. bool isTerminate() const { return _bTerminate; }
  1572. /**
  1573. * 根据名称获取BindAdapter
  1574. * @param sName
  1575. * @return BindAdapterPtr
  1576. */
  1577. BindAdapterPtr getBindAdapter(const string &sName);
  1578. /**
  1579. * 获取所有adatapters
  1580. * @return
  1581. */
  1582. vector<BindAdapterPtr> getBindAdapters();
  1583. /**
  1584. * 向网络线程添加连接
  1585. */
  1586. void addConnection(Connection * cPtr, int fd, CONN_TYPE iType);
  1587. /**
  1588. * 关闭连接
  1589. * @param uid
  1590. */
  1591. void close(const shared_ptr<TC_EpollServer::RecvContext> &data);
  1592. /**
  1593. * 发送数据
  1594. * @param uid
  1595. * @param s
  1596. */
  1597. void send(const shared_ptr<SendContext> &data);
  1598. /**
  1599. * 获取某一监听端口的连接数
  1600. * @param lfd
  1601. *
  1602. * @return vector<TC_EpollServer::ConnStatus>
  1603. */
  1604. vector<ConnStatus> getConnStatus(int lfd);
  1605. /**
  1606. * 获取监听socket信息
  1607. *
  1608. * @return map<int,ListenSocket>
  1609. */
  1610. unordered_map<int, BindAdapterPtr> getListenSocketInfo();
  1611. /**
  1612. * 获取所有连接的数目
  1613. *
  1614. * @return size_t
  1615. */
  1616. size_t getConnectionCount();
  1617. /**
  1618. * 记录日志
  1619. * @param s
  1620. */
  1621. void debug(const string &s);
  1622. /**
  1623. * INFO日志
  1624. * @param s
  1625. */
  1626. void info(const string &s);
  1627. /**
  1628. * 记录错误日志
  1629. * @param s
  1630. */
  1631. void error(const string &s);
  1632. /**
  1633. * 获取网络线程的数目
  1634. */
  1635. unsigned int getNetThreadNum() { return _netThreadNum; }
  1636. /**
  1637. * 获取网络线程的指针集合
  1638. */
  1639. vector<TC_EpollServer::NetThread*> getNetThread() { return _netThreads; }
  1640. /**
  1641. * 停止线程
  1642. */
  1643. void stopThread();
  1644. /**
  1645. * 获取所有业务线程的数目
  1646. */
  1647. size_t getLogicThreadNum();
  1648. //回调给应用服务
  1649. typedef std::function<void(TC_EpollServer*)> application_callback_functor;
  1650. /**
  1651. * 设置waitForShutdown线程回调的心跳
  1652. * @param hf [description]
  1653. */
  1654. void setCallbackFunctor(const application_callback_functor &hf) { _hf = hf; }
  1655. //网络线程发送心跳的函数
  1656. typedef std::function<void(const string &)> heartbeat_callback_functor;
  1657. /**
  1658. * 设置netthread网络线程发送心跳的函数
  1659. * @param hf [description]
  1660. */
  1661. void setHeartBeatFunctor(const heartbeat_callback_functor& heartFunc) { _heartFunc = heartFunc; }
  1662. heartbeat_callback_functor& getHeartBeatFunctor() { return _heartFunc; }
  1663. protected:
  1664. friend class BindAdapter;
  1665. /**
  1666. * 接收句柄
  1667. * @param fd
  1668. * @return
  1669. */
  1670. bool accept(int fd, int domain = AF_INET);
  1671. /**
  1672. * 绑定端口
  1673. * @param ep
  1674. * @param s
  1675. * @param manualListen
  1676. */
  1677. void bind(const TC_Endpoint &ep, TC_Socket &s, bool manualListen);
  1678. static void applicationCallback(TC_EpollServer *epollServer);
  1679. // public:
  1680. //统计服务端相应队列大小的上报的对象
  1681. // PropertyReport * _pReportRspQueue;
  1682. private:
  1683. /**
  1684. * 网络线程
  1685. */
  1686. std::vector<NetThread*> _netThreads;
  1687. /*
  1688. * 网络线程数目
  1689. */
  1690. unsigned int _netThreadNum;
  1691. /**
  1692. * epoll
  1693. */
  1694. TC_Epoller _epoller;
  1695. /**
  1696. * 通知epoll
  1697. */
  1698. TC_Epoller::NotifyInfo _notify;
  1699. /*
  1700. * 服务是否停止
  1701. */
  1702. bool _bTerminate;
  1703. /*
  1704. * 业务线程是否启动
  1705. */
  1706. bool _handleStarted;
  1707. /**
  1708. * 合并网络和业务线程
  1709. */
  1710. bool _mergeHandleNetThread = false;
  1711. /**
  1712. * 本地循环日志
  1713. */
  1714. RollWrapperInterface *_pLocalLogger;
  1715. /**
  1716. *
  1717. */
  1718. vector<BindAdapterPtr> _bindAdapters;
  1719. /**
  1720. * 监听socket
  1721. */
  1722. unordered_map<int, BindAdapterPtr> _listeners;
  1723. /**
  1724. * 应用回调
  1725. */
  1726. application_callback_functor _hf;
  1727. /**
  1728. * 发送心跳的函数
  1729. */
  1730. heartbeat_callback_functor _heartFunc;
  1731. /**
  1732. * 处理handle对象
  1733. */
  1734. // map<string, HandleGroupPtr> _handleGroups;
  1735. };
  1736. typedef TC_AutoPtr<TC_EpollServer> TC_EpollServerPtr;
  1737. }
  1738. #endif