1
0

znet.cpp 11 KB

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