StatisticWorker.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. require_once WORKERMAN_ROOT_DIR . 'Core/SocketWorker.php';
  3. /**
  4. *
  5. * 接口成功率统计worker
  6. * 定时写入磁盘,用来统计请求量、延迟、波动等信息
  7. * @author walkor <worker-man@qq.com>
  8. */
  9. class StatisticWorker extends WORKERMAN\Core\SocketWorker
  10. {
  11. /**
  12. * 最大buffer长度
  13. * @var ineger
  14. */
  15. const MAX_BUFFER_SIZE = 524288;
  16. /**
  17. * 上次写日志数据到磁盘的时间
  18. * @var integer
  19. */
  20. protected $logLastWriteTime = 0;
  21. /**
  22. * 上次写统计数据到磁盘的时间
  23. * @var integer
  24. */
  25. protected $stLastWriteTime = 0;
  26. /**
  27. * 上次清理磁盘的时间
  28. * @var integer
  29. */
  30. protected $lastClearTime = 0;
  31. /**
  32. * 缓冲的日志数据
  33. * @var string
  34. */
  35. protected $logBuffer = '';
  36. /**
  37. * 缓冲的统计数据
  38. * modid=>interface=>['code'=>[xx=>count,xx=>count],'suc_cost_time'=>xx,'fail_cost_time'=>xx, 'suc_count'=>xx, 'fail_count'=>xx, 'time'=>xxx]
  39. * @var array
  40. */
  41. protected $statisticData = array();
  42. /**
  43. * 多长时间写一次log数据
  44. * @var integer
  45. */
  46. protected $logSendTimeLong = 20;
  47. /**
  48. * 多长时间写一次统计数据
  49. * @var integer
  50. */
  51. protected $stSendTimeLong = 300;
  52. /**
  53. * 多长时间清除一次统计数据
  54. * @var integer
  55. */
  56. protected $clearTimeLong = 86400;
  57. /**
  58. * 日志过期时间 14days
  59. * @var integer
  60. */
  61. protected $logExpTimeLong = 1296000;
  62. /**
  63. * 统计结果过期时间 14days
  64. * @var integer
  65. */
  66. protected $stExpTimeLong = 1296000;
  67. /**
  68. * 固定包长
  69. * @var integer
  70. */
  71. const PACKEGE_FIXED_LENGTH = 25;
  72. /**
  73. * 默认只收1个包
  74. * 上报包的格式如下
  75. * struct{
  76. * int code, // 返回码
  77. * unsigned int time, // 时间
  78. * float cost_time, // 消耗时间 单位秒 例如1.xxx
  79. * unsigned int source_ip, // 来源ip
  80. * unsigned int target_ip, // 目标ip
  81. * unsigned char success, // 是否成功
  82. * unsigned char module_name_length, // 模块名字长度
  83. * unsigned char interface_name_length,//接口名字长度
  84. * unsigned short msg_length, // 日志信息长度
  85. * unsigned char[module_name_length] module, // 模块名字
  86. * unsigned char[interface_name_length] interface, // 接口名字
  87. * char[msg_length] msg // 日志内容
  88. * }
  89. * @see Worker::dealInput()
  90. */
  91. public function dealInput($recv_str)
  92. {
  93. return 0;
  94. }
  95. /**
  96. * 处理上报的数据 log buffer满的时候写入磁盘
  97. * @see Worker::dealProcess()
  98. */
  99. public function dealProcess($recv_str)
  100. {
  101. // 解包
  102. $time_now = time();
  103. $unpack_data = unpack("icode/Itime/fcost_time/Isource_ip/Itarget_ip/Csuccess/Cmodule_name_length/Cinterface_name_length/Smsg_length", $recv_str);
  104. $module = substr($recv_str, self::PACKEGE_FIXED_LENGTH, $unpack_data['module_name_length']);
  105. $interface = substr($recv_str, self::PACKEGE_FIXED_LENGTH + $unpack_data['module_name_length'], $unpack_data['interface_name_length']);
  106. $msg = substr($recv_str, self::PACKEGE_FIXED_LENGTH + $unpack_data['module_name_length'] + $unpack_data['interface_name_length'], $unpack_data['msg_length']);
  107. $msg = str_replace("\n", '<br>', $msg);
  108. $code = $unpack_data['code'];
  109. // 统计调用量、延迟、成功率等信息
  110. if(!isset($this->statisticData[$module]))
  111. {
  112. $this->statisticData[$module] = array();
  113. }
  114. if(!isset($this->statisticData[$module][$interface]))
  115. {
  116. $this->statisticData[$module][$interface] = array('code'=>array(), 'suc_cost_time'=>0, 'fail_cost_time'=>0, 'suc_count'=>0, 'fail_count'=>0, 'time'=>$this->stLastWriteTime);
  117. }
  118. if(!isset($this->statisticData[$module][$interface]['code'][$code]))
  119. {
  120. $this->statisticData[$module][$interface]['code'][$code] = 0;
  121. }
  122. $this->statisticData[$module][$interface]['code'][$code]++;
  123. if($unpack_data['success'])
  124. {
  125. $this->statisticData[$module][$interface]['suc_cost_time'] += $unpack_data['cost_time'];
  126. $this->statisticData[$module][$interface]['suc_count'] ++;
  127. }
  128. else
  129. {
  130. $this->statisticData[$module][$interface]['fail_cost_time'] += $unpack_data['cost_time'];
  131. $this->statisticData[$module][$interface]['fail_count'] ++;
  132. }
  133. // 如果不成功写入日志
  134. if(!$unpack_data['success'])
  135. {
  136. $log_str = date('Y-m-d H:i:s',$unpack_data['time'])."\t{$module}::{$interface}\tcode:{$unpack_data['code']}\tmsg:{$msg}\tsource_ip:".long2ip($unpack_data['source_ip'])."\ttarget_ip:".long2ip($unpack_data['target_ip'])."\n";
  137. // 如果buffer溢出,则写磁盘,并清空buffer
  138. if(strlen($this->logBuffer) + strlen($recv_str) > self::MAX_BUFFER_SIZE)
  139. {
  140. // 写入log数据到磁盘
  141. $this->wirteLogToDisk();
  142. $this->logBuffer = $log_str;
  143. }
  144. else
  145. {
  146. $this->logBuffer .= $log_str;
  147. }
  148. }
  149. }
  150. /**
  151. * 将日志数据写入磁盘
  152. * @return void
  153. */
  154. protected function wirteLogToDisk()
  155. {
  156. // 初始化下一波统计数据
  157. $this->logLastWriteTime = time();
  158. // 有数据才写
  159. if(empty($this->logBuffer))
  160. {
  161. return true;
  162. }
  163. file_put_contents(WORKERMAN_LOG_DIR . 'statistic/log/'.date('Y-m-d', $this->logLastWriteTime), $this->logBuffer, FILE_APPEND | LOCK_EX);
  164. $this->logBuffer = '';
  165. }
  166. /**
  167. * 将统计数据写入磁盘
  168. * @return void
  169. */
  170. protected function wirteStToDisk()
  171. {
  172. // 记录
  173. $this->stLastWriteTime = $this->stLastWriteTime + $this->stSendTimeLong;
  174. // 有数据才写磁盘
  175. if(empty($this->statisticData))
  176. {
  177. return true;
  178. }
  179. $ip = $this->getRemoteIp();
  180. foreach($this->statisticData as $module=>$items)
  181. {
  182. if(!is_dir(WORKERMAN_LOG_DIR . 'statistic/st/'.$module))
  183. {
  184. umask(0);
  185. mkdir(WORKERMAN_LOG_DIR . 'statistic/st/'.$module, 0777, true);
  186. }
  187. foreach($items as $interface=>$data)
  188. {
  189. // modid=>['code'=>[xx=>count,xx=>count],'suc_cost_time'=>xx,'fail_cost_time'=>xx, 'suc_count'=>xx, 'fail_count'=>xx, 'time'=>xxx]
  190. file_put_contents(WORKERMAN_LOG_DIR . "statistic/st/{$module}/{$interface}|".date('Y-m-d',$data['time']-1), "$ip\t{$data['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);
  191. }
  192. }
  193. $this->statisticData = array();
  194. }
  195. /**
  196. * 该worker进程开始服务的时候会触发一次,初始化$logLastWriteTime
  197. * @return bool
  198. */
  199. protected function onStart()
  200. {
  201. // 创建LOG目录
  202. if(!is_dir(WORKERMAN_LOG_DIR . 'statistic/log'))
  203. {
  204. umask(0);
  205. @mkdir(WORKERMAN_LOG_DIR . 'statistic/log', 0777, true);
  206. }
  207. $time_now = time();
  208. $this->logLastWriteTime = $time_now;
  209. $this->stLastWriteTime = $time_now - $time_now%$this->stSendTimeLong;
  210. \WORKERMAN\Core\Lib\Task::init($this->event);
  211. \WORKERMAN\Core\Lib\Task::add(1, array($this, 'onAlarm'));
  212. }
  213. /**
  214. * 该worker进程停止服务的时候会触发一次,保存数据到磁盘
  215. * @return bool
  216. */
  217. protected function onStop()
  218. {
  219. // 发送数据到统计中心
  220. $this->wirteLogToDisk();
  221. $this->wirteStToDisk();
  222. return false;
  223. }
  224. /**
  225. * 每隔一定时间触发一次
  226. * @see Worker::onAlarm()
  227. */
  228. public function onAlarm()
  229. {
  230. $time_now = time();
  231. // 检查距离最后一次发送数据到统计中心的时间是否超过设定时间
  232. if($time_now - $this->logLastWriteTime >= $this->logSendTimeLong)
  233. {
  234. // 发送数据到统计中心
  235. $this->wirteLogToDisk();
  236. }
  237. // 检查是否到了该发送统计数据的时间
  238. if($time_now - $this->stLastWriteTime >= $this->stSendTimeLong)
  239. {
  240. $this->wirteStToDisk();
  241. }
  242. // 检查是否到了清理数据的时间
  243. if($time_now - $this->lastClearTime >= $this->clearTimeLong)
  244. {
  245. $this->lastClearTime = $time_now;
  246. $this->clearDisk(WORKERMAN_LOG_DIR . 'statistic/log/', $this->logExpTimeLong);
  247. $this->clearDisk(WORKERMAN_LOG_DIR . 'statistic/st/', $this->stExpTimeLong);
  248. }
  249. }
  250. /**
  251. * 清除磁盘数据
  252. * @param string $file
  253. * @param int $exp_time
  254. */
  255. protected function clearDisk($file = null, $exp_time = 86400)
  256. {
  257. $time_now = time();
  258. if(is_file($file))
  259. {
  260. $stat = stat($file);
  261. if(!$stat)
  262. {
  263. $this->notice("stat $file fail");
  264. return;
  265. }
  266. $mtime = $stat['mtime'];
  267. if($time_now - $mtime > $exp_time)
  268. {
  269. unlink($file);
  270. }
  271. return;
  272. }
  273. foreach (glob($file."/*") as $file_name) {
  274. if(is_dir($file_name))
  275. {
  276. $this->clearDisk($file_name, $exp_time);
  277. continue;
  278. }
  279. $stat = stat($file_name);
  280. if(!$stat)
  281. {
  282. $this->notice("stat $file fail");
  283. return;
  284. }
  285. $mtime = $stat['mtime'];
  286. if($time_now - $mtime > $exp_time)
  287. {
  288. unlink($file_name);
  289. }
  290. }
  291. }
  292. }