znet.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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. #include "module_service/module_device_net.h"
  23. extern config_file config;
  24. struct client_ex:client
  25. {
  26. virtual void on_notify()=0;
  27. virtual void close_impl()=0;
  28. };
  29. struct io_context: zloop<std::shared_ptr<client>> ,service_handle
  30. {
  31. private:
  32. service_callback&m_serv;
  33. ev::timer m_timer;
  34. public:
  35. std::vector<std::shared_ptr<client>> m_thread_clts;
  36. io_context(service_callback&serv)
  37. :m_serv(serv)
  38. ,m_timer(*this)
  39. {
  40. m_thread_clts.reserve(2048);
  41. m_timer.set<io_context,&io_context::on_timer>(this);
  42. m_timer.start(0,1);
  43. }
  44. virtual ~io_context()
  45. {
  46. }
  47. void boardcast(const std::vector<char>&msg)
  48. {
  49. for(const auto&i:m_thread_clts)
  50. {
  51. std::vector<char> tmp(msg);
  52. i->send(std::move(tmp));
  53. }
  54. }
  55. void on_timer()
  56. {
  57. m_serv.on_timer();
  58. }
  59. void on_connect(const std::shared_ptr<client> &clt)
  60. {
  61. if(clt->handle()>=(int)m_thread_clts.size())
  62. {
  63. m_thread_clts.resize(clt->handle()+1);
  64. }
  65. m_thread_clts[clt->handle()]=clt;
  66. m_serv.on_connect(clt);
  67. }
  68. void on_close(const std::shared_ptr<client> &clt)
  69. {
  70. m_serv.on_close(clt);
  71. m_thread_clts[clt->handle()].reset();
  72. }
  73. void on_send_timeout(const std::shared_ptr<client> &clt)
  74. {
  75. m_serv.on_send_timeout(clt);
  76. }
  77. void on_recv_timeout(const std::shared_ptr<client> &clt)
  78. {
  79. m_serv.on_recv_timeout(clt);
  80. }
  81. void on_message(const std::shared_ptr<client>& clt,const char*data,size_t len)
  82. {
  83. m_serv.on_message(clt,data,len);
  84. }
  85. void close_all()
  86. {
  87. for(const auto&clt:m_thread_clts)
  88. {
  89. if(!clt)
  90. continue;
  91. ((client_ex*)clt.get())->close_impl();
  92. }
  93. }
  94. void on_async(const std::list<std::shared_ptr<client>>&notify_clts)
  95. {
  96. for(const auto&clt:notify_clts)
  97. {
  98. ((client_ex*)clt.get())->on_notify();
  99. }
  100. }
  101. void stop()
  102. {
  103. async_stop();
  104. }
  105. };
  106. struct fd_io:ev::io
  107. {
  108. io_context&m_ic;
  109. int m_fd;
  110. fd_io(io_context&ic,int fd,int ev_flag=EV_READ)
  111. :ev::io(ic)
  112. ,m_ic(ic)
  113. ,m_fd(fd)
  114. {
  115. zio::setblocking(fd,false);
  116. this->set(this);
  117. this->set(m_fd,ev_flag);
  118. this->start();
  119. }
  120. void stop () throw () \
  121. {
  122. ev::io::stop();
  123. }
  124. io_context&context()
  125. {
  126. return m_ic;
  127. }
  128. virtual void operator()(ev::io &w, int)=0;
  129. virtual ~fd_io()
  130. {
  131. stop();
  132. zio::close(m_fd);
  133. }
  134. };
  135. struct stdin_io:fd_io
  136. {
  137. stdin_io(io_context&ic)
  138. :fd_io(ic,0)
  139. {}
  140. virtual void operator()(ev::io &w, int)
  141. {
  142. #if 0
  143. char buf[256];
  144. if(!gets(buf))
  145. return;
  146. if(strchr(buf,'X'))
  147. {
  148. log_info("stdin input 'X', exiting...");
  149. worker::instance()->stop();
  150. stop();
  151. m_ic.stop();
  152. }
  153. #endif
  154. }
  155. };
  156. struct sock_client:fd_io,client_ex
  157. {
  158. io_context&m_ic;
  159. std::string m_name;
  160. std::atomic<bool> m_close_flag{false};
  161. int m_type=1;//site
  162. char *m_b{0};
  163. int m_clen{0};
  164. int m_size{1<<16};
  165. int m_max_package_size{2048};
  166. int m_recv_time_out;
  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. int m_site_id{-1};
  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_time_out=recv_time_out;
  185. m_recv_timer.set<sock_client,&sock_client::on_recv_timeout>(this);
  186. int recv_timeout_first=config.get("service.recv_timeout_first",10);
  187. m_recv_timer.start(recv_timeout_first,0);
  188. int site_sync=config.get("site_sync",0);//分站时间同步,考虑到双IP双机情况,缺省关闭
  189. int site_sync_freq=config.get("site_sync.freq",10*60);//分站时间同步间隔
  190. m_sync_timer.set<sock_client,&sock_client::on_sync_timeout>(this);
  191. if(site_sync)
  192. {
  193. log_info("启动分站同步定时器:%s,%d",name,site_sync_freq);
  194. struct timeval tv;
  195. gettimeofday(&tv,0);
  196. m_sync_timer.start(2-tv.tv_usec/1000000.+0.01,site_sync_freq);
  197. }
  198. // m_send_timer.set(ic);
  199. // m_send_timer.set(5,0);
  200. // m_send_timer.set<sock_client,&sock_client::on_send_timeout>(this);
  201. // m_send_timer.start();
  202. m_b=(char*)malloc(m_size);
  203. // m_timestamp[0]=0;
  204. }
  205. ~sock_client()
  206. {
  207. free(m_b);
  208. }
  209. #if 0
  210. bool check_timestamp(const char*time)
  211. {
  212. //秒、分、时、天、周、月、年, 脑残的设计
  213. char buf[6];
  214. buf[0]=time[6];
  215. buf[1]=time[5];
  216. buf[2]=time[3];
  217. buf[3]=time[2];
  218. buf[4]=time[1];
  219. buf[5]=time[0];
  220. if(memcmp(m_timestamp,buf,6)<=0)
  221. {
  222. memcpy(m_timestamp,buf,6);
  223. return true;
  224. }
  225. return false;
  226. }
  227. #endif
  228. int type()
  229. {
  230. return m_type;
  231. }
  232. void set_conn_type(int t)
  233. {
  234. m_type=t;
  235. }
  236. void close()
  237. {
  238. m_close_flag.store(true);
  239. m_ic.async_request(shared_from_this());
  240. }
  241. void send(std::vector<char>&&b)
  242. {
  243. {
  244. std::unique_lock<std::mutex> _lock(m_mutex);
  245. m_olist.push_back(std::move(b));
  246. }
  247. m_ic.async_request(shared_from_this());
  248. }
  249. void on_sync_timeout()
  250. {
  251. // 从第一个字节开始,分别表示毫秒(2字节)、秒、分、时、天、月、年
  252. unsigned char buf[20]={0,13,0x78,0x3b};
  253. struct timeval tv;
  254. gettimeofday(&tv,0);
  255. struct tm buff={0};
  256. const struct tm*t=localtime_r(&tv.tv_sec,&buff);
  257. int p=4;
  258. buf[p++]=(tv.tv_usec/1000)&0xFF;
  259. buf[p++]=((tv.tv_usec/1000)>>8)&0xFF;
  260. buf[p++]=t->tm_sec;
  261. buf[p++]=t->tm_min;
  262. buf[p++]=t->tm_hour;
  263. buf[p++]=t->tm_mday;
  264. buf[p++]=t->tm_wday;
  265. buf[p++]=t->tm_mon+1;
  266. buf[p++]=t->tm_year-100;
  267. uint16_t ccrc=do_crc(buf+2,11);
  268. buf[p++]=ccrc>>8;
  269. buf[p++]=ccrc&0xff;
  270. std::vector<char> tmp((char*)buf,(char*)buf+15);
  271. send(std::move(tmp));
  272. logn_info(1,"分站同步:ip=%s,time=%d-%02d-%02d %02d:%02d:%02d.%03d",m_name.c_str(),buf[12]+2000,buf[11],buf[9],buf[8],buf[7],buf[6],buf[5]*256+buf[4]);
  273. }
  274. void on_send_timeout()
  275. {
  276. m_ic.on_send_timeout(shared_from_this());
  277. }
  278. void on_recv_timeout()
  279. {
  280. m_ic.on_recv_timeout(shared_from_this());
  281. logn_warn(1,"socket %s recv timeout.",m_name.c_str());
  282. close_impl();
  283. }
  284. std::string name()
  285. {
  286. return m_name;
  287. }
  288. int handle()
  289. {
  290. return m_fd;
  291. }
  292. void grow_buf(int len)
  293. {
  294. if(m_size-m_clen>=len)
  295. return;
  296. int size=m_size;
  297. while(m_size-m_clen<len)
  298. size<<=1;
  299. if(size!=m_size)
  300. {
  301. m_b=(char*)realloc(m_b,m_size=size);
  302. }
  303. }
  304. int read_clt()
  305. {
  306. //先清空数据
  307. memset(m_b, 0, m_size);
  308. for(;m_clen<m_size;)
  309. {
  310. int rc=zio::read(m_fd,m_b+m_clen,m_size-m_clen);
  311. if(rc>0)
  312. {
  313. m_clen+=rc;
  314. continue;
  315. }
  316. if(rc==-2)
  317. return 0;
  318. if(rc==0)
  319. {
  320. logn_info(1,"socket %d(%s) close by remote",m_fd,m_name.c_str());
  321. }
  322. else if(rc==-1)
  323. {
  324. logn_errno(1,"hava a error on socket %d(%s)",m_fd,m_name.c_str());
  325. }
  326. return -1;
  327. }
  328. return 0;
  329. }
  330. int read_clt_cp_buf(char* buf, int nLengthBeforeDecode, int nBufLength)
  331. {
  332. //先清空数据
  333. memset(m_b, 0, m_size);
  334. memcpy(m_b, buf, nBufLength);
  335. free(buf);
  336. m_clen -= nLengthBeforeDecode;
  337. m_clen += nBufLength;
  338. return 0;
  339. }
  340. void close_impl()
  341. {
  342. m_recv_timer.stop();
  343. fd_io::stop();
  344. // 清除网络下的所有设备
  345. module_device_net::instance()->clear(m_name);
  346. logn_info(1,"socket %s closed.",m_name.c_str());
  347. m_ic.on_close(shared_from_this());
  348. }
  349. size_t calc_length(uint8_t*b)const
  350. {
  351. return (b[0]<<8)|b[1];
  352. }
  353. int indexOfCode(const char c) {
  354. const char * code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  355. for (unsigned int i = 0; i < 64; i++) {
  356. if (code[i] == c)
  357. return i;
  358. }
  359. return 0;
  360. }
  361. std::string decodeBase64(std::string input,int& nBufLength) {
  362. nBufLength = 0;
  363. unsigned char input_char[4];
  364. unsigned char output_char[4];
  365. int output_num = 0;
  366. int k = 0;
  367. std::string output_str = "";
  368. for (unsigned int i = 0; i < input.size(); i++) {
  369. input_char[k] = indexOfCode(input[i]);
  370. k++;
  371. if (k == 4) {
  372. output_num = ((int)input_char[0] << 18) + ((int)input_char[1] << 12) + ((int)input_char[2] << 6) + ((int)input_char[3]);
  373. output_char[0] = (unsigned char)((output_num & 0x00FF0000) >> 16);
  374. output_char[1] = (unsigned char)((output_num & 0x0000FF00) >> 8);
  375. output_char[2] = (unsigned char)(output_num & 0x000000FF);
  376. output_char[3] = '\0';
  377. output_str.append((char *)output_char);
  378. nBufLength++;
  379. k = 0;
  380. }
  381. }
  382. return output_str;
  383. }
  384. char *base64_decode(char *code,long& ref_length)
  385. {
  386. //根据base64表,以字符找到对应的十进制数据
  387. int table[] = { 0,0,0,0,0,0,0,0,0,0,0,0,
  388. 0,0,0,0,0,0,0,0,0,0,0,0,
  389. 0,0,0,0,0,0,0,0,0,0,0,0,
  390. 0,0,0,0,0,0,0,62,0,0,0,
  391. 63,52,53,54,55,56,57,58,
  392. 59,60,61,0,0,0,0,0,0,0,0,
  393. 1,2,3,4,5,6,7,8,9,10,11,12,
  394. 13,14,15,16,17,18,19,20,21,
  395. 22,23,24,25,0,0,0,0,0,0,26,
  396. 27,28,29,30,31,32,33,34,35,
  397. 36,37,38,39,40,41,42,43,44,
  398. 45,46,47,48,49,50,51
  399. };
  400. long len;
  401. long str_len;
  402. char *res;
  403. int i, j;
  404. //计算解码后的字符串长度
  405. len = strlen(code);
  406. //判断编码后的字符串后是否有=
  407. if (strstr(code, "=="))
  408. str_len = len / 4 * 3 - 2;
  409. else if (strstr(code, "="))
  410. str_len = len / 4 * 3 - 1;
  411. else
  412. str_len = len / 4 * 3;
  413. res = (char*)malloc(sizeof(char)*str_len + 1);
  414. res[str_len] = '\0';
  415. //以4个字符为一位进行解码
  416. for (i = 0, j = 0; i < len - 2; j += 3, i += 4)
  417. {
  418. res[j] = ((unsigned char)table[code[i]]) << 2 | (((unsigned char)table[code[i + 1]]) >> 4); //取出第一个字符对应base64表的十进制数的前6位与第二个字符对应base64表的十进制数的后2位进行组合
  419. res[j + 1] = (((unsigned char)table[code[i + 1]]) << 4) | (((unsigned char)table[code[i + 2]]) >> 2); //取出第二个字符对应base64表的十进制数的后4位与第三个字符对应bas464表的十进制数的后4位进行组合
  420. res[j + 2] = (((unsigned char)table[code[i + 2]]) << 6) | ((unsigned char)table[code[i + 3]]); //取出第三个字符对应base64表的十进制数的后2位与第4个字符进行组合
  421. }
  422. ref_length = str_len;
  423. return res;
  424. }
  425. int io_read()
  426. {
  427. if(read_clt()<0)
  428. return -1;
  429. try
  430. {
  431. bool bLoRa = false;
  432. // 若以POST开头,则是LoRa的数据包
  433. std::string txtPOST = "POST";
  434. if (0 == strncmp(m_b, txtPOST.c_str(), txtPOST.length()))
  435. {
  436. log_info("LoRa:%s", m_b);
  437. std::string LoRaMsg = m_b;
  438. //为LoRa基站推送数据
  439. std::string txtType = "\"type\":7001";
  440. if (LoRaMsg.find(txtType.c_str()) != std::string::npos)
  441. {
  442. log_info("LoRaType");
  443. std::string txtData = "\"data\":\"";
  444. int nPos = LoRaMsg.find(txtData.c_str());
  445. if (nPos != std::string::npos)
  446. {
  447. std::string strDataTmp = LoRaMsg.substr(nPos + txtData.length());
  448. std::string strData = strDataTmp.substr(0, strDataTmp.find("\""));
  449. log_info("LoRaData:%s",strData.c_str());
  450. long ref_length = 0;
  451. char * szBase64Decode = base64_decode((char*)strData.c_str(), ref_length);
  452. log_info("LoRaDataDecode:%s,Length=%d", szBase64Decode, ref_length);
  453. log_info("LoRaDataDecode 1=%d,2=%d", (unsigned char)(szBase64Decode[2]), (unsigned char)(szBase64Decode[3]));
  454. if ((unsigned char)(szBase64Decode[2]) == 0x90 && (unsigned char)(szBase64Decode[3]) == 0x1c)
  455. {
  456. bLoRa = true;
  457. log_info("LoRaDataDecode OK");
  458. }
  459. if (read_clt_cp_buf(szBase64Decode, LoRaMsg.length(), ref_length) < 0)
  460. {
  461. return -1;
  462. }
  463. if(bLoRa == true)
  464. {
  465. }
  466. else
  467. {
  468. return -1;
  469. }
  470. }
  471. }
  472. }
  473. int msg_len;
  474. for(;m_clen>=2;)
  475. {
  476. msg_len=calc_length((uint8_t*)m_b)+2;
  477. /*if (bLoRa)
  478. {
  479. logn_bin(1, name().c_str(), m_b, msg_len);//输出二进制日志
  480. }*/
  481. if(msg_len>m_max_package_size)
  482. {
  483. log_info("zmg516");
  484. logn_error(1,"package too big:%d/%d,close socket. site=%s.",msg_len,m_max_package_size,m_name.c_str());
  485. return -1;
  486. }
  487. if(msg_len<=2)
  488. {
  489. log_info("zmg515");
  490. logn_error(1,"package too small:%d,close socket. site=%s.",msg_len,m_name.c_str());
  491. return -1;
  492. }
  493. if (m_clen < msg_len)
  494. {
  495. log_info("LoRaDataDecode:msg_len=%d,m_clen=%d", msg_len, m_clen);
  496. log_info("zmg511");
  497. break;
  498. }
  499. if(check_crc(m_b,msg_len))
  500. {
  501. log_info("zmg512");
  502. on_message(m_b,msg_len);
  503. logn_bin(1,name().c_str(),m_b,msg_len);//输出二进制日志
  504. }
  505. else
  506. {
  507. log_info("zmg513");
  508. logn_bin(1,name().c_str(),m_b,msg_len);//输出二进制日志
  509. logn_error(1,"check_crc_error,close socket. site=%s.",m_name.c_str());
  510. return -1;
  511. }
  512. log_info("zmg514");
  513. memmove(m_b,&m_b[msg_len],m_clen-msg_len);
  514. m_clen-=msg_len;
  515. }
  516. }
  517. catch(const std::exception&e)
  518. {
  519. logn_error(1,"package error,close socket. site=%s,err_info=%s",m_name.c_str(),e.what());
  520. return -1;
  521. }
  522. return 0;
  523. }
  524. int io_write()
  525. {
  526. if(! m_can_write)
  527. {
  528. set(EV_READ|EV_WRITE);
  529. return 0;
  530. }
  531. for(;;)
  532. {
  533. if(m_obuf.size()==m_opos)
  534. {
  535. std::unique_lock<std::mutex> _lock(m_mutex);
  536. if(m_olist.empty())
  537. break;
  538. m_obuf.swap(m_olist.front());
  539. m_olist.pop_front();
  540. m_opos=0;
  541. }
  542. int left=m_obuf.size()-m_opos;
  543. int rc=zio::write(m_fd,&*m_obuf.begin()+m_opos,left);
  544. if(rc>0)
  545. {
  546. m_opos+=rc;
  547. if(m_opos==m_obuf.size())
  548. continue;
  549. }
  550. else if(rc==0||rc==-2)//缓冲区满
  551. {
  552. m_can_write=false;
  553. set(EV_READ|EV_WRITE);
  554. break;
  555. }
  556. else
  557. {
  558. logn_errno(1,"zio::write(%d,ptr,%d)",m_fd,m_obuf.size()-m_opos);
  559. return -1;
  560. }
  561. }
  562. if(m_olist.empty() && m_can_write)
  563. {
  564. set(EV_READ);
  565. }
  566. return 0;
  567. }
  568. void operator()(ev::io &w, int flag)
  569. {
  570. if(flag & EV_WRITE)
  571. {
  572. logn_debug(1,"socket %d(%s) can write,flag=%d." ,m_fd,m_name.c_str(),flag);
  573. m_can_write=true;
  574. if(io_write()<0)
  575. {
  576. close_impl();
  577. return;
  578. }
  579. }
  580. if(flag & EV_READ)
  581. {
  582. if(io_read()<0)
  583. {
  584. close_impl();
  585. return;
  586. }
  587. m_recv_timer.start(m_recv_time_out);
  588. }
  589. }
  590. bool check_crc(void *b0,size_t mlen)
  591. {
  592. uint8_t*b=(uint8_t*)b0;
  593. uint16_t crc=b[mlen-2];
  594. crc<<=8;
  595. crc|=b[mlen-1];
  596. uint16_t ccrc=do_crc((unsigned char*)b+2,mlen-4);
  597. return ccrc==crc;
  598. }
  599. void on_message(const char*m,int mlen)
  600. {
  601. m_ic.on_message(shared_from_this(),m,mlen);
  602. }
  603. void on_notify()
  604. {
  605. if(m_close_flag)
  606. {
  607. close_impl();
  608. return;
  609. }
  610. io_write();
  611. }
  612. };
  613. struct sock_listen: fd_io
  614. {
  615. sock_listen(io_context&ic,int fd):fd_io(ic,fd){}
  616. int recv_time_out=config.get("service.recv_timeout",3);
  617. int max_package_size=config.get("service.max_package",2048);
  618. void operator()(ev::io &w, int)
  619. {
  620. char name[32];
  621. int fd=zio::accept(m_fd,name);
  622. if(fd<0)
  623. {
  624. logn_errno(1,"socket %s connect error.",name);
  625. return;
  626. }
  627. zio::setiobuf(fd,32<<10,32<<10);
  628. m_ic.on_connect(std::make_shared<sock_client>(m_ic,name,fd,recv_time_out,max_package_size));
  629. logn_info(1,"socket %s connected.",name);
  630. }
  631. };
  632. struct signal_w:ev::sig
  633. {
  634. io_context&m_ic;
  635. signal_w(io_context&ic, int s)
  636. :ev::sig(ic)
  637. ,m_ic(ic)
  638. {
  639. this->set(this);
  640. this->set(s);
  641. this->start();
  642. }
  643. void operator()(ev::sig &w, int s)
  644. {
  645. log_info("recved signal %d",s);
  646. worker::instance()->stop();
  647. stop();
  648. m_ic.stop();
  649. }
  650. };
  651. struct main_loop:io_context
  652. {
  653. main_loop(service_callback&sc)
  654. :io_context(sc)
  655. {
  656. }
  657. virtual int run(int port)
  658. {
  659. int fd=zio::listen_on(port);
  660. if(fd<0)
  661. {
  662. log_errno("try listen_on %d", port);
  663. std_errno("listen %d failed", port);
  664. return -1;
  665. }
  666. sock_listen _1(*this,fd);
  667. block_sig(SIGPIPE);
  668. signal_w sint(*this,SIGINT),term(*this,SIGTERM);
  669. while(!check_stop_flag())
  670. {
  671. try
  672. {
  673. ev::dynamic_loop::run(0);
  674. }
  675. catch(const std::exception&e)
  676. {
  677. log_error("捕获到异常:%s",e.what());
  678. }
  679. catch(...)
  680. {
  681. log_error("捕获到未知异常");
  682. }
  683. }
  684. _1.stop();
  685. close_all();
  686. return 0;
  687. }
  688. void block_sig(int sig)
  689. {
  690. sigset_t signal_mask;
  691. sigemptyset(&signal_mask);
  692. sigaddset(&signal_mask, sig);
  693. if(pthread_sigmask(SIG_BLOCK, &signal_mask, NULL) == -1)
  694. {
  695. log_errno("block signal:%d",sig);
  696. }
  697. }
  698. };
  699. service_handle*service_handle::instance(service_callback*sc)
  700. {
  701. static main_loop _impl(*sc);
  702. sc->set_handle(&_impl);
  703. return &_impl;
  704. }