update_daemon2.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #!/usr/bin/env php
  2. <?php
  3. set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
  4. get_include_path());
  5. declare(ticks = 1);
  6. chdir(dirname(__FILE__));
  7. define('DISABLE_SESSIONS', true);
  8. require_once "version.php";
  9. require_once "autoload.php";
  10. require_once "functions.php";
  11. require_once "config.php";
  12. // defaults
  13. define_default('PURGE_INTERVAL', 3600); // seconds
  14. define_default('MAX_CHILD_RUNTIME', 1800); // seconds
  15. define_default('MAX_JOBS', 2);
  16. define_default('SPAWN_INTERVAL', DAEMON_SLEEP_INTERVAL); // seconds
  17. require_once "sanity_check.php";
  18. require_once "db.php";
  19. require_once "db-prefs.php";
  20. if (!function_exists('pcntl_fork')) {
  21. die("error: This script requires PHP compiled with PCNTL module.\n");
  22. }
  23. $options = getopt("");
  24. if (!is_array($options)) {
  25. die("error: getopt() failed. ".
  26. "Most probably you are using PHP CGI to run this script ".
  27. "instead of required PHP CLI. Check tt-rss wiki page on updating feeds for ".
  28. "additional information.\n");
  29. }
  30. $master_handlers_installed = false;
  31. $children = array();
  32. $ctimes = array();
  33. $last_checkpoint = -1;
  34. /**
  35. * @SuppressWarnings(unused)
  36. */
  37. function reap_children() {
  38. global $children;
  39. global $ctimes;
  40. $tmp = array();
  41. foreach ($children as $pid) {
  42. if (pcntl_waitpid($pid, $status, WNOHANG) != $pid) {
  43. if (file_is_locked("update_daemon-$pid.lock")) {
  44. array_push($tmp, $pid);
  45. } else {
  46. Debug::log("[reap_children] child $pid seems active but lockfile is unlocked.");
  47. unset($ctimes[$pid]);
  48. }
  49. } else {
  50. Debug::log("[reap_children] child $pid reaped.");
  51. unset($ctimes[$pid]);
  52. }
  53. }
  54. $children = $tmp;
  55. return count($tmp);
  56. }
  57. function check_ctimes() {
  58. global $ctimes;
  59. foreach (array_keys($ctimes) as $pid) {
  60. $started = $ctimes[$pid];
  61. if (time() - $started > MAX_CHILD_RUNTIME) {
  62. Debug::log("[MASTER] child process $pid seems to be stuck, aborting...");
  63. posix_kill($pid, SIGKILL);
  64. }
  65. }
  66. }
  67. /**
  68. * @SuppressWarnings(unused)
  69. */
  70. function sigchld_handler($signal) {
  71. $running_jobs = reap_children();
  72. Debug::log("[SIGCHLD] jobs left: $running_jobs");
  73. pcntl_waitpid(-1, $status, WNOHANG);
  74. }
  75. function shutdown($caller_pid) {
  76. if ($caller_pid == posix_getpid()) {
  77. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  78. Debug::log("removing lockfile (master)...");
  79. unlink(LOCK_DIRECTORY . "/update_daemon.lock");
  80. }
  81. }
  82. }
  83. function task_shutdown() {
  84. $pid = posix_getpid();
  85. if (file_exists(LOCK_DIRECTORY . "/update_daemon-$pid.lock")) {
  86. Debug::log("removing lockfile ($pid)...");
  87. unlink(LOCK_DIRECTORY . "/update_daemon-$pid.lock");
  88. }
  89. }
  90. function sigint_handler() {
  91. Debug::log("[MASTER] SIG_INT received.\n");
  92. shutdown(posix_getpid());
  93. die;
  94. }
  95. function task_sigint_handler() {
  96. Debug::log("[TASK] SIG_INT received.\n");
  97. task_shutdown();
  98. die;
  99. }
  100. pcntl_signal(SIGCHLD, 'sigchld_handler');
  101. $longopts = array("log:",
  102. "log-level:",
  103. "tasks:",
  104. "interval:",
  105. "quiet",
  106. "help");
  107. $options = getopt("", $longopts);
  108. if (isset($options["help"]) ) {
  109. print "Tiny Tiny RSS update daemon.\n\n";
  110. print "Options:\n";
  111. print " --log FILE - log messages to FILE\n";
  112. print " --log-level N - log verbosity level\n";
  113. print " --tasks N - amount of update tasks to spawn\n";
  114. print " default: " . MAX_JOBS . "\n";
  115. print " --interval N - task spawn interval\n";
  116. print " default: " . SPAWN_INTERVAL . " seconds.\n";
  117. print " --quiet - don't output messages to stdout\n";
  118. return;
  119. }
  120. Debug::set_enabled(true);
  121. if (isset($options["log-level"])) {
  122. Debug::set_loglevel((int)$options["log-level"]);
  123. }
  124. if (isset($options["log"])) {
  125. Debug::set_quiet(isset($options['quiet']));
  126. Debug::set_logfile($options["log"]);
  127. Debug::log("Logging to " . $options["log"]);
  128. } else {
  129. if (isset($options['quiet'])) {
  130. Debug::set_loglevel(Debug::$LOG_DISABLED);
  131. }
  132. }
  133. if (isset($options["tasks"])) {
  134. Debug::log("Set to spawn " . $options["tasks"] . " children.");
  135. $max_jobs = $options["tasks"];
  136. } else {
  137. $max_jobs = MAX_JOBS;
  138. }
  139. if (isset($options["interval"])) {
  140. Debug::log("Spawn interval: " . $options["interval"] . " seconds.");
  141. $spawn_interval = $options["interval"];
  142. } else {
  143. $spawn_interval = SPAWN_INTERVAL;
  144. }
  145. // let's enforce a minimum spawn interval as to not forkbomb the host
  146. $spawn_interval = max(60, $spawn_interval);
  147. Debug::log("Spawn interval: $spawn_interval sec");
  148. if (file_is_locked("update_daemon.lock")) {
  149. die("error: Can't create lockfile. ".
  150. "Maybe another daemon is already running.\n");
  151. }
  152. // Try to lock a file in order to avoid concurrent update.
  153. $lock_handle = make_lockfile("update_daemon.lock");
  154. if (!$lock_handle) {
  155. die("error: Can't create lockfile. ".
  156. "Maybe another daemon is already running.\n");
  157. }
  158. $schema_version = get_schema_version();
  159. if ($schema_version != SCHEMA_VERSION) {
  160. die("Schema version is wrong, please upgrade the database.\n");
  161. }
  162. // Protip: children close shared database handle when terminating, it's a bad idea to
  163. // do database stuff on main process from now on.
  164. while (true) {
  165. // Since sleep is interupted by SIGCHLD, we need another way to
  166. // respect the spawn interval
  167. $next_spawn = $last_checkpoint + $spawn_interval - time();
  168. if ($next_spawn % 60 == 0) {
  169. $running_jobs = count($children);
  170. Debug::log("[MASTER] active jobs: $running_jobs, next spawn at $next_spawn sec.");
  171. }
  172. if ($last_checkpoint + $spawn_interval < time()) {
  173. check_ctimes();
  174. reap_children();
  175. for ($j = count($children); $j < $max_jobs; $j++) {
  176. $pid = pcntl_fork();
  177. if ($pid == -1) {
  178. die("fork failed!\n");
  179. } else if ($pid) {
  180. if (!$master_handlers_installed) {
  181. Debug::log("[MASTER] installing shutdown handlers");
  182. pcntl_signal(SIGINT, 'sigint_handler');
  183. pcntl_signal(SIGTERM, 'sigint_handler');
  184. register_shutdown_function('shutdown', posix_getpid());
  185. $master_handlers_installed = true;
  186. }
  187. Debug::log("[MASTER] spawned client $j [PID:$pid]...");
  188. array_push($children, $pid);
  189. $ctimes[$pid] = time();
  190. } else {
  191. pcntl_signal(SIGCHLD, SIG_IGN);
  192. pcntl_signal(SIGINT, 'task_sigint_handler');
  193. register_shutdown_function('task_shutdown');
  194. $quiet = (isset($options["quiet"])) ? "--quiet" : "";
  195. $log = function_exists("flock") && isset($options['log']) ? '--log '.$options['log'] : '';
  196. $my_pid = posix_getpid();
  197. passthru(PHP_EXECUTABLE . " update.php --daemon-loop $quiet $log --task $j --pidlock $my_pid");
  198. sleep(1);
  199. // We exit in order to avoid fork bombing.
  200. exit(0);
  201. }
  202. }
  203. $last_checkpoint = time();
  204. }
  205. sleep(1);
  206. }
  207. ?>