znet.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. log_info("socket %s recv timeout.",m_name.c_str());
  273. }
  274. std::string name()
  275. {
  276. return m_name;
  277. }
  278. int handle()
  279. {
  280. return m_fd;
  281. }
  282. void grow_buf(int len)
  283. {
  284. if(m_size-m_clen>=len)
  285. return;
  286. int size=m_size;
  287. while(m_size-m_clen<len)
  288. size<<=1;
  289. if(size!=m_size)
  290. {
  291. m_b=(char*)realloc(m_b,m_size=size);
  292. }
  293. }
  294. int read_clt()
  295. {
  296. for(;m_clen<m_size;)
  297. {
  298. int rc=zio::read(m_fd,m_b+m_clen,m_size-m_clen);
  299. if(rc>0)
  300. {
  301. m_clen+=rc;
  302. continue;
  303. }
  304. if(rc==-2)
  305. return 0;
  306. if(rc==0)
  307. {
  308. logn_info(1,"socket %d(%s) close by remote",m_fd,m_name.c_str());
  309. }
  310. else if(rc==-1)
  311. {
  312. logn_errno(1,"hava a error on socket %d(%s)",m_fd,m_name.c_str());
  313. }
  314. return -1;
  315. }
  316. return 0;
  317. }
  318. void close_impl()
  319. {
  320. m_recv_timer.stop();
  321. // m_send_timer.stop();
  322. fd_io::stop();
  323. m_ic.on_close(shared_from_this());
  324. log_info("socket %s closed.",m_name.c_str());
  325. }
  326. size_t calc_length(uint8_t*b)const
  327. {
  328. return (b[0]<<8)|b[1];
  329. }
  330. int io_read()
  331. {
  332. if(read_clt()<0)
  333. return -1;
  334. try
  335. {
  336. int msg_len;
  337. for(;m_clen>=2;)
  338. {
  339. msg_len=calc_length((uint8_t*)m_b)+2;
  340. if(msg_len>m_max_package_size)
  341. {
  342. logn_error(1,"package too big:%d/%d,close socket. site=%s.",msg_len,m_max_package_size,m_name.c_str());
  343. return -1;
  344. }
  345. if(msg_len<=8)
  346. {
  347. logn_error(1,"package too small:%d,close socket. site=%s.",msg_len,m_name.c_str());
  348. return -1;
  349. }
  350. if(m_clen<msg_len)
  351. break;
  352. logn_bin(1,name().c_str(),m_b,msg_len);//输出二进制日志
  353. if(check_crc(m_b,msg_len))
  354. {
  355. on_message(m_b,msg_len);
  356. }
  357. else
  358. {
  359. logn_error(1,"check_crc_error,close socket. site=%s.",m_name.c_str());
  360. return -1;
  361. }
  362. memmove(m_b,&m_b[msg_len],m_clen-msg_len);
  363. m_clen-=msg_len;
  364. }
  365. }
  366. catch(const std::exception&e)
  367. {
  368. logn_error(1,"package error,close socket. site=%s,err_info=%s",m_name.c_str(),e.what());
  369. return -1;
  370. }
  371. return 0;
  372. }
  373. int io_write()
  374. {
  375. if(! m_can_write)
  376. {
  377. set(EV_READ|EV_WRITE);
  378. // m_send_timer.set(5);
  379. // m_send_timer.start();
  380. return 0;
  381. }
  382. for(;;)
  383. {
  384. if(m_obuf.size()==m_opos)
  385. {
  386. std::unique_lock<std::mutex> _lock(m_mutex);
  387. if(m_olist.empty())
  388. break;
  389. m_obuf.swap(m_olist.front());
  390. m_olist.pop_front();
  391. m_opos=0;
  392. }
  393. int left=m_obuf.size()-m_opos;
  394. int rc=zio::write(m_fd,&*m_obuf.begin()+m_opos,left);
  395. if(rc>0)
  396. {
  397. m_opos+=rc;
  398. if(m_opos==m_obuf.size())
  399. continue;
  400. }
  401. else if(rc==0||rc==-2)//缓冲区满
  402. {
  403. m_can_write=false;
  404. set(EV_READ|EV_WRITE);
  405. // m_send_timer.set(5);
  406. // m_send_timer.start();
  407. break;
  408. }
  409. else
  410. {
  411. logn_errno(1,"zio::write(%d,ptr,%d)",m_fd,m_obuf.size()-m_opos);
  412. return -1;
  413. }
  414. }
  415. if(m_olist.empty() && m_can_write)
  416. {
  417. set(EV_READ);
  418. // m_send_timer.stop();
  419. }
  420. return 0;
  421. }
  422. void operator()(ev::io &w, int flag)
  423. {
  424. if(flag & EV_WRITE)
  425. {
  426. logn_debug(1,"socket %d(%s) can write,flag=%d." ,m_fd,m_name.c_str(),flag);
  427. m_can_write=true;
  428. // m_send_timer.stop();
  429. if(io_write()<0)
  430. {
  431. close_impl();
  432. return;
  433. }
  434. }
  435. if(flag & EV_READ)
  436. {
  437. // log_debug("socket %d(%s) can read,flag=%d." ,m_fd,m_name.c_str(),flag);
  438. // zclock c;
  439. if(io_read()<0)
  440. {
  441. close_impl();
  442. return;
  443. }
  444. // log_info("use time %d ms.",c.count_us());
  445. m_recv_timer.start(m_recv_time_out);
  446. }
  447. }
  448. bool check_crc(void *b0,size_t mlen)
  449. {
  450. uint8_t*b=(uint8_t*)b0;
  451. uint16_t crc=b[mlen-2];
  452. crc<<=8;
  453. crc|=b[mlen-1];
  454. uint16_t ccrc=do_crc((unsigned char*)b+2,mlen-4);
  455. return ccrc==crc;
  456. }
  457. void on_message(const char*m,int mlen)
  458. {
  459. m_ic.on_message(shared_from_this(),m,mlen);
  460. }
  461. void on_notify()
  462. {
  463. if(m_close_flag)
  464. {
  465. close_impl();
  466. return;
  467. }
  468. io_write();
  469. }
  470. };
  471. struct sock_listen: fd_io
  472. {
  473. sock_listen(io_context&ic,int fd):fd_io(ic,fd){}
  474. int recv_time_out=config.get("service.recv_timeout",30);
  475. int max_package_size=config.get("service.max_package",2048);
  476. void operator()(ev::io &w, int)
  477. {
  478. char name[32];
  479. int fd=zio::accept(m_fd,name);
  480. if(fd<0)
  481. return;
  482. zio::setiobuf(fd,32<<10,32<<10);
  483. m_ic.on_connect(std::make_shared<sock_client>(m_ic,name,fd,recv_time_out,max_package_size));
  484. logn_info(1,"socket %s connected.",name);
  485. }
  486. };
  487. struct signal_w:ev::sig
  488. {
  489. io_context&m_ic;
  490. signal_w(io_context&ic, int s)
  491. :ev::sig(ic)
  492. ,m_ic(ic)
  493. {
  494. //this->set(m_ic);
  495. this->set(this);
  496. this->set(s);
  497. this->start();
  498. }
  499. void operator()(ev::sig &w, int s)
  500. {
  501. log_info("recved signal %d",s);
  502. worker::instance()->stop();
  503. stop();
  504. m_ic.stop();
  505. }
  506. };
  507. struct main_loop:io_context
  508. {
  509. main_loop(service_callback&sc)
  510. :io_context(sc)
  511. {
  512. }
  513. virtual int run(int port)
  514. {
  515. int fd=zio::listen_on(port);
  516. if(fd<0)
  517. {
  518. log_errno("try listen_on %d",port);
  519. return -1;
  520. }
  521. sock_listen _1(*this,fd);
  522. // stdin_io _2(*this);
  523. block_sig(SIGPIPE);
  524. signal_w sint(*this,SIGINT),term(*this,SIGTERM);
  525. ev::dynamic_loop::run(0);
  526. _1.stop();
  527. close_all();
  528. return 0;
  529. }
  530. void block_sig(int sig)
  531. {
  532. sigset_t signal_mask;
  533. sigemptyset(&signal_mask);
  534. sigaddset(&signal_mask, sig);
  535. if(pthread_sigmask(SIG_BLOCK, &signal_mask, NULL) == -1)
  536. {
  537. log_errno("block signal:%d",sig);
  538. }
  539. }
  540. };
  541. service_handle*service_handle::instance(service_callback*sc)
  542. {
  543. static main_loop _impl(*sc);
  544. sc->set_handle(&_impl);
  545. return &_impl;
  546. }