Host.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace app\host;
  3. use app\process\Process;
  4. use Illuminate\Support\Facades\Redis;
  5. class Host
  6. {
  7. public $hostName;
  8. public function __construct($hostName)
  9. {
  10. $this->hostName = $hostName;
  11. }
  12. public function register()
  13. {
  14. Redis::hset('hosts', gethostname(),getmypid());
  15. Redis::expire('hosts',40);
  16. }
  17. public function pids()
  18. {
  19. return Redis::hvals($this->hashKey());
  20. }
  21. public function pidKeys()
  22. {
  23. return Redis::hkeys($this->hashKey());
  24. }
  25. public function clearPid($key)
  26. {
  27. return Redis::hdel($this->hashKey(), $key);
  28. }
  29. public function clearPids()
  30. {
  31. foreach ($this->map() as $key => $pid) {
  32. if (!posix_kill($pid, 0)) {
  33. $this->clearPid($key);
  34. }
  35. }
  36. return true;
  37. }
  38. public function killAll()
  39. {
  40. foreach ($this->pids() as $pid) {
  41. posix_kill($pid, SIGKILL);
  42. }
  43. }
  44. private function hashKey()
  45. {
  46. return 'forkPids:' . $this->hostName;
  47. }
  48. public function numberOfPids()
  49. {
  50. return Redis::hlen($this->hashKey());
  51. }
  52. public function map()
  53. {
  54. return Redis::hgetall($this->hashKey())?:[];
  55. }
  56. public function show()
  57. {
  58. $result = [];
  59. $pids = $this->map();
  60. foreach ($pids as $key=>$pid){
  61. $result[$key] = new Process($pid);
  62. }
  63. return $result;
  64. }
  65. public function pid($key)
  66. {
  67. return Redis::hget($this->hashKey(), $key);
  68. }
  69. public function killProcess($key)
  70. {
  71. Redis::hdel($this->hashKey(), $key);
  72. return posix_kill($this->pid($key), SIGKILL);
  73. }
  74. public function processRunning($key)
  75. {
  76. if (!$this->pid($key)) {
  77. return false;
  78. }
  79. return posix_kill($this->pid($key), 0);
  80. }
  81. }