znet.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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(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(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(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. // char m_timestamp[8];
  177. sock_client(io_context&ic,const char*name,int fd,int recv_time_out,int max_package_size)
  178. :fd_io(ic,fd,EV_READ|EV_WRITE)
  179. ,m_ic(ic)
  180. ,m_name(name)
  181. ,m_recv_timer(ic)
  182. ,m_sync_timer(ic)
  183. {
  184. m_max_package_size=max_package_size;
  185. m_recv_time_out=recv_time_out;
  186. // m_recv_timer.set(ic);
  187. m_recv_timer.set<sock_client,&sock_client::on_recv_timeout>(this);
  188. m_recv_timer.start(recv_time_out,0);
  189. m_sync_timer.set<sock_client,&sock_client::on_sync_timeout>(this);
  190. if(site_sync)
  191. {
  192. m_sync_timer.start(0,site_sync_freq);
  193. }
  194. // m_send_timer.set(ic);
  195. // m_send_timer.set(5,0);
  196. // m_send_timer.set<sock_client,&sock_client::on_send_timeout>(this);
  197. // m_send_timer.start();
  198. m_b=(char*)malloc(m_size);
  199. // m_timestamp[0]=0;
  200. }
  201. ~sock_client()
  202. {
  203. free(m_b);
  204. }
  205. #if 0
  206. bool check_timestamp(const char*time)
  207. {
  208. //秒、分、时、天、周、月、年, 脑残的设计
  209. char buf[6];
  210. buf[0]=time[6];
  211. buf[1]=time[5];
  212. buf[2]=time[3];
  213. buf[3]=time[2];
  214. buf[4]=time[1];
  215. buf[5]=time[0];
  216. if(memcmp(m_timestamp,buf,6)<=0)
  217. {
  218. memcpy(m_timestamp,buf,6);
  219. return true;
  220. }
  221. return false;
  222. }
  223. #endif
  224. int type()
  225. {
  226. return m_type;
  227. }
  228. void close()
  229. {
  230. m_close_flag.store(true);
  231. m_ic.async_request(shared_from_this());
  232. }
  233. void send(std::vector<char>&&b)
  234. {
  235. {
  236. std::unique_lock<std::mutex> _lock(m_mutex);
  237. m_olist.push_back(std::move(b));
  238. }
  239. m_ic.async_request(shared_from_this());
  240. }
  241. void on_sync_timeout()
  242. {
  243. // 从第一个字节开始,分别表示毫秒(2字节)、秒、分、时、天、月、年
  244. char buf[14]={0,12,0x78,0x3b};
  245. struct timeval tv;
  246. gettimeofday(&tv,0);
  247. struct tm buff={0};
  248. const struct tm*t=localtime_r(&tv.tv_sec,&buff);
  249. int p=4;
  250. buf[p++]=(tv.tv_usec/1000)>>8;
  251. buf[p++]=(tv.tv_usec/1000)&0xff;
  252. //为防止分站重启时发送上来过大的时间
  253. buf[p++]=t->tm_sec;
  254. buf[p++]=t->tm_min;
  255. buf[p++]=t->tm_hour;
  256. buf[p++]=t->tm_mday;
  257. buf[p++]=t->tm_mon;
  258. buf[p++]=t->tm_year;
  259. uint16_t ccrc=do_crc((unsigned char*)buf+2,10);
  260. buf[p++]=ccrc>>8;
  261. buf[p++]=ccrc&0xff;
  262. std::vector<char> tmp(buf,buf+14);
  263. send(std::move(tmp));
  264. }
  265. void on_send_timeout()
  266. {
  267. m_ic.on_send_timeout(shared_from_this());
  268. }
  269. void on_recv_timeout()
  270. {
  271. m_ic.on_recv_timeout(shared_from_this());
  272. logn_warn(1,"socket %s recv timeout.",m_name.c_str());
  273. close_impl();
  274. }
  275. std::string name()
  276. {
  277. return m_name;
  278. }
  279. int handle()
  280. {
  281. return m_fd;
  282. }
  283. void grow_buf(int len)
  284. {
  285. if(m_size-m_clen>=len)
  286. return;
  287. int size=m_size;
  288. while(m_size-m_clen<len)
  289. size<<=1;
  290. if(size!=m_size)
  291. {
  292. m_b=(char*)realloc(m_b,m_size=size);
  293. }
  294. }
  295. int read_clt()
  296. {
  297. for(;m_clen<m_size;)
  298. {
  299. int rc=zio::read(m_fd,m_b+m_clen,m_size-m_clen);
  300. if(rc>0)
  301. {
  302. m_clen+=rc;
  303. continue;
  304. }
  305. if(rc==-2)
  306. return 0;
  307. if(rc==0)
  308. {
  309. logn_info(1,"socket %d(%s) close by remote",m_fd,m_name.c_str());
  310. }
  311. else if(rc==-1)
  312. {
  313. logn_warn(1,"hava a error on socket %d(%s)",m_fd,m_name.c_str());
  314. }
  315. return -1;
  316. }
  317. return 0;
  318. }
  319. void close_impl()
  320. {
  321. m_recv_timer.stop();
  322. // m_send_timer.stop();
  323. fd_io::stop();
  324. m_ic.on_close(shared_from_this());
  325. logn_info(1,"socket %s closed.",m_name.c_str());
  326. }
  327. size_t calc_length(uint8_t*b)const
  328. {
  329. return (b[0]<<8)|b[1];
  330. }
  331. int io_read()
  332. {
  333. if(read_clt()<0)
  334. return -1;
  335. try
  336. {
  337. int msg_len;
  338. for(;m_clen>=2;)
  339. {
  340. msg_len=calc_length((uint8_t*)m_b)+2;
  341. if(msg_len>m_max_package_size)
  342. {
  343. logn_error(1,"package too big:%d/%d,close socket. site=%s.",msg_len,m_max_package_size,m_name.c_str());
  344. return -1;
  345. }
  346. if(msg_len<=8)
  347. {
  348. logn_error(1,"package too small:%d,close socket. site=%s.",msg_len,m_name.c_str());
  349. return -1;
  350. }
  351. if(m_clen<msg_len)
  352. break;
  353. logn_bin(1,name().c_str(),m_b,msg_len);//输出二进制日志
  354. if(check_crc(m_b,msg_len))
  355. {
  356. on_message(m_b,msg_len);
  357. }
  358. else
  359. {
  360. logn_error(1,"check_crc_error,close socket. site=%s.",m_name.c_str());
  361. return -1;
  362. }
  363. memmove(m_b,&m_b[msg_len],m_clen-msg_len);
  364. m_clen-=msg_len;
  365. }
  366. }
  367. catch(const std::exception&e)
  368. {
  369. logn_error(1,"package error,close socket. site=%s,err_info=%s",m_name.c_str(),e.what());
  370. return -1;
  371. }
  372. return 0;
  373. }
  374. int io_write()
  375. {
  376. if(! m_can_write)
  377. {
  378. set(EV_READ|EV_WRITE);
  379. // m_send_timer.set(5);
  380. // m_send_timer.start();
  381. return 0;
  382. }
  383. for(;;)
  384. {
  385. if(m_obuf.size()==m_opos)
  386. {
  387. std::unique_lock<std::mutex> _lock(m_mutex);
  388. if(m_olist.empty())
  389. break;
  390. m_obuf.swap(m_olist.front());
  391. m_olist.pop_front();
  392. m_opos=0;
  393. }
  394. int left=m_obuf.size()-m_opos;
  395. int rc=zio::write(m_fd,&*m_obuf.begin()+m_opos,left);
  396. if(rc>0)
  397. {
  398. m_opos+=rc;
  399. if(m_opos==m_obuf.size())
  400. continue;
  401. }
  402. else if(rc==0||rc==-2)//缓冲区满
  403. {
  404. m_can_write=false;
  405. set(EV_READ|EV_WRITE);
  406. // m_send_timer.set(5);
  407. // m_send_timer.start();
  408. break;
  409. }
  410. else
  411. {
  412. logn_errno(1,"zio::write(%d,ptr,%d)",m_fd,m_obuf.size()-m_opos);
  413. return -1;
  414. }
  415. }
  416. if(m_olist.empty() && m_can_write)
  417. {
  418. set(EV_READ);
  419. // m_send_timer.stop();
  420. }
  421. return 0;
  422. }
  423. void operator()(ev::io &w, int flag)
  424. {
  425. if(flag & EV_WRITE)
  426. {
  427. logn_debug(1,"socket %d(%s) can write,flag=%d." ,m_fd,m_name.c_str(),flag);
  428. m_can_write=true;
  429. // m_send_timer.stop();
  430. if(io_write()<0)
  431. {
  432. close_impl();
  433. return;
  434. }
  435. }
  436. if(flag & EV_READ)
  437. {
  438. // log_debug("socket %d(%s) can read,flag=%d." ,m_fd,m_name.c_str(),flag);
  439. // zclock c;
  440. if(io_read()<0)
  441. {
  442. close_impl();
  443. return;
  444. }
  445. // log_info("use time %d ms.",c.count_us());
  446. m_recv_timer.start(m_recv_time_out);
  447. }
  448. }
  449. bool check_crc(void *b0,size_t mlen)
  450. {
  451. uint8_t*b=(uint8_t*)b0;
  452. uint16_t crc=b[mlen-2];
  453. crc<<=8;
  454. crc|=b[mlen-1];
  455. uint16_t ccrc=do_crc((unsigned char*)b+2,mlen-4);
  456. return ccrc==crc;
  457. }
  458. void on_message(const char*m,int mlen)
  459. {
  460. m_ic.on_message(shared_from_this(),m,mlen);
  461. }
  462. void on_notify()
  463. {
  464. if(m_close_flag)
  465. {
  466. close_impl();
  467. return;
  468. }
  469. io_write();
  470. }
  471. };
  472. struct sock_listen: fd_io
  473. {
  474. sock_listen(io_context&ic,int fd):fd_io(ic,fd){}
  475. int recv_time_out=config.get("service.recv_timeout",10);
  476. int max_package_size=config.get("service.max_package",2048);
  477. void operator()(ev::io &w, int)
  478. {
  479. char name[32];
  480. int fd=zio::accept(m_fd,name);
  481. if(fd<0)
  482. {
  483. logn_errno(1,"socket %s connect error.",name);
  484. return;
  485. }
  486. zio::setiobuf(fd,32<<10,32<<10);
  487. m_ic.on_connect(std::make_shared<sock_client>(m_ic,name,fd,recv_time_out,max_package_size));
  488. logn_info(1,"socket %s connected.",name);
  489. }
  490. };
  491. struct signal_w:ev::sig
  492. {
  493. io_context&m_ic;
  494. signal_w(io_context&ic, int s)
  495. :ev::sig(ic)
  496. ,m_ic(ic)
  497. {
  498. //this->set(m_ic);
  499. this->set(this);
  500. this->set(s);
  501. this->start();
  502. }
  503. void operator()(ev::sig &w, int s)
  504. {
  505. log_info("recved signal %d",s);
  506. worker::instance()->stop();
  507. stop();
  508. m_ic.stop();
  509. }
  510. };
  511. struct main_loop:io_context
  512. {
  513. main_loop(service_callback&sc)
  514. :io_context(sc)
  515. {
  516. }
  517. virtual int run(int port)
  518. {
  519. int fd=zio::listen_on(port);
  520. if(fd<0)
  521. {
  522. log_errno("try listen_on %d",port);
  523. return -1;
  524. }
  525. sock_listen _1(*this,fd);
  526. // stdin_io _2(*this);
  527. block_sig(SIGPIPE);
  528. signal_w sint(*this,SIGINT),term(*this,SIGTERM);
  529. ev::dynamic_loop::run(0);
  530. _1.stop();
  531. close_all();
  532. return 0;
  533. }
  534. void block_sig(int sig)
  535. {
  536. sigset_t signal_mask;
  537. sigemptyset(&signal_mask);
  538. sigaddset(&signal_mask, sig);
  539. if(pthread_sigmask(SIG_BLOCK, &signal_mask, NULL) == -1)
  540. {
  541. log_errno("block signal:%d",sig);
  542. }
  543. }
  544. };
  545. service_handle*service_handle::instance(service_callback*sc)
  546. {
  547. static main_loop _impl(*sc);
  548. sc->set_handle(&_impl);
  549. return &_impl;
  550. }