znet.cpp 11 KB

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