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.

216 lines
5.2KB

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