StatisticProvider.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. require_once WORKERMAN_ROOT_DIR . 'man/Core/SocketWorker.php';
  3. /**
  4. *
  5. * @author walkor <worker-man@qq.com>
  6. */
  7. class StatisticProvider extends Man\Core\SocketWorker
  8. {
  9. /**
  10. * 最大日志buffer,大于这个值就写磁盘
  11. * @var integer
  12. */
  13. const MAX_LOG_BUFFER_SZIE = 1024000;
  14. /**
  15. * 多长时间写一次数据到磁盘
  16. * @var integer
  17. */
  18. const WRITE_PERIOD_LENGTH = 60;
  19. /**
  20. * 多长时间清理一次老的磁盘数据
  21. * @var integer
  22. */
  23. const CLEAR_PERIOD_LENGTH = 86400;
  24. /**
  25. * 数据多长时间过期
  26. * @var integer
  27. */
  28. const EXPIRED_TIME = 1296000;
  29. /**
  30. * 统计数据
  31. * ip=>modid=>interface=>['code'=>[xx=>count,xx=>count],'suc_cost_time'=>xx,'fail_cost_time'=>xx, 'suc_count'=>xx, 'fail_count'=>xx]
  32. * @var array
  33. */
  34. protected $statisticData = array();
  35. /**
  36. * 日志的buffer
  37. * @var string
  38. */
  39. protected $logBuffer = '';
  40. /**
  41. * 放统计数据的目录(相对于workerman/logs/)
  42. * @var string
  43. */
  44. protected $statisticDir = 'statistic/statistic/';
  45. /**
  46. * 存放统计日志的目录(相对于workerman/logs/)
  47. * @var string
  48. */
  49. protected $logDir = 'statistic/log/';
  50. /**
  51. * 用于接收广播的udp socket
  52. * @var resource
  53. */
  54. protected $broadcastSocket = null;
  55. public function onStart()
  56. {
  57. $listen = \Man\Core\Lib\Config::get($this->workerName . '.listen');
  58. $udp_address = str_replace('tcp', 'udp', $listen);
  59. $this->broadcastSocket = stream_socket_server($udp_address, $error_no, $error_msg, STREAM_SERVER_BIND);
  60. $this->event->add($this->broadcastSocket, \Man\Core\Events\BaseEvent::EV_READ, array($this, 'dealBroadcastUdp'));
  61. }
  62. /**
  63. * 接收Udp数据
  64. * 如果数据超过一个udp包长,需要业务自己解析包体,判断数据是否全部到达
  65. * @param resource $socket
  66. * @param $null_one $flag
  67. * @param $null_two $base
  68. * @return void
  69. */
  70. public function dealBroadcastUdp($socket, $null_one = null, $null_two = null)
  71. {
  72. $data = stream_socket_recvfrom($socket , self::MAX_UDP_PACKEG_SIZE, 0, $address);
  73. // 可能是惊群效应
  74. if(false === $data || empty($address))
  75. {
  76. return false;
  77. }
  78. // 解析包体
  79. $data = json_decode(trim($data), true);
  80. if(empty($data))
  81. {
  82. return false;
  83. }
  84. // 无法解析的包
  85. if(empty($data['cmd']) || $data['cmd'] != 'REPORT_IP' )
  86. {
  87. return false;
  88. }
  89. // 回应
  90. return stream_socket_sendto($this->broadcastSocket, json_encode(array('result'=>'ok')), 0, $address);
  91. }
  92. /**
  93. * udp 默认全部接收完毕
  94. * @see Man\Core.SocketWorker::dealInput()
  95. */
  96. public function dealInput($recv_str)
  97. {
  98. return 0;
  99. }
  100. /**
  101. * 处理请求统计
  102. * @param string $recv_str
  103. */
  104. public function dealProcess($recv_str)
  105. {
  106. $req_data = json_decode(trim($recv_str), true);
  107. $module = $req_data['module'];
  108. $interface = $req_data['interface'];
  109. $cmd = $req_data['cmd'];
  110. $start_time = isset($req_data['start_time']) ? $req_data['start_time'] : '';
  111. $end_time = isset($req_data['end_time']) ? $req_data['end_time'] : '';
  112. $date = isset($req_data['date']) ? $req_data['date'] : '';
  113. $code = isset($req_data['code']) ? $req_data['code'] : '';
  114. $msg = isset($req_data['msg']) ? $req_data['msg'] : '';
  115. $offset = isset($req_data['offset']) ? $req_data['offset'] : '';
  116. $count = isset($req_data['count']) ? $req_data['count'] : 10;
  117. switch($cmd)
  118. {
  119. case 'get_statistic':
  120. $buffer = json_encode(array('modules'=>$this->getModules($module), 'statistic' => $this->getStatistic($date, $module, $interface)))."\n";
  121. $this->sendToClient($buffer);
  122. break;
  123. case 'get_log':
  124. $buffer = json_encode($this->getStasticLog($module, $interface , $start_time , $end_time, $code, $msg, $offset, $count))."\n";
  125. $this->sendToClient($buffer);
  126. break;
  127. default :
  128. $this->sendToClient('pack err');
  129. }
  130. }
  131. /**
  132. * 获取模块
  133. * @return array
  134. */
  135. public function getModules($current_module = '')
  136. {
  137. $st_dir = WORKERMAN_LOG_DIR . $this->statisticDir;
  138. $modules_name_array = array();
  139. foreach(glob($st_dir."/*", GLOB_ONLYDIR) as $module_file)
  140. {
  141. $tmp = explode("/", $module_file);
  142. $module = end($tmp);
  143. $modules_name_array[$module] = array();
  144. if($current_module == $module)
  145. {
  146. $st_dir = $st_dir.$current_module.'/';
  147. $all_interface = array();
  148. foreach(glob($st_dir."*") as $file)
  149. {
  150. if(is_dir($file))
  151. {
  152. continue;
  153. }
  154. list($interface, $date) = explode("|", basename($file));
  155. $all_interface[$interface] = $interface;
  156. }
  157. $modules_name_array[$module] = $all_interface;
  158. }
  159. }
  160. return $modules_name_array;
  161. }
  162. /**
  163. * 获得统计数据
  164. * @param string $module
  165. * @param string $interface
  166. * @param int $date
  167. * @return bool/string
  168. */
  169. protected function getStatistic($date, $module, $interface)
  170. {
  171. if(empty($module) || empty($interface))
  172. {
  173. return '';
  174. }
  175. // log文件
  176. $log_file = WORKERMAN_LOG_DIR . $this->statisticDir."{$module}/{$interface}|{$date}";
  177. return @file_get_contents($log_file);
  178. }
  179. /**
  180. * 获取指定日志
  181. *
  182. */
  183. protected function getStasticLog($module, $interface , $start_time = '', $end_time = '', $code = '', $msg = '', $offset='', $count=100)
  184. {
  185. // log文件
  186. $log_file = WORKERMAN_LOG_DIR . $this->logDir. (empty($start_time) ? date('Y-m-d') : date('Y-m-d', $start_time));
  187. if(!is_readable($log_file))
  188. {
  189. return array('offset'=>0, 'data'=>'');
  190. }
  191. // 读文件
  192. $h = fopen($log_file, 'r');
  193. // 如果有时间,则进行二分查找,加速查询
  194. if($start_time && $offset == 0 && ($file_size = filesize($log_file)) > 1024000)
  195. {
  196. $offset = $this->binarySearch(0, $file_size, $start_time-1, $h);
  197. $offset = $offset < 100000 ? 0 : $offset - 100000;
  198. }
  199. // 正则表达式
  200. $pattern = "/^([\d: \-]+)\t\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\t";
  201. if($module && $module != 'WorkerMan')
  202. {
  203. $pattern .= $module."::";
  204. }
  205. else
  206. {
  207. $pattern .= ".*::";
  208. }
  209. if($interface && $module != 'WorkerMan')
  210. {
  211. $pattern .= $interface."\t";
  212. }
  213. else
  214. {
  215. $pattern .= ".*\t";
  216. }
  217. if($code !== '')
  218. {
  219. $pattern .= "code:$code\t";
  220. }
  221. else
  222. {
  223. $pattern .= "code:\d+\t";
  224. }
  225. if($msg)
  226. {
  227. $pattern .= "msg:$msg";
  228. }
  229. $pattern .= '/';
  230. // 指定偏移位置
  231. if($offset > 0)
  232. {
  233. fseek($h, (int)$offset-1);
  234. }
  235. // 查找符合条件的数据
  236. $now_count = 0;
  237. $log_buffer = '';
  238. while(1)
  239. {
  240. if(feof($h))
  241. {
  242. break;
  243. }
  244. // 读1行
  245. $line = fgets($h);
  246. if(preg_match($pattern, $line, $match))
  247. {
  248. // 判断时间是否符合要求
  249. $time = strtotime($match[1]);
  250. if($start_time)
  251. {
  252. if($time<$start_time)
  253. {
  254. continue;
  255. }
  256. }
  257. if($end_time)
  258. {
  259. if($time>$end_time)
  260. {
  261. break;
  262. }
  263. }
  264. // 收集符合条件的log
  265. $log_buffer .= $line;
  266. if(++$now_count >= $count)
  267. {
  268. break;
  269. }
  270. }
  271. }
  272. // 记录偏移位置
  273. $offset = ftell($h);
  274. return array('offset'=>$offset, 'data'=>$log_buffer);
  275. }
  276. /**
  277. * 日志二分查找法
  278. * @param int $start_point
  279. * @param int $end_point
  280. * @param int $time
  281. * @param fd $fd
  282. * @return int
  283. */
  284. protected function binarySearch($start_point, $end_point, $time, $fd)
  285. {
  286. if($end_point - $start_point < 65535)
  287. {
  288. return $start_point;
  289. }
  290. // 计算中点
  291. $mid_point = (int)(($end_point+$start_point)/2);
  292. // 定位文件指针在中点
  293. fseek($fd, $mid_point - 1);
  294. // 读第一行
  295. $line = fgets($fd);
  296. if(feof($fd) || false === $line)
  297. {
  298. return $start_point;
  299. }
  300. // 第一行可能数据不全,再读一行
  301. $line = fgets($fd);
  302. if(feof($fd) || false === $line || trim($line) == '')
  303. {
  304. return $start_point;
  305. }
  306. // 判断是否越界
  307. $current_point = ftell($fd);
  308. if($current_point>=$end_point)
  309. {
  310. return $start_point;
  311. }
  312. // 获得时间
  313. $tmp = explode("\t", $line);
  314. $tmp_time = strtotime($tmp[0]);
  315. // 判断时间,返回指针位置
  316. if($tmp_time > $time)
  317. {
  318. return $this->binarySearch($start_point, $current_point, $time, $fd);
  319. }
  320. elseif($tmp_time < $time)
  321. {
  322. return $this->binarySearch($current_point, $end_point, $time, $fd);
  323. }
  324. else
  325. {
  326. return $current_point;
  327. }
  328. }
  329. }
  330. /**
  331. *
  332. * struct statisticPortocol
  333. * {
  334. * unsigned char module_name_len;
  335. * unsigned char interface_name_len;
  336. * float cost_time;
  337. * unsigned char success;
  338. * int code;
  339. * unsigned short msg_len;
  340. * unsigned int time;
  341. * char[module_name_len] module_name;
  342. * char[interface_name_len] interface_name;
  343. * char[msg_len] msg;
  344. * }
  345. *
  346. * @author workerman.net
  347. */
  348. class StatisticProtocol
  349. {
  350. /**
  351. * 包头长度
  352. * @var integer
  353. */
  354. const PACKEGE_FIXED_LENGTH = 17;
  355. /**
  356. * udp 包最大长度
  357. * @var integer
  358. */
  359. const MAX_UDP_PACKGE_SIZE = 65507;
  360. /**
  361. * char类型能保存的最大数值
  362. * @var integer
  363. */
  364. const MAX_CHAR_VALUE = 255;
  365. /**
  366. * usigned short 能保存的最大数值
  367. * @var integer
  368. */
  369. const MAX_UNSIGNED_SHORT_VALUE = 65535;
  370. /**
  371. * 编码
  372. * @param string $module
  373. * @param string $interface
  374. * @param float $cost_time
  375. * @param int $success
  376. * @param int $code
  377. * @param string $msg
  378. * @return string
  379. */
  380. public static function encode($module, $interface , $cost_time, $success, $code = 0,$msg = '')
  381. {
  382. // 防止模块名过长
  383. if(strlen($module) > self::MAX_CHAR_VALUE)
  384. {
  385. $module = substr($module, 0, self::MAX_CHAR_VALUE);
  386. }
  387. // 防止接口名过长
  388. if(strlen($interface) > self::MAX_CHAR_VALUE)
  389. {
  390. $interface = substr($interface, 0, self::MAX_CHAR_VALUE);
  391. }
  392. // 防止msg过长
  393. $module_name_length = strlen($module);
  394. $interface_name_length = strlen($interface);
  395. $avalible_size = self::MAX_UDP_PACKGE_SIZE - self::PACKEGE_FIXED_LENGTH - $module_name_length - $interface_name_length;
  396. if(strlen($msg) > $avalible_size)
  397. {
  398. $msg = substr($msg, 0, $avalible_size);
  399. }
  400. // 打包
  401. return pack('CCfCNnN', $module_name_length, $interface_name_length, $cost_time, $success ? 1 : 0, $code, strlen($msg), time()).$module.$interface.$msg;
  402. }
  403. /**
  404. * 解包
  405. * @param string $bin_data
  406. * @return array
  407. */
  408. public static function decode($bin_data)
  409. {
  410. // 解包
  411. $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $bin_data);
  412. $module = substr($bin_data, self::PACKEGE_FIXED_LENGTH, $data['module_name_len']);
  413. $interface = substr($bin_data, self::PACKEGE_FIXED_LENGTH + $data['module_name_len'], $data['interface_name_len']);
  414. $msg = substr($bin_data, self::PACKEGE_FIXED_LENGTH + $data['module_name_len'] + $data['interface_name_len']);
  415. return array(
  416. 'module' => $module,
  417. 'interface' => $interface,
  418. 'cost_time' => $data['cost_time'],
  419. 'success' => $data['success'],
  420. 'time' => $data['time'],
  421. 'code' => $data['code'],
  422. 'msg' => $msg,
  423. );
  424. }
  425. }