Worker.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace app\worker;
  3. use Illuminate\Support\Facades\Redis;
  4. use Workerman\Lib\Timer;
  5. class Worker extends \Workerman\Worker
  6. {
  7. /**
  8. * Run all worker instances.
  9. *
  10. * @return void
  11. */
  12. public static function runAll()
  13. {
  14. static::checkSapiEnv();
  15. static::init();
  16. static::lock();
  17. static::parseCommand();
  18. static::daemonize();
  19. static::initWorkers();
  20. static::installSignal();
  21. static::saveMasterPid();
  22. static::unlock();
  23. static::displayUI();
  24. static::forkWorkers();
  25. static::resetStd();
  26. static::monitorWorkers();
  27. }
  28. /**
  29. * Lock.
  30. *
  31. * @return void
  32. */
  33. protected static function lock()
  34. {
  35. Redis::lock('WorkerStarting',gethostname());
  36. }
  37. /**
  38. * Unlock.
  39. *
  40. * @return void
  41. */
  42. protected static function unlock()
  43. {
  44. Redis::unlock('WorkerStarting');
  45. }
  46. /**
  47. * Init.
  48. *
  49. * @return void
  50. */
  51. protected static function init()
  52. {
  53. \set_error_handler(function ($code, $msg, $file, $line) {
  54. \Workerman\Worker::safeEcho("$msg in file $file on line $line\n");
  55. });
  56. // Start file.
  57. static::$_startFile = __FILE__;
  58. $unique_prefix = \str_replace('/', '_', gethostname() . static::$_startFile);
  59. // Pid file.
  60. if (empty(static::$pidFile)) {
  61. static::$pidFile = storage_path('logs') . "/$unique_prefix.pid";
  62. }
  63. // Log file.
  64. if (empty(static::$logFile)) {
  65. static::$logFile = storage_path('logs') . '/workerman.log';
  66. }
  67. $log_file = (string)static::$logFile;
  68. if (!\is_file($log_file)) {
  69. \touch($log_file);
  70. \chmod($log_file, 0622);
  71. }
  72. // State.
  73. static::$_status = static::STATUS_STARTING;
  74. // For statistics.
  75. static::$_globalStatistics['start_timestamp'] = \time();
  76. static::$_statisticsFile = \sys_get_temp_dir() . "/$unique_prefix.status";
  77. // Process title.
  78. static::setProcessTitle(static::$processTitle . ': master process start_file=' . static::$_startFile);
  79. // Init data for worker id.
  80. static::initId();
  81. // Timer init.
  82. Timer::init();
  83. }
  84. /**
  85. * @param string $msg
  86. */
  87. public static function log($msg)
  88. {
  89. $msg = $msg . "\n";
  90. if (!static::$daemonize) {
  91. static::safeEcho($msg);
  92. }
  93. //todo 取消写入日志,不断重试写入导致磁盘满空间
  94. // \file_put_contents((string)static::$logFile, \date('Y-m-d H:i:s') . ' ' . 'pid:'
  95. // . (static::$_OS === \OS_TYPE_LINUX ? \posix_getpid() : 1) . ' ' . $msg, \FILE_APPEND | \LOCK_EX);
  96. }
  97. }