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.
 
 
 
 
 
 

235 lines
5.8 KiB

  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * @copyright Copyright (C) 2020, Friendica
  5. *
  6. * @license GNU AGPL version 3 or any later version
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. * Run the worker from a daemon.
  22. *
  23. * This script was taken from http://php.net/manual/en/function.pcntl-fork.php
  24. */
  25. if (php_sapi_name() !== 'cli') {
  26. header($_SERVER["SERVER_PROTOCOL"] . ' 403 Forbidden');
  27. exit();
  28. }
  29. use Dice\Dice;
  30. use Friendica\Core\Logger;
  31. use Friendica\Core\Worker;
  32. use Friendica\Database\DBA;
  33. use Friendica\DI;
  34. use Psr\Log\LoggerInterface;
  35. // Get options
  36. $shortopts = 'f';
  37. $longopts = ['foreground'];
  38. $options = getopt($shortopts, $longopts);
  39. // Ensure that daemon.php is executed from the base path of the installation
  40. if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
  41. $directory = dirname($_SERVER["argv"][0]);
  42. if (substr($directory, 0, 1) != "/") {
  43. $directory = $_SERVER["PWD"] . "/" . $directory;
  44. }
  45. $directory = realpath($directory . "/..");
  46. chdir($directory);
  47. }
  48. require dirname(__DIR__) . '/vendor/autoload.php';
  49. $dice = (new Dice())->addRules(include __DIR__ . '/../static/dependencies.config.php');
  50. $dice = $dice->addRule(LoggerInterface::class,['constructParams' => ['daemon']]);
  51. DI::init($dice);
  52. $a = DI::app();
  53. if (DI::mode()->isInstall()) {
  54. die("Friendica isn't properly installed yet.\n");
  55. }
  56. DI::config()->load();
  57. if (empty(DI::config()->get('system', 'pidfile'))) {
  58. die(<<<TXT
  59. Please set system.pidfile in config/local.config.php. For example:
  60. 'system' => [
  61. 'pidfile' => '/path/to/daemon.pid',
  62. ],
  63. TXT
  64. );
  65. }
  66. $pidfile = DI::config()->get('system', 'pidfile');
  67. if (in_array("start", $_SERVER["argv"])) {
  68. $mode = "start";
  69. }
  70. if (in_array("stop", $_SERVER["argv"])) {
  71. $mode = "stop";
  72. }
  73. if (in_array("status", $_SERVER["argv"])) {
  74. $mode = "status";
  75. }
  76. $foreground = array_key_exists('f', $options) || array_key_exists('foreground', $options);
  77. if (!isset($mode)) {
  78. die("Please use either 'start', 'stop' or 'status'.\n");
  79. }
  80. if (empty($_SERVER["argv"][0])) {
  81. die("Unexpected script behaviour. This message should never occur.\n");
  82. }
  83. $pid = null;
  84. if (is_readable($pidfile)) {
  85. $pid = intval(file_get_contents($pidfile));
  86. }
  87. if (empty($pid) && in_array($mode, ["stop", "status"])) {
  88. DI::config()->set('system', 'worker_daemon_mode', false);
  89. die("Pidfile wasn't found. Is the daemon running?\n");
  90. }
  91. if ($mode == "status") {
  92. if (posix_kill($pid, 0)) {
  93. die("Daemon process $pid is running.\n");
  94. }
  95. unlink($pidfile);
  96. DI::config()->set('system', 'worker_daemon_mode', false);
  97. die("Daemon process $pid isn't running.\n");
  98. }
  99. if ($mode == "stop") {
  100. posix_kill($pid, SIGTERM);
  101. unlink($pidfile);
  102. Logger::notice("Worker daemon process was killed", ["pid" => $pid]);
  103. DI::config()->set('system', 'worker_daemon_mode', false);
  104. die("Worker daemon process $pid was killed.\n");
  105. }
  106. if (!empty($pid) && posix_kill($pid, 0)) {
  107. die("Daemon process $pid is already running.\n");
  108. }
  109. Logger::notice('Starting worker daemon.', ["pid" => $pid]);
  110. if (!$foreground) {
  111. echo "Starting worker daemon.\n";
  112. // Switch over to daemon mode.
  113. if ($pid = pcntl_fork()) {
  114. return; // Parent
  115. }
  116. fclose(STDIN); // Close all of the standard
  117. // Enabling this seem to block a running php process with 100% CPU usage when there is an outpout
  118. // fclose(STDOUT); // file descriptors as we
  119. // fclose(STDERR); // are running as a daemon.
  120. DBA::disconnect();
  121. register_shutdown_function('shutdown');
  122. if (posix_setsid() < 0) {
  123. return;
  124. }
  125. if ($pid = pcntl_fork()) {
  126. return; // Parent
  127. }
  128. $pid = getmypid();
  129. file_put_contents($pidfile, $pid);
  130. // We lose the database connection upon forking
  131. DBA::reconnect();
  132. }
  133. DI::config()->set('system', 'worker_daemon_mode', true);
  134. // Just to be sure that this script really runs endlessly
  135. set_time_limit(0);
  136. $wait_interval = intval(DI::config()->get('system', 'cron_interval', 5)) * 60;
  137. $do_cron = true;
  138. $last_cron = 0;
  139. // Now running as a daemon.
  140. while (true) {
  141. if (!$do_cron && ($last_cron + $wait_interval) < time()) {
  142. Logger::info('Forcing cron worker call.', ["pid" => $pid]);
  143. $do_cron = true;
  144. }
  145. if ($do_cron || (!DI::process()->isMaxLoadReached() && Worker::entriesExists() && Worker::isReady())) {
  146. Worker::spawnWorker($do_cron);
  147. } else {
  148. Logger::info('Cool down', ['pid' => $pid]);
  149. sleep(10);
  150. }
  151. if ($do_cron) {
  152. // We force a reconnect of the database connection.
  153. // This is done to ensure that the connection don't get lost over time.
  154. DBA::reconnect();
  155. $last_cron = time();
  156. }
  157. Logger::info("Sleeping", ["pid" => $pid]);
  158. $start = time();
  159. do {
  160. $seconds = (time() - $start);
  161. // logarithmic wait time calculation.
  162. // Background: After jobs had been started, they often fork many workers.
  163. // To not waste too much time, the sleep period increases.
  164. $arg = (($seconds + 1) / ($wait_interval / 9)) + 1;
  165. $sleep = round(log10($arg) * 1000000, 0);
  166. usleep($sleep);
  167. $timeout = ($seconds >= $wait_interval);
  168. } while (!$timeout && !Worker::IPCJobsExists());
  169. if ($timeout) {
  170. $do_cron = true;
  171. Logger::info("Woke up after $wait_interval seconds.", ["pid" => $pid, 'sleep' => $wait_interval]);
  172. } else {
  173. $do_cron = false;
  174. Logger::info("Worker jobs are calling to be forked.", ["pid" => $pid]);
  175. }
  176. }
  177. function shutdown() {
  178. posix_kill(posix_getpid(), SIGHUP);
  179. }