Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

209 lines
4.8KB

  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * @file bin/daemon.php
  5. * @brief Run the worker from a daemon.
  6. *
  7. * This script was taken from http://php.net/manual/en/function.pcntl-fork.php
  8. */
  9. use Dice\Dice;
  10. use Friendica\Core\Config;
  11. use Friendica\Core\Logger;
  12. use Friendica\Core\Worker;
  13. use Friendica\Database\DBA;
  14. use Psr\Log\LoggerInterface;
  15. // Get options
  16. $shortopts = 'f';
  17. $longopts = ['foreground'];
  18. $options = getopt($shortopts, $longopts);
  19. // Ensure that daemon.php is executed from the base path of the installation
  20. if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
  21. $directory = dirname($_SERVER["argv"][0]);
  22. if (substr($directory, 0, 1) != "/") {
  23. $directory = $_SERVER["PWD"] . "/" . $directory;
  24. }
  25. $directory = realpath($directory . "/..");
  26. chdir($directory);
  27. }
  28. require dirname(__DIR__) . '/vendor/autoload.php';
  29. $dice = (new Dice())->addRules(include __DIR__ . '/../static/dependencies.config.php');
  30. $dice = $dice->addRule(LoggerInterface::class,['constructParams' => ['daemon']]);
  31. \Friendica\BaseObject::setDependencyInjection($dice);
  32. $a = \Friendica\BaseObject::getApp();
  33. if ($a->getMode()->isInstall()) {
  34. die("Friendica isn't properly installed yet.\n");
  35. }
  36. Config::load();
  37. if (empty(Config::get('system', 'pidfile'))) {
  38. die(<<<TXT
  39. Please set system.pidfile in config/local.config.php. For example:
  40. 'system' => [
  41. 'pidfile' => '/path/to/daemon.pid',
  42. ],
  43. TXT
  44. );
  45. }
  46. $pidfile = Config::get('system', 'pidfile');
  47. if (in_array("start", $_SERVER["argv"])) {
  48. $mode = "start";
  49. }
  50. if (in_array("stop", $_SERVER["argv"])) {
  51. $mode = "stop";
  52. }
  53. if (in_array("status", $_SERVER["argv"])) {
  54. $mode = "status";
  55. }
  56. $foreground = array_key_exists('f', $options) || array_key_exists('foreground', $options);
  57. if (!isset($mode)) {
  58. die("Please use either 'start', 'stop' or 'status'.\n");
  59. }
  60. if (empty($_SERVER["argv"][0])) {
  61. die("Unexpected script behaviour. This message should never occur.\n");
  62. }
  63. $pid = null;
  64. if (is_readable($pidfile)) {
  65. $pid = intval(file_get_contents($pidfile));
  66. }
  67. if (empty($pid) && in_array($mode, ["stop", "status"])) {
  68. Config::set('system', 'worker_daemon_mode', false);
  69. die("Pidfile wasn't found. Is the daemon running?\n");
  70. }
  71. if ($mode == "status") {
  72. if (posix_kill($pid, 0)) {
  73. die("Daemon process $pid is running.\n");
  74. }
  75. unlink($pidfile);
  76. Config::set('system', 'worker_daemon_mode', false);
  77. die("Daemon process $pid isn't running.\n");
  78. }
  79. if ($mode == "stop") {
  80. posix_kill($pid, SIGTERM);
  81. unlink($pidfile);
  82. Logger::notice("Worker daemon process was killed", ["pid" => $pid]);
  83. Config::set('system', 'worker_daemon_mode', false);
  84. die("Worker daemon process $pid was killed.\n");
  85. }
  86. if (!empty($pid) && posix_kill($pid, 0)) {
  87. die("Daemon process $pid is already running.\n");
  88. }
  89. Logger::notice('Starting worker daemon.', ["pid" => $pid]);
  90. if (!$foreground) {
  91. echo "Starting worker daemon.\n";
  92. // Switch over to daemon mode.
  93. if ($pid = pcntl_fork()) {
  94. return; // Parent
  95. }
  96. fclose(STDIN); // Close all of the standard
  97. // Enabling this seem to block a running php process with 100% CPU usage when there is an outpout
  98. // fclose(STDOUT); // file descriptors as we
  99. // fclose(STDERR); // are running as a daemon.
  100. DBA::disconnect();
  101. register_shutdown_function('shutdown');
  102. if (posix_setsid() < 0) {
  103. return;
  104. }
  105. if ($pid = pcntl_fork()) {
  106. return; // Parent
  107. }
  108. $pid = getmypid();
  109. file_put_contents($pidfile, $pid);
  110. // We lose the database connection upon forking
  111. DBA::reconnect();
  112. }
  113. Config::set('system', 'worker_daemon_mode', true);
  114. // Just to be sure that this script really runs endlessly
  115. set_time_limit(0);
  116. $wait_interval = intval(Config::get('system', 'cron_interval', 5)) * 60;
  117. $do_cron = true;
  118. $last_cron = 0;
  119. // Now running as a daemon.
  120. while (true) {
  121. if (!$do_cron && ($last_cron + $wait_interval) < time()) {
  122. Logger::info('Forcing cron worker call.', ["pid" => $pid]);
  123. $do_cron = true;
  124. }
  125. Worker::spawnWorker($do_cron);
  126. if ($do_cron) {
  127. // We force a reconnect of the database connection.
  128. // This is done to ensure that the connection don't get lost over time.
  129. DBA::reconnect();
  130. $last_cron = time();
  131. }
  132. Logger::info("Sleeping", ["pid" => $pid]);
  133. $start = time();
  134. do {
  135. $seconds = (time() - $start);
  136. // logarithmic wait time calculation.
  137. // Background: After jobs had been started, they often fork many workers.
  138. // To not waste too much time, the sleep period increases.
  139. $arg = (($seconds + 1) / ($wait_interval / 9)) + 1;
  140. $sleep = round(log10($arg) * 1000000, 0);
  141. usleep($sleep);
  142. $timeout = ($seconds >= $wait_interval);
  143. } while (!$timeout && !Worker::IPCJobsExists());
  144. if ($timeout) {
  145. $do_cron = true;
  146. Logger::info("Woke up after $wait_interval seconds.", ["pid" => $pid, 'sleep' => $wait_interval]);
  147. } else {
  148. $do_cron = false;
  149. Logger::info("Worker jobs are calling to be forked.", ["pid" => $pid]);
  150. }
  151. }
  152. function shutdown() {
  153. posix_kill(posix_getpid(), SIGHUP);
  154. }