NodeObserver.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Observers;
  3. use App\Jobs\VNet\reloadNode;
  4. use App\Models\Node;
  5. use App\Models\NodeAuth;
  6. use App\Models\RuleGroup;
  7. use App\Models\UserGroup;
  8. use App\Services\NodeService;
  9. use Log;
  10. use Str;
  11. class NodeObserver
  12. {
  13. public function saved(Node $node): void
  14. {
  15. (new NodeService())->getNodeGeo($node->id);
  16. }
  17. public function created(Node $node): void
  18. {
  19. $auth = new NodeAuth();
  20. $auth->node_id = $node->id;
  21. $auth->key = Str::random();
  22. $auth->secret = Str::random(8);
  23. if (!$auth->save()) {
  24. Log::error('节点生成-自动生成授权时出现错误,请稍后自行生成授权!');
  25. }
  26. }
  27. public function updated(Node $node): void
  28. {
  29. if ($node->type === 4) {
  30. reloadNode::dispatchNow(Node::whereId($node->id)->get());
  31. }
  32. }
  33. public function deleted(Node $node): void
  34. {
  35. // 删除分组关联、节点标签、节点相关日志
  36. $node->labels()->delete();
  37. $node->heartBeats()->delete();
  38. $node->onlineLogs()->delete();
  39. $node->pingLogs()->delete();
  40. $node->dailyDataFlows()->delete();
  41. $node->hourlyDataFlows()->delete();
  42. $node->rules()->delete();
  43. $node->ruleGroup()->delete();
  44. $node->auth()->delete();
  45. // 断开审计规则分组节点联系
  46. foreach (RuleGroup::all() as $ruleGroup) {
  47. $nodes = $ruleGroup->nodes;
  48. if ($nodes && in_array($node->id, $nodes, true)) {
  49. $ruleGroup->nodes = array_merge(array_diff($nodes, [$node->id]));
  50. $ruleGroup->save();
  51. }
  52. }
  53. // 断开用户分组控制节点联系
  54. foreach (UserGroup::all() as $userGroup) {
  55. $nodes = $userGroup->nodes;
  56. if ($nodes && in_array($node->id, $nodes, true)) {
  57. $userGroup->nodes = array_merge(array_diff($nodes, [$node->id]));
  58. $userGroup->save();
  59. }
  60. }
  61. }
  62. }