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.

664 lines
19 KiB

11 years ago
4 years ago
4 years ago
4 years ago
10 years ago
11 years ago
  1. <?php
  2. if (!file_exists("boot.php") AND (sizeof($_SERVER["argv"]) != 0)) {
  3. $directory = dirname($_SERVER["argv"][0]);
  4. if (substr($directory, 0, 1) != "/")
  5. $directory = $_SERVER["PWD"]."/".$directory;
  6. $directory = realpath($directory."/..");
  7. chdir($directory);
  8. }
  9. use \Friendica\Core\Config;
  10. require_once("boot.php");
  11. function poller_run($argv, $argc){
  12. global $a, $db;
  13. if(is_null($a)) {
  14. $a = new App;
  15. }
  16. if(is_null($db)) {
  17. @include(".htconfig.php");
  18. require_once("include/dba.php");
  19. $db = new dba($db_host, $db_user, $db_pass, $db_data);
  20. unset($db_host, $db_user, $db_pass, $db_data);
  21. };
  22. Config::load();
  23. // Quit when in maintenance
  24. if (Config::get('system', 'maintenance', true)) {
  25. return;
  26. }
  27. $a->set_baseurl(Config::get('system', 'url'));
  28. load_hooks();
  29. $a->start_process();
  30. if (poller_max_connections_reached()) {
  31. return;
  32. }
  33. if ($a->maxload_reached()) {
  34. return;
  35. }
  36. if(($argc <= 1) OR ($argv[1] != "no_cron")) {
  37. poller_run_cron();
  38. }
  39. if ($a->max_processes_reached()) {
  40. return;
  41. }
  42. // Checking the number of workers
  43. if (poller_too_much_workers()) {
  44. poller_kill_stale_workers();
  45. return;
  46. }
  47. $starttime = time();
  48. while ($r = poller_worker_process()) {
  49. // Count active workers and compare them with a maximum value that depends on the load
  50. if (poller_too_much_workers()) {
  51. return;
  52. }
  53. if (!poller_execute($r[0])) {
  54. return;
  55. }
  56. // Quit the poller once every hour
  57. if (time() > ($starttime + 3600))
  58. return;
  59. }
  60. }
  61. /**
  62. * @brief Execute a worker entry
  63. *
  64. * @param array $queue Workerqueue entry
  65. *
  66. * @return boolean "true" if further processing should be stopped
  67. */
  68. function poller_execute($queue) {
  69. $a = get_app();
  70. $mypid = getmypid();
  71. // Quit when in maintenance
  72. if (Config::get('system', 'maintenance', true)) {
  73. return false;
  74. }
  75. // Constantly check the number of parallel database processes
  76. if ($a->max_processes_reached()) {
  77. return false;
  78. }
  79. // Constantly check the number of available database connections to let the frontend be accessible at any time
  80. if (poller_max_connections_reached()) {
  81. return false;
  82. }
  83. $upd = q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `pid` = 0",
  84. dbesc(datetime_convert()),
  85. intval($mypid),
  86. intval($queue["id"]));
  87. if (!$upd) {
  88. logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
  89. q("COMMIT");
  90. return true;
  91. }
  92. // Assure that there are no tasks executed twice
  93. $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
  94. if (!$id) {
  95. logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
  96. q("COMMIT");
  97. return true;
  98. } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
  99. logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
  100. q("COMMIT");
  101. return true;
  102. } elseif ($id[0]["pid"] != $mypid) {
  103. logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
  104. q("COMMIT");
  105. return true;
  106. }
  107. q("COMMIT");
  108. $argv = json_decode($queue["parameter"]);
  109. // Check for existance and validity of the include file
  110. $include = $argv[0];
  111. if (!validate_include($include)) {
  112. logger("Include file ".$argv[0]." is not valid!");
  113. q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
  114. return true;
  115. }
  116. require_once($include);
  117. $funcname = str_replace(".php", "", basename($argv[0]))."_run";
  118. if (function_exists($funcname)) {
  119. poller_exec_function($queue, $funcname, $argv);
  120. q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
  121. } else {
  122. logger("Function ".$funcname." does not exist");
  123. }
  124. return true;
  125. }
  126. /**
  127. * @brief Execute a function from the queue
  128. *
  129. * @param array $queue Workerqueue entry
  130. * @param string $funcname name of the function
  131. * @param array $argv Array of values to be passed to the function
  132. */
  133. function poller_exec_function($queue, $funcname, $argv) {
  134. $a = get_app();
  135. $mypid = getmypid();
  136. $argc = count($argv);
  137. logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
  138. $stamp = (float)microtime(true);
  139. // We use the callstack here to analyze the performance of executed worker entries.
  140. // For this reason the variables have to be initialized.
  141. if (Config::get("system", "profiler")) {
  142. $a->performance["start"] = microtime(true);
  143. $a->performance["database"] = 0;
  144. $a->performance["database_write"] = 0;
  145. $a->performance["network"] = 0;
  146. $a->performance["file"] = 0;
  147. $a->performance["rendering"] = 0;
  148. $a->performance["parser"] = 0;
  149. $a->performance["marktime"] = 0;
  150. $a->performance["markstart"] = microtime(true);
  151. $a->callstack = array();
  152. }
  153. // For better logging create a new process id for every worker call
  154. // But preserve the old one for the worker
  155. $old_process_id = $a->process_id;
  156. $a->process_id = uniqid("wrk", true);
  157. $funcname($argv, $argc);
  158. $a->process_id = $old_process_id;
  159. $duration = number_format(microtime(true) - $stamp, 3);
  160. logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
  161. // Write down the performance values into the log
  162. if (Config::get("system", "profiler")) {
  163. $duration = microtime(true)-$a->performance["start"];
  164. if (Config::get("rendertime", "callstack")) {
  165. if (isset($a->callstack["database"])) {
  166. $o = "\nDatabase Read:\n";
  167. foreach ($a->callstack["database"] AS $func => $time) {
  168. $time = round($time, 3);
  169. if ($time > 0)
  170. $o .= $func.": ".$time."\n";
  171. }
  172. }
  173. if (isset($a->callstack["database_write"])) {
  174. $o .= "\nDatabase Write:\n";
  175. foreach ($a->callstack["database_write"] AS $func => $time) {
  176. $time = round($time, 3);
  177. if ($time > 0)
  178. $o .= $func.": ".$time."\n";
  179. }
  180. }
  181. if (isset($a->callstack["network"])) {
  182. $o .= "\nNetwork:\n";
  183. foreach ($a->callstack["network"] AS $func => $time) {
  184. $time = round($time, 3);
  185. if ($time > 0)
  186. $o .= $func.": ".$time."\n";
  187. }
  188. }
  189. } else {
  190. $o = '';
  191. }
  192. logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
  193. number_format($a->performance["database"] - $a->performance["database_write"], 2),
  194. number_format($a->performance["database_write"], 2),
  195. number_format($a->performance["network"], 2),
  196. number_format($a->performance["file"], 2),
  197. number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
  198. number_format($duration, 2)),
  199. LOGGER_DEBUG);
  200. }
  201. $cooldown = Config::get("system", "worker_cooldown", 0);
  202. if ($cooldown > 0) {
  203. logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
  204. sleep($cooldown);
  205. }
  206. }
  207. /**
  208. * @brief Checks if the number of database connections has reached a critical limit.
  209. *
  210. * @return bool Are more than 3/4 of the maximum connections used?
  211. */
  212. function poller_max_connections_reached() {
  213. // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
  214. $max = Config::get("system", "max_connections");
  215. // Fetch the percentage level where the poller will get active
  216. $maxlevel = Config::get("system", "max_connections_level", 75);
  217. if ($max == 0) {
  218. // the maximum number of possible user connections can be a system variable
  219. $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
  220. if ($r)
  221. $max = $r[0]["Value"];
  222. // Or it can be granted. This overrides the system variable
  223. $r = q("SHOW GRANTS");
  224. if ($r)
  225. foreach ($r AS $grants) {
  226. $grant = array_pop($grants);
  227. if (stristr($grant, "GRANT USAGE ON"))
  228. if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
  229. $max = $match[1];
  230. }
  231. }
  232. // If $max is set we will use the processlist to determine the current number of connections
  233. // The processlist only shows entries of the current user
  234. if ($max != 0) {
  235. $r = q("SHOW PROCESSLIST");
  236. if (!dbm::is_result($r))
  237. return false;
  238. $used = count($r);
  239. logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
  240. $level = ($used / $max) * 100;
  241. if ($level >= $maxlevel) {
  242. logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
  243. return true;
  244. }
  245. }
  246. // We will now check for the system values.
  247. // This limit could be reached although the user limits are fine.
  248. $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
  249. if (!$r)
  250. return false;
  251. $max = intval($r[0]["Value"]);
  252. if ($max == 0)
  253. return false;
  254. $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
  255. if (!$r)
  256. return false;
  257. $used = intval($r[0]["Value"]);
  258. if ($used == 0)
  259. return false;
  260. logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
  261. $level = $used / $max * 100;
  262. if ($level < $maxlevel)
  263. return false;
  264. logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
  265. return true;
  266. }
  267. /**
  268. * @brief fix the queue entry if the worker process died
  269. *
  270. */
  271. function poller_kill_stale_workers() {
  272. $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
  273. if (!dbm::is_result($r)) {
  274. // No processing here needed
  275. return;
  276. }
  277. foreach($r AS $pid)
  278. if (!posix_kill($pid["pid"], 0))
  279. q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
  280. intval($pid["pid"]));
  281. else {
  282. // Kill long running processes
  283. // Check if the priority is in a valid range
  284. if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
  285. $pid["priority"] = PRIORITY_MEDIUM;
  286. // Define the maximum durations
  287. $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
  288. $max_duration = $max_duration_defaults[$pid["priority"]];
  289. $argv = json_decode($pid["parameter"]);
  290. $argv[0] = basename($argv[0]);
  291. // How long is the process already running?
  292. $duration = (time() - strtotime($pid["executed"])) / 60;
  293. if ($duration > $max_duration) {
  294. logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
  295. posix_kill($pid["pid"], SIGTERM);
  296. // We killed the stale process.
  297. // To avoid a blocking situation we reschedule the process at the beginning of the queue.
  298. // Additionally we are lowering the priority.
  299. q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
  300. `priority` = %d, `pid` = 0 WHERE `pid` = %d",
  301. dbesc(datetime_convert()),
  302. intval(PRIORITY_NEGLIGIBLE),
  303. intval($pid["pid"]));
  304. } else
  305. logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
  306. }
  307. }
  308. /**
  309. * @brief Checks if the number of active workers exceeds the given limits
  310. *
  311. * @return bool Are there too much workers running?
  312. */
  313. function poller_too_much_workers() {
  314. $queues = Config::get("system", "worker_queues", 4);
  315. $maxqueues = $queues;
  316. $active = poller_active_workers();
  317. // Decrease the number of workers at higher load
  318. $load = current_load();
  319. if($load) {
  320. $maxsysload = intval(Config::get("system", "maxloadavg", 50));
  321. $maxworkers = $queues;
  322. // Some magical mathemathics to reduce the workers
  323. $exponent = 3;
  324. $slope = $maxworkers / pow($maxsysload, $exponent);
  325. $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
  326. $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
  327. $entries = $s[0]["total"];
  328. if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
  329. $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
  330. $top_priority = $s[0]["priority"];
  331. $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
  332. intval($top_priority));
  333. $high_running = dbm::is_result($s);
  334. if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
  335. logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
  336. $queues = $active + 1;
  337. }
  338. }
  339. // Create a list of queue entries grouped by their priority
  340. $running = array(PRIORITY_CRITICAL => 0,
  341. PRIORITY_HIGH => 0,
  342. PRIORITY_MEDIUM => 0,
  343. PRIORITY_LOW => 0,
  344. PRIORITY_NEGLIGIBLE => 0);
  345. $r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
  346. if (dbm::is_result($r))
  347. foreach ($r AS $process)
  348. $running[$process["priority"]] = $process["running"];
  349. $processlist = "";
  350. $r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
  351. if (dbm::is_result($r))
  352. foreach ($r as $entry) {
  353. if ($processlist != "")
  354. $processlist .= ", ";
  355. $processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
  356. }
  357. logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
  358. // Are there fewer workers running as possible? Then fork a new one.
  359. if (!Config::get("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
  360. logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
  361. $args = array("include/poller.php", "no_cron");
  362. $a = get_app();
  363. $a->proc_run($args);
  364. }
  365. }
  366. return($active >= $queues);
  367. }
  368. /**
  369. * @brief Returns the number of active poller processes
  370. *
  371. * @return integer Number of active poller processes
  372. */
  373. function poller_active_workers() {
  374. $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
  375. return($workers[0]["processes"]);
  376. }
  377. /**
  378. * @brief Check if we should pass some slow processes
  379. *
  380. * When the active processes of the highest priority are using more than 2/3
  381. * of all processes, we let pass slower processes.
  382. *
  383. * @param string $highest_priority Returns the currently highest priority
  384. * @return bool We let pass a slower process than $highest_priority
  385. */
  386. function poller_passing_slow(&$highest_priority) {
  387. $highest_priority = 0;
  388. $r = q("SELECT `priority`
  389. FROM `process`
  390. INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
  391. // No active processes at all? Fine
  392. if (!dbm::is_result($r))
  393. return(false);
  394. $priorities = array();
  395. foreach ($r AS $line)
  396. $priorities[] = $line["priority"];
  397. // Should not happen
  398. if (count($priorities) == 0)
  399. return(false);
  400. $highest_priority = min($priorities);
  401. // The highest process is already the slowest one?
  402. // Then we quit
  403. if ($highest_priority == PRIORITY_NEGLIGIBLE)
  404. return(false);
  405. $high = 0;
  406. foreach ($priorities AS $priority)
  407. if ($priority == $highest_priority)
  408. ++$high;
  409. logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
  410. $passing_slow = (($high/count($priorities)) > (2/3));
  411. if ($passing_slow)
  412. logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
  413. return($passing_slow);
  414. }
  415. /**
  416. * @brief Returns the next worker process
  417. *
  418. * @return string SQL statement
  419. */
  420. function poller_worker_process() {
  421. q("START TRANSACTION;");
  422. // Check if we should pass some low priority process
  423. $highest_priority = 0;
  424. if (poller_passing_slow($highest_priority)) {
  425. // Are there waiting processes with a higher priority than the currently highest?
  426. $r = q("SELECT * FROM `workerqueue`
  427. WHERE `executed` = '0000-00-00 00:00:00' AND `priority` < %d
  428. ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
  429. if (dbm::is_result($r))
  430. return $r;
  431. // Give slower processes some processing time
  432. $r = q("SELECT * FROM `workerqueue`
  433. WHERE `executed` = '0000-00-00 00:00:00' AND `priority` > %d
  434. ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
  435. }
  436. // If there is no result (or we shouldn't pass lower processes) we check without priority limit
  437. if (($highest_priority == 0) OR !dbm::is_result($r))
  438. $r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1");
  439. return $r;
  440. }
  441. /**
  442. * @brief Call the front end worker
  443. */
  444. function call_worker() {
  445. if (!Config::get("system", "frontend_worker")) {
  446. return;
  447. }
  448. $url = App::get_baseurl()."/worker";
  449. fetch_url($url, false, $redirects, 1);
  450. }
  451. /**
  452. * @brief Call the front end worker if there aren't any active
  453. */
  454. function call_worker_if_idle() {
  455. if (!Config::get("system", "frontend_worker")) {
  456. return;
  457. }
  458. // Do we have "proc_open"? Then we can fork the poller
  459. if (function_exists("proc_open")) {
  460. // When was the last time that we called the worker?
  461. // Less than one minute? Then we quit
  462. if ((time() - Config::get("system", "worker_started")) < 60) {
  463. return;
  464. }
  465. set_config("system", "worker_started", time());
  466. // Do we have enough running workers? Then we quit here.
  467. if (poller_too_much_workers()) {
  468. // Cleaning dead processes
  469. poller_kill_stale_workers();
  470. get_app()->remove_inactive_processes();
  471. return;
  472. }
  473. poller_run_cron();
  474. logger('Call poller', LOGGER_DEBUG);
  475. $args = array("include/poller.php", "no_cron");
  476. $a = get_app();
  477. $a->proc_run($args);
  478. return;
  479. }
  480. // We cannot execute background processes.
  481. // We now run the processes from the frontend.
  482. // This won't work with long running processes.
  483. poller_run_cron();
  484. clear_worker_processes();
  485. $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
  486. if ($workers[0]["processes"] == 0) {
  487. call_worker();
  488. }
  489. }
  490. /**
  491. * @brief Removes long running worker processes
  492. */
  493. function clear_worker_processes() {
  494. $timeout = Config::get("system", "frontend_worker_timeout", 10);
  495. /// @todo We should clean up the corresponding workerqueue entries as well
  496. q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
  497. dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
  498. }
  499. /**
  500. * @brief Runs the cron processes
  501. */
  502. function poller_run_cron() {
  503. logger('Add cron entries', LOGGER_DEBUG);
  504. // Check for spooled items
  505. proc_run(PRIORITY_HIGH, "include/spool_post.php");
  506. // Run the cron job that calls all other jobs
  507. proc_run(PRIORITY_MEDIUM, "include/cron.php");
  508. // Run the cronhooks job separately from cron for being able to use a different timing
  509. proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
  510. // Cleaning dead processes
  511. poller_kill_stale_workers();
  512. }
  513. if (array_search(__file__,get_included_files())===0){
  514. poller_run($_SERVER["argv"],$_SERVER["argc"]);
  515. get_app()->end_process();
  516. killme();
  517. }
  518. ?>