buffer_looper.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: stanley-king
  5. * Date: 2018/7/23
  6. * Time: 下午10:58
  7. */
  8. namespace event;
  9. use Log;
  10. class buffer_looper
  11. {
  12. const body_header_len = 10;
  13. const read_time_out = 600;
  14. const write_time_out = 30;
  15. protected $mEvBase;
  16. protected $mEvAccepts;
  17. protected $mEvSignals;
  18. protected $mEvConnects;
  19. protected $mStreams;
  20. protected $mBuffers;
  21. protected $mContents;
  22. protected $mProcessor;
  23. public function __construct()
  24. {
  25. $this->mStreams = [];
  26. $this->mBuffers = [];
  27. $this->mContents = [];
  28. $this->mEvAccepts = [];
  29. $this->mEvSignals = [];
  30. $this->mEvConnects = [];
  31. $this->mEvTimeouts = [];
  32. //event_init(); //for libevent C 库 2.16 版本
  33. $this->mEvBase = event_base_new();
  34. }
  35. public function init(IProcessor $processor)
  36. {
  37. $this->mProcessor = $processor;
  38. $this->mProcessor->onStart();
  39. }
  40. public function handle_error($level, $message, $file, $line)
  41. {
  42. if($level == E_NOTICE) return;
  43. $trace = "buffer_looper: level={$level},msg={$message} file={$file},line={$line}\n";
  44. $backtrace = debug_backtrace();
  45. foreach ($backtrace as $item) {
  46. $trace .= "{$item['file']}\t{$item['line']}\t{$item['function']}\n";
  47. }
  48. Log::record($trace,Log::ERR);
  49. }
  50. public function run_loop()
  51. {
  52. set_error_handler([$this, 'handle_error']);
  53. $this->add_signal(SIGINT);
  54. $this->add_signal(SIGQUIT);
  55. $this->add_signal(SIGTERM);
  56. Log::record("event_base_loop running....",Log::DEBUG);
  57. $ret = event_base_loop($this->mEvBase);
  58. Log::record("event_base_loop ret={$ret}",Log::DEBUG);
  59. }
  60. public function add_listen($stream)
  61. {
  62. $fd = intval($stream);
  63. if($fd < 0) return false;
  64. $this->mEvAccepts[$fd] = event_new();
  65. $this->mStreams[$fd] = $stream;
  66. if(event_set($this->mEvAccepts[$fd], $stream, EV_READ | EV_PERSIST, [$this, 'onAccept']) == false) {
  67. Log::record("event_set error EV_READ | EV_PERSIST",Log::DEBUG);
  68. }
  69. if(event_base_set($this->mEvAccepts[$fd], $this->mEvBase) == false) {
  70. Log::record("event_set error EV_READ | EV_PERSIST",Log::DEBUG);
  71. }
  72. if(event_add($this->mEvAccepts[$fd]) == false) {
  73. Log::record("event_add error EV_READ | EV_PERSIST",Log::DEBUG);
  74. }
  75. }
  76. private function add_signal($val)
  77. {
  78. $this->mEvSignals[$val] = event_new();
  79. if(event_set($this->mEvSignals[$val], $val, EV_SIGNAL, [$this, 'onSignal']) == false) {
  80. Log::record("event_set error EV_SIGNAL sig={$val}",Log::DEBUG);
  81. }
  82. if(event_base_set($this->mEvSignals[$val], $this->mEvBase) == false) {
  83. Log::record("event_base_set error EV_SIGNAL sig={$val}",Log::DEBUG);
  84. }
  85. if(event_add($this->mEvSignals[$val]) == false) {
  86. Log::record("event_add error EV_SIGNAL sig={$val}",Log::DEBUG);
  87. }
  88. }
  89. public function onSignal($sig, $flag)
  90. {
  91. Log::record("ev_signal sig={$sig},flag={$flag}",Log::DEBUG);
  92. if($sig == SIGINT || $sig == SIGQUIT || $sig == SIGTERM)
  93. {
  94. event_base_loopexit($this->mEvBase);
  95. foreach ($this->mEvTimeouts as $event) {
  96. event_del($event);
  97. event_free($event);
  98. }
  99. $this->mEvTimeouts = [];
  100. foreach ($this->mBuffers as $bufid => $buffer) {
  101. event_buffer_disable($buffer, EV_READ | EV_WRITE);
  102. event_buffer_free($buffer);
  103. }
  104. $this->mBuffers = [];
  105. foreach ($this->mStreams as $fd => $stream) {
  106. socket_close($this->mStreams[$fd]);
  107. }
  108. $this->mStreams = [];
  109. $this->mContents = [];
  110. foreach ($this->mEvSignals as $event) {
  111. event_del($event);
  112. event_free($event);
  113. }
  114. $this->mEvSignals = [];
  115. }
  116. }
  117. public function onAccept($socket, $event)
  118. {
  119. Log::record("onAccept",Log::DEBUG);
  120. Log::record("onAccept socket_fd={$socket} flag={$event}",Log::DEBUG);
  121. $stream = socket_accept($socket);
  122. if($stream == false) {
  123. Log::record("socket_accept return false socket_fd={$socket}",Log::DEBUG);
  124. return;
  125. } else {
  126. Log::record("socket_accept stream={$stream}",Log::DEBUG);
  127. $this->add_stream($stream);
  128. }
  129. }
  130. public function onWrite($buffer, $bufid)
  131. {
  132. }
  133. private function add_stream($stream)
  134. {
  135. $bufid = intval($stream);
  136. socket_set_nonblock($stream);
  137. $buffer = event_buffer_new($stream, [$this,'onRead'], NULL, [$this,'onError'], $bufid);
  138. if($buffer == false) {
  139. socket_close($stream);
  140. return false;
  141. }
  142. else
  143. {
  144. event_buffer_base_set($buffer,$this->mEvBase);
  145. event_buffer_timeout_set($buffer, self::read_time_out, self::write_time_out);
  146. event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
  147. event_buffer_priority_set($buffer, 10);
  148. event_buffer_enable($buffer, EV_READ | EV_PERSIST);
  149. $this->mStreams[$bufid] = $stream;
  150. $this->mBuffers[$bufid] = $buffer;
  151. $this->mContents[$bufid] = "";
  152. return $bufid;
  153. }
  154. }
  155. public function block($bufid)
  156. {
  157. $stream = $this->mStreams[$bufid];
  158. $buffer = $this->mBuffers[$bufid];
  159. $success = event_buffer_disable($buffer, EV_READ | EV_PERSIST);
  160. Log::record("event_buffer_disable success={$success}",Log::DEBUG);
  161. $success = socket_set_block($stream);
  162. Log::record("socket_set_block success={$success}",Log::DEBUG);
  163. }
  164. public function unblock($bufid)
  165. {
  166. $stream = $this->mStreams[$bufid];
  167. $buffer = $this->mBuffers[$bufid];
  168. $success = socket_set_nonblock($stream);
  169. Log::record("socket_set_nonblock success={$success}",Log::DEBUG);
  170. $success = event_buffer_enable($buffer, EV_READ | EV_PERSIST);
  171. Log::record("event_buffer_enable success={$success}",Log::DEBUG);
  172. }
  173. public function onConnectTimer($stream, $event, $params)
  174. {
  175. $error = socket_last_error();
  176. Log::record("onConnectTimer sig={$stream},flag={$event},error={$error}",Log::DEBUG);
  177. $stream = $this->do_connect($params['host'],$params['port'],$params['args'],$params['stream']);
  178. if($stream != false) {
  179. $bufid = $this->add_stream($stream);
  180. $this->mProcessor->onConnected($bufid, $stream,$params['host'],$params['port'],$params['args']);
  181. }
  182. }
  183. public function onConnect($stream, $event, $params)
  184. {
  185. $error = socket_last_error();
  186. Log::record("onConnect sig={$stream},flag={$event},socket error={$error}",Log::DEBUG);
  187. if($event == EV_WRITE)
  188. {
  189. $ret = socket_getopt($stream,SOL_SOCKET,SO_ERROR);
  190. if($ret == 0) {
  191. Log::record("onConnect EV_WRITE success ",Log::DEBUG);
  192. $fd = intval($stream);
  193. event_del($this->mEvConnects[$fd]);
  194. event_free($this->mEvConnects[$fd]);
  195. event_del($this->mEvTimeouts[$fd]);
  196. event_free($this->mEvTimeouts[$fd]);
  197. unset($this->mEvConnects[$fd]);
  198. unset($this->mEvTimeouts[$fd]);
  199. $bufid = $this->add_stream($stream);
  200. $this->mProcessor->onConnected($bufid, $stream,$params['host'],$params['port'],$params['args']);
  201. }
  202. else {
  203. Log::record("onConnect EV_WRITE Error",Log::DEBUG);
  204. }
  205. }
  206. elseif($event == EV_WRITE | EV_READ)
  207. {
  208. Log::record("onConnect EV_WRITE | EV_READ",Log::DEBUG);
  209. }
  210. else {
  211. Log::record("onConnect ETIMEOUT",Log::DEBUG);
  212. }
  213. }
  214. private function do_connect($host,$port,$args,$old_stream = false)
  215. {
  216. $stream = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  217. if($stream === false) return false;
  218. socket_set_nonblock($stream);
  219. $fd = intval($stream);
  220. if($old_stream == false)
  221. {
  222. $this->mEvConnects[$fd] = event_new();
  223. $this->mEvTimeouts[$fd] = event_timer_new();
  224. }
  225. else {
  226. $oldfd = intval($old_stream);
  227. socket_close($old_stream);
  228. Log::record("close old stream={$old_stream}",Log::DEBUG);
  229. $this->mEvConnects[$fd] = $this->mEvConnects[$oldfd];
  230. $this->mEvTimeouts[$fd] = $this->mEvTimeouts[$oldfd];
  231. unset($this->mEvConnects[$oldfd]);
  232. unset($this->mEvTimeouts[$oldfd]);
  233. }
  234. $ret = socket_connect($stream,$host,$port);
  235. if($ret == false)
  236. {
  237. if(event_set($this->mEvConnects[$fd], $stream, EV_WRITE | EV_READ, [$this, 'onConnect'],['host' => $host,'port' => $port,'args' => $args]) == false) {
  238. Log::record("event_set error connect fd={$stream}",Log::DEBUG);
  239. }
  240. if(event_base_set($this->mEvConnects[$fd], $this->mEvBase) == false) {
  241. Log::record("event_base_set error connect fd={$stream}",Log::DEBUG);
  242. }
  243. if(event_add($this->mEvConnects[$fd]) == false) {
  244. Log::record("event_add error connect fd={$stream}",Log::DEBUG);
  245. }
  246. if(event_timer_set($this->mEvTimeouts[$fd], [$this, 'onConnectTimer'],['stream' => $stream, 'host' => $host,'port' => $port,'args' => $args]) == false) {
  247. Log::record("event_set error connect fd={$stream}",Log::DEBUG);
  248. }
  249. if(event_base_set($this->mEvTimeouts[$fd], $this->mEvBase) == false) {
  250. Log::record("event_base_set error connect fd={$stream}",Log::DEBUG);
  251. }
  252. if(event_timer_add($this->mEvTimeouts[$fd],1000000) == false) {
  253. Log::record("event_base_set error connect fd={$stream}",Log::DEBUG);
  254. }
  255. return false;
  256. }
  257. else {
  258. event_del($this->mEvConnects[$fd]);
  259. event_free($this->mEvConnects[$fd]);
  260. event_del($this->mEvTimeouts[$fd]);
  261. event_free($this->mEvTimeouts[$fd]);
  262. unset($this->mEvConnects[$fd]);
  263. unset($this->mEvTimeouts[$fd]);
  264. return $stream;
  265. }
  266. }
  267. public function connect($host,$port,$args)
  268. {
  269. $stream = $this->do_connect($host,$port,$args,false);
  270. if($stream != false) {
  271. $bufid = $this->add_stream($stream);
  272. $this->mProcessor->onConnected($bufid, $stream,$host,$port,$args);
  273. }
  274. }
  275. public function onRead($buffer, $bufid)
  276. {
  277. Log::record("onRead bufid={$bufid}",Log::DEBUG);
  278. while($read = event_buffer_read($buffer, 1024)) {
  279. Log::record("read={$read}",Log::DEBUG);
  280. $this->mContents[$bufid] .= $read;
  281. $this->proc($bufid);
  282. }
  283. }
  284. public function onError($buffer, $event, $bufid)
  285. {
  286. Log::record("onError bufid={$bufid} flag={$event}",Log::DEBUG);
  287. if ($event == (EVBUFFER_READ | EVBUFFER_TIMEOUT)) {
  288. event_buffer_enable($buffer, EV_READ);
  289. $ret = $this->write($bufid,'');
  290. if($ret == false) {
  291. $this->close($bufid);
  292. }
  293. }
  294. else
  295. {
  296. event_buffer_disable($buffer, EV_READ | EV_WRITE);
  297. event_buffer_free($buffer);
  298. if(array_key_exists($bufid,$this->mStreams)) {
  299. socket_close($this->mStreams[$bufid]);
  300. unset($this->mStreams[$bufid]);
  301. }
  302. if(array_key_exists($bufid,$this->mBuffers)) {
  303. unset($this->mBuffers[$bufid]);
  304. }
  305. if(array_key_exists($bufid,$this->mContents)) {
  306. unset($this->mContents[$bufid]);
  307. }
  308. if($this->mProcessor != null) {
  309. $this->mProcessor->onClose($bufid);
  310. }
  311. }
  312. }
  313. private function proc($bufid)
  314. {
  315. $content = $this->mContents[$bufid];
  316. $start = 0;
  317. $left = strlen($content);
  318. while($left > self::body_header_len)
  319. {
  320. $header = substr($content,$start,self::body_header_len);
  321. if(!is_numeric($header)) {
  322. $this->close($bufid);
  323. return;
  324. }
  325. $body_len = intval($header);
  326. if($body_len == 0) { //这是一个心跳包
  327. $start += self::body_header_len;
  328. $left -= self::body_header_len;
  329. }
  330. elseif($left >= self::body_header_len + $body_len)
  331. {
  332. $body = substr($content,$start + self::body_header_len,$body_len);
  333. $this->mProcessor->onRequest($bufid,$body);
  334. $start += self::body_header_len + $body_len;
  335. $left -= self::body_header_len + $body_len;
  336. }
  337. else {
  338. break;
  339. }
  340. }
  341. if($start > 0)
  342. {
  343. $str = substr($content,$start);
  344. if($str === false) {
  345. $this->mContents[$bufid] = '';
  346. }
  347. else {
  348. $this->mContents[$bufid] = $str;
  349. }
  350. }
  351. }
  352. public function write($bufid,$data)
  353. {
  354. if(!is_string($data)) {
  355. Log::record(__METHOD__ . " write data is not string.",Log::ERR);
  356. }
  357. if(array_key_exists($bufid,$this->mBuffers)) {
  358. $buffer = $this->mBuffers[$bufid];
  359. $header = sprintf("%010d",strlen($data));
  360. $data = $header . $data;
  361. $ret = event_buffer_write($buffer,$data,strlen($data));
  362. if($ret == false) {
  363. Log::record(__METHOD__ . " event_buffer_write return false.",Log::ERR);
  364. }
  365. return $ret;
  366. } else {
  367. return false;
  368. }
  369. }
  370. public function close($bufid)
  371. {
  372. if(!array_key_exists($bufid,$this->mBuffers)) return false;
  373. Log::record(__METHOD__ . " close socket.",Log::DEBUG);
  374. $buffer = $this->mBuffers[$bufid];
  375. event_buffer_disable($buffer, EV_READ | EV_WRITE);
  376. event_buffer_free($buffer);
  377. if(array_key_exists($bufid,$this->mStreams)) {
  378. socket_close($this->mStreams[$bufid]);
  379. unset($this->mStreams[$bufid]);
  380. }
  381. if(array_key_exists($bufid,$this->mBuffers)) {
  382. unset($this->mBuffers[$bufid]);
  383. }
  384. if(array_key_exists($bufid,$this->mContents)) {
  385. unset($this->mContents[$bufid]);
  386. }
  387. if($this->mProcessor != null) {
  388. $this->mProcessor->onClose($bufid);
  389. }
  390. }
  391. }