znet.cpp 10 KB

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