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.

daemon.php 5.2KB

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