UserHourlyTrafficMonitoring.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\User;
  4. use App\Notifications\DataAnomaly;
  5. use Illuminate\Console\Command;
  6. use Log;
  7. use Notification;
  8. class UserHourlyTrafficMonitoring extends Command
  9. {
  10. protected $signature = 'userHourlyTrafficMonitoring';
  11. protected $description = '用户每小时流量监控';
  12. private $data_anomaly_notification;
  13. private $traffic_ban_value;
  14. public function handle()
  15. {
  16. $jobTime = microtime(true);
  17. $this->data_anomaly_notification = sysConfig('data_anomaly_notification');
  18. $this->traffic_ban_value = sysConfig('traffic_ban_value') * GB;
  19. User::activeUser()->with('dataFlowLogs')->WhereHas('dataFlowLogs')->chunk(config('tasks.chunk'), function ($users) {
  20. foreach ($users as $user) {
  21. $this->statisticsByUser($user);
  22. }
  23. });
  24. $jobTime = round((microtime(true) - $jobTime), 4);
  25. Log::info('---【'.$this->description.'】完成---,耗时'.$jobTime.'秒');
  26. }
  27. private function statisticsByUser(User $user)
  28. {
  29. $created_at = date('Y-m-d H:59:59', strtotime('-1 hour'));
  30. $time = strtotime($created_at);
  31. $logs = $user->dataFlowLogs()
  32. ->whereBetween('log_time', [$time - 3599, $time])
  33. ->groupBy('node_id')
  34. ->selectRaw('node_id, sum(`u`) as u, sum(`d`) as d')
  35. ->get();
  36. if ($logs->isNotEmpty()) { // 有数据才记录
  37. $data = $logs->each(function ($log) use ($created_at) {
  38. $log->total = $log->u + $log->d;
  39. $log->traffic = flowAutoShow($log->total);
  40. $log->created_at = $created_at;
  41. })->flatten()->toArray();
  42. $data[] = [ // 每小时节点流量合计
  43. 'u' => $logs->sum('u'),
  44. 'd' => $logs->sum('d'),
  45. 'total' => $logs->sum('total'),
  46. 'traffic' => flowAutoShow($logs->sum('total')),
  47. 'created_at' => $created_at,
  48. ];
  49. $user->hourlyDataFlows()->createMany($data);
  50. if ($this->data_anomaly_notification) { // 用户流量异常警告
  51. $traffic = $user->hourlyDataFlows()->whereNodeId(null)->latest()->first();
  52. if ($traffic->total >= $this->traffic_ban_value) {
  53. Notification::send(User::find(1), new DataAnomaly($user->username, flowAutoShow($traffic->u), flowAutoShow($traffic->d), flowAutoShow($traffic->traffic)));
  54. }
  55. }
  56. }
  57. }
  58. }