UserHourlyTrafficMonitoring.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. $jobStartTime = 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. $jobEndTime = microtime(true);
  25. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  26. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  27. }
  28. private function statisticsByUser(User $user)
  29. {
  30. $logs = $user->dataFlowLogs()
  31. ->whereBetween('log_time', [strtotime('-1 hour'), time()])
  32. ->groupBy('node_id')
  33. ->selectRaw('node_id, sum(`u`) as u, sum(`d`) as d')
  34. ->get();
  35. if ($logs->isNotEmpty()) { // 有数据才记录
  36. $data = $logs->each(function ($log) {
  37. $log->total = $log->u + $log->d;
  38. $log->traffic = flowAutoShow($log->total);
  39. })->flatten()->toArray();
  40. $data[] = [ // 每小时节点流量合计
  41. 'u' => $logs->sum('u'),
  42. 'd' => $logs->sum('d'),
  43. 'total' => $logs->sum('total'),
  44. 'traffic' => flowAutoShow($logs->sum('total')),
  45. ];
  46. $user->hourlyDataFlows()->createMany($data);
  47. if ($this->data_anomaly_notification) { // 用户流量异常警告
  48. $traffic = $user->hourlyDataFlows()->whereNodeId(null)->latest()->first();
  49. if ($traffic->total >= $this->traffic_ban_value) {
  50. Notification::send(User::find(1), new DataAnomaly($user->username, flowAutoShow($traffic->u), flowAutoShow($traffic->d), flowAutoShow($traffic->traffic)));
  51. }
  52. }
  53. }
  54. }
  55. }