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.

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