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.

211 lines
4.9KB

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