update_daemon2.php 6.7 KB

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