znet.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. #include <log.h>
  2. #include <unistd.h>
  3. #include <signal.h>
  4. #include <sys/time.h>
  5. #include <stdio.h>
  6. #include <list>
  7. #include <vector>
  8. #include <set>
  9. #include <thread>
  10. #include <mutex>
  11. #include <atomic>
  12. #include <algorithm>
  13. #include <fstream>
  14. #include <time.h>
  15. #include <zio.h>
  16. #include <znet.h>
  17. #include <zloop.h>
  18. #include <clock.h>
  19. #include <worker.h>
  20. #include "config_file.h"
  21. #include "crc.h"
  22. extern config_file config;
  23. static int recv_timeout_first=config.get("service.recv_timeout_first",10);
  24. static int site_sync_freq=config.get("site_sync.freq",60);//分站时间同步间隔
  25. static int site_sync=config.get("site_sync",0);//分站时间同步,考虑到双IP双机情况,缺省关闭
  26. struct client_ex:client
  27. {
  28. virtual void on_notify()=0;
  29. virtual void close_impl()=0;
  30. };
  31. struct io_context: zloop<std::shared_ptr<client>> ,service_handle
  32. {
  33. private:
  34. service_callback&m_serv;
  35. ev::timer m_timer;
  36. public:
  37. std::vector<std::shared_ptr<client>> m_thread_clts;
  38. io_context(service_callback&serv)
  39. :m_serv(serv)
  40. ,m_timer(*this)
  41. {
  42. m_thread_clts.reserve(2048);
  43. m_timer.set<io_context,&io_context::on_timer>(this);
  44. m_timer.start(0,1);
  45. }
  46. virtual ~io_context()
  47. {
  48. }
  49. void boardcast(const std::vector<char>&msg)
  50. {
  51. for(const auto&i:m_thread_clts)
  52. {
  53. std::vector<char> tmp(msg);
  54. i->send(std::move(tmp));
  55. }
  56. }
  57. void on_timer()
  58. {
  59. m_serv.on_timer();
  60. }
  61. void on_connect(const std::shared_ptr<client> &clt)
  62. {
  63. if(clt->handle()>=(int)m_thread_clts.size())
  64. {
  65. m_thread_clts.resize(clt->handle()+1);
  66. }
  67. m_thread_clts[clt->handle()]=clt;
  68. m_serv.on_connect(clt);
  69. }
  70. void on_close(const std::shared_ptr<client> &clt)
  71. {
  72. m_serv.on_close(clt);
  73. m_thread_clts[clt->handle()].reset();
  74. }
  75. void on_send_timeout(const std::shared_ptr<client> &clt)
  76. {
  77. m_serv.on_send_timeout(clt);
  78. }
  79. void on_recv_timeout(const std::shared_ptr<client> &clt)
  80. {
  81. m_serv.on_recv_timeout(clt);
  82. }
  83. void on_message(const std::shared_ptr<client>& clt,const char*data,size_t len)
  84. {
  85. m_serv.on_message(clt,data,len);
  86. }
  87. void close_all()
  88. {
  89. for(const auto&clt:m_thread_clts)
  90. {
  91. if(!clt)
  92. continue;
  93. ((client_ex*)clt.get())->close_impl();
  94. }
  95. }
  96. void on_async(const std::list<std::shared_ptr<client>>&notify_clts)
  97. {
  98. for(const auto&clt:notify_clts)
  99. {
  100. ((client_ex*)clt.get())->on_notify();
  101. }
  102. }
  103. void stop()
  104. {
  105. async_stop();
  106. }
  107. };
  108. struct fd_io:ev::io
  109. {
  110. io_context&m_ic;
  111. int m_fd;
  112. fd_io(io_context&ic,int fd,int ev_flag=EV_READ)
  113. :ev::io(ic)
  114. ,m_ic(ic)
  115. ,m_fd(fd)
  116. {
  117. zio::setblocking(fd,false);
  118. this->set(this);
  119. this->set(m_fd,ev_flag);
  120. this->start();
  121. }
  122. void stop () throw () \
  123. {
  124. ev::io::stop();
  125. }
  126. io_context&context()
  127. {
  128. return m_ic;
  129. }
  130. virtual void operator()(ev::io &w, int)=0;
  131. virtual ~fd_io()
  132. {
  133. stop();
  134. zio::close(m_fd);
  135. }
  136. };
  137. struct stdin_io:fd_io
  138. {
  139. stdin_io(io_context&ic)
  140. :fd_io(ic,0)
  141. {}
  142. virtual void operator()(ev::io &w, int)
  143. {
  144. #if 0
  145. char buf[256];
  146. if(!gets(buf))
  147. return;
  148. if(strchr(buf,'X'))
  149. {
  150. log_info("stdin input 'X', exiting...");
  151. worker::instance()->stop();
  152. stop();
  153. m_ic.stop();
  154. }
  155. #endif
  156. }
  157. };
  158. struct sock_client:fd_io,client_ex
  159. {
  160. io_context&m_ic;
  161. std::string m_name;
  162. std::atomic<bool> m_close_flag{false};
  163. int m_type=1;//site
  164. char *m_b{0};
  165. int m_clen{0};
  166. int m_size{1<<16};
  167. int m_max_package_size{2048};
  168. int m_recv_time_out;
  169. ev::timer m_recv_timer;
  170. ev::timer m_sync_timer;
  171. // ev::timer m_send_timer;
  172. std::mutex m_mutex;
  173. std::list<std::vector<char>> m_olist;
  174. std::vector<char> m_obuf;
  175. size_t m_opos=0;
  176. bool m_can_write{false};
  177. int m_site_id{-1};
  178. // char m_timestamp[8];
  179. sock_client(io_context&ic,const char*name,int fd,int recv_time_out,int max_package_size)
  180. :fd_io(ic,fd,EV_READ|EV_WRITE)
  181. ,m_ic(ic)
  182. ,m_name(name)
  183. ,m_recv_timer(ic)
  184. ,m_sync_timer(ic)
  185. {
  186. m_max_package_size=max_package_size;
  187. m_recv_time_out=recv_time_out;
  188. // m_recv_timer.set(ic);
  189. m_recv_timer.set<sock_client,&sock_client::on_recv_timeout>(this);
  190. m_recv_timer.start(recv_timeout_first,0);
  191. m_sync_timer.set<sock_client,&sock_client::on_sync_timeout>(this);
  192. if(site_sync)
  193. {
  194. m_sync_timer.start(0,site_sync_freq);
  195. }
  196. // m_send_timer.set(ic);
  197. // m_send_timer.set(5,0);
  198. // m_send_timer.set<sock_client,&sock_client::on_send_timeout>(this);
  199. // m_send_timer.start();
  200. m_b=(char*)malloc(m_size);
  201. // m_timestamp[0]=0;
  202. }
  203. ~sock_client()
  204. {
  205. free(m_b);
  206. }
  207. #if 0
  208. bool check_timestamp(const char*time)
  209. {
  210. //秒、分、时、天、周、月、年, 脑残的设计
  211. char buf[6];
  212. buf[0]=time[6];
  213. buf[1]=time[5];
  214. buf[2]=time[3];
  215. buf[3]=time[2];
  216. buf[4]=time[1];
  217. buf[5]=time[0];
  218. if(memcmp(m_timestamp,buf,6)<=0)
  219. {
  220. memcpy(m_timestamp,buf,6);
  221. return true;
  222. }
  223. return false;
  224. }
  225. #endif
  226. int type()
  227. {
  228. return m_type;
  229. }
  230. void close()
  231. {
  232. m_close_flag.store(true);
  233. m_ic.async_request(shared_from_this());
  234. }
  235. void send(std::vector<char>&&b)
  236. {
  237. {
  238. std::unique_lock<std::mutex> _lock(m_mutex);
  239. m_olist.push_back(std::move(b));
  240. }
  241. m_ic.async_request(shared_from_this());
  242. }
  243. void on_sync_timeout()
  244. {
  245. // 从第一个字节开始,分别表示毫秒(2字节)、秒、分、时、天、月、年
  246. char buf[14]={0,12,0x78,0x3b};
  247. struct timeval tv;
  248. gettimeofday(&tv,0);
  249. struct tm buff={0};
  250. const struct tm*t=localtime_r(&tv.tv_sec,&buff);
  251. int p=4;
  252. buf[p++]=(tv.tv_usec/1000)>>8;
  253. buf[p++]=(tv.tv_usec/1000)&0xff;
  254. //为防止分站重启时发送上来过大的时间
  255. buf[p++]=t->tm_sec;
  256. buf[p++]=t->tm_min;
  257. buf[p++]=t->tm_hour;
  258. buf[p++]=t->tm_mday;
  259. buf[p++]=t->tm_mon;
  260. buf[p++]=t->tm_year;
  261. uint16_t ccrc=do_crc((unsigned char*)buf+2,10);
  262. buf[p++]=ccrc>>8;
  263. buf[p++]=ccrc&0xff;
  264. std::vector<char> tmp(buf,buf+14);
  265. send(std::move(tmp));
  266. }
  267. void on_send_timeout()
  268. {
  269. m_ic.on_send_timeout(shared_from_this());
  270. }
  271. void on_recv_timeout()
  272. {
  273. m_ic.on_recv_timeout(shared_from_this());
  274. logn_warn(1,"socket %s recv timeout.",m_name.c_str());
  275. close_impl();
  276. }
  277. std::string name()
  278. {
  279. return m_name;
  280. }
  281. int handle()
  282. {
  283. return m_fd;
  284. }
  285. //void set_site_id(int sid)
  286. //{
  287. // m_site_id=id;
  288. //}
  289. void grow_buf(int len)
  290. {
  291. if(m_size-m_clen>=len)
  292. return;
  293. int size=m_size;
  294. while(m_size-m_clen<len)
  295. size<<=1;
  296. if(size!=m_size)
  297. {
  298. m_b=(char*)realloc(m_b,m_size=size);
  299. }
  300. }
  301. int read_clt()
  302. {
  303. for(;m_clen<m_size;)
  304. {
  305. int rc=zio::read(m_fd,m_b+m_clen,m_size-m_clen);
  306. if(rc>0)
  307. {
  308. m_clen+=rc;
  309. continue;
  310. }
  311. if(rc==-2)
  312. return 0;
  313. if(rc==0)
  314. {
  315. logn_info(1,"socket %d(%s) close by remote",m_fd,m_name.c_str());
  316. }
  317. else if(rc==-1)
  318. {
  319. logn_warn(1,"hava a error on socket %d(%s)",m_fd,m_name.c_str());
  320. }
  321. return -1;
  322. }
  323. return 0;
  324. }
  325. void close_impl()
  326. {
  327. m_recv_timer.stop();
  328. fd_io::stop();
  329. m_ic.on_close(shared_from_this());
  330. logn_info(1,"socket %s closed.",m_name.c_str());
  331. }
  332. size_t calc_length(uint8_t*b)const
  333. {
  334. return (b[0]<<8)|b[1];
  335. }
  336. int io_read()
  337. {
  338. if(read_clt()<0)
  339. return -1;
  340. try
  341. {
  342. int msg_len;
  343. for(;m_clen>=2;)
  344. {
  345. msg_len=calc_length((uint8_t*)m_b)+2;
  346. if(msg_len>m_max_package_size)
  347. {
  348. logn_error(1,"package too big:%d/%d,close socket. site=%s.",msg_len,m_max_package_size,m_name.c_str());
  349. return -1;
  350. }
  351. if(msg_len<=8)
  352. {
  353. logn_error(1,"package too small:%d,close socket. site=%s.",msg_len,m_name.c_str());
  354. return -1;
  355. }
  356. if(m_clen<msg_len)
  357. break;
  358. logn_bin(1,name().c_str(),m_b,msg_len);//输出二进制日志
  359. if(check_crc(m_b,msg_len))
  360. {
  361. on_message(m_b,msg_len);
  362. }
  363. else
  364. {
  365. logn_error(1,"check_crc_error,close socket. site=%s.",m_name.c_str());
  366. return -1;
  367. }
  368. memmove(m_b,&m_b[msg_len],m_clen-msg_len);
  369. m_clen-=msg_len;
  370. }
  371. }
  372. catch(const std::exception&e)
  373. {
  374. logn_error(1,"package error,close socket. site=%s,err_info=%s",m_name.c_str(),e.what());
  375. return -1;
  376. }
  377. return 0;
  378. }
  379. int io_write()
  380. {
  381. if(! m_can_write)
  382. {
  383. set(EV_READ|EV_WRITE);
  384. // m_send_timer.set(5);
  385. // m_send_timer.start();
  386. return 0;
  387. }
  388. for(;;)
  389. {
  390. if(m_obuf.size()==m_opos)
  391. {
  392. std::unique_lock<std::mutex> _lock(m_mutex);
  393. if(m_olist.empty())
  394. break;
  395. m_obuf.swap(m_olist.front());
  396. m_olist.pop_front();
  397. m_opos=0;
  398. }
  399. int left=m_obuf.size()-m_opos;
  400. int rc=zio::write(m_fd,&*m_obuf.begin()+m_opos,left);
  401. if(rc>0)
  402. {
  403. m_opos+=rc;
  404. if(m_opos==m_obuf.size())
  405. continue;
  406. }
  407. else if(rc==0||rc==-2)//缓冲区满
  408. {
  409. m_can_write=false;
  410. set(EV_READ|EV_WRITE);
  411. // m_send_timer.set(5);
  412. // m_send_timer.start();
  413. break;
  414. }
  415. else
  416. {
  417. logn_errno(1,"zio::write(%d,ptr,%d)",m_fd,m_obuf.size()-m_opos);
  418. return -1;
  419. }
  420. }
  421. if(m_olist.empty() && m_can_write)
  422. {
  423. set(EV_READ);
  424. // m_send_timer.stop();
  425. }
  426. return 0;
  427. }
  428. void operator()(ev::io &w, int flag)
  429. {
  430. if(flag & EV_WRITE)
  431. {
  432. logn_debug(1,"socket %d(%s) can write,flag=%d." ,m_fd,m_name.c_str(),flag);
  433. m_can_write=true;
  434. // m_send_timer.stop();
  435. if(io_write()<0)
  436. {
  437. close_impl();
  438. return;
  439. }
  440. }
  441. if(flag & EV_READ)
  442. {
  443. // log_debug("socket %d(%s) can read,flag=%d." ,m_fd,m_name.c_str(),flag);
  444. // zclock c;
  445. if(io_read()<0)
  446. {
  447. close_impl();
  448. return;
  449. }
  450. // log_info("use time %d ms.",c.count_us());
  451. m_recv_timer.start(m_recv_time_out);
  452. }
  453. }
  454. bool check_crc(void *b0,size_t mlen)
  455. {
  456. uint8_t*b=(uint8_t*)b0;
  457. uint16_t crc=b[mlen-2];
  458. crc<<=8;
  459. crc|=b[mlen-1];
  460. uint16_t ccrc=do_crc((unsigned char*)b+2,mlen-4);
  461. return ccrc==crc;
  462. }
  463. void on_message(const char*m,int mlen)
  464. {
  465. m_ic.on_message(shared_from_this(),m,mlen);
  466. }
  467. void on_notify()
  468. {
  469. if(m_close_flag)
  470. {
  471. close_impl();
  472. return;
  473. }
  474. io_write();
  475. }
  476. };
  477. struct sock_listen: fd_io
  478. {
  479. sock_listen(io_context&ic,int fd):fd_io(ic,fd){}
  480. int recv_time_out=config.get("service.recv_timeout",3);
  481. int max_package_size=config.get("service.max_package",2048);
  482. void operator()(ev::io &w, int)
  483. {
  484. char name[32];
  485. int fd=zio::accept(m_fd,name);
  486. if(fd<0)
  487. {
  488. logn_errno(1,"socket %s connect error.",name);
  489. return;
  490. }
  491. zio::setiobuf(fd,32<<10,32<<10);
  492. m_ic.on_connect(std::make_shared<sock_client>(m_ic,name,fd,recv_time_out,max_package_size));
  493. logn_info(1,"socket %s connected.",name);
  494. }
  495. };
  496. struct signal_w:ev::sig
  497. {
  498. io_context&m_ic;
  499. signal_w(io_context&ic, int s)
  500. :ev::sig(ic)
  501. ,m_ic(ic)
  502. {
  503. //this->set(m_ic);
  504. this->set(this);
  505. this->set(s);
  506. this->start();
  507. }
  508. void operator()(ev::sig &w, int s)
  509. {
  510. log_info("recved signal %d",s);
  511. worker::instance()->stop();
  512. stop();
  513. m_ic.stop();
  514. }
  515. };
  516. struct main_loop:io_context
  517. {
  518. main_loop(service_callback&sc)
  519. :io_context(sc)
  520. {
  521. }
  522. virtual int run(int port)
  523. {
  524. int fd=zio::listen_on(port);
  525. if(fd<0)
  526. {
  527. log_errno("try listen_on %d",port);
  528. return -1;
  529. }
  530. sock_listen _1(*this,fd);
  531. // stdin_io _2(*this);
  532. block_sig(SIGPIPE);
  533. signal_w sint(*this,SIGINT),term(*this,SIGTERM);
  534. while(!check_stop_flag())
  535. {
  536. try
  537. {
  538. ev::dynamic_loop::run(0);
  539. }
  540. catch(const std::exception&e)
  541. {
  542. log_error("捕获到异常:%s",e.what());
  543. }
  544. catch(...)
  545. {
  546. log_error("捕获到未知异常");
  547. }
  548. }
  549. _1.stop();
  550. close_all();
  551. return 0;
  552. }
  553. void block_sig(int sig)
  554. {
  555. sigset_t signal_mask;
  556. sigemptyset(&signal_mask);
  557. sigaddset(&signal_mask, sig);
  558. if(pthread_sigmask(SIG_BLOCK, &signal_mask, NULL) == -1)
  559. {
  560. log_errno("block signal:%d",sig);
  561. }
  562. }
  563. };
  564. service_handle*service_handle::instance(service_callback*sc)
  565. {
  566. static main_loop _impl(*sc);
  567. sc->set_handle(&_impl);
  568. return &_impl;
  569. }