StatisticProvider.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. * 提供统计查询的socket
  52. * @var resource
  53. */
  54. protected $providerSocket = null;
  55. /**
  56. * udp 默认全部接收完毕
  57. * @see Man\Core.SocketWorker::dealInput()
  58. */
  59. public function dealInput($recv_str)
  60. {
  61. return 0;
  62. }
  63. /**
  64. * 处理请求统计
  65. * @param string $recv_str
  66. */
  67. public function dealProcess($recv_str)
  68. {
  69. $req_data = json_decode(trim($recv_str), true);
  70. $module = $req_data['module'];
  71. $interface = $req_data['interface'];
  72. $cmd = $req_data['cmd'];
  73. $start_time = isset($req_data['start_time']) ? $req_data['start_time'] : '';
  74. $end_time = isset($req_data['end_time']) ? $req_data['end_time'] : '';
  75. $date = isset($req_data['date']) ? $req_data['date'] : '';
  76. $code = isset($req_data['code']) ? $req_data['code'] : '';
  77. $msg = isset($req_data['msg']) ? $req_data['msg'] : '';
  78. $offset = isset($req_data['offset']) ? $req_data['offset'] : '';
  79. $count = isset($req_data['count']) ? $req_data['count'] : 10;
  80. switch($cmd)
  81. {
  82. case 'get_statistic':
  83. $buffer = json_encode(array('modules'=>$this->getModules($module), 'statistic' => $this->getStatistic($date, $module, $interface)))."\n";
  84. $this->sendToClient($buffer);
  85. break;
  86. case 'get_log':
  87. $buffer = json_encode($this->getStasticLog($module, $interface , $start_time , $end_time, $code = '', $msg = '', $offset='', $count=10))."\n";
  88. $this->sendToClient($buffer);
  89. break;
  90. default :
  91. $this->sendToClient('pack err');
  92. }
  93. }
  94. /**
  95. * 获取模块
  96. * @return array
  97. */
  98. public function getModules($current_module = '')
  99. {
  100. $st_dir = WORKERMAN_ROOT_DIR . $this->statisticDir;
  101. $modules_name_array = array();
  102. foreach(glob($st_dir."/*", GLOB_ONLYDIR) as $module_file)
  103. {
  104. $tmp = explode("/", $module_file);
  105. $module = end($tmp);
  106. $modules_name_array[$module] = array();
  107. if($current_module == $module)
  108. {
  109. $st_dir = $st_dir.$current_module.'/';
  110. $all_interface = array();
  111. foreach(glob($st_dir."*") as $file)
  112. {
  113. if(is_dir($file))
  114. {
  115. continue;
  116. }
  117. list($interface, $date) = explode("|", basename($file));
  118. $all_interface[$interface] = $interface;
  119. }
  120. $modules_name_array[$module] = $all_interface;
  121. }
  122. }
  123. return $modules_name_array;
  124. }
  125. /**
  126. * 获得统计数据
  127. * @param string $module
  128. * @param string $interface
  129. * @param int $date
  130. * @return bool/string
  131. */
  132. protected function getStatistic($date, $module, $interface)
  133. {
  134. if(empty($module) || empty($interface))
  135. {
  136. return '';
  137. }
  138. // log文件
  139. $log_file = WORKERMAN_LOG_DIR . $this->statisticDir."{$module}/{$interface}|{$date}";
  140. return @file_get_contents($log_file);
  141. }
  142. /**
  143. * 获取指定日志
  144. *
  145. */
  146. protected function getStasticLog($module, $interface , $start_time = '', $end_time = '', $code = '', $msg = '', $offset='', $count=100)
  147. {
  148. // log文件
  149. $log_file = WORKERMAN_ROOT_DIR . $this->logDir. (empty($start_time) ? date('Y-m-d') : date('Y-m-d', $start_time));
  150. if(!is_readable($log_file))
  151. {
  152. return array('offset'=>0, 'data'=>$log_file . 'not exists or not readable');
  153. }
  154. // 读文件
  155. $h = fopen($log_file, 'r');
  156. // 如果有时间,则进行二分查找,加速查询
  157. if($start_time && $offset === '' && ($file_size = filesize($log_file) > 50000))
  158. {
  159. $offset = $this->binarySearch(0, $file_size, $start_time-1, $h);
  160. $offset = $offset < 1000 ? 0 : $offset - 1000;
  161. }
  162. // 正则表达式
  163. $pattern = "/^([\d: \-]+)\t";
  164. if($module && $module != 'WorkerMan')
  165. {
  166. $pattern .= $module."::";
  167. }
  168. else
  169. {
  170. $pattern .= ".*::";
  171. }
  172. if($interface && $module != 'WorkerMan')
  173. {
  174. $pattern .= $interface."\t";
  175. }
  176. else
  177. {
  178. $pattern .= ".*\t";
  179. }
  180. if($code !== '')
  181. {
  182. $pattern .= "code:$code\t";
  183. }
  184. else
  185. {
  186. $pattern .= "code:\d+\t";
  187. }
  188. if($msg)
  189. {
  190. $pattern .= "msg:$msg";
  191. }
  192. $pattern .= '/';
  193. // 指定偏移位置
  194. if($offset >= 0)
  195. {
  196. fseek($h, (int)$offset);
  197. }
  198. // 查找符合条件的数据
  199. $now_count = 0;
  200. $log_buffer = '';
  201. while(1)
  202. {
  203. if(feof($h))
  204. {
  205. break;
  206. }
  207. // 读1行
  208. $line = fgets($h);
  209. if(preg_match($pattern, $line, $match))
  210. {
  211. // 判断时间是否符合要求
  212. $time = strtotime($match[1]);
  213. if($start_time)
  214. {
  215. if($time<$start_time)
  216. {
  217. continue;
  218. }
  219. }
  220. if($end_time)
  221. {
  222. if($time>$end_time)
  223. {
  224. break;
  225. }
  226. }
  227. // 收集符合条件的log
  228. $log_buffer .= $line;
  229. if(++$now_count >= $count)
  230. {
  231. break;
  232. }
  233. }
  234. }
  235. // 记录偏移位置
  236. $offset = ftell($h);
  237. return array('offset'=>$offset, 'data'=>$log_buffer);
  238. }
  239. /**
  240. * 日志二分查找法
  241. * @param int $start_point
  242. * @param int $end_point
  243. * @param int $time
  244. * @param fd $fd
  245. * @return int
  246. */
  247. protected function binarySearch($start_point, $end_point, $time, $fd)
  248. {
  249. // 计算中点
  250. $mid_point = (int)(($end_point+$start_point)/2);
  251. // 定位文件指针在中点
  252. fseek($fd, $mid_point);
  253. // 读第一行
  254. $line = fgets($fd);
  255. if(feof($fd) || false === $line)
  256. {
  257. return ftell($fd);
  258. }
  259. // 第一行可能数据不全,再读一行
  260. $line = fgets($fd);
  261. if(feof($fd) || false === $line || trim($line) == '')
  262. {
  263. return ftell($fd);
  264. }
  265. // 判断是否越界
  266. $current_point = ftell($fd);
  267. if($current_point>=$end_point)
  268. {
  269. return $end_point;
  270. }
  271. // 获得时间
  272. $tmp = explode("\t", $line);
  273. $tmp_time = strtotime($tmp[0]);
  274. // 判断时间,返回指针位置
  275. if($tmp_time > $time)
  276. {
  277. return $this->binarySearch($start_point, $current_point, $time, $fd);
  278. }
  279. elseif($tmp_time < $time)
  280. {
  281. return $this->binarySearch($current_point, $end_point, $time, $fd);
  282. }
  283. else
  284. {
  285. return $current_point;
  286. }
  287. }
  288. }
  289. /**
  290. *
  291. * struct statisticPortocol
  292. * {
  293. * unsigned char module_name_len;
  294. * unsigned char interface_name_len;
  295. * float cost_time;
  296. * unsigned char success;
  297. * int code;
  298. * unsigned short msg_len;
  299. * unsigned int time;
  300. * char[module_name_len] module_name;
  301. * char[interface_name_len] interface_name;
  302. * char[msg_len] msg;
  303. * }
  304. *
  305. * @author workerman.net
  306. */
  307. class StatisticProtocol
  308. {
  309. /**
  310. * 包头长度
  311. * @var integer
  312. */
  313. const PACKEGE_FIXED_LENGTH = 17;
  314. /**
  315. * udp 包最大长度
  316. * @var integer
  317. */
  318. const MAX_UDP_PACKGE_SIZE = 65507;
  319. /**
  320. * char类型能保存的最大数值
  321. * @var integer
  322. */
  323. const MAX_CHAR_VALUE = 255;
  324. /**
  325. * usigned short 能保存的最大数值
  326. * @var integer
  327. */
  328. const MAX_UNSIGNED_SHORT_VALUE = 65535;
  329. /**
  330. * 编码
  331. * @param string $module
  332. * @param string $interface
  333. * @param float $cost_time
  334. * @param int $success
  335. * @param int $code
  336. * @param string $msg
  337. * @return string
  338. */
  339. public static function encode($module, $interface , $cost_time, $success, $code = 0,$msg = '')
  340. {
  341. // 防止模块名过长
  342. if(strlen($module) > self::MAX_CHAR_VALUE)
  343. {
  344. $module = substr($module, 0, self::MAX_CHAR_VALUE);
  345. }
  346. // 防止接口名过长
  347. if(strlen($interface) > self::MAX_CHAR_VALUE)
  348. {
  349. $interface = substr($interface, 0, self::MAX_CHAR_VALUE);
  350. }
  351. // 防止msg过长
  352. $module_name_length = strlen($module);
  353. $interface_name_length = strlen($interface);
  354. $avalible_size = self::MAX_UDP_PACKGE_SIZE - self::PACKEGE_FIXED_LENGTH - $module_name_length - $interface_name_length;
  355. if(strlen($msg) > $avalible_size)
  356. {
  357. $msg = substr($msg, 0, $avalible_size);
  358. }
  359. // 打包
  360. return pack('CCfCNnN', $module_name_length, $interface_name_length, $cost_time, $success ? 1 : 0, $code, strlen($msg), time()).$module.$interface.$msg;
  361. }
  362. /**
  363. * 解包
  364. * @param string $bin_data
  365. * @return array
  366. */
  367. public static function decode($bin_data)
  368. {
  369. // 解包
  370. $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $bin_data);
  371. $module = substr($bin_data, self::PACKEGE_FIXED_LENGTH, $data['module_name_len']);
  372. $interface = substr($bin_data, self::PACKEGE_FIXED_LENGTH + $data['module_name_len'], $data['interface_name_len']);
  373. $msg = substr($bin_data, self::PACKEGE_FIXED_LENGTH + $data['module_name_len'] + $data['interface_name_len']);
  374. return array(
  375. 'module' => $module,
  376. 'interface' => $interface,
  377. 'cost_time' => $data['cost_time'],
  378. 'success' => $data['success'],
  379. 'time' => $data['time'],
  380. 'code' => $data['code'],
  381. 'msg' => $msg,
  382. );
  383. }
  384. }