StatisticWorker.php 11 KB

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