UserTrafficAbnormalAutoWarning.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\User;
  4. use App\Models\UserHourlyDataFlow;
  5. use App\Notifications\DataAnomaly;
  6. use Illuminate\Console\Command;
  7. use Log;
  8. use Notification;
  9. class UserTrafficAbnormalAutoWarning extends Command
  10. {
  11. protected $signature = 'userTrafficAbnormalAutoWarning';
  12. protected $description = '用户流量异常警告';
  13. public function handle(): void
  14. {
  15. $jobStartTime = microtime(true);
  16. // 用户流量异常警告
  17. if (sysConfig('data_anomaly_notification')) {
  18. $this->userTrafficAbnormalWarning();
  19. }
  20. $jobEndTime = microtime(true);
  21. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  22. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  23. }
  24. // 用户流量异常警告
  25. private function userTrafficAbnormalWarning(): void
  26. {
  27. // 1小时内流量异常用户(多往前取5分钟,防止数据统计任务执行时间过长导致没有数据)
  28. $userTotalTrafficLogs = UserHourlyDataFlow::whereNodeId(null)
  29. ->where('total', '>', MB * 50)
  30. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
  31. ->groupBy('user_id')
  32. ->selectRaw('user_id, sum(total) as totalTraffic')
  33. ->get(); // 只统计100M以上的记录,加快查询速度
  34. $trafficBanValue = sysConfig('traffic_ban_value');
  35. foreach ($userTotalTrafficLogs->load('user') as $log) {
  36. // 推送通知管理员
  37. if ($log->totalTraffic > $trafficBanValue * GB) {
  38. $user = $log->user;
  39. $traffic = UserHourlyDataFlow::userRecentUsed($user->id)
  40. ->selectRaw('user_id, sum(`u`) as totalU, sum(`d`) as totalD, sum(total) as totalTraffic')
  41. ->first();
  42. Notification::send(User::permission('admin.user.edit,update')->orWhere(function ($query) {
  43. return $query->role('Super Admin');
  44. })->get(), new DataAnomaly($user->id, flowAutoShow($traffic->totalU), flowAutoShow($traffic->totalD), flowAutoShow($traffic->totalTraffic)));
  45. }
  46. }
  47. }
  48. }