StatisticWorker.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. require_once WORKERMAN_ROOT_DIR . 'man/Core/SocketWorker.php';
  3. /**
  4. *
  5. * @author walkor <worker-man@qq.com>
  6. */
  7. class StatisticWorker 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, 'time'=>xxx]
  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. public function dealInput($recv_str)
  51. {
  52. return 0;
  53. }
  54. /**
  55. * 业务处理
  56. * @see Man\Core.SocketWorker::dealProcess()
  57. */
  58. public function dealProcess($recv_str)
  59. {
  60. // 解码
  61. $unpack_data = StatisticProtocol::decode($recv_str);
  62. $module = $unpack_data['module'];
  63. $interface = $unpack_data['interface'];
  64. $cost_time = $unpack_data['cost_time'];
  65. $success = $unpack_data['success'];
  66. $time = $unpack_data['time'];
  67. $code = $unpack_data['code'];
  68. $msg = str_replace("\n", "<br>", $unpack_data['msg']);
  69. $ip = $this->getRemoteIp();
  70. // 模块接口统计
  71. $this->collectStatistics($module, $interface, $cost_time, $success, $ip, $code, $msg);
  72. // 全局统计
  73. $this->collectStatistics('WorkerMan', 'Statistics', $cost_time, $success, $ip, $code, $msg);
  74. // 失败记录日志
  75. if(!$success)
  76. {
  77. $this->logBuffer .= date('Y-m-d H:i:s',$time)."\t$ip\t$module::$interface\tcode:$code\tmsg:$msg\n";
  78. if(strlen($this->logBuffer) >= self::MAX_LOG_BUFFER_SZIE)
  79. {
  80. $this->writeLogToDisk();
  81. }
  82. }
  83. }
  84. /**
  85. * 收集统计数据
  86. * @param string $module
  87. * @param string $interface
  88. * @param float $cost_time
  89. * @param int $success
  90. * @param string $ip
  91. * @param int $code
  92. * @param string $msg
  93. * @return void
  94. */
  95. protected function collectStatistics($module, $interface , $cost_time, $success, $ip, $code, $msg)
  96. {
  97. // 统计相关信息
  98. if(!isset($this->statisticData[$ip]))
  99. {
  100. $this->statisticData[$ip] = array();
  101. }
  102. if(!isset($this->statisticData[$ip][$module]))
  103. {
  104. $this->statisticData[$ip][$module] = array();
  105. }
  106. if(!isset($this->statisticData[$ip][$module][$interface]))
  107. {
  108. $this->statisticData[$ip][$module][$interface] = array('code'=>array(), 'suc_cost_time'=>0, 'fail_cost_time'=>0, 'suc_count'=>0, 'fail_count'=>0, 'time'=>$this->stLastWriteTime);
  109. }
  110. if(!isset($this->statisticData[$ip][$module][$interface]['code'][$code]))
  111. {
  112. $this->statisticData[$ip][$module][$interface]['code'][$code] = 0;
  113. }
  114. $this->statisticData[$ip][$module][$interface]['code'][$code]++;
  115. if($success)
  116. {
  117. $this->statisticData[$ip][$module][$interface]['suc_cost_time'] += $cost_time;
  118. $this->statisticData[$ip][$module][$interface]['suc_count'] ++;
  119. }
  120. else
  121. {
  122. $this->statisticData[$ip][$module][$interface]['fail_cost_time'] += $cost_time;
  123. $this->statisticData[$ip][$module][$interface]['fail_count'] ++;
  124. }
  125. }
  126. /**
  127. * 将统计数据写入磁盘
  128. * @return void
  129. */
  130. public function writeStatisticsToDisk()
  131. {
  132. $time = time();
  133. // 循环将每个ip的统计数据写入磁盘
  134. foreach($this->statisticData as $ip => $mod_if_data)
  135. {
  136. foreach($mod_if_data as $module=>$items)
  137. {
  138. // 文件夹不存在则创建一个
  139. $file_dir = WORKERMAN_LOG_DIR . $this->statisticDir.$module;
  140. if(!is_dir($file_dir))
  141. {
  142. umask(0);
  143. mkdir($file_dir, 0777, true);
  144. }
  145. // 依次写入磁盘
  146. foreach($items as $interface=>$data)
  147. {
  148. file_put_contents($file_dir. "/{$interface}|".date('Y-m-d'), "$ip\t$time\t{$data['suc_count']}\t{$data['suc_cost_time']}\t{$data['fail_count']}\t{$data['fail_cost_time']}\t".json_encode($data['code'])."\n", FILE_APPEND | LOCK_EX);
  149. }
  150. }
  151. }
  152. // 清空统计
  153. $this->statisticData = array();
  154. }
  155. /**
  156. * 将日志数据写入磁盘
  157. * @return void
  158. */
  159. public function writeLogToDisk()
  160. {
  161. // 没有统计数据则返回
  162. if(empty($this->logBuffer))
  163. {
  164. return;
  165. }
  166. // 写入磁盘
  167. file_put_contents(WORKERMAN_LOG_DIR . $this->logDir . date('Y-m-d'), $this->logBuffer, FILE_APPEND | LOCK_EX);
  168. $this->logBuffer = '';
  169. }
  170. /**
  171. * 初始化
  172. * 统计目录检查
  173. * 初始化任务
  174. * @see Man\Core.SocketWorker::onStart()
  175. */
  176. protected function onStart()
  177. {
  178. // 初始化目录
  179. umask(0);
  180. $statistic_dir = WORKERMAN_LOG_DIR . $this->statisticDir;
  181. if(!is_dir($statistic_dir))
  182. {
  183. mkdir($statistic_dir, 0777, true);
  184. }
  185. $log_dir = WORKERMAN_LOG_DIR . $this->logDir;
  186. if(!is_dir($log_dir))
  187. {
  188. mkdir($log_dir, 0777, true);
  189. }
  190. // 初始化任务
  191. \Man\Core\Lib\Task::init($this->event);
  192. // 定时保存统计数据
  193. \Man\Core\Lib\Task::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeStatisticsToDisk'));
  194. \Man\Core\Lib\Task::add(self::WRITE_PERIOD_LENGTH, array($this, 'writeLogToDisk'));
  195. // 定时清理不用的统计数据
  196. \Man\Core\Lib\Task::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(WORKERMAN_LOG_DIR . $this->statisticDir, self::EXPIRED_TIME));
  197. \Man\Core\Lib\Task::add(self::CLEAR_PERIOD_LENGTH, array($this, 'clearDisk'), array(WORKERMAN_LOG_DIR . $this->logDir, self::EXPIRED_TIME));
  198. }
  199. /**
  200. * 进程停止时需要将数据写入磁盘
  201. * @see Man\Core.SocketWorker::onStop()
  202. */
  203. protected function onStop()
  204. {
  205. $this->writeLogToDisk();
  206. $this->writeStatisticsToDisk();
  207. }
  208. /**
  209. * 清除磁盘数据
  210. * @param string $file
  211. * @param int $exp_time
  212. */
  213. protected function clearDisk($file = null, $exp_time = 86400)
  214. {
  215. $time_now = time();
  216. if(is_file($file))
  217. {
  218. $mtime = filemtime($file);
  219. if(!$mtime)
  220. {
  221. $this->notice("filemtime $file fail");
  222. return;
  223. }
  224. if($time_now - $mtime > $exp_time)
  225. {
  226. unlink($file);
  227. }
  228. return;
  229. }
  230. foreach (glob($file."/*") as $file_name) {
  231. if(is_dir($file_name))
  232. {
  233. $this->clearDisk($file_name, $exp_time);
  234. continue;
  235. }
  236. $mtime = filemtime($file);
  237. if(!$mtime)
  238. {
  239. $this->notice("filemtime $file fail");
  240. return;
  241. }
  242. if($time_now - $mtime > $exp_time)
  243. {
  244. unlink($file_name);
  245. }
  246. }
  247. }
  248. }
  249. /**
  250. *
  251. * struct statisticPortocol
  252. * {
  253. * unsigned char module_name_len;
  254. * unsigned char interface_name_len;
  255. * float cost_time;
  256. * unsigned char success;
  257. * int code;
  258. * unsigned short msg_len;
  259. * unsigned int time;
  260. * char[module_name_len] module_name;
  261. * char[interface_name_len] interface_name;
  262. * char[msg_len] msg;
  263. * }
  264. *
  265. * @author valkor
  266. */
  267. class StatisticProtocol
  268. {
  269. /**
  270. * 包头长度
  271. * @var integer
  272. */
  273. const PACKEGE_FIXED_LENGTH = 17;
  274. /**
  275. * udp 包最大长度
  276. * @var integer
  277. */
  278. const MAX_UDP_PACKGE_SIZE = 65507;
  279. /**
  280. * char类型能保存的最大数值
  281. * @var integer
  282. */
  283. const MAX_CHAR_VALUE = 255;
  284. /**
  285. * usigned short 能保存的最大数值
  286. * @var integer
  287. */
  288. const MAX_UNSIGNED_SHORT_VALUE = 65535;
  289. /**
  290. * 编码
  291. * @param string $module
  292. * @param string $interface
  293. * @param float $cost_time
  294. * @param int $success
  295. * @param int $code
  296. * @param string $msg
  297. * @return string
  298. */
  299. public static function encode($module, $interface , $cost_time, $success, $code = 0,$msg = '')
  300. {
  301. // 防止模块名过长
  302. if(strlen($module) > self::MAX_CHAR_VALUE)
  303. {
  304. $module = substr($module, 0, self::MAX_CHAR_VALUE);
  305. }
  306. // 防止接口名过长
  307. if(strlen($interface) > self::MAX_CHAR_VALUE)
  308. {
  309. $interface = substr($interface, 0, self::MAX_CHAR_VALUE);
  310. }
  311. // 防止msg过长
  312. $module_name_length = strlen($module);
  313. $interface_name_length = strlen($interface);
  314. $avalible_size = self::MAX_UDP_PACKGE_SIZE - self::PACKEGE_FIXED_LENGTH - $module_name_length - $interface_name_length;
  315. if(strlen($msg) > $avalible_size)
  316. {
  317. $msg = substr($msg, 0, $avalible_size);
  318. }
  319. // 打包
  320. return pack('CCfCNnN', $module_name_length, $interface_name_length, $cost_time, $success ? 1 : 0, $code, strlen($msg), time()).$module.$interface.$msg;
  321. }
  322. /**
  323. * 解包
  324. * @param string $bin_data
  325. * @return array
  326. */
  327. public static function decode($bin_data)
  328. {
  329. // 解包
  330. $data = unpack("Cmodule_name_len/Cinterface_name_len/fcost_time/Csuccess/Ncode/nmsg_len/Ntime", $data);
  331. $module = substr($bin_data, self::PACKEGE_FIXED_LENGTH, $data['module_name_len']);
  332. $interface = substr($bin_data, self::PACKEGE_FIXED_LENGTH + $data['module_name_len'], $data['interface_name_len']);
  333. $msg = substr($bin_data, self::PACKEGE_FIXED_LENGTH + $data['module_name_len'] + $data['interface_name_len']);
  334. return array(
  335. 'module' => $module,
  336. 'interface' => $interface,
  337. 'cost_time' => $data['cost_time'],
  338. 'success' => $data['success'],
  339. 'time' => $data['time'],
  340. 'code' => $data['code'],
  341. 'msg' => $msg,
  342. );
  343. }
  344. }