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.

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